{"commit":"eab8feaedeb2eba7ff85bbeff1bba3e766a5dc22","subject":"gio: don't use Control.Monad.>","message":"gio: don't use Control.Monad.>\n\ndarcs-hash:20081020132048-21862-2fe583b56f5e616bc9f6207b91e0fdfb28f41823.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gio\/System\/GIO\/File.chs","new_file":"gio\/System\/GIO\/File.chs","new_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gio -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 13-Oct-2008\n--\n-- Copyright (c) 2008 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GIO, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GIO documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.GIO.File (\n File,\n FileClass,\n FileQueryInfoFlags,\n FileCreateFlags,\n FileCopyFlags,\n FileMonitorFlags,\n FilesystemPreviewType,\n FileProgressCallback,\n FileReadMoreCallback,\n fileFromPath,\n fileFromURI,\n fileFromCommandlineArg,\n fileFromParseName,\n fileEqual,\n fileBasename,\n filePath,\n fileURI,\n fileParseName,\n fileGetChild,\n fileGetChildForDisplayName,\n fileHasPrefix,\n fileGetRelativePath,\n fileResolveRelativePath,\n fileIsNative,\n fileHasURIScheme,\n fileURIScheme,\n fileRead,\n fileReadAsync,\n fileReadFinish,\n fileAppendTo,\n fileCreate,\n fileReplace,\n fileAppendToAsync,\n fileAppendToFinish,\n fileCreateAsync,\n fileCreateFinish,\n fileReplaceAsync,\n fileReplaceFinish,\n fileQueryInfo,\n fileQueryInfoAsync,\n fileQueryInfoFinish,\n fileQueryExists,\n fileQueryFilesystemInfo,\n fileQueryFilesystemInfoAsync,\n fileQueryFilesystemInfoFinish,\n fileQueryDefaultHandler,\n fileFindEnclosingMount,\n fileFindEnclosingMountAsync,\n fileFindEnclosingMountFinish,\n fileEnumerateChildren,\n fileEnumerateChildrenAsync,\n fileEnumerateChildrenFinish,\n fileSetDisplayName,\n fileSetDisplayNameAsync,\n fileSetDisplayNameFinish,\n fileDelete,\n fileTrash,\n fileCopy,\n fileCopyAsync,\n fileCopyFinish,\n fileMove,\n fileMakeDirectory,\n fileMakeDirectoryWithParents,\n fileMakeSymbolicLink\n ) where\n\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport Data.Typeable\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.UTFString\n\nimport System.GIO.Base\n{#import System.GIO.Types#}\n\n{# context lib = \"gio\" prefix = \"g\" #}\n\n{# enum GFileQueryInfoFlags as FileQueryInfoFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileQueryInfoFlags\n\n{# enum GFileCreateFlags as FileCreateFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCreateFlags\n\n{# enum GFileCopyFlags as FileCopyFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCopyFlags\n\n{# enum GFileMonitorFlags as FileMonitorFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileMonitorFlags\n\n{# enum GFilesystemPreviewType as FilesystemPreviewType {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\ntype FileProgressCallback = Offset -> Offset -> IO ()\ntype CFileProgressCallback = {# type goffset #} -> {# type goffset #} -> Ptr () -> IO ()\nforeign import ccall \"wrapper\"\n makeFileProgressCallback :: CFileProgressCallback\n -> IO {# type GFileProgressCallback #}\n\nmarshalFileProgressCallback :: FileProgressCallback -> IO {# type GFileProgressCallback #}\nmarshalFileProgressCallback fileProgressCallback =\n makeFileProgressCallback cFileProgressCallback\n where cFileProgressCallback :: CFileProgressCallback\n cFileProgressCallback cCurrentNumBytes cTotalNumBytes _ = do\n fileProgressCallback (fromIntegral cCurrentNumBytes)\n (fromIntegral cTotalNumBytes)\n\ntype FileReadMoreCallback = BS.ByteString -> IO Bool\n\nfileFromPath :: FilePath -> File\nfileFromPath path =\n unsafePerformIO $ withUTFString path $ \\cPath -> {# call file_new_for_path #} cPath >>= takeGObject\n\nfileFromURI :: String -> File\nfileFromURI uri =\n unsafePerformIO $ withUTFString uri $ \\cURI -> {# call file_new_for_uri #} cURI >>= takeGObject\n\nfileFromCommandlineArg :: String -> File\nfileFromCommandlineArg arg =\n unsafePerformIO $ withUTFString arg $ \\cArg -> {# call file_new_for_commandline_arg #} cArg >>= takeGObject\n\nfileFromParseName :: String -> File\nfileFromParseName parseName =\n unsafePerformIO $ withUTFString parseName $ \\cParseName -> {# call file_parse_name #} cParseName >>= takeGObject\n\nfileEqual :: (FileClass file1, FileClass file2)\n => file1 -> file2 -> Bool\nfileEqual file1 file2 =\n unsafePerformIO $ liftM toBool $ {# call file_equal #} (toFile file1) (toFile file2)\n\ninstance Eq File where\n (==) = fileEqual\n\nfileBasename :: FileClass file => file -> String\nfileBasename file =\n unsafePerformIO $ {# call file_get_basename #} (toFile file) >>= readUTFString\n\nfilePath :: FileClass file => file -> FilePath\nfilePath file =\n unsafePerformIO $ {# call file_get_path #} (toFile file) >>= readUTFString\n\nfileURI :: FileClass file => file -> String\nfileURI file =\n unsafePerformIO $ {# call file_get_uri #} (toFile file) >>= readUTFString\n\nfileParseName :: FileClass file => file -> String\nfileParseName file =\n unsafePerformIO $ {# call file_get_parse_name #} (toFile file) >>= readUTFString\n\nfileParent :: FileClass file => file -> Maybe File\nfileParent file =\n unsafePerformIO $ {# call file_get_parent #} (toFile file) >>= maybePeek takeGObject\n\nfileGetChild :: FileClass file => file -> String -> File\nfileGetChild file name =\n unsafePerformIO $\n withUTFString name $ \\cName ->\n {# call file_get_child #} (toFile file) cName >>= takeGObject\n\nfileGetChildForDisplayName :: FileClass file => file -> String -> Maybe File\nfileGetChildForDisplayName file displayName =\n unsafePerformIO $\n withUTFString displayName $ \\cDisplayName ->\n propagateGError ({# call file_get_child_for_display_name #} (toFile file) cDisplayName) >>=\n maybePeek takeGObject\n\nfileHasPrefix :: (FileClass file1, FileClass file2) => file1 -> file2 -> Bool\nfileHasPrefix file1 file2 =\n unsafePerformIO $\n liftM toBool $ {# call file_has_prefix #} (toFile file1) (toFile file2)\n\nfileGetRelativePath :: (FileClass file1, FileClass file2) => file1 -> file2 -> Maybe FilePath\nfileGetRelativePath file1 file2 =\n unsafePerformIO $\n {# call file_get_relative_path #} (toFile file1) (toFile file2) >>=\n maybePeek readUTFString\n\nfileResolveRelativePath :: FileClass file => file -> FilePath -> Maybe File\nfileResolveRelativePath file relativePath =\n unsafePerformIO $\n withUTFString relativePath $ \\cRelativePath ->\n {# call file_resolve_relative_path #} (toFile file) cRelativePath >>=\n maybePeek takeGObject\n\nfileIsNative :: FileClass file => file -> Bool\nfileIsNative =\n unsafePerformIO .\n liftM toBool . {# call file_is_native #} . toFile\n\nfileHasURIScheme :: FileClass file => file -> String -> Bool\nfileHasURIScheme file uriScheme =\n unsafePerformIO $\n withUTFString uriScheme $ \\cURIScheme ->\n liftM toBool $ {# call file_has_uri_scheme #} (toFile file) cURIScheme\n\nfileURIScheme :: FileClass file => file -> String\nfileURIScheme file =\n unsafePerformIO $ {# call file_get_uri_scheme #} (toFile file) >>= readUTFString\n\nfileRead :: FileClass file => file -> Maybe Cancellable -> IO FileInputStream\nfileRead file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_read cFile cCancellable) >>= takeGObject\n where _ = {# call file_read #}\n\nfileReadAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReadAsync file ioPriority mbCancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject mbCancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_read_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_read_async #}\n\nfileReadFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInputStream\nfileReadFinish file asyncResult =\n propagateGError ({# call file_read_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileAppendTo :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileAppendTo file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_append_to cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_append_to #}\n\nfileCreate :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileCreate file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_create cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_create #}\n\nfileReplace :: FileClass file\n => file\n -> Maybe String\n -> Bool\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileReplace file etag makeBackup flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_replace cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_replace #}\n\nfileAppendToAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileAppendToAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_append_to_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_append_to_async #}\n\nfileAppendToFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileAppendToFinish file asyncResult =\n propagateGError ({# call file_append_to_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileCreateAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileCreateAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_create_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_create_async #}\n\nfileCreateFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileCreateFinish file asyncResult =\n propagateGError ({# call file_create_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileReplaceAsync :: FileClass file\n => file\n -> String\n -> Bool\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReplaceAsync file etag makeBackup flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_replace_async cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_replace_async #}\n\nfileReplaceFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileReplaceFinish file asyncResult =\n propagateGError ({# call file_replace_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileQueryInfo :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryInfo file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_info cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_query_info #}\n\nfileQueryInfoAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryInfoAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_info_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_info_async #}\n\nfileQueryInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryInfoFinish file asyncResult =\n propagateGError ({#call file_query_info_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileQueryExists :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Bool\nfileQueryExists file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n liftM toBool $ g_file_query_exists cFile cCancellable\n where _ = {# call file_query_exists #}\n\nfileQueryFilesystemInfo :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryFilesystemInfo file attributes cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_filesystem_info cFile cAttributes cCancellable) >>=\n takeGObject\n where _ = {# call file_query_filesystem_info #}\n\nfileQueryFilesystemInfoAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryFilesystemInfoAsync file attributes ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_filesystem_info_async cFile\n cAttributes\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_filesystem_info_async #}\n\nfileQueryFilesystemInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryFilesystemInfoFinish file asyncResult =\n propagateGError ({# call file_query_filesystem_info_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileQueryDefaultHandler :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO AppInfo\nfileQueryDefaultHandler file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_default_handler cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_query_default_handler #}\n\nfileFindEnclosingMount :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Mount\nfileFindEnclosingMount file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_find_enclosing_mount cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_find_enclosing_mount #}\n\nfileFindEnclosingMountAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileFindEnclosingMountAsync file ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_find_enclosing_mount_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_find_enclosing_mount_async #}\n\nfileFindEnclosingMountFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Mount\nfileFindEnclosingMountFinish file asyncResult =\n propagateGError ({# call file_find_enclosing_mount_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileEnumerateChildren :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileEnumerator\nfileEnumerateChildren file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_enumerate_children cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_enumerate_children #}\n\nfileEnumerateChildrenAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileEnumerateChildrenAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_enumerate_children_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_enumerate_children_async #}\n\nfileEnumerateChildrenFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileEnumerator\nfileEnumerateChildrenFinish file asyncResult =\n propagateGError ({# call file_enumerate_children_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileSetDisplayName :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO File\nfileSetDisplayName file displayName cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_set_display_name cFile cDisplayName cCancellable) >>=\n takeGObject\n where _ = {# call file_set_display_name #}\n\nfileSetDisplayNameAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileSetDisplayNameAsync file displayName ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_set_display_name_async cFile\n cDisplayName\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_set_display_name_async #}\n\nfileSetDisplayNameFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO File\nfileSetDisplayNameFinish file asyncResult =\n propagateGError ({# call file_set_display_name_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileDelete :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileDelete file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_delete cFile cCancellable) >> return ()\n where _ = {# call file_delete #}\n\nfileTrash :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileTrash file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_trash cFile cCancellable) >> return ()\n where _ = {# call file_trash #}\n\nfileCopy :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileCopy source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_copy cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_copy #}\n\nfileCopyAsync :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Int\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> AsyncReadyCallback\n -> IO ()\nfileCopyAsync source destination flags ioPriority cancellable progressCallback callback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n cCallback <- marshalAsyncReadyCallback $ \\sourceObject res -> do\n freeHaskellFunPtr cProgressCallback\n callback sourceObject res\n g_file_copy_async cSource\n cDestination\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cProgressCallback\n nullPtr\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_copy_async #}\n\nfileCopyFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Bool\nfileCopyFinish file asyncResult =\n liftM toBool $ propagateGError ({# call file_copy_finish #} (toFile file) asyncResult)\n\nfileMove :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileMove source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_move cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_move #}\n\nfileMakeDirectory :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectory file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory cFile cCancellable\n return ()\n where _ = {# call file_make_directory #}\n\nfileMakeDirectoryWithParents :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectoryWithParents file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory_with_parents cFile cCancellable\n return ()\n where _ = {# call file_make_directory_with_parents #}\n\nfileMakeSymbolicLink :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO ()\nfileMakeSymbolicLink file symlinkValue cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString symlinkValue $ \\cSymlinkValue ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_symbolic_link cFile cSymlinkValue cCancellable\n return ()\n where _ = {# call file_make_symbolic_link #}\n\n","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gio -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 13-Oct-2008\n--\n-- Copyright (c) 2008 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GIO, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GIO documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.GIO.File (\n File,\n FileClass,\n FileQueryInfoFlags,\n FileCreateFlags,\n FileCopyFlags,\n FileMonitorFlags,\n FilesystemPreviewType,\n FileProgressCallback,\n FileReadMoreCallback,\n fileFromPath,\n fileFromURI,\n fileFromCommandlineArg,\n fileFromParseName,\n fileEqual,\n fileBasename,\n filePath,\n fileURI,\n fileParseName,\n fileGetChild,\n fileGetChildForDisplayName,\n fileHasPrefix,\n fileGetRelativePath,\n fileResolveRelativePath,\n fileIsNative,\n fileHasURIScheme,\n fileURIScheme,\n fileRead,\n fileReadAsync,\n fileReadFinish,\n fileAppendTo,\n fileCreate,\n fileReplace,\n fileAppendToAsync,\n fileAppendToFinish,\n fileCreateAsync,\n fileCreateFinish,\n fileReplaceAsync,\n fileReplaceFinish,\n fileQueryInfo,\n fileQueryInfoAsync,\n fileQueryInfoFinish,\n fileQueryExists,\n fileQueryFilesystemInfo,\n fileQueryFilesystemInfoAsync,\n fileQueryFilesystemInfoFinish,\n fileQueryDefaultHandler,\n fileFindEnclosingMount,\n fileFindEnclosingMountAsync,\n fileFindEnclosingMountFinish,\n fileEnumerateChildren,\n fileEnumerateChildrenAsync,\n fileEnumerateChildrenFinish,\n fileSetDisplayName,\n fileSetDisplayNameAsync,\n fileSetDisplayNameFinish,\n fileDelete,\n fileTrash,\n fileCopy,\n fileCopyAsync,\n fileCopyFinish,\n fileMove,\n fileMakeDirectory,\n fileMakeDirectoryWithParents,\n fileMakeSymbolicLink\n ) where\n\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport Data.Typeable\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.UTFString\n\nimport System.GIO.Base\n{#import System.GIO.Types#}\n\n{# context lib = \"gio\" prefix = \"g\" #}\n\n{# enum GFileQueryInfoFlags as FileQueryInfoFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileQueryInfoFlags\n\n{# enum GFileCreateFlags as FileCreateFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCreateFlags\n\n{# enum GFileCopyFlags as FileCopyFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCopyFlags\n\n{# enum GFileMonitorFlags as FileMonitorFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileMonitorFlags\n\n{# enum GFilesystemPreviewType as FilesystemPreviewType {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\ntype FileProgressCallback = Offset -> Offset -> IO ()\ntype CFileProgressCallback = {# type goffset #} -> {# type goffset #} -> Ptr () -> IO ()\nforeign import ccall \"wrapper\"\n makeFileProgressCallback :: CFileProgressCallback\n -> IO {# type GFileProgressCallback #}\n\nmarshalFileProgressCallback :: FileProgressCallback -> IO {# type GFileProgressCallback #}\nmarshalFileProgressCallback fileProgressCallback =\n makeFileProgressCallback cFileProgressCallback\n where cFileProgressCallback :: CFileProgressCallback\n cFileProgressCallback cCurrentNumBytes cTotalNumBytes _ = do\n fileProgressCallback (fromIntegral cCurrentNumBytes)\n (fromIntegral cTotalNumBytes)\n\ntype FileReadMoreCallback = BS.ByteString -> IO Bool\n\nfileFromPath :: FilePath -> File\nfileFromPath path =\n unsafePerformIO $ withUTFString path $ {# call file_new_for_path #} >=> takeGObject\n\nfileFromURI :: String -> File\nfileFromURI uri =\n unsafePerformIO $ withUTFString uri $ {# call file_new_for_uri #} >=> takeGObject\n\nfileFromCommandlineArg :: String -> File\nfileFromCommandlineArg arg =\n unsafePerformIO $ withUTFString arg $ {# call file_new_for_commandline_arg #} >=> takeGObject\n\nfileFromParseName :: String -> File\nfileFromParseName parseName =\n unsafePerformIO $ withUTFString parseName $ {# call file_parse_name #} >=> takeGObject\n\nfileEqual :: (FileClass file1, FileClass file2)\n => file1 -> file2 -> Bool\nfileEqual file1 file2 =\n unsafePerformIO $ liftM toBool $ {# call file_equal #} (toFile file1) (toFile file2)\n\ninstance Eq File where\n (==) = fileEqual\n\nfileBasename :: FileClass file => file -> String\nfileBasename =\n unsafePerformIO . ({# call file_get_basename #} . toFile >=> readUTFString)\n\nfilePath :: FileClass file => file -> FilePath\nfilePath =\n unsafePerformIO . ({# call file_get_path #} . toFile >=> readUTFString)\n\nfileURI :: FileClass file => file -> String\nfileURI =\n unsafePerformIO . ({# call file_get_uri #} . toFile >=> readUTFString)\n\nfileParseName :: FileClass file => file -> String\nfileParseName =\n unsafePerformIO . ({# call file_get_parse_name #} . toFile >=> readUTFString)\n\nfileParent :: FileClass file => file -> Maybe File\nfileParent =\n unsafePerformIO . ({# call file_get_parent #} . toFile >=> maybePeek takeGObject)\n\nfileGetChild :: FileClass file => file -> String -> File\nfileGetChild file name =\n unsafePerformIO $\n withUTFString name $\n {# call file_get_child #} (toFile file) >=> takeGObject\n\nfileGetChildForDisplayName :: FileClass file => file -> String -> Maybe File\nfileGetChildForDisplayName file displayName =\n unsafePerformIO $\n withUTFString displayName $ \\cDisplayName ->\n propagateGError ({# call file_get_child_for_display_name #} (toFile file) cDisplayName) >>=\n maybePeek takeGObject\n\nfileHasPrefix :: (FileClass file1, FileClass file2) => file1 -> file2 -> Bool\nfileHasPrefix file1 file2 =\n unsafePerformIO $\n liftM toBool $ {# call file_has_prefix #} (toFile file1) (toFile file2)\n\nfileGetRelativePath :: (FileClass file1, FileClass file2) => file1 -> file2 -> Maybe FilePath\nfileGetRelativePath file1 file2 =\n unsafePerformIO $\n {# call file_get_relative_path #} (toFile file1) (toFile file2) >>=\n maybePeek readUTFString\n\nfileResolveRelativePath :: FileClass file => file -> FilePath -> Maybe File\nfileResolveRelativePath file relativePath =\n unsafePerformIO $\n withUTFString relativePath $ \\cRelativePath ->\n {# call file_resolve_relative_path #} (toFile file) cRelativePath >>=\n maybePeek takeGObject\n\nfileIsNative :: FileClass file => file -> Bool\nfileIsNative =\n unsafePerformIO .\n liftM toBool . {# call file_is_native #} . toFile\n\nfileHasURIScheme :: FileClass file => file -> String -> Bool\nfileHasURIScheme file uriScheme =\n unsafePerformIO $\n withUTFString uriScheme $ \\cURIScheme ->\n liftM toBool $ {# call file_has_uri_scheme #} (toFile file) cURIScheme\n\nfileURIScheme :: FileClass file => file -> String\nfileURIScheme =\n unsafePerformIO . ({# call file_get_uri_scheme #} . toFile >=> readUTFString)\n\nfileRead :: FileClass file => file -> Maybe Cancellable -> IO FileInputStream\nfileRead file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_read cFile cCancellable) >>= takeGObject\n where _ = {# call file_read #}\n\nfileReadAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReadAsync file ioPriority mbCancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject mbCancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_read_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_read_async #}\n\nfileReadFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInputStream\nfileReadFinish file asyncResult =\n propagateGError ({# call file_read_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileAppendTo :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileAppendTo file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_append_to cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_append_to #}\n\nfileCreate :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileCreate file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_create cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_create #}\n\nfileReplace :: FileClass file\n => file\n -> Maybe String\n -> Bool\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileReplace file etag makeBackup flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_replace cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_replace #}\n\nfileAppendToAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileAppendToAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_append_to_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_append_to_async #}\n\nfileAppendToFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileAppendToFinish file asyncResult =\n propagateGError ({# call file_append_to_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileCreateAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileCreateAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_create_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_create_async #}\n\nfileCreateFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileCreateFinish file asyncResult =\n propagateGError ({# call file_create_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileReplaceAsync :: FileClass file\n => file\n -> String\n -> Bool\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReplaceAsync file etag makeBackup flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_replace_async cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_replace_async #}\n\nfileReplaceFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileReplaceFinish file asyncResult =\n propagateGError ({# call file_replace_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileQueryInfo :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryInfo file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_info cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_query_info #}\n\nfileQueryInfoAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryInfoAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_info_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_info_async #}\n\nfileQueryInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryInfoFinish file asyncResult =\n propagateGError ({#call file_query_info_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileQueryExists :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Bool\nfileQueryExists file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n liftM toBool $ g_file_query_exists cFile cCancellable\n where _ = {# call file_query_exists #}\n\nfileQueryFilesystemInfo :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryFilesystemInfo file attributes cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_filesystem_info cFile cAttributes cCancellable) >>=\n takeGObject\n where _ = {# call file_query_filesystem_info #}\n\nfileQueryFilesystemInfoAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryFilesystemInfoAsync file attributes ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_filesystem_info_async cFile\n cAttributes\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_filesystem_info_async #}\n\nfileQueryFilesystemInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryFilesystemInfoFinish file asyncResult =\n propagateGError ({# call file_query_filesystem_info_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileQueryDefaultHandler :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO AppInfo\nfileQueryDefaultHandler file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_default_handler cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_query_default_handler #}\n\nfileFindEnclosingMount :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Mount\nfileFindEnclosingMount file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_find_enclosing_mount cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_find_enclosing_mount #}\n\nfileFindEnclosingMountAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileFindEnclosingMountAsync file ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_find_enclosing_mount_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_find_enclosing_mount_async #}\n\nfileFindEnclosingMountFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Mount\nfileFindEnclosingMountFinish file asyncResult =\n propagateGError ({# call file_find_enclosing_mount_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileEnumerateChildren :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileEnumerator\nfileEnumerateChildren file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_enumerate_children cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_enumerate_children #}\n\nfileEnumerateChildrenAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileEnumerateChildrenAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_enumerate_children_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_enumerate_children_async #}\n\nfileEnumerateChildrenFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileEnumerator\nfileEnumerateChildrenFinish file asyncResult =\n propagateGError ({# call file_enumerate_children_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileSetDisplayName :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO File\nfileSetDisplayName file displayName cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_set_display_name cFile cDisplayName cCancellable) >>=\n takeGObject\n where _ = {# call file_set_display_name #}\n\nfileSetDisplayNameAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileSetDisplayNameAsync file displayName ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_set_display_name_async cFile\n cDisplayName\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_set_display_name_async #}\n\nfileSetDisplayNameFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO File\nfileSetDisplayNameFinish file asyncResult =\n propagateGError ({# call file_set_display_name_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileDelete :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileDelete file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_delete cFile cCancellable) >> return ()\n where _ = {# call file_delete #}\n\nfileTrash :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileTrash file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_trash cFile cCancellable) >> return ()\n where _ = {# call file_trash #}\n\nfileCopy :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileCopy source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_copy cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_copy #}\n\nfileCopyAsync :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Int\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> AsyncReadyCallback\n -> IO ()\nfileCopyAsync source destination flags ioPriority cancellable progressCallback callback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n cCallback <- marshalAsyncReadyCallback $ \\sourceObject res -> do\n freeHaskellFunPtr cProgressCallback\n callback sourceObject res\n g_file_copy_async cSource\n cDestination\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cProgressCallback\n nullPtr\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_copy_async #}\n\nfileCopyFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Bool\nfileCopyFinish file asyncResult =\n liftM toBool $ propagateGError ({# call file_copy_finish #} (toFile file) asyncResult)\n\nfileMove :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileMove source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_move cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_move #}\n\nfileMakeDirectory :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectory file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory cFile cCancellable\n return ()\n where _ = {# call file_make_directory #}\n\nfileMakeDirectoryWithParents :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectoryWithParents file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory_with_parents cFile cCancellable\n return ()\n where _ = {# call file_make_directory_with_parents #}\n\nfileMakeSymbolicLink :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO ()\nfileMakeSymbolicLink file symlinkValue cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString symlinkValue $ \\cSymlinkValue ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_symbolic_link cFile cSymlinkValue cCancellable\n return ()\n where _ = {# call file_make_symbolic_link #}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"20eba885369435b449b719ef30fa61576cba2595","subject":"make the payload of IArg an Int32, to match the C type","message":"make the payload of IArg an Int32, to match the C type\n","repos":"phaazon\/cuda,phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda","old_file":"Foreign\/CUDA\/Driver\/Exec.chs","new_file":"Foreign\/CUDA\/Driver\/Exec.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE GADTs #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Exec\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Kernel execution control for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Exec (\n\n -- * Kernel Execution\n Fun(Fun), FunParam(..), FunAttribute(..),\n requires, setBlockShape, setSharedSize, setParams, setCacheConfigFun,\n launch, launchKernel, launchKernel'\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Context (Cache(..))\nimport Foreign.CUDA.Driver.Stream (Stream(..))\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Data.Maybe\nimport Control.Monad (zipWithM_)\n\n\n#if CUDA_VERSION >= 4000\n{-# DEPRECATED setBlockShape, setSharedSize, setParams, launch\n \"use launchKernel instead\" #-}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A @__global__@ device function\n--\nnewtype Fun = Fun { useFun :: {# type CUfunction #}}\n\n\n-- |\n-- Function attributes\n--\n{# enum CUfunction_attribute as FunAttribute\n { underscoreToCase\n , MAX_THREADS_PER_BLOCK as MaxKernelThreadsPerBlock\n , MAX as CU_FUNC_ATTRIBUTE_MAX } -- ignore\n with prefix=\"CU_FUNC_ATTRIBUTE\" deriving (Eq, Show) #}\n\n-- |\n-- Kernel function parameters\n--\ndata FunParam where\n IArg :: !Int32 -> FunParam\n FArg :: !Float -> FunParam\n VArg :: Storable a => !a -> FunParam\n\ninstance Storable FunParam where\n sizeOf (IArg _) = sizeOf (undefined :: CUInt)\n sizeOf (FArg _) = sizeOf (undefined :: CFloat)\n sizeOf (VArg v) = sizeOf v\n\n alignment (IArg _) = alignment (undefined :: CUInt)\n alignment (FArg _) = alignment (undefined :: CFloat)\n alignment (VArg v) = alignment v\n\n poke p (IArg i) = poke (castPtr p) i\n poke p (FArg f) = poke (castPtr p) f\n poke p (VArg v) = poke (castPtr p) v\n\n\n--------------------------------------------------------------------------------\n-- Execution Control\n--------------------------------------------------------------------------------\n\n-- |\n-- Returns the value of the selected attribute requirement for the given kernel\n--\n{-# INLINEABLE requires #-}\nrequires :: Fun -> FunAttribute -> IO Int\nrequires !fn !att = resultIfOk =<< cuFuncGetAttribute att fn\n\n{-# INLINE cuFuncGetAttribute #-}\n{# fun unsafe cuFuncGetAttribute\n { alloca- `Int' peekIntConv*\n , cFromEnum `FunAttribute'\n , useFun `Fun' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the @(x,y,z)@ dimensions of the thread blocks that are created when\n-- the given kernel function is launched.\n--\n{-# INLINEABLE setBlockShape #-}\nsetBlockShape :: Fun -> (Int,Int,Int) -> IO ()\nsetBlockShape !fn (!x,!y,!z) = nothingIfOk =<< cuFuncSetBlockShape fn x y z\n\n{-# INLINE cuFuncSetBlockShape #-}\n{# fun unsafe cuFuncSetBlockShape\n { useFun `Fun'\n , `Int'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set the number of bytes of dynamic shared memory to be available to each\n-- thread block when the function is launched\n--\n{-# INLINEABLE setSharedSize #-}\nsetSharedSize :: Fun -> Integer -> IO ()\nsetSharedSize !fn !bytes = nothingIfOk =<< cuFuncSetSharedSize fn bytes\n\n{-# INLINE cuFuncSetSharedSize #-}\n{# fun unsafe cuFuncSetSharedSize\n { useFun `Fun'\n , cIntConv `Integer' } -> `Status' cToEnum #}\n\n\n-- |\n-- On devices where the L1 cache and shared memory use the same hardware\n-- resources, this sets the preferred cache configuration for the given device\n-- function. This is only a preference; the driver is free to choose a different\n-- configuration as required to execute the function.\n--\n-- Switching between configuration modes may insert a device-side\n-- synchronisation point for streamed kernel launches.\n--\n{-# INLINEABLE setCacheConfigFun #-}\nsetCacheConfigFun :: Fun -> Cache -> IO ()\n#if CUDA_VERSION < 3000\nsetCacheConfigFun _ _ = requireSDK 3.0 \"setCacheConfigFun\"\n#else\nsetCacheConfigFun !fn !pref = nothingIfOk =<< cuFuncSetCacheConfig fn pref\n\n{-# INLINE cuFuncSetCacheConfig #-}\n{# fun unsafe cuFuncSetCacheConfig\n { useFun `Fun'\n , cFromEnum `Cache' } -> `Status' cToEnum #}\n#endif\n\n-- |\n-- Invoke the kernel on a size @(w,h)@ grid of blocks. Each block contains the\n-- number of threads specified by a previous call to 'setBlockShape'. The launch\n-- may also be associated with a specific 'Stream'.\n--\n{-# INLINEABLE launch #-}\nlaunch :: Fun -> (Int,Int) -> Maybe Stream -> IO ()\nlaunch !fn (!w,!h) mst =\n nothingIfOk =<< case mst of\n Nothing -> cuLaunchGridAsync fn w h (Stream nullPtr)\n Just st -> cuLaunchGridAsync fn w h st\n\n{-# INLINE cuLaunchGridAsync #-}\n{# fun unsafe cuLaunchGridAsync\n { useFun `Fun'\n , `Int'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Invoke a kernel on a @(gx * gy * gz)@ grid of blocks, where each block\n-- contains @(tx * ty * tz)@ threads and has access to a given number of bytes\n-- of shared memory. The launch may also be associated with a specific 'Stream'.\n--\n-- In 'launchKernel', the number of kernel parameters and their offsets and\n-- sizes do not need to be specified, as this information is retrieved directly\n-- from the kernel's image. This requires the kernel to have been compiled with\n-- toolchain version 3.2 or later.\n--\n-- The alternative 'launchKernel'' will pass the arguments in directly,\n-- requiring the application to know the size and alignment\/padding of each\n-- kernel parameter.\n--\n{-# INLINEABLE launchKernel #-}\n{-# INLINEABLE launchKernel' #-}\nlaunchKernel, launchKernel'\n :: Fun -- ^ function to execute\n -> (Int,Int,Int) -- ^ block grid dimension\n -> (Int,Int,Int) -- ^ thread block shape\n -> Int -- ^ shared memory (bytes)\n -> Maybe Stream -- ^ (optional) stream to execute in\n -> [FunParam] -- ^ list of function parameters\n -> IO ()\n#if CUDA_VERSION >= 4000\nlaunchKernel !fn (!gx,!gy,!gz) (!tx,!ty,!tz) !sm !mst !args\n = (=<<) nothingIfOk\n $ withMany withFP args\n $ \\pa -> withArray pa\n $ \\pp -> cuLaunchKernel fn gx gy gz tx ty tz sm st pp nullPtr\n where\n !st = fromMaybe (Stream nullPtr) mst\n\n withFP :: FunParam -> (Ptr FunParam -> IO b) -> IO b\n withFP !p !f = case p of\n IArg v -> with' v (f . castPtr)\n FArg v -> with' v (f . castPtr)\n VArg v -> with' v (f . castPtr)\n\n -- can't use the standard 'with' because 'alloca' will pass an undefined\n -- dummy argument when determining 'sizeOf' and 'alignment', but sometimes\n -- instances in Accelerate need to evaluate this argument.\n --\n with' :: Storable a => a -> (Ptr a -> IO b) -> IO b\n with' !val !f =\n allocaBytes (sizeOf val) $ \\ptr -> do\n poke ptr val\n f ptr\n\n\nlaunchKernel' !fn (!gx,!gy,!gz) (!tx,!ty,!tz) !sm !mst !args\n = (=<<) nothingIfOk\n $ with bytes\n $ \\pb -> withArray' args\n $ \\pa -> withArray0 nullPtr [buffer, castPtr pa, size, castPtr pb]\n $ \\pp -> cuLaunchKernel fn gx gy gz tx ty tz sm st nullPtr pp\n where\n buffer = wordPtrToPtr 0x01 -- CU_LAUNCH_PARAM_BUFFER_POINTER\n size = wordPtrToPtr 0x02 -- CU_LAUNCH_PARAM_BUFFER_SIZE\n bytes = foldl (\\a x -> a + sizeOf x) 0 args\n st = fromMaybe (Stream nullPtr) mst\n\n -- can't use the standard 'withArray' because 'mallocArray' will pass\n -- 'undefined' to 'sizeOf' when determining how many bytes to allocate, but\n -- our Storable instance for FunParam needs to dispatch on each constructor,\n -- hence evaluating the undefined.\n --\n withArray' !vals !f =\n allocaBytes bytes $ \\ptr -> do\n pokeArray ptr vals\n f ptr\n\n\n{-# INLINE cuLaunchKernel #-}\n{# fun unsafe cuLaunchKernel\n { useFun `Fun'\n , `Int', `Int', `Int'\n , `Int', `Int', `Int'\n , `Int'\n , useStream `Stream'\n , castPtr `Ptr (Ptr FunParam)'\n , castPtr `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n#else\nlaunchKernel !fn (!gx,!gy,_) (!tx,!ty,!tz) !sm !mst !args = do\n setParams fn args\n setSharedSize fn (toInteger sm)\n setBlockShape fn (tx,ty,tz)\n launch fn (gx,gy) mst\n\nlaunchKernel' = launchKernel\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Kernel function parameters\n--------------------------------------------------------------------------------\n\n-- |\n-- Set the parameters that will specified next time the kernel is invoked\n--\n{-# INLINEABLE setParams #-}\nsetParams :: Fun -> [FunParam] -> IO ()\nsetParams !fn !prs = do\n zipWithM_ (set fn) offsets prs\n nothingIfOk =<< cuParamSetSize fn (last offsets)\n where\n offsets = scanl (\\a b -> a + size b) 0 prs\n\n size (IArg _) = sizeOf (undefined :: CUInt)\n size (FArg _) = sizeOf (undefined :: CFloat)\n size (VArg v) = sizeOf v\n\n set f o (IArg v) = nothingIfOk =<< cuParamSeti f o v\n set f o (FArg v) = nothingIfOk =<< cuParamSetf f o v\n set f o (VArg v) = with v $ \\p -> (nothingIfOk =<< cuParamSetv f o p (sizeOf v))\n\n\n{-# INLINE cuParamSetSize #-}\n{# fun unsafe cuParamSetSize\n { useFun `Fun'\n , `Int' } -> `Status' cToEnum #}\n\n{-# INLINE cuParamSeti #-}\n{# fun unsafe cuParamSeti\n { useFun `Fun'\n , `Int'\n , `Int32' } -> `Status' cToEnum #}\n\n{-# INLINE cuParamSetf #-}\n{# fun unsafe cuParamSetf\n { useFun `Fun'\n , `Int'\n , `Float' } -> `Status' cToEnum #}\n\n{-# INLINE cuParamSetv #-}\n{# fun unsafe cuParamSetv\n `Storable a' =>\n { useFun `Fun'\n , `Int'\n , castPtr `Ptr a'\n , `Int' } -> `Status' cToEnum #}\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE GADTs #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Exec\n-- Copyright : (c) [2009..2012] Trevor L. McDonell\n-- License : BSD\n--\n-- Kernel execution control for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Exec (\n\n -- * Kernel Execution\n Fun(Fun), FunParam(..), FunAttribute(..),\n requires, setBlockShape, setSharedSize, setParams, setCacheConfigFun,\n launch, launchKernel, launchKernel'\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Context (Cache(..))\nimport Foreign.CUDA.Driver.Stream (Stream(..))\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Data.Maybe\nimport Control.Monad (zipWithM_)\n\n\n#if CUDA_VERSION >= 4000\n{-# DEPRECATED setBlockShape, setSharedSize, setParams, launch\n \"use launchKernel instead\" #-}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A @__global__@ device function\n--\nnewtype Fun = Fun { useFun :: {# type CUfunction #}}\n\n\n-- |\n-- Function attributes\n--\n{# enum CUfunction_attribute as FunAttribute\n { underscoreToCase\n , MAX_THREADS_PER_BLOCK as MaxKernelThreadsPerBlock\n , MAX as CU_FUNC_ATTRIBUTE_MAX } -- ignore\n with prefix=\"CU_FUNC_ATTRIBUTE\" deriving (Eq, Show) #}\n\n-- |\n-- Kernel function parameters\n--\ndata FunParam where\n IArg :: !Int -> FunParam\n FArg :: !Float -> FunParam\n VArg :: Storable a => !a -> FunParam\n\ninstance Storable FunParam where\n sizeOf (IArg _) = sizeOf (undefined :: CUInt)\n sizeOf (FArg _) = sizeOf (undefined :: CFloat)\n sizeOf (VArg v) = sizeOf v\n\n alignment (IArg _) = alignment (undefined :: CUInt)\n alignment (FArg _) = alignment (undefined :: CFloat)\n alignment (VArg v) = alignment v\n\n poke p (IArg i) = poke (castPtr p) i\n poke p (FArg f) = poke (castPtr p) f\n poke p (VArg v) = poke (castPtr p) v\n\n\n--------------------------------------------------------------------------------\n-- Execution Control\n--------------------------------------------------------------------------------\n\n-- |\n-- Returns the value of the selected attribute requirement for the given kernel\n--\n{-# INLINEABLE requires #-}\nrequires :: Fun -> FunAttribute -> IO Int\nrequires !fn !att = resultIfOk =<< cuFuncGetAttribute att fn\n\n{-# INLINE cuFuncGetAttribute #-}\n{# fun unsafe cuFuncGetAttribute\n { alloca- `Int' peekIntConv*\n , cFromEnum `FunAttribute'\n , useFun `Fun' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the @(x,y,z)@ dimensions of the thread blocks that are created when\n-- the given kernel function is launched.\n--\n{-# INLINEABLE setBlockShape #-}\nsetBlockShape :: Fun -> (Int,Int,Int) -> IO ()\nsetBlockShape !fn (!x,!y,!z) = nothingIfOk =<< cuFuncSetBlockShape fn x y z\n\n{-# INLINE cuFuncSetBlockShape #-}\n{# fun unsafe cuFuncSetBlockShape\n { useFun `Fun'\n , `Int'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set the number of bytes of dynamic shared memory to be available to each\n-- thread block when the function is launched\n--\n{-# INLINEABLE setSharedSize #-}\nsetSharedSize :: Fun -> Integer -> IO ()\nsetSharedSize !fn !bytes = nothingIfOk =<< cuFuncSetSharedSize fn bytes\n\n{-# INLINE cuFuncSetSharedSize #-}\n{# fun unsafe cuFuncSetSharedSize\n { useFun `Fun'\n , cIntConv `Integer' } -> `Status' cToEnum #}\n\n\n-- |\n-- On devices where the L1 cache and shared memory use the same hardware\n-- resources, this sets the preferred cache configuration for the given device\n-- function. This is only a preference; the driver is free to choose a different\n-- configuration as required to execute the function.\n--\n-- Switching between configuration modes may insert a device-side\n-- synchronisation point for streamed kernel launches.\n--\n{-# INLINEABLE setCacheConfigFun #-}\nsetCacheConfigFun :: Fun -> Cache -> IO ()\n#if CUDA_VERSION < 3000\nsetCacheConfigFun _ _ = requireSDK 3.0 \"setCacheConfigFun\"\n#else\nsetCacheConfigFun !fn !pref = nothingIfOk =<< cuFuncSetCacheConfig fn pref\n\n{-# INLINE cuFuncSetCacheConfig #-}\n{# fun unsafe cuFuncSetCacheConfig\n { useFun `Fun'\n , cFromEnum `Cache' } -> `Status' cToEnum #}\n#endif\n\n-- |\n-- Invoke the kernel on a size @(w,h)@ grid of blocks. Each block contains the\n-- number of threads specified by a previous call to 'setBlockShape'. The launch\n-- may also be associated with a specific 'Stream'.\n--\n{-# INLINEABLE launch #-}\nlaunch :: Fun -> (Int,Int) -> Maybe Stream -> IO ()\nlaunch !fn (!w,!h) mst =\n nothingIfOk =<< case mst of\n Nothing -> cuLaunchGridAsync fn w h (Stream nullPtr)\n Just st -> cuLaunchGridAsync fn w h st\n\n{-# INLINE cuLaunchGridAsync #-}\n{# fun unsafe cuLaunchGridAsync\n { useFun `Fun'\n , `Int'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Invoke a kernel on a @(gx * gy * gz)@ grid of blocks, where each block\n-- contains @(tx * ty * tz)@ threads and has access to a given number of bytes\n-- of shared memory. The launch may also be associated with a specific 'Stream'.\n--\n-- In 'launchKernel', the number of kernel parameters and their offsets and\n-- sizes do not need to be specified, as this information is retrieved directly\n-- from the kernel's image. This requires the kernel to have been compiled with\n-- toolchain version 3.2 or later.\n--\n-- The alternative 'launchKernel'' will pass the arguments in directly,\n-- requiring the application to know the size and alignment\/padding of each\n-- kernel parameter.\n--\n{-# INLINEABLE launchKernel #-}\n{-# INLINEABLE launchKernel' #-}\nlaunchKernel, launchKernel'\n :: Fun -- ^ function to execute\n -> (Int,Int,Int) -- ^ block grid dimension\n -> (Int,Int,Int) -- ^ thread block shape\n -> Int -- ^ shared memory (bytes)\n -> Maybe Stream -- ^ (optional) stream to execute in\n -> [FunParam] -- ^ list of function parameters\n -> IO ()\n#if CUDA_VERSION >= 4000\nlaunchKernel !fn (!gx,!gy,!gz) (!tx,!ty,!tz) !sm !mst !args\n = (=<<) nothingIfOk\n $ withMany withFP args\n $ \\pa -> withArray pa\n $ \\pp -> cuLaunchKernel fn gx gy gz tx ty tz sm st pp nullPtr\n where\n !st = fromMaybe (Stream nullPtr) mst\n\n withFP :: FunParam -> (Ptr FunParam -> IO b) -> IO b\n withFP !p !f = case p of\n IArg v -> with' v (f . castPtr)\n FArg v -> with' v (f . castPtr)\n VArg v -> with' v (f . castPtr)\n\n -- can't use the standard 'with' because 'alloca' will pass an undefined\n -- dummy argument when determining 'sizeOf' and 'alignment', but sometimes\n -- instances in Accelerate need to evaluate this argument.\n --\n with' :: Storable a => a -> (Ptr a -> IO b) -> IO b\n with' !val !f =\n allocaBytes (sizeOf val) $ \\ptr -> do\n poke ptr val\n f ptr\n\n\nlaunchKernel' !fn (!gx,!gy,!gz) (!tx,!ty,!tz) !sm !mst !args\n = (=<<) nothingIfOk\n $ with bytes\n $ \\pb -> withArray' args\n $ \\pa -> withArray0 nullPtr [buffer, castPtr pa, size, castPtr pb]\n $ \\pp -> cuLaunchKernel fn gx gy gz tx ty tz sm st nullPtr pp\n where\n buffer = wordPtrToPtr 0x01 -- CU_LAUNCH_PARAM_BUFFER_POINTER\n size = wordPtrToPtr 0x02 -- CU_LAUNCH_PARAM_BUFFER_SIZE\n bytes = foldl (\\a x -> a + sizeOf x) 0 args\n st = fromMaybe (Stream nullPtr) mst\n\n -- can't use the standard 'withArray' because 'mallocArray' will pass\n -- 'undefined' to 'sizeOf' when determining how many bytes to allocate, but\n -- our Storable instance for FunParam needs to dispatch on each constructor,\n -- hence evaluating the undefined.\n --\n withArray' !vals !f =\n allocaBytes bytes $ \\ptr -> do\n pokeArray ptr vals\n f ptr\n\n\n{-# INLINE cuLaunchKernel #-}\n{# fun unsafe cuLaunchKernel\n { useFun `Fun'\n , `Int', `Int', `Int'\n , `Int', `Int', `Int'\n , `Int'\n , useStream `Stream'\n , castPtr `Ptr (Ptr FunParam)'\n , castPtr `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n#else\nlaunchKernel !fn (!gx,!gy,_) (!tx,!ty,!tz) !sm !mst !args = do\n setParams fn args\n setSharedSize fn (toInteger sm)\n setBlockShape fn (tx,ty,tz)\n launch fn (gx,gy) mst\n\nlaunchKernel' = launchKernel\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Kernel function parameters\n--------------------------------------------------------------------------------\n\n-- |\n-- Set the parameters that will specified next time the kernel is invoked\n--\n{-# INLINEABLE setParams #-}\nsetParams :: Fun -> [FunParam] -> IO ()\nsetParams !fn !prs = do\n zipWithM_ (set fn) offsets prs\n nothingIfOk =<< cuParamSetSize fn (last offsets)\n where\n offsets = scanl (\\a b -> a + size b) 0 prs\n\n size (IArg _) = sizeOf (undefined :: CUInt)\n size (FArg _) = sizeOf (undefined :: CFloat)\n size (VArg v) = sizeOf v\n\n set f o (IArg v) = nothingIfOk =<< cuParamSeti f o v\n set f o (FArg v) = nothingIfOk =<< cuParamSetf f o v\n set f o (VArg v) = with v $ \\p -> (nothingIfOk =<< cuParamSetv f o p (sizeOf v))\n\n\n{-# INLINE cuParamSetSize #-}\n{# fun unsafe cuParamSetSize\n { useFun `Fun'\n , `Int' } -> `Status' cToEnum #}\n\n{-# INLINE cuParamSeti #-}\n{# fun unsafe cuParamSeti\n { useFun `Fun'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n\n{-# INLINE cuParamSetf #-}\n{# fun unsafe cuParamSetf\n { useFun `Fun'\n , `Int'\n , `Float' } -> `Status' cToEnum #}\n\n{-# INLINE cuParamSetv #-}\n{# fun unsafe cuParamSetv\n `Storable a' =>\n { useFun `Fun'\n , `Int'\n , castPtr `Ptr a'\n , `Int' } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"5533d8acbf5af065a43d7bc34943febf9356b775","subject":"SetPixel possible fixes","message":"SetPixel possible fixes\n","repos":"TomMD\/CV,aleator\/CV,BeautifulDestinations\/CV,aleator\/CV","old_file":"CV\/Image.chs","new_file":"CV\/Image.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns,ParallelListComp, FlexibleInstances, FlexibleContexts, TypeFamilies, EmptyDataDecls, ScopedTypeVariables, StandaloneDeriving, DeriveDataTypeable, UndecidableInstances #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, create\n, empty \n, emptyCopy \n, cloneImage\n, withClone\n, withCloneValue\n, CreateImage\n\n-- * Colour spaces\n, ChannelOf\n, GrayScale\n, DFT\n, RGB\n, RGBA\n, RGB_Channel(..)\n, LAB\n, LAB_Channel(..)\n, D32\n, D64\n, D8\n, Tag\n, lab\n, rgba\n, rgb\n, compose\n, composeMultichannelImage\n\n-- * IO operations\n, Loadable(..)\n, saveImage\n, loadColorImage\n, loadImage\n\n-- * Pixel level access\n, GetPixel(..)\n, SetPixel(..)\n, getAllPixels\n, getAllPixelsRowMajor\n, mapImageInplace\n\n-- * Image information\n, ImageDepth\n, Sized(..)\n, getArea\n, getChannel\n, getImageChannels\n, getImageDepth\n, getImageInfo\n\n-- * ROI's, COI's and subregions\n, setCOI\n, setROI\n, resetROI\n, getRegion\n, withIOROI\n, withROI\n\n-- * Blitting\n, blendBlit\n, blit\n, blitM\n, subPixelBlit\n, safeBlit\n, montage\n, tileImages\n\n-- * Conversions\n, rgbToGray \n, grayToRGB\n, rgbToLab \n, bgrToRgb\n, rgbToBgr\n, unsafeImageTo32F \n, unsafeImageTo8Bit \n\n-- * Low level access operations\n, BareImage(..)\n, creatingImage\n, unImage\n, unS\n, withGenBareImage\n, withBareImage\n, creatingBareImage\n, withGenImage\n, withImage\n, imageFPTR\n, ensure32F\n\n-- * Extended error handling\n, setCatch\n, CvException\n) where\n\nimport System.Mem\nimport System.Directory\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Utils\nimport Foreign.ForeignPtr hiding (newForeignPtr,unsafeForeignPtrToPtr)\nimport Foreign.Concurrent\nimport Foreign.Ptr\nimport Control.Parallel.Strategies\nimport Control.DeepSeq\nimport CV.Bindings.Error\n\nimport Data.Maybe(catMaybes)\nimport Data.List(genericLength)\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.ForeignPtr (unsafeForeignPtrToPtr)\nimport Foreign.Storable\nimport System.IO.Unsafe\nimport Data.Word\nimport Data.Complex\nimport Data.Complex\nimport Control.Monad\nimport Control.Exception\nimport Data.Data\nimport Data.Typeable\n\n\n\n\n-- Colorspaces\n\n-- | Single channel grayscale image\ndata GrayScale\n\ndata DFT\ndata RGB\ndata RGB_Channel = Red |\u00a0Green |\u00a0Blue deriving (Eq,Ord,Enum)\n\ndata BGR\n\ndata LAB\ndata RGBA\ndata LAB_Channel = LAB_L |\u00a0LAB_A |\u00a0LAB_B deriving (Eq,Ord,Enum)\n\n-- | Type family for expressing which channels a colorspace contains. This needs to be fixed wrt. the BGR color space.\ntype family ChannelOf a :: *\ntype instance ChannelOf RGB_Channel = RGB\ntype instance ChannelOf LAB_Channel = LAB\n\n-- Bit Depths\ntype D8 = Word8\ntype D32 = Float\ntype D64 = Double\n\n-- | The type for Images\nnewtype Image channels depth = S BareImage\n\n-- |\u00a0Remove typing info from an image\nunS (S i) = i -- Unsafe and ugly\n\nimageFPTR :: Image c d -> ForeignPtr BareImage\nimageFPTR (S (BareImage fptr)) = fptr\n\nwithImage :: Image c d -> (Ptr BareImage ->IO a) -> IO a\nwithImage (S i) op = withBareImage i op\n--withGenNewImage (S i) op = withGenImage i op\n\n-- Ok. this is just the example why I need image types\nwithUniPtr with x fun = with x $ \\y ->\n fun (castPtr y)\n\nwithGenImage = withUniPtr withImage\nwithGenBareImage = withUniPtr withBareImage\n\n{#pointer *IplImage as BareImage foreign newtype#}\n\nfreeBareImage ptr = with ptr {#call cvReleaseImage#}\n\n--foreign import ccall \"& wrapReleaseImage\" releaseImage :: FinalizerPtr BareImage\n\ninstance NFData (Image a b) where\n rnf a@(S (BareImage fptr)) = (unsafeForeignPtrToPtr) fptr `seq` a `seq` ()-- This might also need peek?\n\n\ncreatingImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . S . BareImage $ fptr\n\ncreatingBareImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . BareImage $ fptr\n\nunImage (S (BareImage fptr)) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\nrgba = undefined :: Tag RGBA\nlab = undefined :: Tag LAB\n\n-- | Typeclass for elements that are build from component elements. For example,\n-- RGB images can be constructed from three grayscale images.\nclass Composes a where\n type Source a :: *\n compose :: Source a -> a\n\ninstance (CreateImage (Image RGBA a)) => Composes (Image RGBA a) where\n type Source (Image RGBA a) = (Image GrayScale a, Image GrayScale a\n ,Image GrayScale a, Image GrayScale a)\n compose (r,g,b,a) = composeMultichannelImage (Just b) (Just g) (Just r) (Just a) rgba\n\ninstance (CreateImage (Image RGB a)) => Composes (Image RGB a) where\n type Source (Image RGB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (r,g,b) = composeMultichannelImage (Just b) (Just g) (Just r) Nothing rgb\n\ninstance (CreateImage (Image LAB a)) => Composes (Image LAB a) where\n type Source (Image LAB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (l,a,b) = composeMultichannelImage (Just l) (Just a) (Just b) Nothing lab\n\n{-# DEPRECATED composeMultichannelImage \"This is unsafe. Use compose instead\" #-}\ncomposeMultichannelImage :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannelImage = composeMultichannel\n\ncomposeMultichannel :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannel (c2)\n (c1)\n (c3)\n (c4)\n totag\n = unsafePerformIO $\u00a0do\n res <- create (size) -- TODO: Check channel count -- This is NOT correct\n withMaybe c1 $ \\cc1 ->\n withMaybe c2 $ \\cc2 ->\n withMaybe c3 $ \\cc3 ->\n withMaybe c4 $ \\cc4 ->\n withGenImage res $ \\cres -> {#call cvMerge#} cc1 cc2 cc3 cc4 cres\n return res\n where\n withMaybe (Just i) op = withGenImage i op\n withMaybe (Nothing) op = op nullPtr\n size = getSize . head . catMaybes $ [c1,c2,c3,c4]\n\n\n-- | Typeclass for CV items that can be read from file. Mainly images at this point.\nclass Loadable a where\n readFromFile :: FilePath -> IO a\n\n\ninstance Loadable ((Image GrayScale D32)) where\n readFromFile fp = do\n e <- loadImage fp\n case e of\n Just i -> return i\n Nothing -> fail $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D32)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ unsafeImageTo32F $ bgrToRgb i\n Nothing -> fail $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D8)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ bgrToRgb i\n Nothing -> fail $ \"Could not load \"++fp\n\ninstance Loadable ((Image GrayScale D8)) where\n readFromFile fp = do\n e <- loadImage8 fp\n case e of\n Just i -> return i\n Nothing -> fail $ \"Could not load \"++fp\n\n\n-- | This function loads and converts image to an arbitrary format. Notice that it is\n-- polymorphic enough to cause run time errors if the declared and actual types of the\n-- images do not match. Use with care.\nunsafeloadUsing x p n = do\n exists <- doesFileExist n\n if not exists then return Nothing\n else do\n i <- withCString n $ \\name ->\n creatingBareImage ({#call cvLoadImage #} name p)\n bw <- x i\n return . Just .\u00a0S $ bw\n\nloadImage :: FilePath -> IO (Maybe (Image GrayScale D32))\nloadImage = unsafeloadUsing imageTo32F 0\nloadImage8 :: FilePath -> IO (Maybe (Image GrayScale D8))\nloadImage8 = unsafeloadUsing imageTo8Bit 0\nloadColorImage :: FilePath -> IO (Maybe (Image BGR D32))\nloadColorImage = unsafeloadUsing imageTo32F 1\nloadColorImage8 :: FilePath -> IO (Maybe (Image BGR D8))\nloadColorImage8 = unsafeloadUsing imageTo8Bit 1\n\n-- | Typeclass for elements with a size, such as images and matrices.\nclass Sized a where\n type Size a :: *\n getSize :: a -> Size a\n\ninstance Sized BareImage where\n type Size BareImage = (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize image = unsafePerformIO $ withBareImage image $ \\i -> do\n w <- {#call getImageWidth#} i\n h <- {#call getImageHeight#} i\n return (fromIntegral w,fromIntegral h)\n\ninstance Sized (Image c d) where\n type Size (Image c d) = (Int,Int)\n getSize = getSize . unS\n\n\ncvRGBtoGRAY = 7 :: CInt-- NOTE: This will break.\ncvRGBtoLAB = 45 :: CInt-- NOTE: This will break.\n\n\n#c\nenum CvtFlags {\n CvtFlip = CV_CVTIMG_FLIP,\n CvtSwapRB = CV_CVTIMG_SWAP_RB\n };\n#endc\n\n#c\nenum CvtCodes {\n CV_BGR2BGRA =0,\n CV_RGB2RGBA =CV_BGR2BGRA,\n\n CV_BGRA2BGR =1,\n CV_RGBA2RGB =CV_BGRA2BGR,\n\n CV_BGR2RGBA =2,\n CV_RGB2BGRA =CV_BGR2RGBA,\n\n CV_RGBA2BGR =3,\n CV_BGRA2RGB =CV_RGBA2BGR,\n\n CV_BGR2RGB =4,\n CV_RGB2BGR =CV_BGR2RGB,\n\n CV_BGRA2RGBA =5,\n CV_RGBA2BGRA =CV_BGRA2RGBA,\n\n CV_BGR2GRAY =6,\n CV_RGB2GRAY =7,\n CV_GRAY2BGR =8,\n CV_GRAY2RGB =CV_GRAY2BGR,\n CV_GRAY2BGRA =9,\n CV_GRAY2RGBA =CV_GRAY2BGRA,\n CV_BGRA2GRAY =10,\n CV_RGBA2GRAY =11,\n\n CV_BGR2BGR565 =12,\n CV_RGB2BGR565 =13,\n CV_BGR5652BGR =14,\n CV_BGR5652RGB =15,\n CV_BGRA2BGR565 =16,\n CV_RGBA2BGR565 =17,\n CV_BGR5652BGRA =18,\n CV_BGR5652RGBA =19,\n\n CV_GRAY2BGR565 =20,\n CV_BGR5652GRAY =21,\n\n CV_BGR2BGR555 =22,\n CV_RGB2BGR555 =23,\n CV_BGR5552BGR =24,\n CV_BGR5552RGB =25,\n CV_BGRA2BGR555 =26,\n CV_RGBA2BGR555 =27,\n CV_BGR5552BGRA =28,\n CV_BGR5552RGBA =29,\n\n CV_GRAY2BGR555 =30,\n CV_BGR5552GRAY =31,\n\n CV_BGR2XYZ =32,\n CV_RGB2XYZ =33,\n CV_XYZ2BGR =34,\n CV_XYZ2RGB =35,\n\n CV_BGR2YCrCb =36,\n CV_RGB2YCrCb =37,\n CV_YCrCb2BGR =38,\n CV_YCrCb2RGB =39,\n\n CV_BGR2HSV =40,\n CV_RGB2HSV =41,\n\n CV_BGR2Lab =44,\n CV_RGB2Lab =45,\n\n CV_BayerBG2BGR =46,\n CV_BayerGB2BGR =47,\n CV_BayerRG2BGR =48,\n CV_BayerGR2BGR =49,\n\n CV_BayerBG2RGB =CV_BayerRG2BGR,\n CV_BayerGB2RGB =CV_BayerGR2BGR,\n CV_BayerRG2RGB =CV_BayerBG2BGR,\n CV_BayerGR2RGB =CV_BayerGB2BGR,\n\n CV_BGR2Luv =50,\n CV_RGB2Luv =51,\n CV_BGR2HLS =52,\n CV_RGB2HLS =53,\n\n CV_HSV2BGR =54,\n CV_HSV2RGB =55,\n\n CV_Lab2BGR =56,\n CV_Lab2RGB =57,\n CV_Luv2BGR =58,\n CV_Luv2RGB =59,\n CV_HLS2BGR =60,\n CV_HLS2RGB =61,\n\n CV_BayerBG2BGR_VNG =62,\n CV_BayerGB2BGR_VNG =63,\n CV_BayerRG2BGR_VNG =64,\n CV_BayerGR2BGR_VNG =65,\n \n CV_BayerBG2RGB_VNG =CV_BayerRG2BGR_VNG,\n CV_BayerGB2RGB_VNG =CV_BayerGR2BGR_VNG,\n CV_BayerRG2RGB_VNG =CV_BayerBG2BGR_VNG,\n CV_BayerGR2RGB_VNG =CV_BayerGB2BGR_VNG,\n \n CV_BGR2HSV_FULL = 66,\n CV_RGB2HSV_FULL = 67,\n CV_BGR2HLS_FULL = 68,\n CV_RGB2HLS_FULL = 69,\n \n CV_HSV2BGR_FULL = 70,\n CV_HSV2RGB_FULL = 71,\n CV_HLS2BGR_FULL = 72,\n CV_HLS2RGB_FULL = 73,\n \n CV_LBGR2Lab = 74,\n CV_LRGB2Lab = 75,\n CV_LBGR2Luv = 76,\n CV_LRGB2Luv = 77,\n \n CV_Lab2LBGR = 78,\n CV_Lab2LRGB = 79,\n CV_Luv2LBGR = 80,\n CV_Luv2LRGB = 81,\n \n CV_BGR2YUV = 82,\n CV_RGB2YUV = 83,\n CV_YUV2BGR = 84,\n CV_YUV2RGB = 85,\n \n CV_COLORCVT_MAX =100\n};\n#endc\n\n{#enum CvtCodes {}#}\n\n{#enum CvtFlags {}#}\n\n\nrgbToLab :: Image RGB D32 -> Image LAB D32\nrgbToLab = S . convertTo cvRGBtoLAB 3 . unS\n\nrgbToGray :: Image RGB D32 -> Image GrayScale D32\nrgbToGray = S . convertTo cvRGBtoGRAY 1 . unS\n\ngrayToRGB :: Image GrayScale D32 -> Image RGB D32\ngrayToRGB = S . convertTo (fromIntegral . fromEnum $ CV_GRAY2BGR) 3 . unS\n\n\nbgrToRgb :: Image BGR depth -> Image RGB depth\nbgrToRgb = S . swapRB . unS\n\nrgbToBgr :: Image BGR depth -> Image RGB depth\nrgbToBgr = S . swapRB . unS\n\nswapRB :: BareImage -> BareImage\nswapRB img = unsafePerformIO $ do\n res <- cloneBareImage img\n withBareImage img $ \\cimg ->\n withBareImage res $ \\cres ->\n {#call cvConvertImage#} (castPtr cimg) (castPtr cres) (fromIntegral . fromEnum $ CvtSwapRB)\n return res\n\n\nclass GetPixel a where\n type P a :: *\n getPixel :: (Int,Int) -> a -> P a\n\n-- #define FGET(img,x,y) (((float *)((img)->imageData + (y)*(img)->widthStep))[(x)])\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Float))):: Ptr Float)\n\ninstance GetPixel (Image GrayScale D8) where\n type P (Image GrayScale D8) = D8\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Word8))):: Ptr Word8)\n\ninstance GetPixel (Image DFT D32) where\n type P (Image DFT D32) = Complex D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n re <- peek (castPtr (d`plusPtr` (y*cs + x*2*fs)))\n im <- peek (castPtr (d`plusPtr` (y*cs +(x*2+1)*fs)))\n return (re:+im)\n\n-- #define UGETC(img,color,x,y) (((uint8_t *)((img)->imageData + (y)*(img)->widthStep))[(x)*3+(color)])\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image RGB D8) where\n type P (Image RGB D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image LAB D32) where\n type P (Image LAB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n l <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n a <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n b <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (l,a,b)\n\n-- | Perform (a destructive) inplace map of the image. This should be wrapped inside\n-- withClone or an image operation\nmapImageInplace :: (P (Image GrayScale D32) -> P (Image GrayScale D32))\n -> Image GrayScale D32\n -> IO ()\nmapImageInplace f image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let (w,h) = getSize image\n cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n forM_ [(x,y) | x<-[0..w-1], y <- [0..h-1]] $ \\(x,y) ->\u00a0do\n v <- peek (castPtr (d `plusPtr` (y*cs+x*fs)))\n poke (castPtr (d `plusPtr` (y*cs+x*fs))) (f v)\n\n\n\n\nconvertTo :: CInt -> CInt -> BareImage -> BareImage\nconvertTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage32F#} w h channels\n withBareImage img $ \\cimg ->\n {#call cvCvtColor#} (castPtr cimg) (castPtr res) code\n return res\n where\n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\n-- |\u00a0Class for images that exist.\nclass CreateImage a where\n -- | Create an image from size\n create :: (Int,Int) -> IO a\n\n\ninstance CreateImage (Image GrayScale D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image DFT D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 2\ninstance CreateImage (Image LAB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 4\n\n\n\n-- | Allocate a new empty image\nempty :: (CreateImage (Image a b)) => (Int,Int) -> (Image a b)\nempty size = unsafePerformIO $ create size\n\n-- |\u00a0Allocate a new image that of the same size and type as the exemplar image given.\nemptyCopy :: (CreateImage (Image a b)) => Image a b -> (Image a b)\nemptyCopy img = unsafePerformIO $ create (getSize img)\n\n-- | Save image. This will convert the image to 8 bit one before saving\nsaveImage :: FilePath -> Image c d -> IO ()\nsaveImage filename image = do\n fpi <- imageTo8Bit $ unS image\n withCString filename $ \\name ->\n withGenBareImage fpi $ \\cvArr ->\n\t\t\t\t\t\t\t alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\n\ngetArea :: (Sized a,Num b, Size a ~ (b,b)) => a -> b\ngetArea = uncurry (*).getSize\n\ngetRegion :: (Int,Int) -> (Int,Int) -> Image c d -> Image c d\ngetRegion (fromIntegral -> x,fromIntegral -> y) (fromIntegral -> w,fromIntegral -> h) image\n | x+w <= width && y+h <= height = S . getRegion' (x,y) (w,h) $ unS image\n | otherwise = error $ \"Region outside image:\"\n ++ show (getSize image) ++\n \"\/\"++show (x+w,y+h)\n where\n (fromIntegral -> width,fromIntegral -> height) = getSize image\n\ngetRegion' (x,y) (w,h) image = unsafePerformIO $\n withBareImage image $ \\i ->\n creatingBareImage ({#call getSubImage#}\n i x y w h)\n\n\n-- | Tile images by overlapping them on a black canvas.\ntileImages image1 image2 (x,y) = unsafePerformIO $\n withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n creatingImage ({#call simpleMergeImages#}\n i1 i2 x y)\n-- | Blit image2 onto image1.\nblitFix = blit\nblit :: Image GrayScale D32 -> Image GrayScale D32 -> (Int,Int) -> IO ()\nblit image1 image2 (x,y)\n | badSizes = error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n | otherwise = withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call plainBlit#} i1 i2 (fromIntegral y) (fromIntegral x))\n where\n ((w1,h1),(w2,h2)) = (getSize image1,getSize image2)\n badSizes = x+w2>w1 || y+h2>h1 || x<0 || y<0\n\n-- blitM :: (CreateImage (Image c d)) => (Int,Int) -> [((Int,Int),Image c d)] -> Image c d\nblitM (rw,rh) imgs = resultPic\n where\n resultPic = unsafePerformIO $ do\n r <- create (fromIntegral rw,fromIntegral rh)\n sequence_ [blit r i (fromIntegral x, fromIntegral y)\n | ((x,y),i) <- imgs ]\n return r\n\n\nsubPixelBlit\n :: Image c d -> Image c d -> (CDouble, CDouble) -> IO ()\n\nsubPixelBlit (image1) (image2) (x,y)\n | badSizes = error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n | otherwise = withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call subpixel_blit#} i1 i2 y x)\n where\n ((w1,h1),(w2,h2)) = (getSize image1,getSize image2)\n badSizes = ceiling x+w2>w1 || ceiling y+h2>h1 ||\u00a0x<0 || y<0\n\nsafeBlit i1 i2 (x,y) = unsafePerformIO $ do\n res <- cloneImage i1-- createImage32F (getSize i1) 1\n blit res i2 (x,y)\n return res\n\n-- | Blit image2 onto image1.\n-- This uses an alpha channel bitmap for determining the regions where the image should be \"blended\" with\n-- the base image.\nblendBlit image1 image1Alpha image2 image2Alpha (x,y) =\n withImage image1 $ \\i1 ->\n withImage image1Alpha $ \\i1a ->\n withImage image2Alpha $ \\i2a ->\n withImage image2 $ \\i2 ->\n ({#call alphaBlit#} i1 i1a i2 i2a x y)\n\n\n-- | Create a copy of an image\ncloneImage :: Image a b -> IO (Image a b)\ncloneImage img = withGenImage img $ \\image ->\n creatingImage ({#call cvCloneImage #} image)\n\n-- | Create a copy of a non-types image\ncloneBareImage :: BareImage -> IO BareImage\ncloneBareImage img = withGenBareImage img $ \\image ->\n creatingBareImage ({#call cvCloneImage #} image)\n\nwithClone\n :: Image channels depth\n -> (Image channels depth -> IO ())\n -> IO (Image channels depth)\nwithClone img fun = do\n result <- cloneImage img\n fun result\n return result\n\nwithCloneValue\n :: Image channels depth\n -> (Image channels depth -> IO a)\n -> IO a\nwithCloneValue img fun = do\n result <- cloneImage img\n r <- fun result\n return r\n\nunsafeImageTo32F :: Image c d -> Image c D32\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure32F #} image)\n\nunsafeImageTo8Bit :: Image cspace a -> Image cspace D8\nunsafeImageTo8Bit img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure8U #} image)\n\n--toD32 :: Image c d -> Image c D32\n--toD32 i =\n-- unsafePerformIO $\n-- withImage i $ \\i_ptr ->\n-- creatingImage\n\n\nimageTo32F img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure32F #} image)\n\nimageTo8Bit img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure8U #} image)\n#c\nenum ImageDepth {\n Depth32F = IPL_DEPTH_32F,\n Depth64F = IPL_DEPTH_64F,\n Depth8U = IPL_DEPTH_8U,\n Depth8S = IPL_DEPTH_8S,\n Depth16U = IPL_DEPTH_16U,\n Depth16S = IPL_DEPTH_16S,\n Depth32S = IPL_DEPTH_32S\n };\n#endc\n\n{#enum ImageDepth {}#}\n\nderiving instance Show ImageDepth\n\ngetImageDepth :: Image c d -> IO ImageDepth\ngetImageDepth i = withImage i $ \\c_img -> {#get IplImage->depth #} c_img >>= return.toEnum.fromIntegral\ngetImageChannels i = withImage i $ \\c_img -> {#get IplImage->nChannels #} c_img\n\ngetImageInfo x = do\n let s = getSize x\n d <- getImageDepth x\n c <- getImageChannels x\n return (s,d,c)\n\n\n-- Manipulating regions of interest:\nsetROI (fromIntegral -> x,fromIntegral -> y)\n (fromIntegral -> w,fromIntegral -> h)\n image = withImage image $ \\i ->\n {#call wrapSetImageROI#} i x y w h\n\nresetROI image = withImage image $ \\i ->\n {#call cvResetImageROI#} i\n\nsetCOI chnl image = withImage image $ \\i ->\n {#call cvSetImageCOI#} i (fromIntegral chnl)\nresetCOI image = withImage image $ \\i ->\n {#call cvSetImageCOI#} i 0\n\n\n-- #TODO: Replace the Int below with proper channel identifier\ngetChannel :: (Enum a) => a -> Image (ChannelOf a) d -> Image GrayScale d\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n setCOI (1+fromEnum no) image\n cres <- {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\n withGenImage image $ \\cimage ->\n {#call cvCopy#} cimage (castPtr cres) (nullPtr)\n resetCOI image\n return cres\n\nwithIOROI pos size image op = do\n setROI pos size image\n x <- op\n resetROI image\n return x\n\nwithROI :: (Int, Int) -> (Int, Int) -> Image c d -> (Image c d -> a) -> a\nwithROI pos size image op = unsafePerformIO $ do\n setROI pos size image\n let x = op image -- BUG\n resetROI image\n return x\n\nclass SetPixel a where\n type SP a :: *\n setPixel :: (Int,Int) -> SP a -> a -> IO ()\n\ninstance SetPixel (Image GrayScale D32) where\n type SP (Image GrayScale D32) = D32\n {-#INLINE setPixel#-}\n setPixel (x,y) v image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Float))):: Ptr Float)\n v\n\ninstance SetPixel (Image GrayScale D8) where\n type SP (Image GrayScale D8) = D8\n {-#INLINE setPixel#-}\n setPixel (x,y) v image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Word8))):: Ptr Word8)\n v\n\ninstance SetPixel (Image RGB D32) where\n type SP (Image RGB D32) = (D32,D32,D32)\n {-#INLINE setPixel#-}\n setPixel (x,y) (r,g,b) image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs +x*3*fs))) b\n poke (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs))) g \n poke (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs))) r\n\ninstance SetPixel (Image DFT D32) where\n type SP (Image DFT D32) = Complex D32\n {-#INLINE setPixel#-}\n setPixel (x,y) (re:+im) image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs + x*2*fs))) re\n poke (castPtr (d`plusPtr` (y*cs + (x*2+1)*fs))) im\n\n\n\ngetAllPixels image = [getPixel (i,j) image\n | i <- [0..width-1 ]\n , j <- [0..height-1]]\n where\n (width,height) = getSize image\n\ngetAllPixelsRowMajor image = [getPixel (i,j) image\n | j <- [0..height-1]\n , i <- [0..width-1]\n ]\n where\n (width,height) = getSize image\n\n-- |Create a montage form given images (u,v) determines the layout and space the spacing\n-- between images. Images are assumed to be the same size (determined by the first image)\nmontage :: (CreateImage (Image GrayScale D32)) => (Int,Int) -> Int -> [Image GrayScale D32] -> Image GrayScale D32\nmontage (u',v') space' imgs\n | u'*v' \/= (length imgs) = error (\"Montage mismatch: \"++show (u,v, length imgs))\n | otherwise = resultPic\n where\n space = fromIntegral space'\n (u,v) = (fromIntegral u', fromIntegral v')\n (rw,rh) = (u*xstep,v*ystep)\n (w,h) = getSize (head imgs)\n (xstep,ystep) = (fromIntegral space + w,fromIntegral space + h)\n edge = space`div`2\n resultPic = unsafePerformIO $ do\n r <- create (rw,rh)\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep)\n | y <- [0..v-1] , x <- [0..u-1]\n | i <- imgs ]\n return r\n\ndata CvException = CvException Int String String String Int\n deriving (Show, Typeable)\n\ninstance Exception CvException\n\nsetCatch = do\n let catch i cstr1 cstr2 cstr3 j = do\n func <- peekCString cstr1\n msg <- peekCString cstr2\n file <- peekCString cstr3\n throw (CvException (fromIntegral i) func msg file (fromIntegral j)) \n return 0\n cb <- mk'CvErrorCallback catch\n c'cvRedirectError cb nullPtr nullPtr\n c'cvSetErrMode c'CV_ErrModeSilent\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns,ParallelListComp, FlexibleInstances, FlexibleContexts, TypeFamilies, EmptyDataDecls, ScopedTypeVariables, StandaloneDeriving, DeriveDataTypeable, UndecidableInstances #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, create\n, empty \n, emptyCopy \n, cloneImage\n, withClone\n, withCloneValue\n, CreateImage\n\n-- * Colour spaces\n, ChannelOf\n, GrayScale\n, DFT\n, RGB\n, RGBA\n, RGB_Channel(..)\n, LAB\n, LAB_Channel(..)\n, D32\n, D64\n, D8\n, Tag\n, lab\n, rgba\n, rgb\n, compose\n, composeMultichannelImage\n\n-- * IO operations\n, Loadable(..)\n, saveImage\n, loadColorImage\n, loadImage\n\n-- * Pixel level access\n, GetPixel(..)\n, SetPixel(..)\n, getAllPixels\n, getAllPixelsRowMajor\n, mapImageInplace\n\n-- * Image information\n, ImageDepth\n, Sized(..)\n, getArea\n, getChannel\n, getImageChannels\n, getImageDepth\n, getImageInfo\n\n-- * ROI's, COI's and subregions\n, setCOI\n, setROI\n, resetROI\n, getRegion\n, withIOROI\n, withROI\n\n-- * Blitting\n, blendBlit\n, blit\n, blitM\n, subPixelBlit\n, safeBlit\n, montage\n, tileImages\n\n-- * Conversions\n, rgbToGray \n, grayToRGB\n, rgbToLab \n, bgrToRgb\n, rgbToBgr\n, unsafeImageTo32F \n, unsafeImageTo8Bit \n\n-- * Low level access operations\n, BareImage(..)\n, creatingImage\n, unImage\n, unS\n, withGenBareImage\n, withBareImage\n, creatingBareImage\n, withGenImage\n, withImage\n, imageFPTR\n, ensure32F\n\n-- * Extended error handling\n, setCatch\n, CvException\n) where\n\nimport System.Mem\nimport System.Directory\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Utils\nimport Foreign.ForeignPtr hiding (newForeignPtr,unsafeForeignPtrToPtr)\nimport Foreign.Concurrent\nimport Foreign.Ptr\nimport Control.Parallel.Strategies\nimport Control.DeepSeq\nimport CV.Bindings.Error\n\nimport Data.Maybe(catMaybes)\nimport Data.List(genericLength)\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.ForeignPtr (unsafeForeignPtrToPtr)\nimport Foreign.Storable\nimport System.IO.Unsafe\nimport Data.Word\nimport Data.Complex\nimport Data.Complex\nimport Control.Monad\nimport Control.Exception\nimport Data.Data\nimport Data.Typeable\n\n\n\n\n-- Colorspaces\n\n-- | Single channel grayscale image\ndata GrayScale\n\ndata DFT\ndata RGB\ndata RGB_Channel = Red |\u00a0Green |\u00a0Blue deriving (Eq,Ord,Enum)\n\ndata BGR\n\ndata LAB\ndata RGBA\ndata LAB_Channel = LAB_L |\u00a0LAB_A |\u00a0LAB_B deriving (Eq,Ord,Enum)\n\n-- | Type family for expressing which channels a colorspace contains. This needs to be fixed wrt. the BGR color space.\ntype family ChannelOf a :: *\ntype instance ChannelOf RGB_Channel = RGB\ntype instance ChannelOf LAB_Channel = LAB\n\n-- Bit Depths\ntype D8 = Word8\ntype D32 = Float\ntype D64 = Double\n\n-- | The type for Images\nnewtype Image channels depth = S BareImage\n\n-- |\u00a0Remove typing info from an image\nunS (S i) = i -- Unsafe and ugly\n\nimageFPTR :: Image c d -> ForeignPtr BareImage\nimageFPTR (S (BareImage fptr)) = fptr\n\nwithImage :: Image c d -> (Ptr BareImage ->IO a) -> IO a\nwithImage (S i) op = withBareImage i op\n--withGenNewImage (S i) op = withGenImage i op\n\n-- Ok. this is just the example why I need image types\nwithUniPtr with x fun = with x $ \\y ->\n fun (castPtr y)\n\nwithGenImage = withUniPtr withImage\nwithGenBareImage = withUniPtr withBareImage\n\n{#pointer *IplImage as BareImage foreign newtype#}\n\nfreeBareImage ptr = with ptr {#call cvReleaseImage#}\n\n--foreign import ccall \"& wrapReleaseImage\" releaseImage :: FinalizerPtr BareImage\n\ninstance NFData (Image a b) where\n rnf a@(S (BareImage fptr)) = (unsafeForeignPtrToPtr) fptr `seq` a `seq` ()-- This might also need peek?\n\n\ncreatingImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . S . BareImage $ fptr\n\ncreatingBareImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . BareImage $ fptr\n\nunImage (S (BareImage fptr)) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\nrgba = undefined :: Tag RGBA\nlab = undefined :: Tag LAB\n\n-- | Typeclass for elements that are build from component elements. For example,\n-- RGB images can be constructed from three grayscale images.\nclass Composes a where\n type Source a :: *\n compose :: Source a -> a\n\ninstance (CreateImage (Image RGBA a)) => Composes (Image RGBA a) where\n type Source (Image RGBA a) = (Image GrayScale a, Image GrayScale a\n ,Image GrayScale a, Image GrayScale a)\n compose (r,g,b,a) = composeMultichannelImage (Just b) (Just g) (Just r) (Just a) rgba\n\ninstance (CreateImage (Image RGB a)) => Composes (Image RGB a) where\n type Source (Image RGB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (r,g,b) = composeMultichannelImage (Just b) (Just g) (Just r) Nothing rgb\n\ninstance (CreateImage (Image LAB a)) => Composes (Image LAB a) where\n type Source (Image LAB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (l,a,b) = composeMultichannelImage (Just l) (Just a) (Just b) Nothing lab\n\n{-# DEPRECATED composeMultichannelImage \"This is unsafe. Use compose instead\" #-}\ncomposeMultichannelImage :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannelImage = composeMultichannel\n\ncomposeMultichannel :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannel (c2)\n (c1)\n (c3)\n (c4)\n totag\n = unsafePerformIO $\u00a0do\n res <- create (size) -- TODO: Check channel count -- This is NOT correct\n withMaybe c1 $ \\cc1 ->\n withMaybe c2 $ \\cc2 ->\n withMaybe c3 $ \\cc3 ->\n withMaybe c4 $ \\cc4 ->\n withGenImage res $ \\cres -> {#call cvMerge#} cc1 cc2 cc3 cc4 cres\n return res\n where\n withMaybe (Just i) op = withGenImage i op\n withMaybe (Nothing) op = op nullPtr\n size = getSize . head . catMaybes $ [c1,c2,c3,c4]\n\n\n-- | Typeclass for CV items that can be read from file. Mainly images at this point.\nclass Loadable a where\n readFromFile :: FilePath -> IO a\n\n\ninstance Loadable ((Image GrayScale D32)) where\n readFromFile fp = do\n e <- loadImage fp\n case e of\n Just i -> return i\n Nothing -> fail $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D32)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ unsafeImageTo32F $ bgrToRgb i\n Nothing -> fail $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D8)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ bgrToRgb i\n Nothing -> fail $ \"Could not load \"++fp\n\ninstance Loadable ((Image GrayScale D8)) where\n readFromFile fp = do\n e <- loadImage8 fp\n case e of\n Just i -> return i\n Nothing -> fail $ \"Could not load \"++fp\n\n\n-- | This function loads and converts image to an arbitrary format. Notice that it is\n-- polymorphic enough to cause run time errors if the declared and actual types of the\n-- images do not match. Use with care.\nunsafeloadUsing x p n = do\n exists <- doesFileExist n\n if not exists then return Nothing\n else do\n i <- withCString n $ \\name ->\n creatingBareImage ({#call cvLoadImage #} name p)\n bw <- x i\n return . Just .\u00a0S $ bw\n\nloadImage :: FilePath -> IO (Maybe (Image GrayScale D32))\nloadImage = unsafeloadUsing imageTo32F 0\nloadImage8 :: FilePath -> IO (Maybe (Image GrayScale D8))\nloadImage8 = unsafeloadUsing imageTo8Bit 0\nloadColorImage :: FilePath -> IO (Maybe (Image BGR D32))\nloadColorImage = unsafeloadUsing imageTo32F 1\nloadColorImage8 :: FilePath -> IO (Maybe (Image BGR D8))\nloadColorImage8 = unsafeloadUsing imageTo8Bit 1\n\n-- | Typeclass for elements with a size, such as images and matrices.\nclass Sized a where\n type Size a :: *\n getSize :: a -> Size a\n\ninstance Sized BareImage where\n type Size BareImage = (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize image = unsafePerformIO $ withBareImage image $ \\i -> do\n w <- {#call getImageWidth#} i\n h <- {#call getImageHeight#} i\n return (fromIntegral w,fromIntegral h)\n\ninstance Sized (Image c d) where\n type Size (Image c d) = (Int,Int)\n getSize = getSize . unS\n\n\ncvRGBtoGRAY = 7 :: CInt-- NOTE: This will break.\ncvRGBtoLAB = 45 :: CInt-- NOTE: This will break.\n\n\n#c\nenum CvtFlags {\n CvtFlip = CV_CVTIMG_FLIP,\n CvtSwapRB = CV_CVTIMG_SWAP_RB\n };\n#endc\n\n#c\nenum CvtCodes {\n CV_BGR2BGRA =0,\n CV_RGB2RGBA =CV_BGR2BGRA,\n\n CV_BGRA2BGR =1,\n CV_RGBA2RGB =CV_BGRA2BGR,\n\n CV_BGR2RGBA =2,\n CV_RGB2BGRA =CV_BGR2RGBA,\n\n CV_RGBA2BGR =3,\n CV_BGRA2RGB =CV_RGBA2BGR,\n\n CV_BGR2RGB =4,\n CV_RGB2BGR =CV_BGR2RGB,\n\n CV_BGRA2RGBA =5,\n CV_RGBA2BGRA =CV_BGRA2RGBA,\n\n CV_BGR2GRAY =6,\n CV_RGB2GRAY =7,\n CV_GRAY2BGR =8,\n CV_GRAY2RGB =CV_GRAY2BGR,\n CV_GRAY2BGRA =9,\n CV_GRAY2RGBA =CV_GRAY2BGRA,\n CV_BGRA2GRAY =10,\n CV_RGBA2GRAY =11,\n\n CV_BGR2BGR565 =12,\n CV_RGB2BGR565 =13,\n CV_BGR5652BGR =14,\n CV_BGR5652RGB =15,\n CV_BGRA2BGR565 =16,\n CV_RGBA2BGR565 =17,\n CV_BGR5652BGRA =18,\n CV_BGR5652RGBA =19,\n\n CV_GRAY2BGR565 =20,\n CV_BGR5652GRAY =21,\n\n CV_BGR2BGR555 =22,\n CV_RGB2BGR555 =23,\n CV_BGR5552BGR =24,\n CV_BGR5552RGB =25,\n CV_BGRA2BGR555 =26,\n CV_RGBA2BGR555 =27,\n CV_BGR5552BGRA =28,\n CV_BGR5552RGBA =29,\n\n CV_GRAY2BGR555 =30,\n CV_BGR5552GRAY =31,\n\n CV_BGR2XYZ =32,\n CV_RGB2XYZ =33,\n CV_XYZ2BGR =34,\n CV_XYZ2RGB =35,\n\n CV_BGR2YCrCb =36,\n CV_RGB2YCrCb =37,\n CV_YCrCb2BGR =38,\n CV_YCrCb2RGB =39,\n\n CV_BGR2HSV =40,\n CV_RGB2HSV =41,\n\n CV_BGR2Lab =44,\n CV_RGB2Lab =45,\n\n CV_BayerBG2BGR =46,\n CV_BayerGB2BGR =47,\n CV_BayerRG2BGR =48,\n CV_BayerGR2BGR =49,\n\n CV_BayerBG2RGB =CV_BayerRG2BGR,\n CV_BayerGB2RGB =CV_BayerGR2BGR,\n CV_BayerRG2RGB =CV_BayerBG2BGR,\n CV_BayerGR2RGB =CV_BayerGB2BGR,\n\n CV_BGR2Luv =50,\n CV_RGB2Luv =51,\n CV_BGR2HLS =52,\n CV_RGB2HLS =53,\n\n CV_HSV2BGR =54,\n CV_HSV2RGB =55,\n\n CV_Lab2BGR =56,\n CV_Lab2RGB =57,\n CV_Luv2BGR =58,\n CV_Luv2RGB =59,\n CV_HLS2BGR =60,\n CV_HLS2RGB =61,\n\n CV_BayerBG2BGR_VNG =62,\n CV_BayerGB2BGR_VNG =63,\n CV_BayerRG2BGR_VNG =64,\n CV_BayerGR2BGR_VNG =65,\n \n CV_BayerBG2RGB_VNG =CV_BayerRG2BGR_VNG,\n CV_BayerGB2RGB_VNG =CV_BayerGR2BGR_VNG,\n CV_BayerRG2RGB_VNG =CV_BayerBG2BGR_VNG,\n CV_BayerGR2RGB_VNG =CV_BayerGB2BGR_VNG,\n \n CV_BGR2HSV_FULL = 66,\n CV_RGB2HSV_FULL = 67,\n CV_BGR2HLS_FULL = 68,\n CV_RGB2HLS_FULL = 69,\n \n CV_HSV2BGR_FULL = 70,\n CV_HSV2RGB_FULL = 71,\n CV_HLS2BGR_FULL = 72,\n CV_HLS2RGB_FULL = 73,\n \n CV_LBGR2Lab = 74,\n CV_LRGB2Lab = 75,\n CV_LBGR2Luv = 76,\n CV_LRGB2Luv = 77,\n \n CV_Lab2LBGR = 78,\n CV_Lab2LRGB = 79,\n CV_Luv2LBGR = 80,\n CV_Luv2LRGB = 81,\n \n CV_BGR2YUV = 82,\n CV_RGB2YUV = 83,\n CV_YUV2BGR = 84,\n CV_YUV2RGB = 85,\n \n CV_COLORCVT_MAX =100\n};\n#endc\n\n{#enum CvtCodes {}#}\n\n{#enum CvtFlags {}#}\n\n\nrgbToLab :: Image RGB D32 -> Image LAB D32\nrgbToLab = S . convertTo cvRGBtoLAB 3 . unS\n\nrgbToGray :: Image RGB D32 -> Image GrayScale D32\nrgbToGray = S . convertTo cvRGBtoGRAY 1 . unS\n\ngrayToRGB :: Image GrayScale D32 -> Image RGB D32\ngrayToRGB = S . convertTo (fromIntegral . fromEnum $ CV_GRAY2BGR) 3 . unS\n\n\nbgrToRgb :: Image BGR depth -> Image RGB depth\nbgrToRgb = S . swapRB . unS\n\nrgbToBgr :: Image BGR depth -> Image RGB depth\nrgbToBgr = S . swapRB . unS\n\nswapRB :: BareImage -> BareImage\nswapRB img = unsafePerformIO $ do\n res <- cloneBareImage img\n withBareImage img $ \\cimg ->\n withBareImage res $ \\cres ->\n {#call cvConvertImage#} (castPtr cimg) (castPtr cres) (fromIntegral . fromEnum $ CvtSwapRB)\n return res\n\n\nclass GetPixel a where\n type P a :: *\n getPixel :: (Int,Int) -> a -> P a\n\n-- #define FGET(img,x,y) (((float *)((img)->imageData + (y)*(img)->widthStep))[(x)])\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Float))):: Ptr Float)\n\ninstance GetPixel (Image GrayScale D8) where\n type P (Image GrayScale D8) = D8\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Word8))):: Ptr Word8)\n\ninstance GetPixel (Image DFT D32) where\n type P (Image DFT D32) = Complex D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n re <- peek (castPtr (d`plusPtr` (y*cs + x*2*fs)))\n im <- peek (castPtr (d`plusPtr` (y*cs +(x*2+1)*fs)))\n return (re:+im)\n\n-- #define UGETC(img,color,x,y) (((uint8_t *)((img)->imageData + (y)*(img)->widthStep))[(x)*3+(color)])\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n r <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n b <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image LAB D32) where\n type P (Image LAB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n r <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n b <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ngetPixelOldRGB (fromIntegral -> x, fromIntegral -> y) image\n = unsafePerformIO $ do\n withGenImage image $ \\img -> do\n r <- {#call wrapGet32F2DC#} img y x 0\n g <- {#call wrapGet32F2DC#} img y x 1\n b <- {#call wrapGet32F2DC#} img y x 2\n return (realToFrac r,realToFrac g, realToFrac b)\n\n-- | Perform (a destructive) inplace map of the image. This should be wrapped inside\n-- withClone or an image operation\nmapImageInplace :: (P (Image GrayScale D32) -> P (Image GrayScale D32))\n -> Image GrayScale D32\n -> IO ()\nmapImageInplace f image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let (w,h) = getSize image\n cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n forM_ [(x,y) | x<-[0..w-1], y <- [0..h-1]] $ \\(x,y) ->\u00a0do\n v <- peek (castPtr (d `plusPtr` (y*cs+x*fs)))\n poke (castPtr (d `plusPtr` (y*cs+x*fs))) (f v)\n\n\ninstance GetPixel (Image RGB D8) where\n type P (Image RGB D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n r <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n b <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\n\nconvertTo :: CInt -> CInt -> BareImage -> BareImage\nconvertTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage32F#} w h channels\n withBareImage img $ \\cimg ->\n {#call cvCvtColor#} (castPtr cimg) (castPtr res) code\n return res\n where\n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\n-- |\u00a0Class for images that exist.\nclass CreateImage a where\n -- | Create an image from size\n create :: (Int,Int) -> IO a\n\n\ninstance CreateImage (Image GrayScale D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image DFT D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 2\ninstance CreateImage (Image LAB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 4\n\n\n\n-- | Allocate a new empty image\nempty :: (CreateImage (Image a b)) => (Int,Int) -> (Image a b)\nempty size = unsafePerformIO $ create size\n\n-- |\u00a0Allocate a new image that of the same size and type as the exemplar image given.\nemptyCopy :: (CreateImage (Image a b)) => Image a b -> (Image a b)\nemptyCopy img = unsafePerformIO $ create (getSize img)\n\n-- | Save image. This will convert the image to 8 bit one before saving\nsaveImage :: FilePath -> Image c d -> IO ()\nsaveImage filename image = do\n fpi <- imageTo8Bit $ unS image\n withCString filename $ \\name ->\n withGenBareImage fpi $ \\cvArr ->\n\t\t\t\t\t\t\t alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\n\ngetArea :: (Sized a,Num b, Size a ~ (b,b)) => a -> b\ngetArea = uncurry (*).getSize\n\ngetRegion :: (Int,Int) -> (Int,Int) -> Image c d -> Image c d\ngetRegion (fromIntegral -> x,fromIntegral -> y) (fromIntegral -> w,fromIntegral -> h) image\n | x+w <= width && y+h <= height = S . getRegion' (x,y) (w,h) $ unS image\n | otherwise = error $ \"Region outside image:\"\n ++ show (getSize image) ++\n \"\/\"++show (x+w,y+h)\n where\n (fromIntegral -> width,fromIntegral -> height) = getSize image\n\ngetRegion' (x,y) (w,h) image = unsafePerformIO $\n withBareImage image $ \\i ->\n creatingBareImage ({#call getSubImage#}\n i x y w h)\n\n\n-- | Tile images by overlapping them on a black canvas.\ntileImages image1 image2 (x,y) = unsafePerformIO $\n withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n creatingImage ({#call simpleMergeImages#}\n i1 i2 x y)\n-- | Blit image2 onto image1.\nblitFix = blit\nblit :: Image GrayScale D32 -> Image GrayScale D32 -> (Int,Int) -> IO ()\nblit image1 image2 (x,y)\n | badSizes = error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n | otherwise = withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call plainBlit#} i1 i2 (fromIntegral y) (fromIntegral x))\n where\n ((w1,h1),(w2,h2)) = (getSize image1,getSize image2)\n badSizes = x+w2>w1 || y+h2>h1 || x<0 || y<0\n\n-- blitM :: (CreateImage (Image c d)) => (Int,Int) -> [((Int,Int),Image c d)] -> Image c d\nblitM (rw,rh) imgs = resultPic\n where\n resultPic = unsafePerformIO $ do\n r <- create (fromIntegral rw,fromIntegral rh)\n sequence_ [blit r i (fromIntegral x, fromIntegral y)\n | ((x,y),i) <- imgs ]\n return r\n\n\nsubPixelBlit\n :: Image c d -> Image c d -> (CDouble, CDouble) -> IO ()\n\nsubPixelBlit (image1) (image2) (x,y)\n | badSizes = error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n | otherwise = withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call subpixel_blit#} i1 i2 y x)\n where\n ((w1,h1),(w2,h2)) = (getSize image1,getSize image2)\n badSizes = ceiling x+w2>w1 || ceiling y+h2>h1 ||\u00a0x<0 || y<0\n\nsafeBlit i1 i2 (x,y) = unsafePerformIO $ do\n res <- cloneImage i1-- createImage32F (getSize i1) 1\n blit res i2 (x,y)\n return res\n\n-- | Blit image2 onto image1.\n-- This uses an alpha channel bitmap for determining the regions where the image should be \"blended\" with\n-- the base image.\nblendBlit image1 image1Alpha image2 image2Alpha (x,y) =\n withImage image1 $ \\i1 ->\n withImage image1Alpha $ \\i1a ->\n withImage image2Alpha $ \\i2a ->\n withImage image2 $ \\i2 ->\n ({#call alphaBlit#} i1 i1a i2 i2a x y)\n\n\n-- | Create a copy of an image\ncloneImage :: Image a b -> IO (Image a b)\ncloneImage img = withGenImage img $ \\image ->\n creatingImage ({#call cvCloneImage #} image)\n\n-- | Create a copy of a non-types image\ncloneBareImage :: BareImage -> IO BareImage\ncloneBareImage img = withGenBareImage img $ \\image ->\n creatingBareImage ({#call cvCloneImage #} image)\n\nwithClone\n :: Image channels depth\n -> (Image channels depth -> IO ())\n -> IO (Image channels depth)\nwithClone img fun = do\n result <- cloneImage img\n fun result\n return result\n\nwithCloneValue\n :: Image channels depth\n -> (Image channels depth -> IO a)\n -> IO a\nwithCloneValue img fun = do\n result <- cloneImage img\n r <- fun result\n return r\n\nunsafeImageTo32F :: Image c d -> Image c D32\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure32F #} image)\n\nunsafeImageTo8Bit :: Image cspace a -> Image cspace D8\nunsafeImageTo8Bit img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure8U #} image)\n\n--toD32 :: Image c d -> Image c D32\n--toD32 i =\n-- unsafePerformIO $\n-- withImage i $ \\i_ptr ->\n-- creatingImage\n\n\nimageTo32F img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure32F #} image)\n\nimageTo8Bit img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure8U #} image)\n#c\nenum ImageDepth {\n Depth32F = IPL_DEPTH_32F,\n Depth64F = IPL_DEPTH_64F,\n Depth8U = IPL_DEPTH_8U,\n Depth8S = IPL_DEPTH_8S,\n Depth16U = IPL_DEPTH_16U,\n Depth16S = IPL_DEPTH_16S,\n Depth32S = IPL_DEPTH_32S\n };\n#endc\n\n{#enum ImageDepth {}#}\n\nderiving instance Show ImageDepth\n\ngetImageDepth :: Image c d -> IO ImageDepth\ngetImageDepth i = withImage i $ \\c_img -> {#get IplImage->depth #} c_img >>= return.toEnum.fromIntegral\ngetImageChannels i = withImage i $ \\c_img -> {#get IplImage->nChannels #} c_img\n\ngetImageInfo x = do\n let s = getSize x\n d <- getImageDepth x\n c <- getImageChannels x\n return (s,d,c)\n\n\n-- Manipulating regions of interest:\nsetROI (fromIntegral -> x,fromIntegral -> y)\n (fromIntegral -> w,fromIntegral -> h)\n image = withImage image $ \\i ->\n {#call wrapSetImageROI#} i x y w h\n\nresetROI image = withImage image $ \\i ->\n {#call cvResetImageROI#} i\n\nsetCOI chnl image = withImage image $ \\i ->\n {#call cvSetImageCOI#} i (fromIntegral chnl)\nresetCOI image = withImage image $ \\i ->\n {#call cvSetImageCOI#} i 0\n\n\n-- #TODO: Replace the Int below with proper channel identifier\ngetChannel :: (Enum a) => a -> Image (ChannelOf a) d -> Image GrayScale d\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n setCOI (1+fromEnum no) image\n cres <- {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\n withGenImage image $ \\cimage ->\n {#call cvCopy#} cimage (castPtr cres) (nullPtr)\n resetCOI image\n return cres\n\nwithIOROI pos size image op = do\n setROI pos size image\n x <- op\n resetROI image\n return x\n\nwithROI :: (Int, Int) -> (Int, Int) -> Image c d -> (Image c d -> a) -> a\nwithROI pos size image op = unsafePerformIO $ do\n setROI pos size image\n let x = op image -- BUG\n resetROI image\n return x\n\nclass SetPixel a where\n type SP a :: *\n setPixel :: (Int,Int) -> SP a -> a -> IO ()\n\ninstance SetPixel (Image GrayScale D32) where\n type SP (Image GrayScale D32) = D32\n {-#INLINE setPixel#-}\n setPixel (x,y) v image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Float))):: Ptr Float)\n v\n\ninstance SetPixel (Image GrayScale D8) where\n type SP (Image GrayScale D8) = D8\n {-#INLINE setPixel#-}\n setPixel (x,y) v image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Word8))):: Ptr Word8)\n v\n\ninstance SetPixel (Image DFT D32) where\n type SP (Image DFT D32) = Complex D32\n {-#INLINE setPixel#-}\n setPixel (x,y) (re:+im) image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs + x*2*fs))) re\n poke (castPtr (d`plusPtr` (y*cs + (x*2+1)*fs))) im\n\n\n\ngetAllPixels image = [getPixel (i,j) image\n | i <- [0..width-1 ]\n , j <- [0..height-1]]\n where\n (width,height) = getSize image\n\ngetAllPixelsRowMajor image = [getPixel (i,j) image\n | j <- [0..height-1]\n , i <- [0..width-1]\n ]\n where\n (width,height) = getSize image\n\n-- |Create a montage form given images (u,v) determines the layout and space the spacing\n-- between images. Images are assumed to be the same size (determined by the first image)\nmontage :: (CreateImage (Image GrayScale D32)) => (Int,Int) -> Int -> [Image GrayScale D32] -> Image GrayScale D32\nmontage (u',v') space' imgs\n | u'*v' \/= (length imgs) = error (\"Montage mismatch: \"++show (u,v, length imgs))\n | otherwise = resultPic\n where\n space = fromIntegral space'\n (u,v) = (fromIntegral u', fromIntegral v')\n (rw,rh) = (u*xstep,v*ystep)\n (w,h) = getSize (head imgs)\n (xstep,ystep) = (fromIntegral space + w,fromIntegral space + h)\n edge = space`div`2\n resultPic = unsafePerformIO $ do\n r <- create (rw,rh)\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep)\n | y <- [0..v-1] , x <- [0..u-1]\n | i <- imgs ]\n return r\n\ndata CvException = CvException Int String String String Int\n deriving (Show, Typeable)\n\ninstance Exception CvException\n\nsetCatch = do\n let catch i cstr1 cstr2 cstr3 j = do\n func <- peekCString cstr1\n msg <- peekCString cstr2\n file <- peekCString cstr3\n throw (CvException (fromIntegral i) func msg file (fromIntegral j)) \n return 0\n cb <- mk'CvErrorCallback catch\n c'cvRedirectError cb nullPtr nullPtr\n c'cvSetErrMode c'CV_ErrModeSilent\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"49152e906fae953e01d8312dcc68bebbc0b9b9db","subject":"[project @ 2002-10-21 11:58:05 by as49] Removed a pair of offending parentesis in signal grab_focus.","message":"[project @ 2002-10-21 11:58:05 by as49]\nRemoved a pair of offending parentesis in signal grab_focus.\n\n","repos":"gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/gtksourceview,gtk2hs\/gtksourceview,gtk2hs\/webkit","old_file":"gtk\/abstract\/Widget.chs","new_file":"gtk\/abstract\/Widget.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget Widget@\n--\n-- Author : Axel Simon\n-- \n-- Created: 27 April 2001\n--\n-- Version $Revision: 1.8 $ from $Date: 2002\/10\/21 11:58:05 $\n--\n-- Copyright (c) 2001 Axel Simon\n--\n-- This file is free software; you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation; either version 2 of the License, or\n-- (at your option) any later version.\n--\n-- This file is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- * Widget is the base class of all widgets. It provides the methods to\n-- attach and detach signals.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * This modules reexports everything a normal widget needs from GObject\n-- and Object.\n--\n--- TODO ----------------------------------------------------------------------\n--\n-- * unimplemented methods that seem to be useful in user programs:\n-- widgetSizeRequest, widgetAddAccelerator, widgetRemoveAccrelerator,\n--\twidgetAcceleratorSignal, widgetIntersect, widgetGrabDefault,\n--\twidgetGetPointer, widgetPath, widgetClassPath, getCompositeName,\n--\twidgetSetCompositeName,\n--\twidgetModifyStyle, widgetGetModifierStyle, widgetModifyFg,\n--\twidgetModifyBG, widgetModifyText, widgetModifyBase, widgetModifyFont,\n--\twidgetPango*, widgetSetAdjustments\n--\t\n--\n-- * implement the following methods in GtkWindow object:\n-- widget_set_uposition, widget_set_usize\n--\n-- * implement the following methods in GtkDrawingArea object:\n-- widgetQueueDrawArea, widgetSetDoubleBufferd, widgetRegionIntersect\n--\nmodule Widget(\n Widget,\n WidgetClass,\n castToWidget,\n Allocation,\n Requisition(..),\n Rectangle(..),\n widgetShow,\t\t\t-- Showing and hiding a widget.\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\t\t-- Functions to be used with DrawingArea.\n widgetHasIntersection,\n widgetActivate,\t\t-- Manipulate widget state.\n widgetSetSensitivity,\n widgetSetSizeRequest,\n widgetIsFocus,\n widgetGrabFocus,\n widgetSetAppPaintable,\n widgetSetName,\t\t-- Naming, Themes\n widgetGetName,\n widgetGetToplevel,\t\t-- Widget browsing.\n widgetIsAncestor,\n widgetReparent,\n TextDirection(..),\n widgetSetDirection,\t\t-- General Setup.\n widgetGetDirection,\n-- widgetLockAccelerators,\n-- widgetUnlockAccelerators,\n Event(..),\n onButtonPress,\n afterButtonPress,\n onButtonRelease,\n afterButtonRelease,\n onClient,\n afterClient,\n onConfigure,\n afterConfigure,\n onDelete,\n afterDelete,\n onDestroyEvent,\t\t-- you probably want onDestroy\n afterDestroyEvent,\n onDirectionChanged,\n afterDirectionChanged,\n onEnterNotify,\n afterEnterNotify,\n onLeaveNotify,\n afterLeaveNotify,\n onExpose,\n afterExpose,\n onFocusIn,\n afterFocusIn,\n onFocusOut,\n afterFocusOut,\n onGrabFocus,\n afterGrabFocus,\n onDestroy,\n afterDestroy,\n onHide,\n afterHide,\n onHierarchyChanged,\n afterHierarchyChanged,\n onKeyPress,\n afterKeyPress,\n onKeyRelease,\n afterKeyRelease,\n onMnemonicActivate,\n afterMnemonicActivate,\n onMotionNotify,\n afterMotionNotify,\n onParentSet,\n afterParentSet,\n onPopupMenu,\n afterPopupMenu,\n onProximityIn,\n afterProximityIn,\n onProximityOut,\n afterProximityOut,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n StateType(..),\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n ) where\n\nimport Monad\t(liftM, unless)\nimport UTFCForeign\nimport Foreign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport GdkEnums\nimport Structs\t(Allocation, Rectangle(..), Requisition(..))\nimport Events\t(Event(..), marshalEvent)\nimport Enums\t(StateType(..), TextDirection(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- @method widgetShow@ Queue a show request.\n--\n-- * Flags a widget to be displayed. Any widget that isn't shown will not\n-- appear on the screen. If you want to show all the widgets in a container,\n-- it's easier to call @ref method widgetShowAll@ on the container, instead\n-- of individually showing the widgets. Note that you have to show the\n-- containers containing a widget, in addition to the widget itself, before\n-- it will appear onscreen. When a toplevel container is shown, it is\n-- immediately realized and mapped; other shown widgets are realized and\n-- mapped when their toplevel container is realized and mapped.\n--\nwidgetShow :: WidgetClass w => w -> IO ()\nwidgetShow = {#call widget_show#}.toWidget\n\n-- @method widgetShowNow@ Queue a show event and wait for it to be executed.\n--\n-- * If the widget is an unmapped toplevel widget (i.e. a @ref arg Window@\n-- that has not yet been shown), enter the main loop and wait for the window\n-- to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass w => w -> IO ()\nwidgetShowNow = {#call widget_show_now#}.toWidget\n\n-- @method widgetHide@ Queue a hide request.\n--\n-- * Reverses the effects of @ref method widgetShow@, causing the widget to be\n-- hidden (make invisible to the user).\n--\nwidgetHide :: WidgetClass w => w -> IO ()\nwidgetHide = {#call widget_hide#}.toWidget\n\n-- @method widgetShowAll@ Show this and all child widgets.\n--\nwidgetShowAll :: WidgetClass w => w -> IO ()\nwidgetShowAll = {#call widget_show_all#}.toWidget\n\n-- @method widgetHideAll@ Hide this and all child widgets.\n--\nwidgetHideAll :: WidgetClass w => w -> IO ()\nwidgetHideAll = {#call widget_hide_all#}.toWidget\n\n-- @method widgetDestroy@ Destroy a widget.\n--\n-- * The @ref method widgetDestroy@ function is used to shutdown an object,\n-- i.e. a widget will be removed from the screen and unrealized. Resources\n-- will be freed when all references are released.\n--\nwidgetDestroy :: WidgetClass obj => obj -> IO ()\nwidgetDestroy = {#call widget_destroy#}.toWidget\n\n-- Functions to be used with DrawingArea.\n\n-- @method widgetQueueDraw@ Send a redraw request to a widget.\n--\nwidgetQueueDraw :: WidgetClass w => w -> IO ()\nwidgetQueueDraw = {#call widget_queue_draw#}.toWidget\n\n-- @method widgetHasIntersection@ Check if the widget intersects with a given\n-- area.\n--\nwidgetHasIntersection :: WidgetClass w => w -> Rectangle -> IO Bool\nwidgetHasIntersection w r = \n liftM toBool $\n withObject r $ \\r' ->\n {#call unsafe widget_intersect#} (toWidget w) (castPtr r') (castPtr nullPtr)\n\n-- Manipulate widget state.\n\n-- @method widgetActivate@ Activate the widget (e.g. clicking a button).\n--\nwidgetActivate :: WidgetClass w => w -> IO Bool\nwidgetActivate w = liftM toBool $ {#call widget_activate#} (toWidget w)\n\n-- @method widgetSetSensitivity@ Set the widgets sensitivity (Grayed or\n-- Usable).\n--\nwidgetSetSensitivity :: WidgetClass w => w -> Bool -> IO ()\nwidgetSetSensitivity w b = \n {#call widget_set_sensitive#} (toWidget w) (fromBool b)\n\n-- @method widgetSetSizeRequest@ Sets the minimum size of a widget.\n--\nwidgetSetSizeRequest :: WidgetClass w => w -> Int -> Int -> IO ()\nwidgetSetSizeRequest w width height =\n {#call widget_set_size_request#} (toWidget w) (fromIntegral width) (fromIntegral height)\n\n-- @method widgetIsFocus@ Set and query the input focus of a widget.\n--\nwidgetIsFocus :: WidgetClass w => w -> IO Bool\nwidgetIsFocus w = liftM toBool $ \n {#call unsafe widget_is_focus#} (toWidget w)\n\nwidgetGrabFocus :: WidgetClass w => w -> IO ()\nwidgetGrabFocus = {#call widget_grab_focus#}.toWidget\n\n-- @method widgetSetAppPaintable@ Sets some weired flag in the widget.\n--\nwidgetSetAppPaintable :: WidgetClass w => w -> Bool -> IO ()\nwidgetSetAppPaintable w p = \n {#call widget_set_app_paintable#} (toWidget w) (fromBool p)\n\n-- @method widgetSetName@ Set the name of a widget.\n--\nwidgetSetName :: WidgetClass w => w -> String -> IO ()\nwidgetSetName w name = \n withCString name ({#call widget_set_name#} (toWidget w))\n\n-- @method widgetGetName@ Get the name of a widget.\n--\nwidgetGetName :: WidgetClass w => w -> IO String\nwidgetGetName w = {#call unsafe widget_get_name#} (toWidget w) >>= \n\t\t peekCString\n\n-- @method widgetAddEvents@ Enable event signals.\n--\nwidgetAddEvents :: WidgetClass w => w -> [EventMask] -> IO ()\nwidgetAddEvents w em = \n {#call widget_add_events#} (toWidget w) (fromIntegral $ fromFlags em)\n\n-- @method widgetGetEvents@ Get enabled event signals.\n--\nwidgetGetEvents :: WidgetClass w => w -> IO [EventMask]\nwidgetGetEvents w = liftM (toFlags.fromIntegral) $ \n {#call unsafe widget_get_events#} (toWidget w)\n\n-- @method widgetSetExtensionEvents@ Set extension events.\n--\nwidgetSetExtensionEvents :: WidgetClass w => w -> [ExtensionMode] -> IO ()\nwidgetSetExtensionEvents w em = \n {#call widget_set_extension_events#} (toWidget w) \n (fromIntegral $ fromFlags em)\n\n-- @method widgetGetExtensionEvents@ Get extension events.\n--\nwidgetGetExtensionEvents :: WidgetClass w => w -> IO [ExtensionMode]\nwidgetGetExtensionEvents w = liftM (toFlags.fromIntegral) $ \n {#call widget_get_extension_events#} (toWidget w)\n\n-- Widget browsing.\n\n-- @method widgetGetToplevel@ Retrieves the topmost widget in this tree.\n--\nwidgetGetToplevel :: WidgetClass w => w -> IO Widget\nwidgetGetToplevel w = makeNewObject mkWidget $\n {#call unsafe widget_get_toplevel#} (toWidget w)\n\n-- @method widgetIsAncestor@ Return True if the second widget is (possibly\n-- indirectly) held by the first.\n--\nwidgetIsAncestor :: (WidgetClass w, WidgetClass anc) => anc -> w -> IO Bool\nwidgetIsAncestor anc w = liftM toBool $ \n {#call unsafe widget_is_ancestor#} (toWidget w) (toWidget anc)\n\n-- @method widgetReparent@ Move a widget to a new parent.\n--\nwidgetReparent :: (WidgetClass w, WidgetClass par) => w -> par -> IO ()\nwidgetReparent w par = \n {#call widget_reparent#} (toWidget w) (toWidget par)\n\n-- @method widgetSetDirection@ Setting packaging and writing direction.\n--\nwidgetSetDirection :: WidgetClass w => w -> TextDirection -> IO ()\nwidgetSetDirection w td = \n {#call widget_set_direction#} (toWidget w) ((fromIntegral.fromEnum) td)\n\n-- @method widgetGetDirection@ Retrieve the default direction of text writing.\n--\nwidgetGetDirection :: WidgetClass w => w -> IO TextDirection\nwidgetGetDirection w = liftM (toEnum.fromIntegral) $ \n {#call widget_get_direction#} (toWidget w)\n\n-- Accelerator handling.\n\n-- Lock accelerators.\n-- * \n--widgetLockAccelerators :: WidgetClass w => w -> IO ()\n--widgetLockAccelerators = {#call unsafe widget_lock_accelerators#}.toWidget\n\n\n-- Unlock accelerators.\n-- * \n--widgetUnlockAccelerators :: WidgetClass w => w -> IO ()\n--widgetUnlockAccelerators = {#call widget_unlock_accelerators#}.toWidget\n\n\n\n\n-- signals\n\n-- Because there are so many similar signals (those that take an Event and\n-- return a Bool) we will abstract out the skeleton. As some of these events\n-- are emitted at a high rate often a bit has to be set to enable emission.\nevent :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (Event -> IO Bool) -> IO (ConnectId w)\nevent name eMask after obj fun = do\n id <- connect_BOXED__BOOL name marshalEvent after obj fun\n widgetAddEvents obj eMask\n return id\n\n-- @signal connectToButtonPress@ A Button was pressed.\n--\n-- * This widget is part of a button which was just pressed. The event passed\n-- to the user function is a @ref arg Button@ event.\n--\nonButtonPress, afterButtonPress :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonButtonPress = event \"button_press_event\" [ButtonPressMask] False\nafterButtonPress = event \"button_press_event\" [ButtonPressMask] True\n\n-- @signal connectToButtonRelease@ A Butten was released.\n--\nonButtonRelease, afterButtonRelease :: WidgetClass w => w ->\n (Event -> IO Bool) -> IO (ConnectId w)\nonButtonRelease = event \"button_release_event\" [ButtonReleaseMask] False\nafterButtonRelease = event \"button_release_event\" [ButtonReleaseMask] True\n\n-- @signal connectToClient@ \n--\nonClient, afterClient :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonClient = event \"client_event\" [] False\nafterClient = event \"client_event\" [] True\n\n-- @signal connectToConfigure@ The widget's status has changed.\n--\nonConfigure, afterConfigure :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonConfigure = event \"configure_event\" [] False\nafterConfigure = event \"configure_event\" [] True\n\n-- @signal connectToDelete@ This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @ref arg destroy@ signal.\n--\nonDelete, afterDelete :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonDelete = event \"delete_event\" [] False\nafterDelete = event \"delete_event\" [] True\n\n-- @signal connectToDestroyEvent@ The widget will be destroyed.\n--\n-- * The widget received a destroy event from the window manager.\n--\nonDestroyEvent, afterDestroyEvent :: WidgetClass w => \n\t\t\t\t w -> (Event -> IO Bool) ->\n\t\t\t\t IO (ConnectId w)\nonDestroyEvent = event \"destroy_event\" [] False\nafterDestroyEvent = event \"destroy_event\" [] True\n\n-- @signal connectToDirectionChanged@ The default text direction was changed.\n--\nonDirectionChanged, afterDirectionChanged :: WidgetClass w => w ->\n (Event -> IO Bool) ->\n IO (ConnectId w)\nonDirectionChanged = event \"direction_changed\" [] False\nafterDirectionChanged = event \"direction_changed\" [] True\n\n-- @signal connectToEnterNotify@ Mouse cursor entered widget.\n--\nonEnterNotify, afterEnterNotify :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonEnterNotify = event \"enter_notify_event\" [EnterNotifyMask] False\nafterEnterNotify = event \"enter_notify_event\" [EnterNotifyMask] True\n\n-- @signal connectToLeaveNotify@ Mouse cursor leaves widget.\n--\nonLeaveNotify, afterLeaveNotify :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonLeaveNotify = event \"leave_notify_event\" [LeaveNotifyMask] False\nafterLeaveNotify = event \"leave_notify_event\" [LeaveNotifyMask] True\n\n-- @signal connectToExpose@ Instructs the widget to redraw.\n--\nonExpose, afterExpose :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonExpose = event \"expose_event\" [] False\nafterExpose = event \"expose_event\" [] True\n\n-- @signal connectToFocusIn@ Widget gains input focus.\n--\nonFocusIn, afterFocusIn :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonFocusIn = event \"focus_in_event\" [FocusChangeMask] False\nafterFocusIn = event \"focus_in_event\" [FocusChangeMask] True\n\n-- @signal connectToFocusOut@ Widget looses input focus.\n--\nonFocusOut, afterFocusOut :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonFocusOut = event \"focus_out_event\" [FocusChangeMask] False\nafterFocusOut = event \"focus_out_event\" [FocusChangeMask] True\n\n-- @signal connectToGrabFocus@ The widget is about to receive all events.\n--\n-- * It is possible to redirect all input events to one widget to force the\n-- user to use only this widget. Such a situation is initiated by\n-- @ref arg addGrab@.\n--\nonGrabFocus, afterGrabFocus :: WidgetClass w => w -> IO () ->\n IO (ConnectId w)\nonGrabFocus = connect_NONE__NONE \"grab_focus\" False\nafterGrabFocus = connect_NONE__NONE \"grab_focus\" True\n\n-- @signal connectToDestroy@ The widget will be destroyed.\n--\n-- * This is the last signal this widget will receive.\n--\nonDestroy, afterDestroy :: WidgetClass w => w -> (IO ()) ->\n IO (ConnectId w)\nonDestroy = connect_NONE__NONE \"destroy\" False\nafterDestroy = connect_NONE__NONE \"destroy\" True\n\n-- @signal connectToHide@ The widget was asked to hide itself.\n--\n-- * This signal is emitted each time @ref arg widgetHide@ is called. Use\n-- @ref method connectToUnmap@ when your application needs to be informed\n-- when the widget is actually removed from screen.\n--\nonHide, afterHide :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonHide = connect_NONE__NONE \"hide\" False\nafterHide = connect_NONE__NONE \"hide\" True\n\n-- @signal connectToHierarchyChanged@ The toplevel window changed.\n--\n-- * When a subtree of widgets is removed or added from a tree with a toplevel\n-- window this signal is emitted. It is emitted on each widget in the\n-- detached or attached subtree.\n--\nonHierarchyChanged, afterHierarchyChanged :: WidgetClass w => w -> IO () ->\n IO (ConnectId w)\nonHierarchyChanged = connect_NONE__NONE \"hierarchy_changed\" False\nafterHierarchyChanged = connect_NONE__NONE \"hierarchy_changed\" True\n\n-- @signal connectToKeyPress@ A key was pressed.\n--\nonKeyPress, afterKeyPress :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonKeyPress = event \"key_press_event\" [KeyPressMask] False\nafterKeyPress = event \"key_press_event\" [KeyPressMask] True\n\n-- @signal connectToKeyRelease@ A key was released.\n--\nonKeyRelease, afterKeyRelease :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonKeyRelease = event \"key_release_event\" [KeyReleaseMask] False\nafterKeyRelease = event \"key_release_event\" [KeyReleaseMask] True\n\n-- @signal connectToMnemonicActivate@ \n--\nonMnemonicActivate, afterMnemonicActivate :: WidgetClass w => w ->\n (Bool -> IO Bool) ->\n IO (ConnectId w)\nonMnemonicActivate = connect_BOOL__BOOL \"mnemonic_activate\" False\nafterMnemonicActivate = connect_BOOL__BOOL \"mnemonic_activate\" True\n\n-- @signal connectToMotionNotify@ Track mouse movements.\n--\n-- * If @ref arg hint@ is False, a callback for every movement of the mouse is\n-- generated. To avoid a backlog of mouse messages, it is usually sufficient\n-- to sent @ref arg hint@ to True, generating only one event. The\n-- application now has to state that it is ready for the next message by\n-- calling @ref arg gdkWindowGetPointer@.\n--\nonMotionNotify, afterMotionNotify :: WidgetClass w => w -> Bool ->\n (Event -> IO Bool) -> \n IO (ConnectId w)\nonMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionHintMask] else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionHintMask] else [PointerMotionMask]) True w\n\n-- @signal connectToParentSet@ \n--\nonParentSet, afterParentSet :: (WidgetClass w, WidgetClass old) => w ->\n (old -> IO ()) -> IO (ConnectId w)\nonParentSet = connect_OBJECT__NONE \"parent_set\" False\nafterParentSet = connect_OBJECT__NONE \"parent_set\" True\n\n-- @signal connectToPopupMenu@ \n--\nonPopupMenu, afterPopupMenu :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonPopupMenu = connect_NONE__NONE \"popup_menu\" False\nafterPopupMenu = connect_NONE__NONE \"popup_menu\" True\n\n-- @signal connectToProximityIn@ The input device became active.\n--\n-- * This event indicates that a pen of a graphics tablet or similar device is\n-- now touching the tablet.\n--\nonProximityIn, afterProximityIn :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonProximityIn = event \"proximity_in_event\" [ProximityInMask] False\nafterProximityIn = event \"proximity_in_event\" [ProximityInMask] True\n\n-- @signal connectToProximityOut@ The input device became inactive.\n--\n-- * The pen was removed from the graphics tablet's surface.\n--\nonProximityOut, afterProximityOut :: WidgetClass w => w ->\n (Event -> IO Bool) -> IO (ConnectId w)\nonProximityOut = event \"proximity_out_event\" [ProximityOutMask] False\nafterProximityOut = event \"proximity_out_event\" [ProximityOutMask] True\n\n-- @signal connectToScroll@ The mouse wheel has turned.\n--\n-- * The @ref arg Event@ is always @ref arg Scroll@.\n--\nonScroll, afterScroll :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonScroll = event \"scroll_event\" [ScrollMask] False\nafterScroll = event \"scroll_event\" [ScrollMask] True\n\n-- @signal connectToShow@ The widget was asked to show itself.\n--\n-- * This signal is emitted each time @ref arg widgetShow@ is called. Use\n-- @ref method connectToMap@ when your application needs to be informed when\n-- the widget is actually shown.\n--\nonShow, afterShow :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonShow = connect_NONE__NONE \"show\" False\nafterShow = connect_NONE__NONE \"show\" True\n\n-- @signal connectToSizeAllocate@ Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @ref arg sizeRequest@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nonSizeAllocate, afterSizeAllocate :: WidgetClass w => w ->\n (Allocation -> IO ()) -> IO (ConnectId w)\nonSizeAllocate = connect_BOXED__NONE \"size_allocate\" peek False\nafterSizeAllocate = connect_BOXED__NONE \"size_allocate\" peek True\n\n-- @signal connectToSizeRequest@ Query the widget for the size it likes to\n-- have.\n--\n-- * A parent container emits this signal to its child to query the needed\n-- height and width of the child. There is not guarantee that the widget\n-- will actually get this area.\n--\nonSizeRequest, afterSizeRequest :: WidgetClass w => w -> (IO Requisition) ->\n IO (ConnectId w)\nonSizeRequest w fun = connect_PTR__NONE \"size_request\" False w (\\rqPtr -> do\n req <- fun\n unless (rqPtr==nullPtr) $ poke rqPtr req)\nafterSizeRequest w fun = connect_PTR__NONE \"size_request\" True w (\\rqPtr -> do\n req <- fun\n unless (rqPtr==nullPtr) $ poke rqPtr req) \n\n-- @signal connectToStateChanged@ \n--\nonStateChanged, afterStateChanged :: WidgetClass w => w ->\n (StateType -> IO ()) -> IO (ConnectId w)\nonStateChanged = connect_ENUM__NONE \"state_changed\" False\nafterStateChanged = connect_ENUM__NONE \"state_changed\" True\n\n-- @signal connectToUnmap@ The widget was removed from screen.\n--\nonUnmap, afterUnmap :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonUnmap = connect_NONE__NONE \"unmap\" False\nafterUnmap = connect_NONE__NONE \"unmap\" True\n\n-- @signal connectToUnrealize@ This widget's drawing area is about to be\n-- destroyed.\n--\nonUnrealize, afterUnrealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonUnrealize = connect_NONE__NONE \"unrealize\" False\nafterUnrealize = connect_NONE__NONE \"unrealize\" True\n\n-- @signal connectToVisibilityNotify@ \n--\nonVisibilityNotify, afterVisibilityNotify :: WidgetClass w => w ->\n (Event -> IO Bool) ->\n IO (ConnectId w)\nonVisibilityNotify = \n event \"visibility_notify_event\" [VisibilityNotifyMask] False\nafterVisibilityNotify = \n event \"visibility_notify_event\" [VisibilityNotifyMask] True\n\n-- @signal connectToWindowState@ \n--\nonWindowState, afterWindowState :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonWindowState = event \"window_state_event\" [] False\nafterWindowState = event \"window_state_event\" [] True\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget Widget@\n--\n-- Author : Axel Simon\n-- \n-- Created: 27 April 2001\n--\n-- Version $Revision: 1.7 $ from $Date: 2002\/10\/21 02:45:53 $\n--\n-- Copyright (c) 2001 Axel Simon\n--\n-- This file is free software; you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation; either version 2 of the License, or\n-- (at your option) any later version.\n--\n-- This file is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- * Widget is the base class of all widgets. It provides the methods to\n-- attach and detach signals.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * This modules reexports everything a normal widget needs from GObject\n-- and Object.\n--\n--- TODO ----------------------------------------------------------------------\n--\n-- * unimplemented methods that seem to be useful in user programs:\n-- widgetSizeRequest, widgetAddAccelerator, widgetRemoveAccrelerator,\n--\twidgetAcceleratorSignal, widgetIntersect, widgetGrabDefault,\n--\twidgetGetPointer, widgetPath, widgetClassPath, getCompositeName,\n--\twidgetSetCompositeName,\n--\twidgetModifyStyle, widgetGetModifierStyle, widgetModifyFg,\n--\twidgetModifyBG, widgetModifyText, widgetModifyBase, widgetModifyFont,\n--\twidgetPango*, widgetSetAdjustments\n--\t\n--\n-- * implement the following methods in GtkWindow object:\n-- widget_set_uposition, widget_set_usize\n--\n-- * implement the following methods in GtkDrawingArea object:\n-- widgetQueueDrawArea, widgetSetDoubleBufferd, widgetRegionIntersect\n--\nmodule Widget(\n Widget,\n WidgetClass,\n castToWidget,\n Allocation,\n Requisition(..),\n Rectangle(..),\n widgetShow,\t\t\t-- Showing and hiding a widget.\n widgetShowNow,\n widgetHide,\n widgetShowAll,\n widgetHideAll,\n widgetDestroy,\n widgetQueueDraw,\t\t-- Functions to be used with DrawingArea.\n widgetHasIntersection,\n widgetActivate,\t\t-- Manipulate widget state.\n widgetSetSensitivity,\n widgetSetSizeRequest,\n widgetIsFocus,\n widgetGrabFocus,\n widgetSetAppPaintable,\n widgetSetName,\t\t-- Naming, Themes\n widgetGetName,\n widgetGetToplevel,\t\t-- Widget browsing.\n widgetIsAncestor,\n widgetReparent,\n TextDirection(..),\n widgetSetDirection,\t\t-- General Setup.\n widgetGetDirection,\n-- widgetLockAccelerators,\n-- widgetUnlockAccelerators,\n Event(..),\n onButtonPress,\n afterButtonPress,\n onButtonRelease,\n afterButtonRelease,\n onClient,\n afterClient,\n onConfigure,\n afterConfigure,\n onDelete,\n afterDelete,\n onDestroyEvent,\t\t-- you probably want onDestroy\n afterDestroyEvent,\n onDirectionChanged,\n afterDirectionChanged,\n onEnterNotify,\n afterEnterNotify,\n onLeaveNotify,\n afterLeaveNotify,\n onExpose,\n afterExpose,\n onFocusIn,\n afterFocusIn,\n onFocusOut,\n afterFocusOut,\n onGrabFocus,\n afterGrabFocus,\n onDestroy,\n afterDestroy,\n onHide,\n afterHide,\n onHierarchyChanged,\n afterHierarchyChanged,\n onKeyPress,\n afterKeyPress,\n onKeyRelease,\n afterKeyRelease,\n onMnemonicActivate,\n afterMnemonicActivate,\n onMotionNotify,\n afterMotionNotify,\n onParentSet,\n afterParentSet,\n onPopupMenu,\n afterPopupMenu,\n onProximityIn,\n afterProximityIn,\n onProximityOut,\n afterProximityOut,\n onScroll,\n afterScroll,\n onShow,\n afterShow,\n onSizeAllocate,\n afterSizeAllocate,\n onSizeRequest,\n afterSizeRequest,\n StateType(..),\n onStateChanged,\n afterStateChanged,\n onUnmap,\n afterUnmap,\n onUnrealize,\n afterUnrealize,\n onVisibilityNotify,\n afterVisibilityNotify,\n onWindowState,\n afterWindowState\n ) where\n\nimport Monad\t(liftM, unless)\nimport UTFCForeign\nimport Foreign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport GdkEnums\nimport Structs\t(Allocation, Rectangle(..), Requisition(..))\nimport Events\t(Event(..), marshalEvent)\nimport Enums\t(StateType(..), TextDirection(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- @method widgetShow@ Queue a show request.\n--\n-- * Flags a widget to be displayed. Any widget that isn't shown will not\n-- appear on the screen. If you want to show all the widgets in a container,\n-- it's easier to call @ref method widgetShowAll@ on the container, instead\n-- of individually showing the widgets. Note that you have to show the\n-- containers containing a widget, in addition to the widget itself, before\n-- it will appear onscreen. When a toplevel container is shown, it is\n-- immediately realized and mapped; other shown widgets are realized and\n-- mapped when their toplevel container is realized and mapped.\n--\nwidgetShow :: WidgetClass w => w -> IO ()\nwidgetShow = {#call widget_show#}.toWidget\n\n-- @method widgetShowNow@ Queue a show event and wait for it to be executed.\n--\n-- * If the widget is an unmapped toplevel widget (i.e. a @ref arg Window@\n-- that has not yet been shown), enter the main loop and wait for the window\n-- to actually be mapped. Be careful; because the main loop is running,\n-- anything can happen during this function.\n--\nwidgetShowNow :: WidgetClass w => w -> IO ()\nwidgetShowNow = {#call widget_show_now#}.toWidget\n\n-- @method widgetHide@ Queue a hide request.\n--\n-- * Reverses the effects of @ref method widgetShow@, causing the widget to be\n-- hidden (make invisible to the user).\n--\nwidgetHide :: WidgetClass w => w -> IO ()\nwidgetHide = {#call widget_hide#}.toWidget\n\n-- @method widgetShowAll@ Show this and all child widgets.\n--\nwidgetShowAll :: WidgetClass w => w -> IO ()\nwidgetShowAll = {#call widget_show_all#}.toWidget\n\n-- @method widgetHideAll@ Hide this and all child widgets.\n--\nwidgetHideAll :: WidgetClass w => w -> IO ()\nwidgetHideAll = {#call widget_hide_all#}.toWidget\n\n-- @method widgetDestroy@ Destroy a widget.\n--\n-- * The @ref method widgetDestroy@ function is used to shutdown an object,\n-- i.e. a widget will be removed from the screen and unrealized. Resources\n-- will be freed when all references are released.\n--\nwidgetDestroy :: WidgetClass obj => obj -> IO ()\nwidgetDestroy = {#call widget_destroy#}.toWidget\n\n-- Functions to be used with DrawingArea.\n\n-- @method widgetQueueDraw@ Send a redraw request to a widget.\n--\nwidgetQueueDraw :: WidgetClass w => w -> IO ()\nwidgetQueueDraw = {#call widget_queue_draw#}.toWidget\n\n-- @method widgetHasIntersection@ Check if the widget intersects with a given\n-- area.\n--\nwidgetHasIntersection :: WidgetClass w => w -> Rectangle -> IO Bool\nwidgetHasIntersection w r = \n liftM toBool $\n withObject r $ \\r' ->\n {#call unsafe widget_intersect#} (toWidget w) (castPtr r') (castPtr nullPtr)\n\n-- Manipulate widget state.\n\n-- @method widgetActivate@ Activate the widget (e.g. clicking a button).\n--\nwidgetActivate :: WidgetClass w => w -> IO Bool\nwidgetActivate w = liftM toBool $ {#call widget_activate#} (toWidget w)\n\n-- @method widgetSetSensitivity@ Set the widgets sensitivity (Grayed or\n-- Usable).\n--\nwidgetSetSensitivity :: WidgetClass w => w -> Bool -> IO ()\nwidgetSetSensitivity w b = \n {#call widget_set_sensitive#} (toWidget w) (fromBool b)\n\n-- @method widgetSetSizeRequest@ Sets the minimum size of a widget.\n--\nwidgetSetSizeRequest :: WidgetClass w => w -> Int -> Int -> IO ()\nwidgetSetSizeRequest w width height =\n {#call widget_set_size_request#} (toWidget w) (fromIntegral width) (fromIntegral height)\n\n-- @method widgetIsFocus@ Set and query the input focus of a widget.\n--\nwidgetIsFocus :: WidgetClass w => w -> IO Bool\nwidgetIsFocus w = liftM toBool $ \n {#call unsafe widget_is_focus#} (toWidget w)\n\nwidgetGrabFocus :: WidgetClass w => w -> IO ()\nwidgetGrabFocus = {#call widget_grab_focus#}.toWidget\n\n-- @method widgetSetAppPaintable@ Sets some weired flag in the widget.\n--\nwidgetSetAppPaintable :: WidgetClass w => w -> Bool -> IO ()\nwidgetSetAppPaintable w p = \n {#call widget_set_app_paintable#} (toWidget w) (fromBool p)\n\n-- @method widgetSetName@ Set the name of a widget.\n--\nwidgetSetName :: WidgetClass w => w -> String -> IO ()\nwidgetSetName w name = \n withCString name ({#call widget_set_name#} (toWidget w))\n\n-- @method widgetGetName@ Get the name of a widget.\n--\nwidgetGetName :: WidgetClass w => w -> IO String\nwidgetGetName w = {#call unsafe widget_get_name#} (toWidget w) >>= \n\t\t peekCString\n\n-- @method widgetAddEvents@ Enable event signals.\n--\nwidgetAddEvents :: WidgetClass w => w -> [EventMask] -> IO ()\nwidgetAddEvents w em = \n {#call widget_add_events#} (toWidget w) (fromIntegral $ fromFlags em)\n\n-- @method widgetGetEvents@ Get enabled event signals.\n--\nwidgetGetEvents :: WidgetClass w => w -> IO [EventMask]\nwidgetGetEvents w = liftM (toFlags.fromIntegral) $ \n {#call unsafe widget_get_events#} (toWidget w)\n\n-- @method widgetSetExtensionEvents@ Set extension events.\n--\nwidgetSetExtensionEvents :: WidgetClass w => w -> [ExtensionMode] -> IO ()\nwidgetSetExtensionEvents w em = \n {#call widget_set_extension_events#} (toWidget w) \n (fromIntegral $ fromFlags em)\n\n-- @method widgetGetExtensionEvents@ Get extension events.\n--\nwidgetGetExtensionEvents :: WidgetClass w => w -> IO [ExtensionMode]\nwidgetGetExtensionEvents w = liftM (toFlags.fromIntegral) $ \n {#call widget_get_extension_events#} (toWidget w)\n\n-- Widget browsing.\n\n-- @method widgetGetToplevel@ Retrieves the topmost widget in this tree.\n--\nwidgetGetToplevel :: WidgetClass w => w -> IO Widget\nwidgetGetToplevel w = makeNewObject mkWidget $\n {#call unsafe widget_get_toplevel#} (toWidget w)\n\n-- @method widgetIsAncestor@ Return True if the second widget is (possibly\n-- indirectly) held by the first.\n--\nwidgetIsAncestor :: (WidgetClass w, WidgetClass anc) => anc -> w -> IO Bool\nwidgetIsAncestor anc w = liftM toBool $ \n {#call unsafe widget_is_ancestor#} (toWidget w) (toWidget anc)\n\n-- @method widgetReparent@ Move a widget to a new parent.\n--\nwidgetReparent :: (WidgetClass w, WidgetClass par) => w -> par -> IO ()\nwidgetReparent w par = \n {#call widget_reparent#} (toWidget w) (toWidget par)\n\n-- @method widgetSetDirection@ Setting packaging and writing direction.\n--\nwidgetSetDirection :: WidgetClass w => w -> TextDirection -> IO ()\nwidgetSetDirection w td = \n {#call widget_set_direction#} (toWidget w) ((fromIntegral.fromEnum) td)\n\n-- @method widgetGetDirection@ Retrieve the default direction of text writing.\n--\nwidgetGetDirection :: WidgetClass w => w -> IO TextDirection\nwidgetGetDirection w = liftM (toEnum.fromIntegral) $ \n {#call widget_get_direction#} (toWidget w)\n\n-- Accelerator handling.\n\n-- Lock accelerators.\n-- * \n--widgetLockAccelerators :: WidgetClass w => w -> IO ()\n--widgetLockAccelerators = {#call unsafe widget_lock_accelerators#}.toWidget\n\n\n-- Unlock accelerators.\n-- * \n--widgetUnlockAccelerators :: WidgetClass w => w -> IO ()\n--widgetUnlockAccelerators = {#call widget_unlock_accelerators#}.toWidget\n\n\n\n\n-- signals\n\n-- Because there are so many similar signals (those that take an Event and\n-- return a Bool) we will abstract out the skeleton. As some of these events\n-- are emitted at a high rate often a bit has to be set to enable emission.\nevent :: WidgetClass w => SignalName -> [EventMask] ->\n ConnectAfter -> w -> (Event -> IO Bool) -> IO (ConnectId w)\nevent name eMask after obj fun = do\n id <- connect_BOXED__BOOL name marshalEvent after obj fun\n widgetAddEvents obj eMask\n return id\n\n-- @signal connectToButtonPress@ A Button was pressed.\n--\n-- * This widget is part of a button which was just pressed. The event passed\n-- to the user function is a @ref arg Button@ event.\n--\nonButtonPress, afterButtonPress :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonButtonPress = event \"button_press_event\" [ButtonPressMask] False\nafterButtonPress = event \"button_press_event\" [ButtonPressMask] True\n\n-- @signal connectToButtonRelease@ A Butten was released.\n--\nonButtonRelease, afterButtonRelease :: WidgetClass w => w ->\n (Event -> IO Bool) -> IO (ConnectId w)\nonButtonRelease = event \"button_release_event\" [ButtonReleaseMask] False\nafterButtonRelease = event \"button_release_event\" [ButtonReleaseMask] True\n\n-- @signal connectToClient@ \n--\nonClient, afterClient :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonClient = event \"client_event\" [] False\nafterClient = event \"client_event\" [] True\n\n-- @signal connectToConfigure@ The widget's status has changed.\n--\nonConfigure, afterConfigure :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonConfigure = event \"configure_event\" [] False\nafterConfigure = event \"configure_event\" [] True\n\n-- @signal connectToDelete@ This signal is emitted when the close icon on the\n-- surrounding window is pressed. The default action is to emit the\n-- @ref arg destroy@ signal.\n--\nonDelete, afterDelete :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonDelete = event \"delete_event\" [] False\nafterDelete = event \"delete_event\" [] True\n\n-- @signal connectToDestroyEvent@ The widget will be destroyed.\n--\n-- * The widget received a destroy event from the window manager.\n--\nonDestroyEvent, afterDestroyEvent :: WidgetClass w => \n\t\t\t\t w -> (Event -> IO Bool) ->\n\t\t\t\t IO (ConnectId w)\nonDestroyEvent = event \"destroy_event\" [] False\nafterDestroyEvent = event \"destroy_event\" [] True\n\n-- @signal connectToDirectionChanged@ The default text direction was changed.\n--\nonDirectionChanged, afterDirectionChanged :: WidgetClass w => w ->\n (Event -> IO Bool) ->\n IO (ConnectId w)\nonDirectionChanged = event \"direction_changed\" [] False\nafterDirectionChanged = event \"direction_changed\" [] True\n\n-- @signal connectToEnterNotify@ Mouse cursor entered widget.\n--\nonEnterNotify, afterEnterNotify :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonEnterNotify = event \"enter_notify_event\" [EnterNotifyMask] False\nafterEnterNotify = event \"enter_notify_event\" [EnterNotifyMask] True\n\n-- @signal connectToLeaveNotify@ Mouse cursor leaves widget.\n--\nonLeaveNotify, afterLeaveNotify :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonLeaveNotify = event \"leave_notify_event\" [LeaveNotifyMask] False\nafterLeaveNotify = event \"leave_notify_event\" [LeaveNotifyMask] True\n\n-- @signal connectToExpose@ Instructs the widget to redraw.\n--\nonExpose, afterExpose :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonExpose = event \"expose_event\" [] False\nafterExpose = event \"expose_event\" [] True\n\n-- @signal connectToFocusIn@ Widget gains input focus.\n--\nonFocusIn, afterFocusIn :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonFocusIn = event \"focus_in_event\" [FocusChangeMask] False\nafterFocusIn = event \"focus_in_event\" [FocusChangeMask] True\n\n-- @signal connectToFocusOut@ Widget looses input focus.\n--\nonFocusOut, afterFocusOut :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonFocusOut = event \"focus_out_event\" [FocusChangeMask] False\nafterFocusOut = event \"focus_out_event\" [FocusChangeMask] True\n\n-- @signal connectToGrabFocus@ The widget is about to receive all events.\n--\n-- * It is possible to redirect all input events to one widget to force the\n-- user to use only this widget. Such a situation is initiated by\n-- @ref arg addGrab@.\n--\nonGrabFocus, afterGrabFocus :: WidgetClass w => w -> IO () ->\n IO (ConnectId w)\nonGrabFocus = connect_NONE__NONE \"grab_focus\" False\nafterGrabFocus = connect_NONE__NONE \"grab_focus\" [] True\n\n-- @signal connectToDestroy@ The widget will be destroyed.\n--\n-- * This is the last signal this widget will receive.\n--\nonDestroy, afterDestroy :: WidgetClass w => w -> (IO ()) ->\n IO (ConnectId w)\nonDestroy = connect_NONE__NONE \"destroy\" False\nafterDestroy = connect_NONE__NONE \"destroy\" True\n\n-- @signal connectToHide@ The widget was asked to hide itself.\n--\n-- * This signal is emitted each time @ref arg widgetHide@ is called. Use\n-- @ref method connectToUnmap@ when your application needs to be informed\n-- when the widget is actually removed from screen.\n--\nonHide, afterHide :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonHide = connect_NONE__NONE \"hide\" False\nafterHide = connect_NONE__NONE \"hide\" True\n\n-- @signal connectToHierarchyChanged@ The toplevel window changed.\n--\n-- * When a subtree of widgets is removed or added from a tree with a toplevel\n-- window this signal is emitted. It is emitted on each widget in the\n-- detached or attached subtree.\n--\nonHierarchyChanged, afterHierarchyChanged :: WidgetClass w => w -> IO () ->\n IO (ConnectId w)\nonHierarchyChanged = connect_NONE__NONE \"hierarchy_changed\" False\nafterHierarchyChanged = connect_NONE__NONE \"hierarchy_changed\" True\n\n-- @signal connectToKeyPress@ A key was pressed.\n--\nonKeyPress, afterKeyPress :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonKeyPress = event \"key_press_event\" [KeyPressMask] False\nafterKeyPress = event \"key_press_event\" [KeyPressMask] True\n\n-- @signal connectToKeyRelease@ A key was released.\n--\nonKeyRelease, afterKeyRelease :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonKeyRelease = event \"key_release_event\" [KeyReleaseMask] False\nafterKeyRelease = event \"key_release_event\" [KeyReleaseMask] True\n\n-- @signal connectToMnemonicActivate@ \n--\nonMnemonicActivate, afterMnemonicActivate :: WidgetClass w => w ->\n (Bool -> IO Bool) ->\n IO (ConnectId w)\nonMnemonicActivate = connect_BOOL__BOOL \"mnemonic_activate\" False\nafterMnemonicActivate = connect_BOOL__BOOL \"mnemonic_activate\" True\n\n-- @signal connectToMotionNotify@ Track mouse movements.\n--\n-- * If @ref arg hint@ is False, a callback for every movement of the mouse is\n-- generated. To avoid a backlog of mouse messages, it is usually sufficient\n-- to sent @ref arg hint@ to True, generating only one event. The\n-- application now has to state that it is ready for the next message by\n-- calling @ref arg gdkWindowGetPointer@.\n--\nonMotionNotify, afterMotionNotify :: WidgetClass w => w -> Bool ->\n (Event -> IO Bool) -> \n IO (ConnectId w)\nonMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionHintMask] else [PointerMotionMask]) False w\nafterMotionNotify w hint = event \"motion_notify_event\" \n (if hint then [PointerMotionHintMask] else [PointerMotionMask]) True w\n\n-- @signal connectToParentSet@ \n--\nonParentSet, afterParentSet :: (WidgetClass w, WidgetClass old) => w ->\n (old -> IO ()) -> IO (ConnectId w)\nonParentSet = connect_OBJECT__NONE \"parent_set\" False\nafterParentSet = connect_OBJECT__NONE \"parent_set\" True\n\n-- @signal connectToPopupMenu@ \n--\nonPopupMenu, afterPopupMenu :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonPopupMenu = connect_NONE__NONE \"popup_menu\" False\nafterPopupMenu = connect_NONE__NONE \"popup_menu\" True\n\n-- @signal connectToProximityIn@ The input device became active.\n--\n-- * This event indicates that a pen of a graphics tablet or similar device is\n-- now touching the tablet.\n--\nonProximityIn, afterProximityIn :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonProximityIn = event \"proximity_in_event\" [ProximityInMask] False\nafterProximityIn = event \"proximity_in_event\" [ProximityInMask] True\n\n-- @signal connectToProximityOut@ The input device became inactive.\n--\n-- * The pen was removed from the graphics tablet's surface.\n--\nonProximityOut, afterProximityOut :: WidgetClass w => w ->\n (Event -> IO Bool) -> IO (ConnectId w)\nonProximityOut = event \"proximity_out_event\" [ProximityOutMask] False\nafterProximityOut = event \"proximity_out_event\" [ProximityOutMask] True\n\n-- @signal connectToScroll@ The mouse wheel has turned.\n--\n-- * The @ref arg Event@ is always @ref arg Scroll@.\n--\nonScroll, afterScroll :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonScroll = event \"scroll_event\" [ScrollMask] False\nafterScroll = event \"scroll_event\" [ScrollMask] True\n\n-- @signal connectToShow@ The widget was asked to show itself.\n--\n-- * This signal is emitted each time @ref arg widgetShow@ is called. Use\n-- @ref method connectToMap@ when your application needs to be informed when\n-- the widget is actually shown.\n--\nonShow, afterShow :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonShow = connect_NONE__NONE \"show\" False\nafterShow = connect_NONE__NONE \"show\" True\n\n-- @signal connectToSizeAllocate@ Inform widget about the size it has.\n--\n-- * After querying a widget for the size it wants to have (through emitting\n-- the @ref arg sizeRequest@ signal) a container will emit this signal to\n-- inform the widget about the real size it should occupy.\n--\nonSizeAllocate, afterSizeAllocate :: WidgetClass w => w ->\n (Allocation -> IO ()) -> IO (ConnectId w)\nonSizeAllocate = connect_BOXED__NONE \"size_allocate\" peek False\nafterSizeAllocate = connect_BOXED__NONE \"size_allocate\" peek True\n\n-- @signal connectToSizeRequest@ Query the widget for the size it likes to\n-- have.\n--\n-- * A parent container emits this signal to its child to query the needed\n-- height and width of the child. There is not guarantee that the widget\n-- will actually get this area.\n--\nonSizeRequest, afterSizeRequest :: WidgetClass w => w -> (IO Requisition) ->\n IO (ConnectId w)\nonSizeRequest w fun = connect_PTR__NONE \"size_request\" False w (\\rqPtr -> do\n req <- fun\n unless (rqPtr==nullPtr) $ poke rqPtr req)\nafterSizeRequest w fun = connect_PTR__NONE \"size_request\" True w (\\rqPtr -> do\n req <- fun\n unless (rqPtr==nullPtr) $ poke rqPtr req) \n\n-- @signal connectToStateChanged@ \n--\nonStateChanged, afterStateChanged :: WidgetClass w => w ->\n (StateType -> IO ()) -> IO (ConnectId w)\nonStateChanged = connect_ENUM__NONE \"state_changed\" False\nafterStateChanged = connect_ENUM__NONE \"state_changed\" True\n\n-- @signal connectToUnmap@ The widget was removed from screen.\n--\nonUnmap, afterUnmap :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonUnmap = connect_NONE__NONE \"unmap\" False\nafterUnmap = connect_NONE__NONE \"unmap\" True\n\n-- @signal connectToUnrealize@ This widget's drawing area is about to be\n-- destroyed.\n--\nonUnrealize, afterUnrealize :: WidgetClass w => w -> IO () -> IO (ConnectId w)\nonUnrealize = connect_NONE__NONE \"unrealize\" False\nafterUnrealize = connect_NONE__NONE \"unrealize\" True\n\n-- @signal connectToVisibilityNotify@ \n--\nonVisibilityNotify, afterVisibilityNotify :: WidgetClass w => w ->\n (Event -> IO Bool) ->\n IO (ConnectId w)\nonVisibilityNotify = \n event \"visibility_notify_event\" [VisibilityNotifyMask] False\nafterVisibilityNotify = \n event \"visibility_notify_event\" [VisibilityNotifyMask] True\n\n-- @signal connectToWindowState@ \n--\nonWindowState, afterWindowState :: WidgetClass w => w -> (Event -> IO Bool) ->\n IO (ConnectId w)\nonWindowState = event \"window_state_event\" [] False\nafterWindowState = event \"window_state_event\" [] True\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"03f9a6465cd864467774959e34b6f7c56b4f5d7c","subject":"Add pixbufRenderThresholdAlpha","message":"Add pixbufRenderThresholdAlpha","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/Pixbuf.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/Pixbuf.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Pixbuf\n--\n-- Author : Vincenzo Ciancia, Axel Simon\n--\n-- Created: 26 March 2002\n--\n-- Copyright (C) 2002-2005 Axel Simon, Vincenzo Ciancia\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- TODO\n--\n-- if anybody writes an image manipulation program, do the checker board\n-- functions: gdk_pixbuf_composite_color_simple and\n-- gdk_pixbuf_composite_color. Moreover, do: pixbuf_saturate_and_pixelate\n--\n--\n-- pixbuf loader\n--\n-- module interface\n--\n-- rendering function for Bitmaps and Pixmaps when the latter are added\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- 'Pixbuf's are bitmap images in memory.\n--\n-- * A Pixbuf is used to represent images. It contains information\n-- about the image's pixel data, its color space, bits per sample, width\n-- and height, and the rowstride or number of bytes between rows.\n--\n-- * This module contains functions to scale and crop\n-- 'Pixbuf's and to scale and crop a 'Pixbuf' and\n-- compose the result with an existing image.\n--\n-- * 'Pixbuf's can be displayed on screen by either creating an 'Image' that\n-- from the 'Pixbuf' or by rendering (part of) the 'Pixbuf' into a\n-- vanilla widget like 'DrawWindow' using\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawPixbuf'.\n--\nmodule Graphics.UI.Gtk.Gdk.Pixbuf (\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----Pixbuf\n-- @\n\n-- * Types\n Pixbuf,\n PixbufClass,\n castToPixbuf, gTypePixbuf,\n toPixbuf,\n PixbufError(..),\n Colorspace(..),\n\n-- * Constructors\n pixbufNew,\n pixbufNewFromFile,\n#if GTK_CHECK_VERSION(2,4,0)\n pixbufNewFromFileAtSize,\n#endif\n#if GTK_CHECK_VERSION(2,6,0)\n pixbufNewFromFileAtScale,\n#endif\n pixbufNewFromInline,\n InlineImage,\n pixbufNewSubpixbuf,\n pixbufNewFromXPMData,\n\n-- * Methods\n pixbufGetColorSpace,\n pixbufGetNChannels,\n pixbufGetHasAlpha,\n pixbufGetBitsPerSample,\n PixbufData,\n pixbufGetPixels,\n pixbufGetWidth,\n pixbufGetHeight,\n pixbufGetRowstride,\n pixbufGetOption,\n ImageFormat,\n pixbufGetFormats,\n pixbufSave,\n pixbufCopy,\n InterpType(..),\n pixbufScaleSimple,\n pixbufScale,\n pixbufComposite,\n#if GTK_CHECK_VERSION(2,6,0)\n pixbufFlipHorizontally,\n pixbufFlipHorazontally,\n pixbufFlipVertically,\n pixbufRotateSimple,\n PixbufRotation(..),\n#endif\n pixbufAddAlpha,\n pixbufCopyArea,\n pixbufFill,\n pixbufGetFromDrawable,\n\n pixbufRenderThresholdAlpha,\n pixbufRenderPixmapAndMaskForColormap\n ) where\n\nimport Control.Monad (liftM)\nimport Data.Ix\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GDateTime\nimport System.Glib.GObject\n{#import Graphics.UI.Gtk.Types#}\nimport Graphics.UI.Gtk.General.Structs\t\t(Rectangle(..))\nimport System.Glib.GError\t(GError(..), GErrorClass(..), GErrorDomain,\n\t\t\t\tpropagateGError)\nimport Graphics.UI.Gtk.Gdk.PixbufData ( PixbufData, mkPixbufData )\nimport Graphics.UI.Gtk.Gdk.Pixmap (Bitmap, Pixmap)\n\n{# context prefix=\"gdk\" #}\n\n-- | Error codes for loading image files.\n--\n{#enum PixbufError {underscoreToCase} #}\n\n-- | Enumerate all supported color spaces.\n--\n-- * Only RGB is supported right now.\n--\n{#enum Colorspace {underscoreToCase} #}\n\n-- | Queries the color space of a pixbuf.\n--\npixbufGetColorSpace :: Pixbuf -> IO Colorspace\npixbufGetColorSpace pb = liftM (toEnum . fromIntegral) $\n {#call unsafe pixbuf_get_colorspace#} pb\n\n-- | Queries the number of colors for each pixel.\n--\n-- * This function returns 3 for an RGB image without alpha (transparency)\n-- channel, 4 for an RGB image with alpha channel.\n--\npixbufGetNChannels :: Pixbuf -> IO Int\npixbufGetNChannels pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_n_channels#} pb\n\n-- | Query if the image has an alpha channel.\n--\n-- * The alpha channel determines the opaqueness of the pixel.\n--\npixbufGetHasAlpha :: Pixbuf -> IO Bool\npixbufGetHasAlpha pb =\n liftM toBool $ {#call unsafe pixbuf_get_has_alpha#} pb\n\n-- | Queries the number of bits for each color.\n--\n-- * Each pixel is has a number of cannels for each pixel, each channel\n-- has this many bits.\n--\npixbufGetBitsPerSample :: Pixbuf -> IO Int\npixbufGetBitsPerSample pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_bits_per_sample#} pb\n\n-- | Retrieve the internal array of raw image data.\n--\n-- * Image data in a pixbuf is stored in memory in uncompressed,\n-- packed format. Rows in the image are stored top to bottom, and in each\n-- row pixels are stored from left to right. There may be padding at the\n-- end of a row. The \"rowstride\" value of a pixbuf, as returned by\n-- 'pixbufGetRowstride', indicates the number of bytes between rows.\n--\n-- * The returned array is a flat representation of a three dimensional\n-- array: x-coordiante, y-coordinate and several channels for each color.\n-- The number of channels is usually 3 for plain RGB data or 4 for\n-- RGB data with an alpha channel. To read or write a specific pixel\n-- use the formula: @p = y * rowstride + x * nChannels@ for the pixel.\n-- If the array contains bytes (or 'Word8's), @p+0@ is the red value,\n-- @p+1@ green, @p+2@ blue and @p+3@ the alpha (transparency) channel\n-- if present. If the alpha channel is present, the array can accessed\n-- as an array over 'Word32' to modify a whole pixel at a time. See also\n-- 'pixbufGetBitsPerSample' and 'pixbufGetNChannels'.\n--\n-- * Calling this function without explicitly giving it a type will often\n-- lead to a compiler error since the type parameter @e@ is underspecified.\n-- If this happens the function can be explicitly typed:\n-- @pbData <- (pixbufGetPixels pb :: IO (PixbufData Int Word8))@\n--\n-- * If modifying an image through Haskell\\'s array interface is not\n-- fast enough, it is possible to use 'unsafeRead' and\n-- 'unsafeWrite' which have the same type signatures\n-- as 'readArray' and 'writeArray'.\n-- Note that these are internal\n-- functions that might change with GHC.\n--\npixbufGetPixels :: Storable e => Pixbuf -> IO (PixbufData Int e)\npixbufGetPixels pb = do\n pixPtr_ <- {#call unsafe pixbuf_get_pixels#} pb\n chan <- pixbufGetNChannels pb\n bits <- pixbufGetBitsPerSample pb\n w <- pixbufGetWidth pb\n h <- pixbufGetHeight pb\n r <- pixbufGetRowstride pb\n let pixPtr = castPtr pixPtr_\n let bytes = (h-1)*r+w*((chan*bits+7) `div` 8)\n return (mkPixbufData pb pixPtr bytes)\n\n-- | Queries the width of this image.\n--\npixbufGetWidth :: Pixbuf -> IO Int\npixbufGetWidth pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_width#} pb\n\n-- | Queries the height of this image.\n--\npixbufGetHeight :: Pixbuf -> IO Int\npixbufGetHeight pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_height#} pb\n\n-- | Queries the rowstride of this image.\n--\n-- * Queries the rowstride of a pixbuf, which is the number of bytes between\n-- rows. Use this value to caculate the offset to a certain row.\n--\npixbufGetRowstride :: Pixbuf -> IO Int\npixbufGetRowstride pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_rowstride#} pb\n\n-- | Returns an attribut of an image.\n--\n-- * Looks up if some information was stored under the @key@ when\n-- this image was saved.\n--\npixbufGetOption :: Pixbuf -> String -> IO (Maybe String)\npixbufGetOption pb key = withUTFString key $ \\strPtr -> do\n resPtr <- {#call unsafe pixbuf_get_option#} pb strPtr\n if (resPtr==nullPtr) then return Nothing else\n liftM Just $ peekUTFString resPtr\n\n-- helper functions\npixbufErrorDomain :: GErrorDomain\npixbufErrorDomain = {#call pure unsafe pixbuf_error_quark#}\n\ninstance GErrorClass PixbufError where\n gerrorDomain _ = pixbufErrorDomain\n\n\n-- | Load an image synchonously.\n--\n-- * Use this function to load only small images as this call will block.\n--\n-- * If an error occurs, the function will throw an exception that can\n-- be caught using e.g. 'System.Glib.GError.catchGErrorJust' and one of the\n-- error codes in 'PixbufError'.\n--\npixbufNewFromFile :: FilePath -> IO Pixbuf\npixbufNewFromFile fname =\n constructNewGObject mkPixbuf $\n propagateGError $ \\errPtrPtr ->\n withUTFString fname $ \\strPtr ->\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,0)\n {#call unsafe pixbuf_new_from_file_utf8#}\n#else\n {#call unsafe pixbuf_new_from_file#}\n#endif\n strPtr errPtrPtr\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Creates a new pixbuf by loading an image from a file. The file format is\n-- detected automatically. The image will be scaled to fit in the requested\n-- size, preserving the image's aspect ratio.\n--\n-- * If an error occurs, the function will throw an exception that can\n-- be caught using e.g. 'System.Glib.GError.catchGErrorJust' and one of the\n-- error codes in 'PixbufError'.\n--\n-- * Available since Gtk+ version 2.4\n--\npixbufNewFromFileAtSize :: String -> Int -> Int -> IO Pixbuf\npixbufNewFromFileAtSize filename width height =\n constructNewGObject mkPixbuf $\n propagateGError $ \\errPtrPtr ->\n withUTFString filename $ \\filenamePtr ->\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,0)\n {# call gdk_pixbuf_new_from_file_at_size_utf8 #}\n#else\n {# call gdk_pixbuf_new_from_file_at_size #}\n#endif\n filenamePtr\n (fromIntegral width)\n (fromIntegral height)\n errPtrPtr\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Creates a new pixbuf by loading an image from a file. The file format is\n-- detected automatically. The image will be scaled to fit in the requested\n-- size, optionally preserving the image's aspect ratio.\n--\n-- When preserving the aspect ratio, a width of -1 will cause the image to be\n-- scaled to the exact given height, and a height of -1 will cause the image to\n-- be scaled to the exact given width. When not preserving aspect ratio, a width\n-- or height of -1 means to not scale the image at all in that dimension.\n-- Negative values for width and height are allowed since Gtk+ 2.8.\n--\n-- * If an error occurs, the function will throw an exception that can\n-- be caught using e.g. 'System.Glib.GError.catchGErrorJust' and one of the\n-- error codes in 'PixbufError'.\n--\n-- * Available since Gtk+ version 2.6\n--\npixbufNewFromFileAtScale ::\n String -- ^ the name of the file\n -> Int -- ^ target width\n -> Int -- ^ target height\n -> Bool -- ^ whether to preserve the aspect ratio\n -> IO Pixbuf\npixbufNewFromFileAtScale filename width height preserveAspectRatio =\n constructNewGObject mkPixbuf $\n propagateGError $ \\errPtrPtr ->\n withUTFString filename $ \\filenamePtr ->\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,0)\n {# call gdk_pixbuf_new_from_file_at_scale_utf8 #}\n#else\n {# call gdk_pixbuf_new_from_file_at_scale #}\n#endif\n filenamePtr\n (fromIntegral width)\n (fromIntegral height)\n (fromBool preserveAspectRatio)\n errPtrPtr\n#endif\n\n-- | A string representing an image file format.\n--\ntype ImageFormat = String\n\n-- constant pixbufGetFormats A list of valid image file formats.\n--\npixbufGetFormats :: [ImageFormat]\n\npixbufGetFormats = [\"png\",\"bmp\",\"wbmp\", \"gif\",\"ico\",\"ani\",\"jpeg\",\"pnm\",\n\t\t \"ras\",\"tiff\",\"xpm\",\"xbm\",\"tga\"]\n\n-- | Save an image to disk.\n--\n-- * The function takes a list of key - value pairs to specify\n-- either how an image is saved or to actually save this additional\n-- data with the image. JPEG images can be saved with a \\\"quality\\\"\n-- parameter; its value should be in the range [0,100]. Text chunks\n-- can be attached to PNG images by specifying parameters of the form\n-- \\\"tEXt::key\\\", where key is an ASCII string of length 1-79.\n-- The values are Unicode strings.\n--\n-- * If an error occurs, the function will throw an exception that can\n-- be caught using e.g. 'System.Glib.GError.catchGErrorJust' and one of the\n-- error codes in 'PixbufError'.\n--\npixbufSave :: Pixbuf -> FilePath -> ImageFormat -> [(String, String)] ->\n\t IO ()\npixbufSave pb fname iType options =\n let (keys, values) = unzip options in\n let optLen = length keys in\n propagateGError $ \\errPtrPtr ->\n withUTFString fname $ \\fnPtr ->\n withUTFString iType $ \\tyPtr ->\n withUTFStringArray0 keys $ \\keysPtr ->\n withUTFStringArray values $ \\valuesPtr -> do\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,5)\n {# call unsafe pixbuf_savev_utf8 #}\n#else\n {# call unsafe pixbuf_savev #}\n#endif\n pb fnPtr tyPtr keysPtr valuesPtr errPtrPtr\n return ()\n\n-- | Create a new image in memory.\n--\n-- * Creates a new pixbuf structure and allocates a buffer for\n-- it. Note that the buffer is not cleared initially.\n--\n-- * The boolean flag is true if the pixbuf should have an alpha\n-- (transparency) channel. The next integer denotes the bits per\n-- color sample, e.g. 8 bits per color for 2^24 colors. The last\n-- two integers denote the width and height, respectively.\n--\npixbufNew :: Colorspace -> Bool -> Int -> Int -> Int -> IO Pixbuf\npixbufNew colorspace hasAlpha bitsPerSample width height =\n constructNewGObject mkPixbuf $\n {#call pixbuf_new#} ((fromIntegral . fromEnum) colorspace)\n (fromBool hasAlpha) (fromIntegral bitsPerSample) (fromIntegral width)\n (fromIntegral height)\n\n-- | Create a new image from a String.\n--\n-- * Creates a new pixbuf from a string description.\n--\npixbufNewFromXPMData :: [String] -> IO Pixbuf\npixbufNewFromXPMData s =\n withUTFStringArray0 s $ \\strsPtr ->\n constructNewGObject mkPixbuf $ {#call pixbuf_new_from_xpm_data#} strsPtr\n\n-- | A dymmy type for inline picture data.\n--\n-- * This dummy type is used to declare pointers to image data\n-- that is embedded in the executable. See\n-- 'pixbufNewFromInline' for an example.\n--\ndata InlineImage = InlineImage\n\n-- | Create a new image from a static pointer.\n--\n-- * Like 'pixbufNewFromXPMData', this function allows to\n-- include images in the final binary program. The method used by this\n-- function uses a binary representation and therefore needs less space\n-- in the final executable. Save the image you want to include as\n-- @png@ and run:\n--\n-- > @echo #include \"my_image.h\" > my_image.c\n-- > gdk-pixbuf-csource --raw --extern --name=my_image myimage.png >> my_image.c\n--\n-- on it. Write a header file @my_image.h@ containing:\n--\n-- > #include \n-- > extern guint8 my_image[];\n--\n-- and save it in the current directory.\n-- The created file can be compiled with: \n--\n-- > cc -c my_image.c `pkg-config --cflags gdk-2.0`\n--\n-- into an object file which must be linked into your Haskell program by\n-- specifying @my_image.o@ and @\\\"-#include my_image.h\\\"@ on\n-- the command line of GHC.\n-- Within you application you delcare a pointer to this image:\n--\n-- > foreign label \"my_image\" myImage :: Ptr InlineImage\n--\n-- Calling 'pixbufNewFromInline' with this pointer will\n-- return the image in the object file. Creating the C file with\n-- the @--raw@ flag will result in a non-compressed image in the\n-- object file. The advantage is that the picture will not be\n-- copied when this function is called.\n--\n--\npixbufNewFromInline :: Ptr InlineImage -> IO Pixbuf\npixbufNewFromInline iPtr = alloca $ \\errPtrPtr -> do\n pbPtr <- {#call unsafe pixbuf_new_from_inline#} (-1) (castPtr iPtr)\n (fromBool False) (castPtr errPtrPtr)\n if pbPtr\/=nullPtr then constructNewGObject mkPixbuf (return pbPtr)\n else do\n errPtr <- peek errPtrPtr\n (GError dom code msg) <- peek errPtr\n error msg\n\n-- | Create a restricted view of an image.\n--\n-- * This function returns a 'Pixbuf' object which shares\n-- the image of the original one but only shows a part of it.\n-- Modifying either buffer will affect the other.\n--\n-- * This function throw an exception if the requested bounds are invalid.\n--\npixbufNewSubpixbuf :: Pixbuf -> Int -> Int -> Int -> Int -> IO Pixbuf\npixbufNewSubpixbuf pb srcX srcY height width =\n constructNewGObject mkPixbuf $ do\n pbPtr <- {#call unsafe pixbuf_new_subpixbuf#} pb\n (fromIntegral srcX) (fromIntegral srcY)\n (fromIntegral height) (fromIntegral width)\n if pbPtr==nullPtr then error \"pixbufNewSubpixbuf: invalid bounds\"\n else return pbPtr\n\n-- | Create a deep copy of an image.\n--\npixbufCopy :: Pixbuf -> IO Pixbuf\npixbufCopy pb = constructNewGObject mkPixbuf $ {#call unsafe pixbuf_copy#} pb\n\n\n-- | How an image is scaled.\n--\n-- [@InterpNearest@] Nearest neighbor sampling; this is the\n-- fastest and lowest quality mode. Quality is normally unacceptable when\n-- scaling down, but may be OK when scaling up.\n--\n-- [@InterpTiles@] This is an accurate simulation of the\n-- PostScript image operator without any interpolation enabled. Each\n-- pixel is rendered as a tiny parallelogram of solid color, the edges of\n-- which are implemented with antialiasing. It resembles nearest neighbor\n-- for enlargement, and bilinear for reduction.\n--\n-- [@InterpBilinear@] Best quality\\\/speed balance; use this\n-- mode by default. Bilinear interpolation. For enlargement, it is\n-- equivalent to point-sampling the ideal bilinear-interpolated\n-- image. For reduction, it is equivalent to laying down small tiles and\n-- integrating over the coverage area.\n--\n-- [@InterpHyper@] This is the slowest and highest quality\n-- reconstruction function. It is derived from the hyperbolic filters in\n-- Wolberg's \\\"Digital Image Warping\\\", and is formally defined as the\n-- hyperbolic-filter sampling the ideal hyperbolic-filter interpolated\n-- image (the filter is designed to be idempotent for 1:1 pixel mapping).\n--\n{#enum InterpType {underscoreToCase} #}\n\n-- | Scale an image.\n--\n-- * Creates a new 'Pixbuf' containing a copy of \n-- @src@ scaled to the given measures. Leaves @src@\n-- unaffected. \n--\n-- * @interp@ affects the quality and speed of the scaling function.\n-- 'InterpNearest' is the fastest option but yields very poor quality\n-- when scaling down. 'InterpBilinear' is a good trade-off between\n-- speed and quality and should thus be used as a default.\n--\npixbufScaleSimple :: \n Pixbuf -- ^ @src@ - the source image\n -> Int -- ^ @width@ - the target width\n -> Int -- ^ @height@ the target height\n -> InterpType -- ^ interpolation type\n -> IO Pixbuf\npixbufScaleSimple pb width height interp =\n constructNewGObject mkPixbuf $ liftM castPtr $\n\t{#call pixbuf_scale_simple#} (toPixbuf pb)\n\t(fromIntegral width) (fromIntegral height)\n\t(fromIntegral $ fromEnum interp)\n\n-- | Copy a scaled image part to another image.\n--\n-- * This function is the generic version of 'pixbufScaleSimple'. It scales\n-- @src@ by @scaleX@ and @scaleY@ and translate the image by @offsetX@ and\n-- @offsetY@. Whatever is in the intersection with the rectangle @destX@,\n-- @destY@, @destWidth@, @destHeight@ will be rendered into @dest@.\n--\n-- * The rectangle in the destination is simply overwritten. Use\n-- 'pixbufComposite' if you need to blend the source image onto the\n-- destination.\n--\npixbufScale :: \n Pixbuf -- ^ @src@ - the source pixbuf\n -> Pixbuf -- ^ @dest@ - the pixbuf into which to render the results\n -> Int -- ^ @destX@ - the left coordinate for region to render\n -> Int -- ^ @destY@ - the top coordinate for region to render \n -> Int -- ^ @destWidth@ - the width of the region to render\n -> Int -- ^ @destHeight@ - the height of the region to render\n -> Double -- ^ @offsetX@ - the offset in the X direction (currently\n -- rounded to an integer)\n -> Double -- ^ @offsetY@ - the offset in the Y direction \n -- (currently rounded to an integer)\n -> Double -- ^ @scaleX@ - the scale factor in the X direction\n -> Double -- ^ @scaleY@ - the scale factor in the Y direction\n -> InterpType -- ^ the interpolation type for the transformation.\n -> IO ()\npixbufScale src dest destX destY destWidth destHeight offsetX offsetY\n scaleX scaleY interp =\n {#call unsafe pixbuf_scale#} src dest\n (fromIntegral destX) (fromIntegral destY)\n (fromIntegral destWidth) (fromIntegral destHeight)\n (realToFrac offsetX) (realToFrac offsetY)\n (realToFrac scaleX) (realToFrac scaleY)\n ((fromIntegral . fromEnum) interp)\n\n-- | Blend a scaled image part onto another image.\n--\n-- * This function is similar to 'pixbufScale' but allows the\n-- original image to \\\"shine through\\\". The @alpha@ value determines\n-- how opaque the source image is. Passing @0@ is\n-- equivalent to not calling this function at all, passing\n-- @255@ has the\n-- same effect as calling 'pixbufScale'.\n--\npixbufComposite ::\n Pixbuf -- ^ @src@ - the source pixbuf\n -> Pixbuf -- ^ @dest@ - the pixbuf into which to render the results\n -> Int -- ^ @destX@ - the left coordinate for region to render\n -> Int -- ^ @destY@ - the top coordinate for region to render \n -> Int -- ^ @destWidth@ - the width of the region to render\n -> Int -- ^ @destHeight@ - the height of the region to render\n -> Double -- ^ @offsetX@ - the offset in the X direction (currently\n -- rounded to an integer)\n -> Double -- ^ @offsetY@ - the offset in the Y direction \n -- (currently rounded to an integer)\n -> Double -- ^ @scaleX@ - the scale factor in the X direction\n -> Double -- ^ @scaleY@ - the scale factor in the Y direction\n -> InterpType -- ^ the interpolation type for the transformation.\n -> Word8 \t-- ^ @alpha@ - the transparency\n -> IO ()\npixbufComposite src dest destX destY destWidth destHeight\n offsetX offsetY scaleX scaleY interp alpha =\n {#call unsafe pixbuf_composite#} src dest\n (fromIntegral destX) (fromIntegral destY) (fromIntegral destWidth)\n (fromIntegral destHeight) (realToFrac offsetX) (realToFrac offsetY)\n (realToFrac scaleX) (realToFrac scaleY)\n ((fromIntegral . fromEnum) interp) (fromIntegral alpha)\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Flips a pixbuf horizontally and returns the result in a new pixbuf.\n--\npixbufFlipHorizontally :: Pixbuf -> IO Pixbuf\npixbufFlipHorizontally self =\n constructNewGObject mkPixbuf $\n {# call pixbuf_flip #}\n self\n (fromBool True)\npixbufFlipHorazontally = pixbufFlipHorizontally\n\n-- | Flips a pixbuf vertically and returns the result in a new pixbuf.\n--\npixbufFlipVertically :: Pixbuf -> IO Pixbuf\npixbufFlipVertically self =\n constructNewGObject mkPixbuf $\n {# call pixbuf_flip #}\n self\n (fromBool False)\n\n-- | Rotates a pixbuf by a multiple of 90 degrees, and returns the result in a\n-- new pixbuf.\n--\npixbufRotateSimple :: Pixbuf -> PixbufRotation -> IO Pixbuf\npixbufRotateSimple self angle =\n constructNewGObject mkPixbuf $\n {# call pixbuf_rotate_simple #}\n self\n ((fromIntegral . fromEnum) angle)\n\n-- | The possible rotations which can be passed to 'pixbufRotateSimple'.\n--\n-- To make them easier to use, their numerical values are the actual degrees.\n--\n{#enum PixbufRotation {underscoreToCase} #}\n#endif\n\n-- | Add an opacity layer to the 'Pixbuf'.\n--\n-- * This function returns a copy of the given @src@\n-- 'Pixbuf', leaving @src@ unmodified.\n-- The new 'Pixbuf' has an alpha (opacity)\n-- channel which defaults to @255@ (fully opaque pixels)\n-- unless @src@ already had an alpha channel in which case\n-- the original values are kept.\n-- Passing in a color triple @(r,g,b)@ makes all\n-- pixels that have this color fully transparent\n-- (opacity of @0@). The pixel color itself remains unchanged\n-- during this substitution.\n--\npixbufAddAlpha :: Pixbuf -> Maybe (Word8, Word8, Word8) -> IO Pixbuf\npixbufAddAlpha pb Nothing = constructNewGObject mkPixbuf $\n {#call unsafe pixbuf_add_alpha#} pb (fromBool False) 0 0 0\npixbufAddAlpha pb (Just (r,g,b)) = constructNewGObject mkPixbuf $\n {#call unsafe pixbuf_add_alpha#} pb (fromBool True)\n (fromIntegral r) (fromIntegral g) (fromIntegral b)\n\n-- | Copy a rectangular portion into another 'Pixbuf'.\n--\n-- The source 'Pixbuf' remains unchanged. Converion between\n-- different formats is done automatically.\n--\npixbufCopyArea ::\n Pixbuf -- ^ Source pixbuf\n -> Int -- ^ Source X coordinate within the source pixbuf\n -> Int -- ^ Source Y coordinate within the source pixbuf\n -> Int -- ^ Width of the area to copy\n -> Int -- ^ Height of the area to copy\n -> Pixbuf -- ^ Destination pixbuf\n -> Int -- ^ X coordinate within the destination pixbuf\n -> Int -- ^ Y coordinate within the destination pixbuf\n -> IO ()\npixbufCopyArea src srcX srcY srcWidth srcHeight dest destX destY =\n {#call unsafe pixbuf_copy_area#} src\n (fromIntegral srcX) (fromIntegral srcY)\n (fromIntegral srcWidth) (fromIntegral srcHeight)\n dest (fromIntegral destX) (fromIntegral destY)\n\n-- | Fills a 'Pixbuf' with a color.\n--\n-- * The passed-in color is a quadruple consisting of the red, green, blue\n-- and alpha component of the pixel. If the 'Pixbuf' does not\n-- have an alpha channel, the alpha value is ignored.\n--\npixbufFill :: Pixbuf -> Word8 -> Word8 -> Word8 -> Word8 -> IO ()\npixbufFill pb red green blue alpha = {#call unsafe pixbuf_fill#} pb\n ((fromIntegral red) `shiftL` 24 .|.\n (fromIntegral green) `shiftL` 16 .|.\n (fromIntegral blue) `shiftL` 8 .|.\n (fromIntegral alpha))\n\n-- | Take a screenshot of a 'Drawable'.\n--\n-- * This function creates a 'Pixbuf' and fills it with the image\n-- currently in the 'Drawable' (which might be invalid if the\n-- window is obscured or minimized). Note that this transfers data from\n-- the server to the client on X Windows.\n--\n-- * This function will return a 'Pixbuf' with no alpha channel\n-- containing the part of the 'Drawable' specified by the\n-- rectangle. The function will return @Nothing@ if the window\n-- is not currently visible.\n--\npixbufGetFromDrawable :: DrawableClass d => d -> Rectangle -> IO (Maybe Pixbuf)\npixbufGetFromDrawable d (Rectangle x y width height) =\n maybeNull (constructNewGObject mkPixbuf) $\n {#call unsafe pixbuf_get_from_drawable#}\n (Pixbuf nullForeignPtr) (toDrawable d) (Colormap nullForeignPtr)\n (fromIntegral x) (fromIntegral y) 0 0\n (fromIntegral width) (fromIntegral height)\n\n\n\n-- | Takes the opacity values in a rectangular portion of a pixbuf and\n-- thresholds them to produce a bi-level alpha mask that can be used\n-- as a clipping mask for a drawable.\npixbufRenderThresholdAlpha ::\n Pixbuf -- ^ A pixbuf.\n -> Bitmap -- ^ Bitmap where the bilevel mask will be painted to.\n -> Int -- ^ Source X coordinate.\n -> Int -- ^ source Y coordinate.\n -> Int -- ^ Destination X coordinate.\n -> Int -- ^ Destination Y coordinate.\n -> Int -- ^ Width of region to threshold, or -1 to use pixbuf width\n -> Int -- ^ Height of region to threshold, or -1 to use pixbuf height\n -> Int -- ^ Opacity values below this will be painted as zero; all other values will be painted as one.\n -> IO ()\npixbufRenderThresholdAlpha src dest srcX srcY destX destY w h at =\n withForeignPtr (unPixmap dest) $ \\destPtr ->\n {#call unsafe pixbuf_render_threshold_alpha#} src\n (castPtr destPtr)\n (fromIntegral srcX)\n (fromIntegral srcY)\n (fromIntegral destX)\n (fromIntegral destY)\n (fromIntegral w)\n (fromIntegral h)\n (fromIntegral at)\n\n\n\n\n\n-- | Creates a pixmap and a mask bitmap which are returned and renders\n-- a pixbuf and its corresponding thresholded alpha mask to them. This\n-- is merely a convenience function; applications that need to render\n-- pixbufs with dither offsets or to given drawables should use\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawPixbuf', and\n-- 'pixbufRenderThresholdAlpha'.\n--\n-- The pixmap that is created uses the 'Colormap' specified by\n-- colormap. This colormap must match the colormap of the window where\n-- the pixmap will eventually be used or an error will result.\n--\n-- If the pixbuf does not have an alpha channel, then the returned\n-- mask will be @Nothing@.\n--\npixbufRenderPixmapAndMaskForColormap ::\n Pixbuf -- ^ A pixbuf.\n -> Colormap -- ^ A Colormap\n -> Int -- ^ Threshold value for opacity values\n -> IO (Pixmap, Maybe Bitmap) -- ^ (Created pixmap, created mask)\npixbufRenderPixmapAndMaskForColormap pixbuf colormap threshold =\n alloca $ \\pmRetPtr ->\n alloca $ \\bmRetPtr -> do\n {#call unsafe pixbuf_render_pixmap_and_mask_for_colormap#} pixbuf\n colormap\n (castPtr pmRetPtr) -- seems to reject Pixmap**, so cast\n (castPtr bmRetPtr)\n (fromIntegral threshold)\n pm <- constructNewGObject mkPixmap (peek pmRetPtr :: IO (Ptr Pixmap))\n bm <- maybeNull (constructNewGObject mkPixmap) (peek bmRetPtr :: IO (Ptr Bitmap))\n return (pm, bm)\n\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Pixbuf\n--\n-- Author : Vincenzo Ciancia, Axel Simon\n--\n-- Created: 26 March 2002\n--\n-- Copyright (C) 2002-2005 Axel Simon, Vincenzo Ciancia\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- TODO\n--\n-- if anybody writes an image manipulation program, do the checker board\n-- functions: gdk_pixbuf_composite_color_simple and\n-- gdk_pixbuf_composite_color. Moreover, do: pixbuf_saturate_and_pixelate\n--\n--\n-- pixbuf loader\n--\n-- module interface\n--\n-- rendering function for Bitmaps and Pixmaps when the latter are added\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- 'Pixbuf's are bitmap images in memory.\n--\n-- * A Pixbuf is used to represent images. It contains information\n-- about the image's pixel data, its color space, bits per sample, width\n-- and height, and the rowstride or number of bytes between rows.\n--\n-- * This module contains functions to scale and crop\n-- 'Pixbuf's and to scale and crop a 'Pixbuf' and\n-- compose the result with an existing image.\n--\n-- * 'Pixbuf's can be displayed on screen by either creating an 'Image' that\n-- from the 'Pixbuf' or by rendering (part of) the 'Pixbuf' into a\n-- vanilla widget like 'DrawWindow' using\n-- 'Graphics.UI.Gtk.Gdk.Drawable.drawPixbuf'.\n--\nmodule Graphics.UI.Gtk.Gdk.Pixbuf (\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----Pixbuf\n-- @\n\n-- * Types\n Pixbuf,\n PixbufClass,\n castToPixbuf, gTypePixbuf,\n toPixbuf,\n PixbufError(..),\n Colorspace(..),\n\n-- * Constructors\n pixbufNew,\n pixbufNewFromFile,\n#if GTK_CHECK_VERSION(2,4,0)\n pixbufNewFromFileAtSize,\n#endif\n#if GTK_CHECK_VERSION(2,6,0)\n pixbufNewFromFileAtScale,\n#endif\n pixbufNewFromInline,\n InlineImage,\n pixbufNewSubpixbuf,\n pixbufNewFromXPMData,\n\n-- * Methods\n pixbufGetColorSpace,\n pixbufGetNChannels,\n pixbufGetHasAlpha,\n pixbufGetBitsPerSample,\n PixbufData,\n pixbufGetPixels,\n pixbufGetWidth,\n pixbufGetHeight,\n pixbufGetRowstride,\n pixbufGetOption,\n ImageFormat,\n pixbufGetFormats,\n pixbufSave,\n pixbufCopy,\n InterpType(..),\n pixbufScaleSimple,\n pixbufScale,\n pixbufComposite,\n#if GTK_CHECK_VERSION(2,6,0)\n pixbufFlipHorizontally,\n pixbufFlipHorazontally,\n pixbufFlipVertically,\n pixbufRotateSimple,\n PixbufRotation(..),\n#endif\n pixbufAddAlpha,\n pixbufCopyArea,\n pixbufFill,\n pixbufGetFromDrawable\n ) where\n\nimport Control.Monad (liftM)\nimport Data.Ix\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GDateTime\nimport System.Glib.GObject\n{#import Graphics.UI.Gtk.Types#}\nimport Graphics.UI.Gtk.General.Structs\t\t(Rectangle(..))\nimport System.Glib.GError\t(GError(..), GErrorClass(..), GErrorDomain,\n\t\t\t\tpropagateGError)\nimport Graphics.UI.Gtk.Gdk.PixbufData ( PixbufData, mkPixbufData )\n\n{# context prefix=\"gdk\" #}\n\n-- | Error codes for loading image files.\n--\n{#enum PixbufError {underscoreToCase} #}\n\n-- | Enumerate all supported color spaces.\n--\n-- * Only RGB is supported right now.\n--\n{#enum Colorspace {underscoreToCase} #}\n\n-- | Queries the color space of a pixbuf.\n--\npixbufGetColorSpace :: Pixbuf -> IO Colorspace\npixbufGetColorSpace pb = liftM (toEnum . fromIntegral) $\n {#call unsafe pixbuf_get_colorspace#} pb\n\n-- | Queries the number of colors for each pixel.\n--\n-- * This function returns 3 for an RGB image without alpha (transparency)\n-- channel, 4 for an RGB image with alpha channel.\n--\npixbufGetNChannels :: Pixbuf -> IO Int\npixbufGetNChannels pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_n_channels#} pb\n\n-- | Query if the image has an alpha channel.\n--\n-- * The alpha channel determines the opaqueness of the pixel.\n--\npixbufGetHasAlpha :: Pixbuf -> IO Bool\npixbufGetHasAlpha pb =\n liftM toBool $ {#call unsafe pixbuf_get_has_alpha#} pb\n\n-- | Queries the number of bits for each color.\n--\n-- * Each pixel is has a number of cannels for each pixel, each channel\n-- has this many bits.\n--\npixbufGetBitsPerSample :: Pixbuf -> IO Int\npixbufGetBitsPerSample pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_bits_per_sample#} pb\n\n-- | Retrieve the internal array of raw image data.\n--\n-- * Image data in a pixbuf is stored in memory in uncompressed,\n-- packed format. Rows in the image are stored top to bottom, and in each\n-- row pixels are stored from left to right. There may be padding at the\n-- end of a row. The \"rowstride\" value of a pixbuf, as returned by\n-- 'pixbufGetRowstride', indicates the number of bytes between rows.\n--\n-- * The returned array is a flat representation of a three dimensional\n-- array: x-coordiante, y-coordinate and several channels for each color.\n-- The number of channels is usually 3 for plain RGB data or 4 for\n-- RGB data with an alpha channel. To read or write a specific pixel\n-- use the formula: @p = y * rowstride + x * nChannels@ for the pixel.\n-- If the array contains bytes (or 'Word8's), @p+0@ is the red value,\n-- @p+1@ green, @p+2@ blue and @p+3@ the alpha (transparency) channel\n-- if present. If the alpha channel is present, the array can accessed\n-- as an array over 'Word32' to modify a whole pixel at a time. See also\n-- 'pixbufGetBitsPerSample' and 'pixbufGetNChannels'.\n--\n-- * Calling this function without explicitly giving it a type will often\n-- lead to a compiler error since the type parameter @e@ is underspecified.\n-- If this happens the function can be explicitly typed:\n-- @pbData <- (pixbufGetPixels pb :: IO (PixbufData Int Word8))@\n--\n-- * If modifying an image through Haskell\\'s array interface is not\n-- fast enough, it is possible to use 'unsafeRead' and\n-- 'unsafeWrite' which have the same type signatures\n-- as 'readArray' and 'writeArray'.\n-- Note that these are internal\n-- functions that might change with GHC.\n--\npixbufGetPixels :: Storable e => Pixbuf -> IO (PixbufData Int e)\npixbufGetPixels pb = do\n pixPtr_ <- {#call unsafe pixbuf_get_pixels#} pb\n chan <- pixbufGetNChannels pb\n bits <- pixbufGetBitsPerSample pb\n w <- pixbufGetWidth pb\n h <- pixbufGetHeight pb\n r <- pixbufGetRowstride pb\n let pixPtr = castPtr pixPtr_\n let bytes = (h-1)*r+w*((chan*bits+7) `div` 8)\n return (mkPixbufData pb pixPtr bytes)\n\n-- | Queries the width of this image.\n--\npixbufGetWidth :: Pixbuf -> IO Int\npixbufGetWidth pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_width#} pb\n\n-- | Queries the height of this image.\n--\npixbufGetHeight :: Pixbuf -> IO Int\npixbufGetHeight pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_height#} pb\n\n-- | Queries the rowstride of this image.\n--\n-- * Queries the rowstride of a pixbuf, which is the number of bytes between\n-- rows. Use this value to caculate the offset to a certain row.\n--\npixbufGetRowstride :: Pixbuf -> IO Int\npixbufGetRowstride pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_rowstride#} pb\n\n-- | Returns an attribut of an image.\n--\n-- * Looks up if some information was stored under the @key@ when\n-- this image was saved.\n--\npixbufGetOption :: Pixbuf -> String -> IO (Maybe String)\npixbufGetOption pb key = withUTFString key $ \\strPtr -> do\n resPtr <- {#call unsafe pixbuf_get_option#} pb strPtr\n if (resPtr==nullPtr) then return Nothing else\n liftM Just $ peekUTFString resPtr\n\n-- helper functions\npixbufErrorDomain :: GErrorDomain\npixbufErrorDomain = {#call pure unsafe pixbuf_error_quark#}\n\ninstance GErrorClass PixbufError where\n gerrorDomain _ = pixbufErrorDomain\n\n\n-- | Load an image synchonously.\n--\n-- * Use this function to load only small images as this call will block.\n--\n-- * If an error occurs, the function will throw an exception that can\n-- be caught using e.g. 'System.Glib.GError.catchGErrorJust' and one of the\n-- error codes in 'PixbufError'.\n--\npixbufNewFromFile :: FilePath -> IO Pixbuf\npixbufNewFromFile fname =\n constructNewGObject mkPixbuf $\n propagateGError $ \\errPtrPtr ->\n withUTFString fname $ \\strPtr ->\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,0)\n {#call unsafe pixbuf_new_from_file_utf8#}\n#else\n {#call unsafe pixbuf_new_from_file#}\n#endif\n strPtr errPtrPtr\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Creates a new pixbuf by loading an image from a file. The file format is\n-- detected automatically. The image will be scaled to fit in the requested\n-- size, preserving the image's aspect ratio.\n--\n-- * If an error occurs, the function will throw an exception that can\n-- be caught using e.g. 'System.Glib.GError.catchGErrorJust' and one of the\n-- error codes in 'PixbufError'.\n--\n-- * Available since Gtk+ version 2.4\n--\npixbufNewFromFileAtSize :: String -> Int -> Int -> IO Pixbuf\npixbufNewFromFileAtSize filename width height =\n constructNewGObject mkPixbuf $\n propagateGError $ \\errPtrPtr ->\n withUTFString filename $ \\filenamePtr ->\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,0)\n {# call gdk_pixbuf_new_from_file_at_size_utf8 #}\n#else\n {# call gdk_pixbuf_new_from_file_at_size #}\n#endif\n filenamePtr\n (fromIntegral width)\n (fromIntegral height)\n errPtrPtr\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Creates a new pixbuf by loading an image from a file. The file format is\n-- detected automatically. The image will be scaled to fit in the requested\n-- size, optionally preserving the image's aspect ratio.\n--\n-- When preserving the aspect ratio, a width of -1 will cause the image to be\n-- scaled to the exact given height, and a height of -1 will cause the image to\n-- be scaled to the exact given width. When not preserving aspect ratio, a width\n-- or height of -1 means to not scale the image at all in that dimension.\n-- Negative values for width and height are allowed since Gtk+ 2.8.\n--\n-- * If an error occurs, the function will throw an exception that can\n-- be caught using e.g. 'System.Glib.GError.catchGErrorJust' and one of the\n-- error codes in 'PixbufError'.\n--\n-- * Available since Gtk+ version 2.6\n--\npixbufNewFromFileAtScale ::\n String -- ^ the name of the file\n -> Int -- ^ target width\n -> Int -- ^ target height\n -> Bool -- ^ whether to preserve the aspect ratio\n -> IO Pixbuf\npixbufNewFromFileAtScale filename width height preserveAspectRatio =\n constructNewGObject mkPixbuf $\n propagateGError $ \\errPtrPtr ->\n withUTFString filename $ \\filenamePtr ->\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,0)\n {# call gdk_pixbuf_new_from_file_at_scale_utf8 #}\n#else\n {# call gdk_pixbuf_new_from_file_at_scale #}\n#endif\n filenamePtr\n (fromIntegral width)\n (fromIntegral height)\n (fromBool preserveAspectRatio)\n errPtrPtr\n#endif\n\n-- | A string representing an image file format.\n--\ntype ImageFormat = String\n\n-- constant pixbufGetFormats A list of valid image file formats.\n--\npixbufGetFormats :: [ImageFormat]\n\npixbufGetFormats = [\"png\",\"bmp\",\"wbmp\", \"gif\",\"ico\",\"ani\",\"jpeg\",\"pnm\",\n\t\t \"ras\",\"tiff\",\"xpm\",\"xbm\",\"tga\"]\n\n-- | Save an image to disk.\n--\n-- * The function takes a list of key - value pairs to specify\n-- either how an image is saved or to actually save this additional\n-- data with the image. JPEG images can be saved with a \\\"quality\\\"\n-- parameter; its value should be in the range [0,100]. Text chunks\n-- can be attached to PNG images by specifying parameters of the form\n-- \\\"tEXt::key\\\", where key is an ASCII string of length 1-79.\n-- The values are Unicode strings.\n--\n-- * If an error occurs, the function will throw an exception that can\n-- be caught using e.g. 'System.Glib.GError.catchGErrorJust' and one of the\n-- error codes in 'PixbufError'.\n--\npixbufSave :: Pixbuf -> FilePath -> ImageFormat -> [(String, String)] ->\n\t IO ()\npixbufSave pb fname iType options =\n let (keys, values) = unzip options in\n let optLen = length keys in\n propagateGError $ \\errPtrPtr ->\n withUTFString fname $ \\fnPtr ->\n withUTFString iType $ \\tyPtr ->\n withUTFStringArray0 keys $ \\keysPtr ->\n withUTFStringArray values $ \\valuesPtr -> do\n#if defined (WIN32) && GTK_CHECK_VERSION(2,6,5)\n {# call unsafe pixbuf_savev_utf8 #}\n#else\n {# call unsafe pixbuf_savev #}\n#endif\n pb fnPtr tyPtr keysPtr valuesPtr errPtrPtr\n return ()\n\n-- | Create a new image in memory.\n--\n-- * Creates a new pixbuf structure and allocates a buffer for\n-- it. Note that the buffer is not cleared initially.\n--\n-- * The boolean flag is true if the pixbuf should have an alpha\n-- (transparency) channel. The next integer denotes the bits per\n-- color sample, e.g. 8 bits per color for 2^24 colors. The last\n-- two integers denote the width and height, respectively.\n--\npixbufNew :: Colorspace -> Bool -> Int -> Int -> Int -> IO Pixbuf\npixbufNew colorspace hasAlpha bitsPerSample width height =\n constructNewGObject mkPixbuf $\n {#call pixbuf_new#} ((fromIntegral . fromEnum) colorspace)\n (fromBool hasAlpha) (fromIntegral bitsPerSample) (fromIntegral width)\n (fromIntegral height)\n\n-- | Create a new image from a String.\n--\n-- * Creates a new pixbuf from a string description.\n--\npixbufNewFromXPMData :: [String] -> IO Pixbuf\npixbufNewFromXPMData s =\n withUTFStringArray0 s $ \\strsPtr ->\n constructNewGObject mkPixbuf $ {#call pixbuf_new_from_xpm_data#} strsPtr\n\n-- | A dymmy type for inline picture data.\n--\n-- * This dummy type is used to declare pointers to image data\n-- that is embedded in the executable. See\n-- 'pixbufNewFromInline' for an example.\n--\ndata InlineImage = InlineImage\n\n-- | Create a new image from a static pointer.\n--\n-- * Like 'pixbufNewFromXPMData', this function allows to\n-- include images in the final binary program. The method used by this\n-- function uses a binary representation and therefore needs less space\n-- in the final executable. Save the image you want to include as\n-- @png@ and run:\n--\n-- > @echo #include \"my_image.h\" > my_image.c\n-- > gdk-pixbuf-csource --raw --extern --name=my_image myimage.png >> my_image.c\n--\n-- on it. Write a header file @my_image.h@ containing:\n--\n-- > #include \n-- > extern guint8 my_image[];\n--\n-- and save it in the current directory.\n-- The created file can be compiled with: \n--\n-- > cc -c my_image.c `pkg-config --cflags gdk-2.0`\n--\n-- into an object file which must be linked into your Haskell program by\n-- specifying @my_image.o@ and @\\\"-#include my_image.h\\\"@ on\n-- the command line of GHC.\n-- Within you application you delcare a pointer to this image:\n--\n-- > foreign label \"my_image\" myImage :: Ptr InlineImage\n--\n-- Calling 'pixbufNewFromInline' with this pointer will\n-- return the image in the object file. Creating the C file with\n-- the @--raw@ flag will result in a non-compressed image in the\n-- object file. The advantage is that the picture will not be\n-- copied when this function is called.\n--\n--\npixbufNewFromInline :: Ptr InlineImage -> IO Pixbuf\npixbufNewFromInline iPtr = alloca $ \\errPtrPtr -> do\n pbPtr <- {#call unsafe pixbuf_new_from_inline#} (-1) (castPtr iPtr)\n (fromBool False) (castPtr errPtrPtr)\n if pbPtr\/=nullPtr then constructNewGObject mkPixbuf (return pbPtr)\n else do\n errPtr <- peek errPtrPtr\n (GError dom code msg) <- peek errPtr\n error msg\n\n-- | Create a restricted view of an image.\n--\n-- * This function returns a 'Pixbuf' object which shares\n-- the image of the original one but only shows a part of it.\n-- Modifying either buffer will affect the other.\n--\n-- * This function throw an exception if the requested bounds are invalid.\n--\npixbufNewSubpixbuf :: Pixbuf -> Int -> Int -> Int -> Int -> IO Pixbuf\npixbufNewSubpixbuf pb srcX srcY height width =\n constructNewGObject mkPixbuf $ do\n pbPtr <- {#call unsafe pixbuf_new_subpixbuf#} pb\n (fromIntegral srcX) (fromIntegral srcY)\n (fromIntegral height) (fromIntegral width)\n if pbPtr==nullPtr then error \"pixbufNewSubpixbuf: invalid bounds\"\n else return pbPtr\n\n-- | Create a deep copy of an image.\n--\npixbufCopy :: Pixbuf -> IO Pixbuf\npixbufCopy pb = constructNewGObject mkPixbuf $ {#call unsafe pixbuf_copy#} pb\n\n\n-- | How an image is scaled.\n--\n-- [@InterpNearest@] Nearest neighbor sampling; this is the\n-- fastest and lowest quality mode. Quality is normally unacceptable when\n-- scaling down, but may be OK when scaling up.\n--\n-- [@InterpTiles@] This is an accurate simulation of the\n-- PostScript image operator without any interpolation enabled. Each\n-- pixel is rendered as a tiny parallelogram of solid color, the edges of\n-- which are implemented with antialiasing. It resembles nearest neighbor\n-- for enlargement, and bilinear for reduction.\n--\n-- [@InterpBilinear@] Best quality\\\/speed balance; use this\n-- mode by default. Bilinear interpolation. For enlargement, it is\n-- equivalent to point-sampling the ideal bilinear-interpolated\n-- image. For reduction, it is equivalent to laying down small tiles and\n-- integrating over the coverage area.\n--\n-- [@InterpHyper@] This is the slowest and highest quality\n-- reconstruction function. It is derived from the hyperbolic filters in\n-- Wolberg's \\\"Digital Image Warping\\\", and is formally defined as the\n-- hyperbolic-filter sampling the ideal hyperbolic-filter interpolated\n-- image (the filter is designed to be idempotent for 1:1 pixel mapping).\n--\n{#enum InterpType {underscoreToCase} #}\n\n-- | Scale an image.\n--\n-- * Creates a new 'Pixbuf' containing a copy of \n-- @src@ scaled to the given measures. Leaves @src@\n-- unaffected. \n--\n-- * @interp@ affects the quality and speed of the scaling function.\n-- 'InterpNearest' is the fastest option but yields very poor quality\n-- when scaling down. 'InterpBilinear' is a good trade-off between\n-- speed and quality and should thus be used as a default.\n--\npixbufScaleSimple :: \n Pixbuf -- ^ @src@ - the source image\n -> Int -- ^ @width@ - the target width\n -> Int -- ^ @height@ the target height\n -> InterpType -- ^ interpolation type\n -> IO Pixbuf\npixbufScaleSimple pb width height interp =\n constructNewGObject mkPixbuf $ liftM castPtr $\n\t{#call pixbuf_scale_simple#} (toPixbuf pb)\n\t(fromIntegral width) (fromIntegral height)\n\t(fromIntegral $ fromEnum interp)\n\n-- | Copy a scaled image part to another image.\n--\n-- * This function is the generic version of 'pixbufScaleSimple'. It scales\n-- @src@ by @scaleX@ and @scaleY@ and translate the image by @offsetX@ and\n-- @offsetY@. Whatever is in the intersection with the rectangle @destX@,\n-- @destY@, @destWidth@, @destHeight@ will be rendered into @dest@.\n--\n-- * The rectangle in the destination is simply overwritten. Use\n-- 'pixbufComposite' if you need to blend the source image onto the\n-- destination.\n--\npixbufScale :: \n Pixbuf -- ^ @src@ - the source pixbuf\n -> Pixbuf -- ^ @dest@ - the pixbuf into which to render the results\n -> Int -- ^ @destX@ - the left coordinate for region to render\n -> Int -- ^ @destY@ - the top coordinate for region to render \n -> Int -- ^ @destWidth@ - the width of the region to render\n -> Int -- ^ @destHeight@ - the height of the region to render\n -> Double -- ^ @offsetX@ - the offset in the X direction (currently\n -- rounded to an integer)\n -> Double -- ^ @offsetY@ - the offset in the Y direction \n -- (currently rounded to an integer)\n -> Double -- ^ @scaleX@ - the scale factor in the X direction\n -> Double -- ^ @scaleY@ - the scale factor in the Y direction\n -> InterpType -- ^ the interpolation type for the transformation.\n -> IO ()\npixbufScale src dest destX destY destWidth destHeight offsetX offsetY\n scaleX scaleY interp =\n {#call unsafe pixbuf_scale#} src dest\n (fromIntegral destX) (fromIntegral destY)\n (fromIntegral destWidth) (fromIntegral destHeight)\n (realToFrac offsetX) (realToFrac offsetY)\n (realToFrac scaleX) (realToFrac scaleY)\n ((fromIntegral . fromEnum) interp)\n\n-- | Blend a scaled image part onto another image.\n--\n-- * This function is similar to 'pixbufScale' but allows the\n-- original image to \\\"shine through\\\". The @alpha@ value determines\n-- how opaque the source image is. Passing @0@ is\n-- equivalent to not calling this function at all, passing\n-- @255@ has the\n-- same effect as calling 'pixbufScale'.\n--\npixbufComposite ::\n Pixbuf -- ^ @src@ - the source pixbuf\n -> Pixbuf -- ^ @dest@ - the pixbuf into which to render the results\n -> Int -- ^ @destX@ - the left coordinate for region to render\n -> Int -- ^ @destY@ - the top coordinate for region to render \n -> Int -- ^ @destWidth@ - the width of the region to render\n -> Int -- ^ @destHeight@ - the height of the region to render\n -> Double -- ^ @offsetX@ - the offset in the X direction (currently\n -- rounded to an integer)\n -> Double -- ^ @offsetY@ - the offset in the Y direction \n -- (currently rounded to an integer)\n -> Double -- ^ @scaleX@ - the scale factor in the X direction\n -> Double -- ^ @scaleY@ - the scale factor in the Y direction\n -> InterpType -- ^ the interpolation type for the transformation.\n -> Word8 \t-- ^ @alpha@ - the transparency\n -> IO ()\npixbufComposite src dest destX destY destWidth destHeight\n offsetX offsetY scaleX scaleY interp alpha =\n {#call unsafe pixbuf_composite#} src dest\n (fromIntegral destX) (fromIntegral destY) (fromIntegral destWidth)\n (fromIntegral destHeight) (realToFrac offsetX) (realToFrac offsetY)\n (realToFrac scaleX) (realToFrac scaleY)\n ((fromIntegral . fromEnum) interp) (fromIntegral alpha)\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Flips a pixbuf horizontally and returns the result in a new pixbuf.\n--\npixbufFlipHorizontally :: Pixbuf -> IO Pixbuf\npixbufFlipHorizontally self =\n constructNewGObject mkPixbuf $\n {# call pixbuf_flip #}\n self\n (fromBool True)\npixbufFlipHorazontally = pixbufFlipHorizontally\n\n-- | Flips a pixbuf vertically and returns the result in a new pixbuf.\n--\npixbufFlipVertically :: Pixbuf -> IO Pixbuf\npixbufFlipVertically self =\n constructNewGObject mkPixbuf $\n {# call pixbuf_flip #}\n self\n (fromBool False)\n\n-- | Rotates a pixbuf by a multiple of 90 degrees, and returns the result in a\n-- new pixbuf.\n--\npixbufRotateSimple :: Pixbuf -> PixbufRotation -> IO Pixbuf\npixbufRotateSimple self angle =\n constructNewGObject mkPixbuf $\n {# call pixbuf_rotate_simple #}\n self\n ((fromIntegral . fromEnum) angle)\n\n-- | The possible rotations which can be passed to 'pixbufRotateSimple'.\n--\n-- To make them easier to use, their numerical values are the actual degrees.\n--\n{#enum PixbufRotation {underscoreToCase} #}\n#endif\n\n-- | Add an opacity layer to the 'Pixbuf'.\n--\n-- * This function returns a copy of the given @src@\n-- 'Pixbuf', leaving @src@ unmodified.\n-- The new 'Pixbuf' has an alpha (opacity)\n-- channel which defaults to @255@ (fully opaque pixels)\n-- unless @src@ already had an alpha channel in which case\n-- the original values are kept.\n-- Passing in a color triple @(r,g,b)@ makes all\n-- pixels that have this color fully transparent\n-- (opacity of @0@). The pixel color itself remains unchanged\n-- during this substitution.\n--\npixbufAddAlpha :: Pixbuf -> Maybe (Word8, Word8, Word8) -> IO Pixbuf\npixbufAddAlpha pb Nothing = constructNewGObject mkPixbuf $\n {#call unsafe pixbuf_add_alpha#} pb (fromBool False) 0 0 0\npixbufAddAlpha pb (Just (r,g,b)) = constructNewGObject mkPixbuf $\n {#call unsafe pixbuf_add_alpha#} pb (fromBool True)\n (fromIntegral r) (fromIntegral g) (fromIntegral b)\n\n-- | Copy a rectangular portion into another 'Pixbuf'.\n--\n-- The source 'Pixbuf' remains unchanged. Converion between\n-- different formats is done automatically.\n--\npixbufCopyArea ::\n Pixbuf -- ^ Source pixbuf\n -> Int -- ^ Source X coordinate within the source pixbuf\n -> Int -- ^ Source Y coordinate within the source pixbuf\n -> Int -- ^ Width of the area to copy\n -> Int -- ^ Height of the area to copy\n -> Pixbuf -- ^ Destination pixbuf\n -> Int -- ^ X coordinate within the destination pixbuf\n -> Int -- ^ Y coordinate within the destination pixbuf\n -> IO ()\npixbufCopyArea src srcX srcY srcWidth srcHeight dest destX destY =\n {#call unsafe pixbuf_copy_area#} src\n (fromIntegral srcX) (fromIntegral srcY)\n (fromIntegral srcWidth) (fromIntegral srcHeight)\n dest (fromIntegral destX) (fromIntegral destY)\n\n-- | Fills a 'Pixbuf' with a color.\n--\n-- * The passed-in color is a quadruple consisting of the red, green, blue\n-- and alpha component of the pixel. If the 'Pixbuf' does not\n-- have an alpha channel, the alpha value is ignored.\n--\npixbufFill :: Pixbuf -> Word8 -> Word8 -> Word8 -> Word8 -> IO ()\npixbufFill pb red green blue alpha = {#call unsafe pixbuf_fill#} pb\n ((fromIntegral red) `shiftL` 24 .|.\n (fromIntegral green) `shiftL` 16 .|.\n (fromIntegral blue) `shiftL` 8 .|.\n (fromIntegral alpha))\n\n-- | Take a screenshot of a 'Drawable'.\n--\n-- * This function creates a 'Pixbuf' and fills it with the image\n-- currently in the 'Drawable' (which might be invalid if the\n-- window is obscured or minimized). Note that this transfers data from\n-- the server to the client on X Windows.\n--\n-- * This function will return a 'Pixbuf' with no alpha channel\n-- containing the part of the 'Drawable' specified by the\n-- rectangle. The function will return @Nothing@ if the window\n-- is not currently visible.\n--\npixbufGetFromDrawable :: DrawableClass d => d -> Rectangle -> IO (Maybe Pixbuf)\npixbufGetFromDrawable d (Rectangle x y width height) =\n maybeNull (constructNewGObject mkPixbuf) $\n {#call unsafe pixbuf_get_from_drawable#}\n (Pixbuf nullForeignPtr) (toDrawable d) (Colormap nullForeignPtr)\n (fromIntegral x) (fromIntegral y) 0 0\n (fromIntegral width) (fromIntegral height)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"aee94ed6b4a5126665465fe27740e04c38a2e39e","subject":"Added loadImage8 and loadColorImage8 functions for loading 8-bit images","message":"Added loadImage8 and loadColorImage8 functions for loading 8-bit images\n","repos":"TomMD\/CV,aleator\/CV,aleator\/CV,BeautifulDestinations\/CV","old_file":"CV\/Image.chs","new_file":"CV\/Image.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns,ParallelListComp, FlexibleInstances, FlexibleContexts, TypeFamilies, EmptyDataDecls, ScopedTypeVariables, StandaloneDeriving #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image where\n\nimport System.Posix.Files\nimport System.Mem\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Utils\nimport Foreign.ForeignPtr hiding (newForeignPtr)\nimport Foreign.Concurrent\nimport Foreign.Ptr\nimport Control.Parallel.Strategies\nimport Control.DeepSeq\n\n-- import C2HSTools\n\nimport Data.Maybe(catMaybes)\nimport Data.List(genericLength)\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.Storable\nimport System.IO.Unsafe\nimport Data.Word\nimport Control.Monad\n\n\n\n-- Colorspaces\ndata GrayScale\ndata RGB\ndata RGB_Channel = Red |\u00a0Green |\u00a0Blue deriving (Eq,Ord,Enum)\ndata RGBA\ndata LAB\ndata LAB_Channel = LAB_L |\u00a0LAB_A |\u00a0LAB_B deriving (Eq,Ord,Enum)\ntype family ChannelOf a :: *\ntype instance ChannelOf RGB_Channel = RGB\ntype instance ChannelOf LAB_Channel = LAB\n\n-- Bit Depths\ntype D8 = Word8\ntype D32 = Float\ntype D64 = Double\n\nnewtype Image channels depth = S BareImage\n\nunS (S i) = i -- Unsafe and ugly\n\nwithImage :: Image c d -> (Ptr BareImage ->IO a) -> IO a\nwithImage (S i) op = withBareImage i op\n--withGenNewImage (S i) op = withGenImage i op\n\n-- Ok. this is just the example why I need image types\nwithUniPtr with x fun = with x $ \\y ->\n fun (castPtr y)\n\nwithGenImage = withUniPtr withImage\nwithGenBareImage = withUniPtr withBareImage\n\n{#pointer *IplImage as BareImage foreign newtype#}\n\nfreeBareImage ptr = with ptr {#call cvReleaseImage#}\n\n--foreign import ccall \"& wrapReleaseImage\" releaseImage :: FinalizerPtr BareImage\n\ninstance NFData (Image a b) where\n rnf a@(S (BareImage fptr)) = (unsafeForeignPtrToPtr) fptr `seq` a `seq` ()-- This might also need peek?\n\n\ncreatingImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . S . BareImage $ fptr\n\ncreatingBareImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . BareImage $ fptr\n\nunImage (S (BareImage fptr)) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\nrgba = undefined :: Tag RGBA\nlab = undefined :: Tag LAB\n\n\ncomposeMultichannelImage :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannelImage (c1)\n (c2)\n (c3)\n (c4)\n totag\n = unsafePerformIO $\u00a0do\n res <- create (size) -- TODO: Check channel count -- This is NOT correct\n withMaybe c1 $ \\cc1 ->\n withMaybe c2 $ \\cc2 ->\n withMaybe c3 $ \\cc3 ->\n withMaybe c4 $ \\cc4 ->\n withGenImage res $ \\cres -> {#call cvMerge#} cc1 cc2 cc3 cc4 cres\n return res\n where\n withMaybe (Just i) op = withGenImage i op\n withMaybe (Nothing) op = op nullPtr\n size = getSize . head . catMaybes $ [c1,c2,c3,c4]\n\n-- Load Image as grayscale image.\n\n--loadImage n = do\n-- exists <- fileExist n\n-- if not exists then return Nothing\n-- else do\n-- i <- withCString n $ \\name ->\n-- creatingImage ({#call cvLoadImage #} name (0))\n-- bw <- imageTo32F i\n-- return $ Just bw\n\nclass Loadable a where\n readFromFile :: FilePath -> IO a\n\n\ninstance Loadable ((Image GrayScale D32)) where\n readFromFile fp = do\n e <- loadImage fp\n case e of\n Just i -> return i\n Nothing -> fail $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D32)) where\n readFromFile fp = do\n e <- loadColorImage fp\n case e of\n Just i -> return i\n Nothing -> fail $ \"Could not load \"++fp\n\nloadImage :: FilePath -> IO (Maybe (Image GrayScale D32))\nloadImage n = do\n exists <- fileExist n\n if not exists then return Nothing\n else do\n i <- withCString n $ \\name ->\n creatingBareImage ({#call cvLoadImage #} name (0))\n bw <- imageTo32F i\n return . Just .\u00a0S $ bw\n\nloadImage8 :: FilePath -> IO (Maybe (Image GrayScale D8))\nloadImage8 n = do\n exists <- fileExist n\n if not exists then return Nothing\n else do\n i <- withCString n $ \\name ->\n creatingBareImage ({#call cvLoadImage #} name (0))\n bw <- imageTo8Bit i\n return . Just .\u00a0S $ bw\n\nloadColorImage :: FilePath -> IO (Maybe (Image RGB D32))\nloadColorImage n = do\n exists <- fileExist n\n if not exists then return Nothing\n else do\n i <- withCString n $ \\name ->\n creatingBareImage ({#call cvLoadImage #} name 1)\n bw <- imageTo32F i\n return . Just . S $ bw\n\nloadColorImage8 :: FilePath -> IO (Maybe (Image RGB D8))\nloadColorImage8 n = do\n exists <- fileExist n\n if not exists then return Nothing\n else do\n i <- withCString n $ \\name ->\n creatingBareImage ({#call cvLoadImage #} name 1)\n bw <- imageTo8Bit i\n return . Just . S $ bw\n\nclass Sized a where\n type Size a :: *\n getSize :: a -> Size a\n\ninstance Sized BareImage where\n type Size BareImage = (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize image = unsafePerformIO $ withBareImage image $ \\i -> do\n w <- {#call getImageWidth#} i\n h <- {#call getImageHeight#} i\n return (fromIntegral w,fromIntegral h)\n\ninstance Sized (Image c d) where\n type Size (Image c d) = (Int,Int)\n getSize = getSize . unS\n\n\ncvRGBtoGRAY = 7 :: CInt-- NOTE: This will break.\ncvRGBtoLAB = 45 :: CInt-- NOTE: This will break.\n\n\nrgbToLab :: Image RGB D32 -> Image LAB D32\nrgbToLab = S . convertTo cvRGBtoLAB 3 . unS\n\nrgbToGray :: Image RGB D32 -> Image GrayScale D32\nrgbToGray = S . convertTo cvRGBtoGRAY 1 . unS\n\n\nclass GetPixel a where\n type P a :: *\n getPixel :: (Int,Int) -> a -> P a\n\n-- #define FGET(img,x,y) (((float *)((img)->imageData + (y)*(img)->widthStep))[(x)])\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Float))):: Ptr Float)\n\n{-#INLINE getPixelOld#-}\ngetPixelOld (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\n-- #define UGETC(img,color,x,y) (((uint8_t *)((img)->imageData + (y)*(img)->widthStep))[(x)*3+(color)])\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n r <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n b <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ngetPixelOldRGB (fromIntegral -> x, fromIntegral -> y) image\n = unsafePerformIO $ do\n withGenImage image $ \\img -> do\n r <- {#call wrapGet32F2DC#} img y x 0\n g <- {#call wrapGet32F2DC#} img y x 1\n b <- {#call wrapGet32F2DC#} img y x 2\n return (realToFrac r,realToFrac g, realToFrac b)\n\n-- | Perform (a destructive) inplace map of the image. This should be wrapped inside\n-- withClone or an image operation\nmapImageInplace :: (P (Image GrayScale D32) -> P (Image GrayScale D32))\n -> Image GrayScale D32\n -> IO ()\nmapImageInplace f image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let (w,h) = getSize image\n cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n forM_ [(x,y) | x<-[0..w-1], y <- [0..h-1]] $ \\(x,y) ->\u00a0do\n v <- peek (castPtr (d `plusPtr` (y*cs+x*fs)))\n poke (castPtr (d `plusPtr` (y*cs+x*fs))) (f v)\n\n\ninstance GetPixel (Image RGB D8) where\n type P (Image RGB D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n r <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n b <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\n\nconvertTo :: CInt -> CInt -> BareImage -> BareImage\nconvertTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage32F#} w h channels\n withBareImage img $ \\cimg ->\n {#call cvCvtColor#} (castPtr cimg) (castPtr res) code\n return res\n where\n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\nclass CreateImage a where\n create :: (Int,Int) -> IO a\n\n\ninstance CreateImage (Image GrayScale D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 4\n\n\n\nempty :: (CreateImage (Image a b)) => (Int,Int) -> (Image a b)\nempty size = unsafePerformIO $ create size\n\nemptyCopy :: (CreateImage (Image a b)) => Image a b -> IO (Image a b)\nemptyCopy img = create (getSize img)\n\nemptyCopy' :: (CreateImage (Image a b)) => Image a b -> (Image a b)\nemptyCopy' img = unsafePerformIO $ create (getSize img)\n\n-- | Save image. This will convert the image to 8 bit one before saving\nsaveImage :: FilePath -> Image c d -> IO ()\nsaveImage filename image = do\n fpi <- imageTo8Bit $ unS image\n withCString filename $ \\name ->\n withGenBareImage fpi $ \\cvArr ->\n\t\t\t\t\t\t\t alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\n\ngetArea :: (Sized a,Num b, Size a ~ (b,b)) => a -> b\ngetArea = uncurry (*).getSize\n\ngetRegion :: (Int,Int) -> (Int,Int) -> Image c d -> Image c d\ngetRegion (fromIntegral -> x,fromIntegral -> y) (fromIntegral -> w,fromIntegral -> h) image\n | x+w <= width && y+h <= height = S . getRegion' (x,y) (w,h) $ unS image\n | otherwise = error $ \"Region outside image:\"\n ++ show (getSize image) ++\n \"\/\"++show (x+w,y+h)\n where\n (fromIntegral -> width,fromIntegral -> height) = getSize image\n\ngetRegion' (x,y) (w,h) image = unsafePerformIO $\n withBareImage image $ \\i ->\n creatingBareImage ({#call getSubImage#}\n i x y w h)\n\n\n-- | Tile images by overlapping them on a black canvas.\ntileImages image1 image2 (x,y) = unsafePerformIO $\n withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n creatingImage ({#call simpleMergeImages#}\n i1 i2 x y)\n-- | Blit image2 onto image1.\nblitFix = blit\nblit image1 image2 (x,y)\n | badSizes = error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n | otherwise = withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call plainBlit#} i1 i2 (fromIntegral y) (fromIntegral x))\n where\n ((w1,h1),(w2,h2)) = (getSize image1,getSize image2)\n badSizes = x+w2>w1 || y+h2>h1 || x<0 || y<0\n\nblitM :: (CreateImage (Image c d)) => (Int,Int) -> [((Int,Int),Image c d)] -> Image c d\nblitM (rw,rh) imgs = resultPic\n where\n resultPic = unsafePerformIO $ do\n r <- create (fromIntegral rw,fromIntegral rh)\n sequence_ [blit r i (fromIntegral x, fromIntegral y)\n | ((x,y),i) <- imgs ]\n return r\n\n\nsubPixelBlit\n :: Image c d -> Image c d -> (CDouble, CDouble) -> IO ()\n\nsubPixelBlit (image1) (image2) (x,y)\n | badSizes = error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n | otherwise = withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call subpixel_blit#} i1 i2 y x)\n where\n ((w1,h1),(w2,h2)) = (getSize image1,getSize image2)\n badSizes = ceiling x+w2>w1 || ceiling y+h2>h1 ||\u00a0x<0 || y<0\n\nsafeBlit i1 i2 (x,y) = unsafePerformIO $ do\n res <- cloneImage i1-- createImage32F (getSize i1) 1\n blit res i2 (x,y)\n return res\n\n-- | Blit image2 onto image1.\n-- This uses an alpha channel bitmap for determining the regions where the image should be \"blended\" with\n-- the base image.\nblendBlit image1 image1Alpha image2 image2Alpha (x,y) =\n withImage image1 $ \\i1 ->\n withImage image1Alpha $ \\i1a ->\n withImage image2Alpha $ \\i2a ->\n withImage image2 $ \\i2 ->\n ({#call alphaBlit#} i1 i1a i2 i2a x y)\n\n\ncloneImage img = withGenImage img $ \\image ->\n creatingImage ({#call cvCloneImage #} image)\n\nwithClone\n :: Image channels depth\n -> (Image channels depth -> IO ())\n -> IO (Image channels depth)\nwithClone img fun = do\n result <- cloneImage img\n fun result\n return result\n\nwithCloneValue\n :: Image channels depth\n -> (Image channels depth -> IO a)\n -> IO a\nwithCloneValue img fun = do\n result <- cloneImage img\n r <- fun result\n return r\n\nunsafeImageTo32F :: Image c d -> Image c D32\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure32F #} image)\n\nunsafeImageTo8Bit :: Image cspace a -> Image cspace D8\nunsafeImageTo8Bit img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure8U #} image)\n\nimageTo32F img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure32F #} image)\n\nimageTo8Bit img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure8U #} image)\n#c\nenum ImageDepth {\n Depth32F = IPL_DEPTH_32F,\n Depth64F = IPL_DEPTH_64F,\n Depth8U = IPL_DEPTH_8U,\n Depth8S = IPL_DEPTH_8S,\n Depth16U = IPL_DEPTH_16U,\n Depth16S = IPL_DEPTH_16S,\n Depth32S = IPL_DEPTH_32S\n };\n#endc\n\n{#enum ImageDepth {}#}\n\nderiving instance Show ImageDepth\n\ngetImageDepth :: Image c d -> IO ImageDepth\ngetImageDepth i = withImage i $ \\c_img -> {#get IplImage->depth #} c_img >>= return.toEnum.fromIntegral\ngetImageChannels i = withImage i $ \\c_img -> {#get IplImage->nChannels #} c_img\n\ngetImageInfo x = do\n let s = getSize x\n d <- getImageDepth x\n c <- getImageChannels x\n return (s,d,c)\n\n\n-- Manipulating regions of interest:\nsetROI (fromIntegral -> x,fromIntegral -> y)\n (fromIntegral -> w,fromIntegral -> h)\n image = withImage image $ \\i ->\n {#call wrapSetImageROI#} i x y w h\n\nresetROI image = withImage image $ \\i ->\n {#call cvResetImageROI#} i\n\nsetCOI chnl image = withImage image $ \\i ->\n {#call cvSetImageCOI#} i (fromIntegral chnl)\nresetCOI image = withImage image $ \\i ->\n {#call cvSetImageCOI#} i 0\n\n\n-- #TODO: Replace the Int below with proper channel identifier\ngetChannel :: (Enum a) => a -> Image (ChannelOf a) d -> Image GrayScale d\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n setCOI (1+fromEnum no) image\n cres <- {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\n withGenImage image $ \\cimage ->\n {#call cvCopy#} cimage (castPtr cres) (nullPtr)\n resetCOI image\n return cres\n\nwithIOROI pos size image op = do\n setROI pos size image\n x <- op\n resetROI image\n return x\n\nwithROI :: (Int, Int) -> (Int, Int) -> Image c d -> (Image c d -> a) -> a\nwithROI pos size image op = unsafePerformIO $ do\n setROI pos size image\n let x = op image -- BUG\n resetROI image\n return x\n\n\n-- | Manipulate image pixels. This is slow, ugly and should be avoided\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\n{-#INLINE setPixelOld#-}\nsetPixelOld :: (Int,Int) -> D32 -> Image GrayScale D32 -> IO ()\nsetPixelOld (x,y) v image = withGenImage image $ \\img ->\n {#call wrapSet32F2D#} img (fromIntegral y) (fromIntegral x) (realToFrac v)\n\n{-#INLINE setPixel#-}\nsetPixel :: (Int,Int) -> D32 -> Image GrayScale D32 -> IO ()\nsetPixel (x,y) v image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Float))):: Ptr Float)\n v\n\n{-#INLINE setPixel8U#-}\nsetPixel8U :: (Int,Int) -> Word8 -> Image GrayScale D8 -> IO ()\nsetPixel8U (x,y) v image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Word8))):: Ptr Word8)\n v\n\n\ngetAllPixels image = [getPixel (i,j) image\n | i <- [0..width-1 ]\n , j <- [0..height-1]]\n where\n (width,height) = getSize image\n\ngetAllPixelsRowMajor image = [getPixel (i,j) image\n | j <- [0..height-1]\n , i <- [0..width-1]\n ]\n where\n (width,height) = getSize image\n\n-- |Create a montage form given images (u,v) determines the layout and space the spacing\n-- between images. Images are assumed to be the same size (determined by the first image)\nmontage :: (CreateImage (Image c d)) => (Int,Int) -> Int -> [Image c d] -> Image c d\nmontage (u',v') space' imgs\n | u'*v' \/= (length imgs) = error (\"Montage mismatch: \"++show (u,v, length imgs))\n | otherwise = resultPic\n where\n space = fromIntegral space'\n (u,v) = (fromIntegral u', fromIntegral v')\n (rw,rh) = (u*xstep,v*ystep)\n (w,h) = getSize (head imgs)\n (xstep,ystep) = (fromIntegral space + w,fromIntegral space + h)\n edge = space`div`2\n resultPic = unsafePerformIO $ do\n r <- create (rw,rh)\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep)\n | y <- [0..v-1] , x <- [0..u-1]\n | i <- imgs ]\n return r\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns,ParallelListComp, FlexibleInstances, FlexibleContexts, TypeFamilies, EmptyDataDecls, ScopedTypeVariables, StandaloneDeriving #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image where\n\nimport System.Posix.Files\nimport System.Mem\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Utils\nimport Foreign.ForeignPtr hiding (newForeignPtr)\nimport Foreign.Concurrent \nimport Foreign.Ptr\nimport Control.Parallel.Strategies\nimport Control.DeepSeq\n\n-- import C2HSTools\n\nimport Data.Maybe(catMaybes)\nimport Data.List(genericLength)\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.Storable\nimport System.IO.Unsafe\nimport Data.Word\nimport Control.Monad\n\n\n\n-- Colorspaces\ndata GrayScale\ndata RGB\ndata RGB_Channel = Red |\u00a0Green |\u00a0Blue deriving (Eq,Ord,Enum)\ndata RGBA\ndata LAB\ndata LAB_Channel = LAB_L |\u00a0LAB_A |\u00a0LAB_B deriving (Eq,Ord,Enum)\ntype family ChannelOf a :: *\ntype instance ChannelOf RGB_Channel = RGB\ntype instance ChannelOf LAB_Channel = LAB\n\n-- Bit Depths\ntype D8 = Word8\ntype D32 = Float\ntype D64 = Double\n\nnewtype Image channels depth = S BareImage\n\nunS (S i) = i -- Unsafe and ugly\n\nwithImage :: Image c d -> (Ptr BareImage ->IO a) -> IO a\nwithImage (S i) op = withBareImage i op\n--withGenNewImage (S i) op = withGenImage i op \n\n-- Ok. this is just the example why I need image types\nwithUniPtr with x fun = with x $ \\y -> \n fun (castPtr y)\n\nwithGenImage = withUniPtr withImage\nwithGenBareImage = withUniPtr withBareImage\n\n{#pointer *IplImage as BareImage foreign newtype#}\n\nfreeBareImage ptr = with ptr {#call cvReleaseImage#}\n\n--foreign import ccall \"& wrapReleaseImage\" releaseImage :: FinalizerPtr BareImage\n\ninstance NFData (Image a b) where\n rnf a@(S (BareImage fptr)) = (unsafeForeignPtrToPtr) fptr `seq` a `seq` ()-- This might also need peek?\n\n\ncreatingImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr) \n return . S . BareImage $ fptr\n\ncreatingBareImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . BareImage $ fptr\n\nunImage (S (BareImage fptr)) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\nrgba = undefined :: Tag RGBA\nlab = undefined :: Tag LAB\n\n\ncomposeMultichannelImage :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannelImage (c1) \n (c2)\n (c3)\n (c4)\n totag\n = unsafePerformIO $\u00a0do\n res <- create (size) -- TODO: Check channel count -- This is NOT correct\n withMaybe c1 $ \\cc1 -> \n withMaybe c2 $ \\cc2 -> \n withMaybe c3 $ \\cc3 -> \n withMaybe c4 $ \\cc4 -> \n withGenImage res $ \\cres -> {#call cvMerge#} cc1 cc2 cc3 cc4 cres\n return res\n where\n withMaybe (Just i) op = withGenImage i op\n withMaybe (Nothing) op = op nullPtr\n size = getSize . head . catMaybes $ [c1,c2,c3,c4]\n\n-- Load Image as grayscale image.\n\n--loadImage n = do\n-- exists <- fileExist n\n-- if not exists then return Nothing\n-- else do\n-- i <- withCString n $ \\name -> \n-- creatingImage ({#call cvLoadImage #} name (0))\n-- bw <- imageTo32F i\n-- return $ Just bw\n\nclass Loadable a where\n readFromFile :: FilePath -> IO a\n\n\ninstance Loadable ((Image GrayScale D32)) where\n readFromFile fp = do\n e <- loadImage fp\n case e of\n Just i -> return i\n Nothing -> fail $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D32)) where\n readFromFile fp = do\n e <- loadColorImage fp\n case e of\n Just i -> return i\n Nothing -> fail $ \"Could not load \"++fp\n\nloadImage :: FilePath -> IO (Maybe (Image GrayScale D32))\nloadImage n = do\n exists <- fileExist n\n if not exists then return Nothing\n else do\n i <- withCString n $ \\name -> \n creatingBareImage ({#call cvLoadImage #} name (0))\n bw <- imageTo32F i\n return . Just .\u00a0S $ bw\n\nloadColorImage :: FilePath -> IO (Maybe (Image RGB D32))\nloadColorImage n = do\n exists <- fileExist n\n if not exists then return Nothing\n else do\n i <- withCString n $ \\name -> \n creatingBareImage ({#call cvLoadImage #} name 1)\n bw <- imageTo32F i\n return . Just . S $ bw\n\nclass Sized a where\n type Size a :: *\n getSize :: a -> Size a\n\ninstance Sized BareImage where\n type Size BareImage = (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize image = unsafePerformIO $ withBareImage image $ \\i -> do\n w <- {#call getImageWidth#} i\n h <- {#call getImageHeight#} i\n return (fromIntegral w,fromIntegral h)\n\ninstance Sized (Image c d) where\n type Size (Image c d) = (Int,Int)\n getSize = getSize . unS\n\n\ncvRGBtoGRAY = 7 :: CInt-- NOTE: This will break.\ncvRGBtoLAB = 45 :: CInt-- NOTE: This will break.\n\n\nrgbToLab :: Image RGB D32 -> Image LAB D32\nrgbToLab = S . convertTo cvRGBtoLAB 3 . unS\n\nrgbToGray :: Image RGB D32 -> Image GrayScale D32\nrgbToGray = S . convertTo cvRGBtoGRAY 1 . unS\n\n\nclass GetPixel a where\n type P a :: *\n getPixel :: (Int,Int) -> a -> P a\n\n-- #define FGET(img,x,y) (((float *)((img)->imageData + (y)*(img)->widthStep))[(x)])\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32 \n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Float))):: Ptr Float)\n\n{-#INLINE getPixelOld#-}\ngetPixelOld (fromIntegral -> x, fromIntegral -> y) image = realToFrac $\u00a0unsafePerformIO $\n withGenImage image $ \\img -> {#call wrapGet32F2D#} img y x\n\n-- #define UGETC(img,color,x,y) (((uint8_t *)((img)->imageData + (y)*(img)->widthStep))[(x)*3+(color)])\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32) \n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n r <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n b <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ngetPixelOldRGB (fromIntegral -> x, fromIntegral -> y) image \n = unsafePerformIO $ do \n withGenImage image $ \\img -> do\n r <- {#call wrapGet32F2DC#} img y x 0\n g <- {#call wrapGet32F2DC#} img y x 1\n b <- {#call wrapGet32F2DC#} img y x 2\n return (realToFrac r,realToFrac g, realToFrac b)\n\n-- | Perform (a destructive) inplace map of the image. This should be wrapped inside \n-- withClone or an image operation \nmapImageInplace :: (P (Image GrayScale D32) -> P (Image GrayScale D32)) \n -> Image GrayScale D32 \n -> IO ()\nmapImageInplace f image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let (w,h) = getSize image\n cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n forM_ [(x,y) | x<-[0..w-1], y <- [0..h-1]] $ \\(x,y) ->\u00a0do\n v <- peek (castPtr (d `plusPtr` (y*cs+x*fs))) \n poke (castPtr (d `plusPtr` (y*cs+x*fs))) (f v)\n \n\ninstance GetPixel (Image RGB D8) where\n type P (Image RGB D8) = (D8,D8,D8) \n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n r <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n b <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\n\nconvertTo :: CInt -> CInt -> BareImage -> BareImage\nconvertTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage32F#} w h channels\n withBareImage img $ \\cimg -> \n {#call cvCvtColor#} (castPtr cimg) (castPtr res) code\n return res\n where \n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\nclass CreateImage a where\n create :: (Int,Int) -> IO a\n\n\ninstance CreateImage (Image GrayScale D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 4\n\n\n\nempty :: (CreateImage (Image a b)) => (Int,Int) -> (Image a b)\nempty size = unsafePerformIO $ create size \n\nemptyCopy :: (CreateImage (Image a b)) => Image a b -> IO (Image a b)\nemptyCopy img = create (getSize img) \n\nemptyCopy' :: (CreateImage (Image a b)) => Image a b -> (Image a b)\nemptyCopy' img = unsafePerformIO $ create (getSize img) \n\n-- | Save image. This will convert the image to 8 bit one before saving\nsaveImage :: FilePath -> Image c d -> IO ()\nsaveImage filename image = do\n fpi <- imageTo8Bit $ unS image\n withCString filename $ \\name -> \n withGenBareImage fpi $ \\cvArr ->\n\t\t\t\t\t\t\t alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\n\ngetArea :: (Sized a,Num b, Size a ~ (b,b)) => a -> b\ngetArea = uncurry (*).getSize\n\ngetRegion :: (Int,Int) -> (Int,Int) -> Image c d -> Image c d\ngetRegion (fromIntegral -> x,fromIntegral -> y) (fromIntegral -> w,fromIntegral -> h) image \n | x+w <= width && y+h <= height = S . getRegion' (x,y) (w,h) $ unS image\n | otherwise = error $ \"Region outside image:\"\n ++ show (getSize image) ++\n \"\/\"++show (x+w,y+h)\n where\n (fromIntegral -> width,fromIntegral -> height) = getSize image\n \ngetRegion' (x,y) (w,h) image = unsafePerformIO $\n withBareImage image $ \\i ->\n creatingBareImage ({#call getSubImage#} \n i x y w h)\n\n\n-- | Tile images by overlapping them on a black canvas.\ntileImages image1 image2 (x,y) = unsafePerformIO $\n withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n creatingImage ({#call simpleMergeImages#} \n i1 i2 x y)\n-- | Blit image2 onto image1. \nblitFix = blit\nblit image1 image2 (x,y) \n | badSizes = error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y) \n | otherwise = withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call plainBlit#} i1 i2 (fromIntegral y) (fromIntegral x))\n where \n ((w1,h1),(w2,h2)) = (getSize image1,getSize image2)\n badSizes = x+w2>w1 || y+h2>h1 || x<0 || y<0\n\nblitM :: (CreateImage (Image c d)) => (Int,Int) -> [((Int,Int),Image c d)] -> Image c d\nblitM (rw,rh) imgs = resultPic\n where\n resultPic = unsafePerformIO $ do\n r <- create (fromIntegral rw,fromIntegral rh) \n sequence_ [blit r i (fromIntegral x, fromIntegral y) \n | ((x,y),i) <- imgs ]\n return r\n\n\nsubPixelBlit\n :: Image c d -> Image c d -> (CDouble, CDouble) -> IO ()\n\nsubPixelBlit (image1) (image2) (x,y) \n | badSizes = error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y) \n | otherwise = withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call subpixel_blit#} i1 i2 y x)\n where \n ((w1,h1),(w2,h2)) = (getSize image1,getSize image2)\n badSizes = ceiling x+w2>w1 || ceiling y+h2>h1 ||\u00a0x<0 || y<0\n\nsafeBlit i1 i2 (x,y) = unsafePerformIO $ do\n res <- cloneImage i1-- createImage32F (getSize i1) 1\n blit res i2 (x,y)\n return res\n\n-- | Blit image2 onto image1. \n-- This uses an alpha channel bitmap for determining the regions where the image should be \"blended\" with \n-- the base image.\nblendBlit image1 image1Alpha image2 image2Alpha (x,y) = \n withImage image1 $ \\i1 ->\n withImage image1Alpha $ \\i1a ->\n withImage image2Alpha $ \\i2a ->\n withImage image2 $ \\i2 ->\n ({#call alphaBlit#} i1 i1a i2 i2a x y)\n\n\ncloneImage img = withGenImage img $ \\image -> \n creatingImage ({#call cvCloneImage #} image)\n\nwithClone\n :: Image channels depth\n -> (Image channels depth -> IO ())\n -> IO (Image channels depth)\nwithClone img fun = do \n result <- cloneImage img\n fun result\n return result\n\nwithCloneValue\n :: Image channels depth\n -> (Image channels depth -> IO a)\n -> IO a\nwithCloneValue img fun = do \n result <- cloneImage img\n r <- fun result\n return r\n\nunsafeImageTo32F :: Image c d -> Image c D32\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image -> \n creatingImage \n ({#call ensure32F #} image)\n\nunsafeImageTo8Bit :: Image cspace a -> Image cspace D8\nunsafeImageTo8Bit img = unsafePerformIO $ withGenImage img $ \\image -> \n creatingImage \n ({#call ensure8U #} image)\n\nimageTo32F img = withGenBareImage img $ \\image -> \n creatingBareImage \n ({#call ensure32F #} image)\n\nimageTo8Bit img = withGenBareImage img $ \\image -> \n creatingBareImage \n ({#call ensure8U #} image)\n#c\nenum ImageDepth {\n Depth32F = IPL_DEPTH_32F,\n Depth64F = IPL_DEPTH_64F,\n Depth8U = IPL_DEPTH_8U, \n Depth8S = IPL_DEPTH_8S, \n Depth16U = IPL_DEPTH_16U, \n Depth16S = IPL_DEPTH_16S,\n Depth32S = IPL_DEPTH_32S\n };\n#endc\n \n{#enum ImageDepth {}#}\n\nderiving instance Show ImageDepth\n\ngetImageDepth :: Image c d -> IO ImageDepth\ngetImageDepth i = withImage i $ \\c_img -> {#get IplImage->depth #} c_img >>= return.toEnum.fromIntegral\ngetImageChannels i = withImage i $ \\c_img -> {#get IplImage->nChannels #} c_img\n\ngetImageInfo x = do\n let s = getSize x\n d <- getImageDepth x\n c <- getImageChannels x\n return (s,d,c)\n\n\n-- Manipulating regions of interest:\nsetROI (fromIntegral -> x,fromIntegral -> y) \n (fromIntegral -> w,fromIntegral -> h) \n image = withImage image $ \\i -> \n {#call wrapSetImageROI#} i x y w h\n\nresetROI image = withImage image $ \\i ->\n {#call cvResetImageROI#} i\n\nsetCOI chnl image = withImage image $ \\i -> \n {#call cvSetImageCOI#} i (fromIntegral chnl)\nresetCOI image = withImage image $ \\i ->\n {#call cvSetImageCOI#} i 0\n\n\n-- #TODO: Replace the Int below with proper channel identifier\ngetChannel :: (Enum a) => a -> Image (ChannelOf a) d -> Image GrayScale d\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n setCOI (1+fromEnum no) image\n cres <- {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\n withGenImage image $ \\cimage ->\n {#call cvCopy#} cimage (castPtr cres) (nullPtr)\n resetCOI image\n return cres\n\nwithIOROI pos size image op = do\n setROI pos size image\n x <- op\n resetROI image\n return x\n\nwithROI :: (Int, Int) -> (Int, Int) -> Image c d -> (Image c d -> a) -> a\nwithROI pos size image op = unsafePerformIO $ do\n setROI pos size image\n let x = op image -- BUG\n resetROI image\n return x\n\n\n-- | Manipulate image pixels. This is slow, ugly and should be avoided\n--setPixel :: (CInt,CInt) -> CDouble -> Image c d -> IO ()\n{-#INLINE setPixelOld#-}\nsetPixelOld :: (Int,Int) -> D32 -> Image GrayScale D32 -> IO ()\nsetPixelOld (x,y) v image = withGenImage image $ \\img ->\n {#call wrapSet32F2D#} img (fromIntegral y) (fromIntegral x) (realToFrac v)\n\n{-#INLINE setPixel#-}\nsetPixel :: (Int,Int) -> D32 -> Image GrayScale D32 -> IO ()\nsetPixel (x,y) v image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s) \n + x*sizeOf (0::Float))):: Ptr Float)\n v\n\n{-#INLINE setPixel8U#-}\nsetPixel8U :: (Int,Int) -> Word8 -> Image GrayScale D8 -> IO ()\nsetPixel8U (x,y) v image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s) \n + x*sizeOf (0::Word8))):: Ptr Word8)\n v\n\n\ngetAllPixels image = [getPixel (i,j) image \n | i <- [0..width-1 ]\n , j <- [0..height-1]] \n where\n (width,height) = getSize image\n\ngetAllPixelsRowMajor image = [getPixel (i,j) image \n | j <- [0..height-1]\n , i <- [0..width-1]\n ] \n where\n (width,height) = getSize image\n\n-- |Create a montage form given images (u,v) determines the layout and space the spacing\n-- between images. Images are assumed to be the same size (determined by the first image)\nmontage :: (CreateImage (Image c d)) => (Int,Int) -> Int -> [Image c d] -> Image c d\nmontage (u',v') space' imgs \n | u'*v' \/= (length imgs) = error (\"Montage mismatch: \"++show (u,v, length imgs))\n | otherwise = resultPic\n where\n space = fromIntegral space'\n (u,v) = (fromIntegral u', fromIntegral v')\n (rw,rh) = (u*xstep,v*ystep) \n (w,h) = getSize (head imgs)\n (xstep,ystep) = (fromIntegral space + w,fromIntegral space + h)\n edge = space`div`2\n resultPic = unsafePerformIO $ do\n r <- create (rw,rh)\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep) \n | y <- [0..v-1] , x <- [0..u-1] \n | i <- imgs ]\n return r\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"a37feb4f99a585b1ffb2cdcdf31bcb7f33488ebd","subject":"gstreamer: fix marshaling on Structure where GValues weren't initialized properly reported\/fixed by Oleg Belozeorov ","message":"gstreamer: fix marshaling on Structure where GValues weren't initialized properly\nreported\/fixed by Oleg Belozeorov \n","repos":"vincenthz\/webkit","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Structure.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Structure.chs","new_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gstreamer -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GStreamer, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GStreamer documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Structure (\n Structure,\n structureEmpty,\n structureToString,\n structureFromString,\n structureName,\n structureHasName,\n structureGetBool,\n structureGetInt,\n structureGetFourCC,\n structureGetDouble, \n structureGetString,\n structureGetDate, \n structureGetClockTime,\n structureGetFraction,\n \n StructureM,\n structureCreate,\n structureModify,\n structureSetNameM,\n structureRemoveFieldM,\n structureSetBoolM,\n structureSetIntM,\n structureSetFourCCM,\n structureSetDoubleM,\n structureSetStringM,\n structureSetDateM,\n structureSetClockTimeM,\n structureSetFractionM,\n structureFixateFieldNearestIntM,\n structureFixateFieldNearestDoubleM,\n structureFixateFieldNearestFractionM,\n structureFixateFieldBoolM\n ) where\n\nimport Data.Ratio ( (%)\n , numerator\n , denominator )\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Core.Types#}\nimport System.Glib.UTFString\nimport System.Glib.FFI\nimport System.Glib.GTypeConstants\n{#import System.Glib.GDateTime#}\n{#import System.Glib.GType#}\n{#import System.Glib.GValue#}\n{#import System.Glib.GValueTypes#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nstructureEmpty :: String\n -> Structure\nstructureEmpty name =\n unsafePerformIO $\n withUTFString name {# call structure_empty_new #} >>=\n takeStructure\n\nstructureToString :: Structure\n -> String\nstructureToString structure =\n unsafePerformIO $\n {# call structure_to_string #} structure >>=\n readUTFString\n\nstructureFromString :: String\n -> (Maybe Structure, Int)\nstructureFromString string =\n unsafePerformIO $\n withUTFString string $ \\cString ->\n alloca $ \\endPtr ->\n do structure <- {# call structure_from_string #} cString endPtr >>=\n maybePeek takeStructure\n end <- peek endPtr\n offset <- {# call g_utf8_pointer_to_offset #} cString end\n return (structure, fromIntegral offset)\n\nstructureName :: Structure\n -> String\nstructureName structure =\n unsafePerformIO $\n {# call structure_get_name #} structure >>=\n peekUTFString\n\nstructureHasName :: Structure\n -> String\n -> Bool\nstructureHasName structure name =\n toBool $ unsafePerformIO $\n withUTFString name $\n {# call structure_has_name #} structure\n\nmarshalStructureGet :: Storable a\n => (Structure -> CString -> Ptr a -> IO {# type gboolean #})\n -> (a -> IO b)\n -> Structure\n -> String\n -> Maybe b\nmarshalStructureGet getAction convert structure fieldname =\n unsafePerformIO $\n alloca $ \\ptr ->\n withUTFString fieldname $ \\cFieldname ->\n do result <- getAction structure cFieldname ptr\n if toBool result\n then liftM Just $ peek (castPtr ptr) >>= convert\n else return Nothing\n\nstructureGetBool :: Structure\n -> String\n -> Maybe Bool\nstructureGetBool =\n marshalStructureGet {# call structure_get_boolean #} $\n return . toBool\n\nstructureGetInt :: Structure\n -> String\n -> Maybe Int\nstructureGetInt =\n marshalStructureGet {# call structure_get_int #} $\n return . fromIntegral\n\nstructureGetFourCC :: Structure\n -> String\n -> Maybe FourCC\nstructureGetFourCC =\n marshalStructureGet {# call structure_get_fourcc #} $\n return . fromIntegral\n\nstructureGetDouble :: Structure\n -> String\n -> Maybe Double\nstructureGetDouble =\n marshalStructureGet {# call structure_get_double #} $\n return . realToFrac\n\nstructureGetString :: Structure\n -> String\n -> Maybe String\nstructureGetString structure fieldname =\n unsafePerformIO $\n (withUTFString fieldname $ {# call structure_get_string #} structure) >>=\n maybePeek peekUTFString\n\nstructureGetDate :: Structure\n -> String\n -> Maybe GDate\nstructureGetDate =\n marshalStructureGet {# call structure_get_date #} $\n peek . castPtr\n\nstructureGetClockTime :: Structure\n -> String\n -> Maybe ClockTime\nstructureGetClockTime =\n marshalStructureGet {# call structure_get_clock_time #} $\n return . fromIntegral\n\nstructureGetFraction :: Structure\n -> String\n -> Maybe Fraction\nstructureGetFraction structure fieldname =\n unsafePerformIO $\n alloca $ \\numPtr -> alloca $ \\denPtr ->\n withUTFString fieldname $ \\cFieldname ->\n do result <- {# call structure_get_fraction #} structure cFieldname numPtr denPtr\n if toBool result\n then do num <- peek numPtr\n den <- peek denPtr\n return $ Just $ (fromIntegral num) % (fromIntegral den)\n else return Nothing\n\nmarshalStructureModify :: IO (Ptr Structure)\n -> StructureM a\n -> (Structure, a)\nmarshalStructureModify mkStructure (StructureM action) =\n unsafePerformIO $\n do ptr <- mkStructure\n structure <- liftM Structure $ newForeignPtr_ ptr\n result <- action structure\n structure' <- takeStructure ptr\n return (structure', result)\n\nstructureCreate :: String\n -> StructureM a\n -> (Structure, a)\nstructureCreate name action =\n marshalStructureModify\n (withUTFString name {# call structure_empty_new #})\n action\n\nstructureModify :: Structure\n -> StructureM a\n -> (Structure, a)\nstructureModify structure action =\n marshalStructureModify\n ({# call structure_copy #} structure)\n action\n\nstructureSetNameM :: String\n -> StructureM ()\nstructureSetNameM name =\n StructureM $ \\structure ->\n withUTFString name $ {# call structure_set_name #} structure\n\nstructureRemoveFieldM :: String\n -> StructureM ()\nstructureRemoveFieldM name =\n StructureM $ \\structure ->\n withUTFString name $ {# call structure_remove_field #} structure\n\nmarshalStructureSetM :: GType\n -> (GValue -> a -> IO ())\n -> String\n -> a\n -> StructureM ()\nmarshalStructureSetM valueType setGValue fieldname value =\n StructureM $ \\structure ->\n withUTFString fieldname $ \\cFieldname ->\n allocaGValue $ \\gValue ->\n do valueInit gValue valueType\n setGValue gValue value\n {# call structure_set_value #} structure cFieldname gValue\n\nstructureSetBoolM :: String\n -> Bool\n -> StructureM ()\nstructureSetBoolM =\n marshalStructureSetM bool valueSetBool\n\nstructureSetIntM :: String\n -> Int\n -> StructureM ()\nstructureSetIntM =\n marshalStructureSetM int valueSetInt\n\nstructureSetFourCCM :: String\n -> FourCC\n -> StructureM ()\nstructureSetFourCCM =\n marshalStructureSetM fourcc $ \\gValue fourcc ->\n {# call value_set_fourcc #} gValue $ fromIntegral fourcc\n\nstructureSetDoubleM :: String\n -> Double\n -> StructureM ()\nstructureSetDoubleM =\n marshalStructureSetM double valueSetDouble\n\nstructureSetStringM :: String\n -> String\n -> StructureM ()\nstructureSetStringM =\n marshalStructureSetM string valueSetString\n\nstructureSetDateM :: String\n -> GDate\n -> StructureM ()\nstructureSetDateM =\n marshalStructureSetM date $ \\gValue date ->\n with date $ ({# call value_set_date #} gValue) . castPtr\n\nstructureSetClockTimeM :: String\n -> ClockTime\n -> StructureM ()\nstructureSetClockTimeM =\n marshalStructureSetM uint64 $ \\gValue clockTime ->\n {# call g_value_set_uint64 #} gValue $ fromIntegral clockTime\n\nstructureSetFractionM :: String\n -> Fraction\n -> StructureM ()\nstructureSetFractionM =\n marshalStructureSetM fraction $ \\gValue fraction ->\n {# call value_set_fraction #} gValue\n (fromIntegral $ numerator fraction)\n (fromIntegral $ denominator fraction)\n\nmarshalStructureFixateM :: (Structure -> CString -> a -> IO {# type gboolean #})\n -> String\n -> a\n -> StructureM Bool\nmarshalStructureFixateM fixate fieldname target =\n StructureM $ \\structure ->\n withUTFString fieldname $ \\cFieldname ->\n liftM toBool $\n fixate structure cFieldname target\n\nstructureFixateFieldNearestIntM :: String\n -> Int\n -> StructureM Bool\nstructureFixateFieldNearestIntM =\n marshalStructureFixateM $ \\structure cFieldname target ->\n {# call structure_fixate_field_nearest_int #}\n structure\n cFieldname\n (fromIntegral target)\n\nstructureFixateFieldNearestDoubleM :: String\n -> Double\n -> StructureM Bool\nstructureFixateFieldNearestDoubleM =\n marshalStructureFixateM $ \\structure cFieldname target ->\n {# call structure_fixate_field_nearest_double #}\n structure\n cFieldname\n (realToFrac target)\n\nstructureFixateFieldNearestFractionM :: String\n -> Fraction\n -> StructureM Bool\nstructureFixateFieldNearestFractionM =\n marshalStructureFixateM $ \\structure cFieldname target ->\n {# call structure_fixate_field_nearest_fraction #}\n structure\n cFieldname\n (fromIntegral $ numerator target)\n (fromIntegral $ denominator target)\n\nstructureFixateFieldBoolM :: String\n -> Bool\n -> StructureM Bool\nstructureFixateFieldBoolM =\n marshalStructureFixateM $ \\structure cFieldname target ->\n {# call structure_fixate_field_boolean #}\n structure\n cFieldname\n (fromBool target)\n\n\nfourcc = {# call fun fourcc_get_type #}\ndate = {# call fun date_get_type #} \nfraction = {# call fun fraction_get_type #} \n","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gstreamer -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GStreamer, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GStreamer documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule Media.Streaming.GStreamer.Core.Structure (\n Structure,\n structureEmpty,\n structureToString,\n structureFromString,\n structureName,\n structureHasName,\n structureGetBool,\n structureGetInt,\n structureGetFourCC,\n structureGetDouble, \n structureGetString,\n structureGetDate, \n structureGetClockTime,\n structureGetFraction,\n \n StructureM,\n structureCreate,\n structureModify,\n structureSetNameM,\n structureRemoveFieldM,\n structureSetBoolM,\n structureSetIntM,\n structureSetFourCCM,\n structureSetDoubleM,\n structureSetStringM,\n structureSetDateM,\n structureSetClockTimeM,\n structureSetFractionM,\n structureFixateFieldNearestIntM,\n structureFixateFieldNearestDoubleM,\n structureFixateFieldNearestFractionM,\n structureFixateFieldBoolM\n ) where\n\nimport Data.Ratio ( (%)\n , numerator\n , denominator )\nimport Control.Monad (liftM)\n{#import Media.Streaming.GStreamer.Core.Types#}\nimport System.Glib.UTFString\nimport System.Glib.FFI\n{#import System.Glib.GDateTime#}\n{#import System.Glib.GValue#}\n{#import System.Glib.GValueTypes#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nstructureEmpty :: String\n -> Structure\nstructureEmpty name =\n unsafePerformIO $\n withUTFString name {# call structure_empty_new #} >>=\n takeStructure\n\nstructureToString :: Structure\n -> String\nstructureToString structure =\n unsafePerformIO $\n {# call structure_to_string #} structure >>=\n readUTFString\n\nstructureFromString :: String\n -> (Maybe Structure, Int)\nstructureFromString string =\n unsafePerformIO $\n withUTFString string $ \\cString ->\n alloca $ \\endPtr ->\n do structure <- {# call structure_from_string #} cString endPtr >>=\n maybePeek takeStructure\n end <- peek endPtr\n offset <- {# call g_utf8_pointer_to_offset #} cString end\n return (structure, fromIntegral offset)\n\nstructureName :: Structure\n -> String\nstructureName structure =\n unsafePerformIO $\n {# call structure_get_name #} structure >>=\n peekUTFString\n\nstructureHasName :: Structure\n -> String\n -> Bool\nstructureHasName structure name =\n toBool $ unsafePerformIO $\n withUTFString name $\n {# call structure_has_name #} structure\n\nmarshalStructureGet :: Storable a\n => (Structure -> CString -> Ptr a -> IO {# type gboolean #})\n -> (a -> IO b)\n -> Structure\n -> String\n -> Maybe b\nmarshalStructureGet getAction convert structure fieldname =\n unsafePerformIO $\n alloca $ \\ptr ->\n withUTFString fieldname $ \\cFieldname ->\n do result <- getAction structure cFieldname ptr\n if toBool result\n then liftM Just $ peek (castPtr ptr) >>= convert\n else return Nothing\n\nstructureGetBool :: Structure\n -> String\n -> Maybe Bool\nstructureGetBool =\n marshalStructureGet {# call structure_get_boolean #} $\n return . toBool\n\nstructureGetInt :: Structure\n -> String\n -> Maybe Int\nstructureGetInt =\n marshalStructureGet {# call structure_get_int #} $\n return . fromIntegral\n\nstructureGetFourCC :: Structure\n -> String\n -> Maybe FourCC\nstructureGetFourCC =\n marshalStructureGet {# call structure_get_fourcc #} $\n return . fromIntegral\n\nstructureGetDouble :: Structure\n -> String\n -> Maybe Double\nstructureGetDouble =\n marshalStructureGet {# call structure_get_double #} $\n return . realToFrac\n\nstructureGetString :: Structure\n -> String\n -> Maybe String\nstructureGetString structure fieldname =\n unsafePerformIO $\n (withUTFString fieldname $ {# call structure_get_string #} structure) >>=\n maybePeek peekUTFString\n\nstructureGetDate :: Structure\n -> String\n -> Maybe GDate\nstructureGetDate =\n marshalStructureGet {# call structure_get_date #} $\n peek . castPtr\n\nstructureGetClockTime :: Structure\n -> String\n -> Maybe ClockTime\nstructureGetClockTime =\n marshalStructureGet {# call structure_get_clock_time #} $\n return . fromIntegral\n\nstructureGetFraction :: Structure\n -> String\n -> Maybe Fraction\nstructureGetFraction structure fieldname =\n unsafePerformIO $\n alloca $ \\numPtr -> alloca $ \\denPtr ->\n withUTFString fieldname $ \\cFieldname ->\n do result <- {# call structure_get_fraction #} structure cFieldname numPtr denPtr\n if toBool result\n then do num <- peek numPtr\n den <- peek denPtr\n return $ Just $ (fromIntegral num) % (fromIntegral den)\n else return Nothing\n\nmarshalStructureModify :: IO (Ptr Structure)\n -> StructureM a\n -> (Structure, a)\nmarshalStructureModify mkStructure (StructureM action) =\n unsafePerformIO $\n do ptr <- mkStructure\n structure <- liftM Structure $ newForeignPtr_ ptr\n result <- action structure\n structure' <- takeStructure ptr\n return (structure', result)\n\nstructureCreate :: String\n -> StructureM a\n -> (Structure, a)\nstructureCreate name action =\n marshalStructureModify\n (withUTFString name {# call structure_empty_new #})\n action\n\nstructureModify :: Structure\n -> StructureM a\n -> (Structure, a)\nstructureModify structure action =\n marshalStructureModify\n ({# call structure_copy #} structure)\n action\n\nstructureSetNameM :: String\n -> StructureM ()\nstructureSetNameM name =\n StructureM $ \\structure ->\n withUTFString name $ {# call structure_set_name #} structure\n\nstructureRemoveFieldM :: String\n -> StructureM ()\nstructureRemoveFieldM name =\n StructureM $ \\structure ->\n withUTFString name $ {# call structure_remove_field #} structure\n\nmarshalStructureSetM :: (GValue -> a -> IO ())\n -> String\n -> a\n -> StructureM ()\nmarshalStructureSetM setGValue fieldname value =\n StructureM $ \\structure ->\n withUTFString fieldname $ \\cFieldname ->\n allocaGValue $ \\gValue ->\n do setGValue gValue value\n {# call structure_set_value #} structure cFieldname gValue\n\nstructureSetBoolM :: String\n -> Bool\n -> StructureM ()\nstructureSetBoolM =\n marshalStructureSetM valueSetBool\n\nstructureSetIntM :: String\n -> Int\n -> StructureM ()\nstructureSetIntM =\n marshalStructureSetM valueSetInt\n\nstructureSetFourCCM :: String\n -> FourCC\n -> StructureM ()\nstructureSetFourCCM =\n marshalStructureSetM $ \\gValue fourcc ->\n {# call value_set_fourcc #} gValue $ fromIntegral fourcc\n\nstructureSetDoubleM :: String\n -> Double\n -> StructureM ()\nstructureSetDoubleM =\n marshalStructureSetM valueSetDouble\n\nstructureSetStringM :: String\n -> String\n -> StructureM ()\nstructureSetStringM =\n marshalStructureSetM valueSetString\n\nstructureSetDateM :: String\n -> GDate\n -> StructureM ()\nstructureSetDateM =\n marshalStructureSetM $ \\gValue date ->\n with date $ ({# call value_set_date #} gValue) . castPtr\n\nstructureSetClockTimeM :: String\n -> ClockTime\n -> StructureM ()\nstructureSetClockTimeM =\n marshalStructureSetM $ \\gValue clockTime ->\n {# call g_value_set_uint64 #} gValue $ fromIntegral clockTime\n\nstructureSetFractionM :: String\n -> Fraction\n -> StructureM ()\nstructureSetFractionM =\n marshalStructureSetM $ \\gValue fraction ->\n {# call value_set_fraction #} gValue\n (fromIntegral $ numerator fraction)\n (fromIntegral $ denominator fraction)\n\nmarshalStructureFixateM :: (Structure -> CString -> a -> IO {# type gboolean #})\n -> String\n -> a\n -> StructureM Bool\nmarshalStructureFixateM fixate fieldname target =\n StructureM $ \\structure ->\n withUTFString fieldname $ \\cFieldname ->\n liftM toBool $\n fixate structure cFieldname target\n\nstructureFixateFieldNearestIntM :: String\n -> Int\n -> StructureM Bool\nstructureFixateFieldNearestIntM =\n marshalStructureFixateM $ \\structure cFieldname target ->\n {# call structure_fixate_field_nearest_int #}\n structure\n cFieldname\n (fromIntegral target)\n\nstructureFixateFieldNearestDoubleM :: String\n -> Double\n -> StructureM Bool\nstructureFixateFieldNearestDoubleM =\n marshalStructureFixateM $ \\structure cFieldname target ->\n {# call structure_fixate_field_nearest_double #}\n structure\n cFieldname\n (realToFrac target)\n\nstructureFixateFieldNearestFractionM :: String\n -> Fraction\n -> StructureM Bool\nstructureFixateFieldNearestFractionM =\n marshalStructureFixateM $ \\structure cFieldname target ->\n {# call structure_fixate_field_nearest_fraction #}\n structure\n cFieldname\n (fromIntegral $ numerator target)\n (fromIntegral $ denominator target)\n\nstructureFixateFieldBoolM :: String\n -> Bool\n -> StructureM Bool\nstructureFixateFieldBoolM =\n marshalStructureFixateM $ \\structure cFieldname target ->\n {# call structure_fixate_field_boolean #}\n structure\n cFieldname\n (fromBool target)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"025e191dcb0c959934c7f667f28366ab921d1e1b","subject":"[project @ 2002-07-12 13:09:23 by dg22] Fixed references that used the old names for packing widgets.","message":"[project @ 2002-07-12 13:09:23 by dg22]\nFixed references that used the old names for packing widgets.\n\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"gtk\/layout\/Notebook.chs","new_file":"gtk\/layout\/Notebook.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget Notebook@\n--\n-- Author : Axel Simon\n-- \n-- Created: 15 May 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/07\/12 13:09:23 $\n--\n-- Copyright (c) 1999..2002 Axel Simon\n--\n-- This file is free software; you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation; either version 2 of the License, or\n-- (at your option) any later version.\n--\n-- This file is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- * This widget can display several pages of widgets. Each page can be \n-- selected by a tab at the top of the widget. It is useful in dialogs where\n-- a lot of information has to be displayed.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * check if it is sensible and possible to have something else than a Label\n-- widget in the context menu. If so, change the notebook*PageMenu function\n-- and add notebookSetMenuLabel and notebookSetMenuText.\n--\n-- * notebookSetTabLabelText is not bound.\n--\n-- * The signals focus-tab and select-page are not bound because it is unclear\n-- what they mean. As far as I can see they are not emitted anywhere.\n--\nmodule Notebook(\n Notebook,\n NotebookClass,\n castToNotebook,\n notebookNew,\n notebookAppendPage,\n notebookAppendPageMenu,\n notebookPrependPage,\n notebookPrependPageMenu,\n notebookInsertPage,\n notebookInsertPageMenu,\n notebookRemovePage,\n notebookPageNum,\n notebookSetCurrentPage,\n notebookNextPage,\n notebookPrevPage,\n notebookReorderChild,\n PositionType(..),\n notebookSetTabPos,\n notebookSetShowTabs,\n notebookSetShowBorder,\n notebookSetScrollable,\n notebookSetTabBorder,\n notebookSetTabHBorder,\n notebookSetTabVBorder,\n notebookSetPopup,\n notebookGetCurrentPage,\n notebookGetMenuLabel,\n notebookGetNthPage,\n notebookGetTabLabel,\n Packing(..), PackType(..),\n notebookQueryTabLabelPacking,\n notebookSetTabLabelPacking,\n notebookSetHomogeneousTabs,\n notebookSetTabLabel,\n onSwitchPage,\n afterSwitchPage\n ) where\n\nimport Monad\t(liftM)\nimport Maybe\t(maybe)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Label\t(labelNew)\nimport Enums\t(Packing(..), PackType(..), PositionType(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- @constructor notebookNew@ Create a new notebook.\n--\nnotebookNew :: IO Notebook\nnotebookNew = makeNewObject mkNotebook $ \n liftM castPtr {#call unsafe notebook_new#}\n\n-- @method notebookAppendPage@ Insert a new tab to the right of the existing\n-- tabs.\n--\n-- * The @ref arg tabName@ will be inserted as a Label widget. In case the\n-- context menu is enabled, this name will appear in the menu. If you want\n-- to specify something else to go in the tab, use\n-- @ref method notebookAppendPageMenu@ and specify some suitable widget for\n-- @ref arg menuLabel@.\n--\nnotebookAppendPage :: (NotebookClass nb, WidgetClass child) => nb -> child ->\n String -> IO ()\nnotebookAppendPage nb child tabLabel = do\n tab <- labelNew (Just tabLabel)\n {#call notebook_append_page#} (toNotebook nb) (toWidget child) \n (toWidget tab)\n\n-- @method notebookAppendPageMenu@ Insert a new tab to the right of the\n-- existing tabs. @ref arg menuLabel@ is the label for the context menu\n-- (useful if @ref arg tabLabel@ is not a Label widget).\n--\nnotebookAppendPageMenu ::(NotebookClass nb, WidgetClass child, \n WidgetClass tab) => nb -> child -> tab -> String -> IO ()\nnotebookAppendPageMenu nb child tabWidget menuLabel = do\n menu <- labelNew (Just menuLabel)\n {#call notebook_append_page_menu#} (toNotebook nb) (toWidget child)\n (toWidget tabWidget) (toWidget menu)\n\n-- @method notebookPrependPage@ Insert a new tab to the left of the existing\n-- tabs.\n--\n-- * The @ref arg tabName@ will be inserted as a Label widget. In case the\n-- context menu is enabled, this name will appear in the menu. If you want\n-- to specify something else to go in the tab, use\n-- @ref method notebookPrependPageMenu@ and specify some suitable widget for\n-- @ref arg menuLabel@.\n--\nnotebookPrependPage :: (NotebookClass nb, WidgetClass child) => nb -> child ->\n String -> IO ()\nnotebookPrependPage nb child tabLabel = do\n tab <- labelNew (Just tabLabel)\n {#call notebook_prepend_page#} (toNotebook nb) (toWidget child) (toWidget tab)\n\n-- @method notebookPrependPageMenu@ Insert a new tab to the left of the\n-- existing tabs. @ref arg menuLabel@ is the label for the context menu\n-- (useful if @ref arg tabLabel@ is not a Label widget).\n--\nnotebookPrependPageMenu ::(NotebookClass nb, WidgetClass child, \n WidgetClass tab) => nb -> child -> tab -> String -> IO ()\nnotebookPrependPageMenu nb child tabWidget menuLabel = do\n menu <- labelNew (Just menuLabel)\n {#call notebook_prepend_page_menu#} (toNotebook nb) (toWidget child)\n (toWidget tabWidget) (toWidget menu)\n\n\n-- @method notebookInsertPage@ Insert a new tab at the specified position.\n--\n-- * The @ref arg tabName@ will be inserted as a Label widget. In case the\n-- context menu is enabled, this name will appear in the menu. If you want\n-- to specify something else to go in the tab, use\n-- @ref method notebookInsertPageMenu@ and specify some suitable widget for\n-- @ref arg menuLabel@.\n--\nnotebookInsertPage :: (NotebookClass nb, WidgetClass child) => nb -> child ->\n String -> Int -> IO ()\nnotebookInsertPage nb child tabLabel pos = do\n lbl <- labelNew (Just tabLabel)\n {#call notebook_insert_page#} (toNotebook nb) (toWidget child) \n (toWidget lbl) (fromIntegral pos)\n\n-- @method notebookInsertPageMenu@ Insert a new tab between the tab no.\n-- @ref arg pos@ and @ref arg pos@+1. @ref arg menuLabel@ is the label for the\n-- context menu (useful if @ref arg tabLabel@ is not a Label widget).\n--\nnotebookInsertPageMenu ::(NotebookClass nb, WidgetClass child, \n WidgetClass tab) => nb -> child -> tab -> String -> Int -> IO ()\nnotebookInsertPageMenu nb child tabWidget menuLabel pos = do\n menu <- labelNew (Just menuLabel)\n {#call notebook_insert_page_menu#} (toNotebook nb) (toWidget child)\n (toWidget tabWidget) (toWidget menu) (fromIntegral pos)\n\n-- @method notebookRemovePage@ Remove a specific page from the notebook,\n-- counting from 0.\n--\nnotebookRemovePage :: NotebookClass nb => nb -> Int -> IO ()\nnotebookRemovePage nb pos = \n {#call notebook_remove_page#} (toNotebook nb) (fromIntegral pos)\n\n-- @method notebookPageNum@ Query the page the @ref arg child@ widget is\n-- contained in.\n--\n-- * The function returns the page number if the child was found, Nothing\n-- otherwise.\n--\nnotebookPageNum :: (NotebookClass nb, WidgetClass w) => nb -> w ->\n IO (Maybe Int)\nnotebookPageNum nb child = \n liftM (\\page -> if page==(-1) then Nothing else Just (fromIntegral page)) $\n {#call unsafe notebook_page_num#} (toNotebook nb) (toWidget child)\n\n-- @method notebookSetCurrentPage@ Move to the specified page of the notebook.\n--\n-- * If @ref arg pos@ is out of range (e.g. negative) select the last page.\n--\nnotebookSetCurrentPage :: NotebookClass nb => nb -> Int -> IO ()\nnotebookSetCurrentPage nb pos =\n {#call notebook_set_current_page#} (toNotebook nb) (fromIntegral pos)\n\n-- @method notebookNextPage@ Move to the right neighbour of the current page.\n--\n-- * Nothing happens if there is no such page.\n--\nnotebookNextPage :: NotebookClass nb => nb -> IO ()\nnotebookNextPage nb = {#call notebook_next_page#} (toNotebook nb)\n\n-- @method notebookPrevPage@ Move to the left neighbour of the current page.\n--\n-- * Nothing happens if there is no such page.\n--\nnotebookPrevPage :: NotebookClass nb => nb -> IO ()\nnotebookPrevPage nb = {#call notebook_prev_page#} (toNotebook nb)\n\n-- @method notebookReorderChild@ Move a page withing the notebook.\n--\nnotebookReorderChild :: (NotebookClass nb, WidgetClass w) => nb -> w -> Int ->\n IO ()\nnotebookReorderChild nb child pos = {#call notebook_reorder_child#}\n (toNotebook nb) (toWidget child) (fromIntegral pos)\n\n-- @method notebookSetTabPos@ Specify at which border the tabs should be\n-- drawn.\n--\nnotebookSetTabPos :: NotebookClass nb => nb -> PositionType -> IO ()\nnotebookSetTabPos nb pt = {#call notebook_set_tab_pos#}\n (toNotebook nb) ((fromIntegral.fromEnum) pt)\n\n-- @method notebookSetShowTabs@ Show or hide the tabs of a notebook.\n--\nnotebookSetShowTabs :: NotebookClass nb => nb -> Bool -> IO ()\nnotebookSetShowTabs nb showTabs = {#call notebook_set_show_tabs#}\n (toNotebook nb) (fromBool showTabs)\n\n-- @method notebookSetShowBorder@ In case the tabs are not shown, specify\n-- whether to draw a border around the notebook.\n--\nnotebookSetShowBorder :: NotebookClass nb => nb -> Bool -> IO ()\nnotebookSetShowBorder nb showBorder = {#call notebook_set_show_border#}\n (toNotebook nb) (fromBool showBorder)\n\n-- @method notebookSetScrollable@ Set whether scroll bars will be added in\n-- case the notebook has too many tabs to fit the widget size.\n--\nnotebookSetScrollable :: NotebookClass nb => nb -> Bool -> IO ()\nnotebookSetScrollable nb scrollable = {#call unsafe notebook_set_scrollable#}\n (toNotebook nb) (fromBool scrollable)\n\n-- @method notebookSetTabBorder@ Set the width of the borders of the tab\n-- labels.\n--\n-- * Sets both vertical and horizontal widths.\n--\nnotebookSetTabBorder :: NotebookClass nb => nb -> Int -> IO ()\nnotebookSetTabBorder nb width = {#call notebook_set_tab_border#}\n (toNotebook nb) (fromIntegral width)\n\n-- @method notebookSetTabHBorder@ Set the width of the borders of the tab\n-- labels.\n--\n-- * Sets horizontal widths.\n--\nnotebookSetTabHBorder :: NotebookClass nb => nb -> Int -> IO ()\nnotebookSetTabHBorder nb width = {#call notebook_set_tab_hborder#}\n (toNotebook nb) (fromIntegral width)\n\n-- @method notebookSetTabVBorder@ Set the width of the borders of the tab\n-- labels.\n--\n-- * Sets vertical widths.\n--\nnotebookSetTabVBorder :: NotebookClass nb => nb -> Int -> IO ()\nnotebookSetTabVBorder nb width = {#call notebook_set_tab_vborder#}\n (toNotebook nb) (fromIntegral width)\n\n-- @method notebookSetPopup@ Enable or disable context menus with all tabs in\n-- it.\n--\nnotebookSetPopup :: NotebookClass nb => nb -> Bool -> IO ()\nnotebookSetPopup nb enable = (if enable \n then {#call notebook_popup_enable#} else {#call notebook_popup_disable#})\n (toNotebook nb)\n\n-- @method notebookGetCurrentPage@ Query the currently selected page.\n--\n-- * Returns -1 if notebook has no pages.\n--\nnotebookGetCurrentPage :: NotebookClass nb => nb -> IO Int\nnotebookGetCurrentPage nb = liftM fromIntegral $\n {#call unsafe notebook_get_current_page#} (toNotebook nb)\n\n-- @method notebookGetMenuLabel@ Extract the menu label from the given\n-- @ref arg child@.\n--\n-- * Returns Nothing if @ref arg child@ was not found.\n--\nnotebookGetMenuLabel :: (NotebookClass nb, WidgetClass w) => nb -> w ->\n IO (Maybe Label)\nnotebookGetMenuLabel nb child = do\n wPtr <- {#call unsafe notebook_get_menu_label#} \n (toNotebook nb) (toWidget child)\n if wPtr==nullPtr then return Nothing else liftM Just $\n makeNewObject mkLabel $ return $ castPtr wPtr\n\n-- @method notebookGetNthPage@ Retrieve the child widget at positon\n-- @ref arg pos@ (stating from 0).\n--\n-- * Returns Nothing if the index is out of bounds.\n--\nnotebookGetNthPage :: NotebookClass nb => nb -> Int -> IO (Maybe Widget)\nnotebookGetNthPage nb pos = do\n wPtr <- {#call unsafe notebook_get_nth_page#} \n (toNotebook nb) (fromIntegral pos)\n if wPtr==nullPtr then return Nothing else liftM Just $\n makeNewObject mkWidget $ return wPtr\n\n-- @method notebookGetTabLabel@ Extract the tab label from the given\n-- @ref arg child@.\n--\nnotebookGetTabLabel :: (NotebookClass nb, WidgetClass w) => nb -> w ->\n IO (Maybe Label)\nnotebookGetTabLabel nb child = do\n wPtr <- {#call unsafe notebook_get_tab_label#} \n (toNotebook nb) (toWidget child)\n if wPtr==nullPtr then return Nothing else liftM Just $\n makeNewObject mkLabel $ return $ castPtr wPtr\n\n-- @method notebookQueryTabLabelPacking@ Query the packing attributes of the\n-- given @ref arg child@.\n--\nnotebookQueryTabLabelPacking :: (NotebookClass nb, WidgetClass w) => nb -> w ->\n IO (Packing,PackType)\nnotebookQueryTabLabelPacking nb child = \n alloca $ \\expPtr -> alloca $ \\fillPtr -> alloca $ \\packPtr -> do\n {#call unsafe notebook_query_tab_label_packing#} (toNotebook nb)\n (toWidget child) expPtr fillPtr packPtr\n expand <- liftM toBool $ peek expPtr\n fill <- liftM toBool $ peek fillPtr\n pt <- liftM (toEnum.fromIntegral) $ peek packPtr\n return (if fill then PackGrow else \n (if expand then PackRepel else PackNatural),\n\t pt)\n\n-- @method notebookSetTabLabelPacking@ Set the packing attributes of the given\n-- @ref arg child@.\n--\nnotebookSetTabLabelPacking :: (NotebookClass nb, WidgetClass w) => nb -> w ->\n Packing -> PackType -> IO ()\nnotebookSetTabLabelPacking nb child pack pt = \n {#call notebook_set_tab_label_packing#} (toNotebook nb) (toWidget child)\n (fromBool $ pack\/=PackNatural) (fromBool $ pack==PackGrow) \n ((fromIntegral.fromEnum) pt)\n\n-- @method notebookSetHomogeneousTabs@ Sets whether the tabs must have all the\n-- same size or not.\n--\nnotebookSetHomogeneousTabs :: NotebookClass nb => nb -> Bool -> IO ()\nnotebookSetHomogeneousTabs nb hom = {#call notebook_set_homogeneous_tabs#}\n (toNotebook nb) (fromBool hom)\n\n\n-- @method notebookSetTabLabel@ Set a new tab label for a given\n-- @ref arg child@.\n--\nnotebookSetTabLabel :: (NotebookClass nb, WidgetClass ch, WidgetClass tab) => \n nb -> ch -> tab -> IO ()\nnotebookSetTabLabel nb child tab = {#call notebook_set_tab_label#}\n (toNotebook nb) (toWidget child) (toWidget tab)\n\n-- signals\n\n-- @signal connectToSwitchPage@ This signal is emitted when a new page is\n-- selected.\n--\nonSwitchPage, afterSwitchPage :: NotebookClass nb => nb -> (Int -> IO ()) ->\n IO (ConnectId nb)\nonSwitchPage nb fun = connect_BOXED_WORD__NONE \"switch-page\" \n\t\t (const $ return ()) False nb \n\t\t (\\_ page -> fun (fromIntegral page))\nafterSwitchPage nb fun = connect_BOXED_WORD__NONE \"switch-page\" \n\t\t\t (const $ return ()) True nb \n\t\t\t (\\_ page -> fun (fromIntegral page))\n\n\n \n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget Notebook@\n--\n-- Author : Axel Simon\n-- \n-- Created: 15 May 2001\n--\n-- Version $Revision: 1.2 $ from $Date: 2002\/05\/24 09:43:25 $\n--\n-- Copyright (c) 1999..2002 Axel Simon\n--\n-- This file is free software; you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation; either version 2 of the License, or\n-- (at your option) any later version.\n--\n-- This file is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- * This widget can display several pages of widgets. Each page can be \n-- selected by a tab at the top of the widget. It is useful in dialogs where\n-- a lot of information has to be displayed.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * check if it is sensible and possible to have something else than a Label\n-- widget in the context menu. If so, change the notebook*PageMenu function\n-- and add notebookSetMenuLabel and notebookSetMenuText.\n--\n-- * notebookSetTabLabelText is not bound.\n--\n-- * The signals focus-tab and select-page are not bound because it is unclear\n-- what they mean. As far as I can see they are not emitted anywhere.\n--\nmodule Notebook(\n Notebook,\n NotebookClass,\n castToNotebook,\n notebookNew,\n notebookAppendPage,\n notebookAppendPageMenu,\n notebookPrependPage,\n notebookPrependPageMenu,\n notebookInsertPage,\n notebookInsertPageMenu,\n notebookRemovePage,\n notebookPageNum,\n notebookSetCurrentPage,\n notebookNextPage,\n notebookPrevPage,\n notebookReorderChild,\n PositionType(..),\n notebookSetTabPos,\n notebookSetShowTabs,\n notebookSetShowBorder,\n notebookSetScrollable,\n notebookSetTabBorder,\n notebookSetTabHBorder,\n notebookSetTabVBorder,\n notebookSetPopup,\n notebookGetCurrentPage,\n notebookGetMenuLabel,\n notebookGetNthPage,\n notebookGetTabLabel,\n Packing(..), PackType(..),\n notebookQueryTabLabelPacking,\n notebookSetTabLabelPacking,\n notebookSetHomogeneousTabs,\n notebookSetTabLabel,\n onSwitchPage,\n afterSwitchPage\n ) where\n\nimport Monad\t(liftM)\nimport Maybe\t(maybe)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Label\t(labelNew)\nimport Enums\t(Packing(..), PackType(..), PositionType(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- @constructor notebookNew@ Create a new notebook.\n--\nnotebookNew :: IO Notebook\nnotebookNew = makeNewObject mkNotebook $ \n liftM castPtr {#call unsafe notebook_new#}\n\n-- @method notebookAppendPage@ Insert a new tab to the right of the existing\n-- tabs.\n--\n-- * The @ref arg tabName@ will be inserted as a Label widget. In case the\n-- context menu is enabled, this name will appear in the menu. If you want\n-- to specify something else to go in the tab, use\n-- @ref method notebookAppendPageMenu@ and specify some suitable widget for\n-- @ref arg menuLabel@.\n--\nnotebookAppendPage :: (NotebookClass nb, WidgetClass child) => nb -> child ->\n String -> IO ()\nnotebookAppendPage nb child tabLabel = do\n tab <- labelNew (Just tabLabel)\n {#call notebook_append_page#} (toNotebook nb) (toWidget child) \n (toWidget tab)\n\n-- @method notebookAppendPageMenu@ Insert a new tab to the right of the\n-- existing tabs. @ref arg menuLabel@ is the label for the context menu\n-- (useful if @ref arg tabLabel@ is not a Label widget).\n--\nnotebookAppendPageMenu ::(NotebookClass nb, WidgetClass child, \n WidgetClass tab) => nb -> child -> tab -> String -> IO ()\nnotebookAppendPageMenu nb child tabWidget menuLabel = do\n menu <- labelNew (Just menuLabel)\n {#call notebook_append_page_menu#} (toNotebook nb) (toWidget child)\n (toWidget tabWidget) (toWidget menu)\n\n-- @method notebookPrependPage@ Insert a new tab to the left of the existing\n-- tabs.\n--\n-- * The @ref arg tabName@ will be inserted as a Label widget. In case the\n-- context menu is enabled, this name will appear in the menu. If you want\n-- to specify something else to go in the tab, use\n-- @ref method notebookPrependPageMenu@ and specify some suitable widget for\n-- @ref arg menuLabel@.\n--\nnotebookPrependPage :: (NotebookClass nb, WidgetClass child) => nb -> child ->\n String -> IO ()\nnotebookPrependPage nb child tabLabel = do\n tab <- labelNew (Just tabLabel)\n {#call notebook_prepend_page#} (toNotebook nb) (toWidget child) (toWidget tab)\n\n-- @method notebookPrependPageMenu@ Insert a new tab to the left of the\n-- existing tabs. @ref arg menuLabel@ is the label for the context menu\n-- (useful if @ref arg tabLabel@ is not a Label widget).\n--\nnotebookPrependPageMenu ::(NotebookClass nb, WidgetClass child, \n WidgetClass tab) => nb -> child -> tab -> String -> IO ()\nnotebookPrependPageMenu nb child tabWidget menuLabel = do\n menu <- labelNew (Just menuLabel)\n {#call notebook_prepend_page_menu#} (toNotebook nb) (toWidget child)\n (toWidget tabWidget) (toWidget menu)\n\n\n-- @method notebookInsertPage@ Insert a new tab at the specified position.\n--\n-- * The @ref arg tabName@ will be inserted as a Label widget. In case the\n-- context menu is enabled, this name will appear in the menu. If you want\n-- to specify something else to go in the tab, use\n-- @ref method notebookInsertPageMenu@ and specify some suitable widget for\n-- @ref arg menuLabel@.\n--\nnotebookInsertPage :: (NotebookClass nb, WidgetClass child) => nb -> child ->\n String -> Int -> IO ()\nnotebookInsertPage nb child tabLabel pos = do\n lbl <- labelNew (Just tabLabel)\n {#call notebook_insert_page#} (toNotebook nb) (toWidget child) \n (toWidget lbl) (fromIntegral pos)\n\n-- @method notebookInsertPageMenu@ Insert a new tab between the tab no.\n-- @ref arg pos@ and @ref arg pos@+1. @ref arg menuLabel@ is the label for the\n-- context menu (useful if @ref arg tabLabel@ is not a Label widget).\n--\nnotebookInsertPageMenu ::(NotebookClass nb, WidgetClass child, \n WidgetClass tab) => nb -> child -> tab -> String -> Int -> IO ()\nnotebookInsertPageMenu nb child tabWidget menuLabel pos = do\n menu <- labelNew (Just menuLabel)\n {#call notebook_insert_page_menu#} (toNotebook nb) (toWidget child)\n (toWidget tabWidget) (toWidget menu) (fromIntegral pos)\n\n-- @method notebookRemovePage@ Remove a specific page from the notebook,\n-- counting from 0.\n--\nnotebookRemovePage :: NotebookClass nb => nb -> Int -> IO ()\nnotebookRemovePage nb pos = \n {#call notebook_remove_page#} (toNotebook nb) (fromIntegral pos)\n\n-- @method notebookPageNum@ Query the page the @ref arg child@ widget is\n-- contained in.\n--\n-- * The function returns the page number if the child was found, Nothing\n-- otherwise.\n--\nnotebookPageNum :: (NotebookClass nb, WidgetClass w) => nb -> w ->\n IO (Maybe Int)\nnotebookPageNum nb child = \n liftM (\\page -> if page==(-1) then Nothing else Just (fromIntegral page)) $\n {#call unsafe notebook_page_num#} (toNotebook nb) (toWidget child)\n\n-- @method notebookSetCurrentPage@ Move to the specified page of the notebook.\n--\n-- * If @ref arg pos@ is out of range (e.g. negative) select the last page.\n--\nnotebookSetCurrentPage :: NotebookClass nb => nb -> Int -> IO ()\nnotebookSetCurrentPage nb pos =\n {#call notebook_set_current_page#} (toNotebook nb) (fromIntegral pos)\n\n-- @method notebookNextPage@ Move to the right neighbour of the current page.\n--\n-- * Nothing happens if there is no such page.\n--\nnotebookNextPage :: NotebookClass nb => nb -> IO ()\nnotebookNextPage nb = {#call notebook_next_page#} (toNotebook nb)\n\n-- @method notebookPrevPage@ Move to the left neighbour of the current page.\n--\n-- * Nothing happens if there is no such page.\n--\nnotebookPrevPage :: NotebookClass nb => nb -> IO ()\nnotebookPrevPage nb = {#call notebook_prev_page#} (toNotebook nb)\n\n-- @method notebookReorderChild@ Move a page withing the notebook.\n--\nnotebookReorderChild :: (NotebookClass nb, WidgetClass w) => nb -> w -> Int ->\n IO ()\nnotebookReorderChild nb child pos = {#call notebook_reorder_child#}\n (toNotebook nb) (toWidget child) (fromIntegral pos)\n\n-- @method notebookSetTabPos@ Specify at which border the tabs should be\n-- drawn.\n--\nnotebookSetTabPos :: NotebookClass nb => nb -> PositionType -> IO ()\nnotebookSetTabPos nb pt = {#call notebook_set_tab_pos#}\n (toNotebook nb) ((fromIntegral.fromEnum) pt)\n\n-- @method notebookSetShowTabs@ Show or hide the tabs of a notebook.\n--\nnotebookSetShowTabs :: NotebookClass nb => nb -> Bool -> IO ()\nnotebookSetShowTabs nb showTabs = {#call notebook_set_show_tabs#}\n (toNotebook nb) (fromBool showTabs)\n\n-- @method notebookSetShowBorder@ In case the tabs are not shown, specify\n-- whether to draw a border around the notebook.\n--\nnotebookSetShowBorder :: NotebookClass nb => nb -> Bool -> IO ()\nnotebookSetShowBorder nb showBorder = {#call notebook_set_show_border#}\n (toNotebook nb) (fromBool showBorder)\n\n-- @method notebookSetScrollable@ Set whether scroll bars will be added in\n-- case the notebook has too many tabs to fit the widget size.\n--\nnotebookSetScrollable :: NotebookClass nb => nb -> Bool -> IO ()\nnotebookSetScrollable nb scrollable = {#call unsafe notebook_set_scrollable#}\n (toNotebook nb) (fromBool scrollable)\n\n-- @method notebookSetTabBorder@ Set the width of the borders of the tab\n-- labels.\n--\n-- * Sets both vertical and horizontal widths.\n--\nnotebookSetTabBorder :: NotebookClass nb => nb -> Int -> IO ()\nnotebookSetTabBorder nb width = {#call notebook_set_tab_border#}\n (toNotebook nb) (fromIntegral width)\n\n-- @method notebookSetTabHBorder@ Set the width of the borders of the tab\n-- labels.\n--\n-- * Sets horizontal widths.\n--\nnotebookSetTabHBorder :: NotebookClass nb => nb -> Int -> IO ()\nnotebookSetTabHBorder nb width = {#call notebook_set_tab_hborder#}\n (toNotebook nb) (fromIntegral width)\n\n-- @method notebookSetTabVBorder@ Set the width of the borders of the tab\n-- labels.\n--\n-- * Sets vertical widths.\n--\nnotebookSetTabVBorder :: NotebookClass nb => nb -> Int -> IO ()\nnotebookSetTabVBorder nb width = {#call notebook_set_tab_vborder#}\n (toNotebook nb) (fromIntegral width)\n\n-- @method notebookSetPopup@ Enable or disable context menus with all tabs in\n-- it.\n--\nnotebookSetPopup :: NotebookClass nb => nb -> Bool -> IO ()\nnotebookSetPopup nb enable = (if enable \n then {#call notebook_popup_enable#} else {#call notebook_popup_disable#})\n (toNotebook nb)\n\n-- @method notebookGetCurrentPage@ Query the currently selected page.\n--\n-- * Returns -1 if notebook has no pages.\n--\nnotebookGetCurrentPage :: NotebookClass nb => nb -> IO Int\nnotebookGetCurrentPage nb = liftM fromIntegral $\n {#call unsafe notebook_get_current_page#} (toNotebook nb)\n\n-- @method notebookGetMenuLabel@ Extract the menu label from the given\n-- @ref arg child@.\n--\n-- * Returns Nothing if @ref arg child@ was not found.\n--\nnotebookGetMenuLabel :: (NotebookClass nb, WidgetClass w) => nb -> w ->\n IO (Maybe Label)\nnotebookGetMenuLabel nb child = do\n wPtr <- {#call unsafe notebook_get_menu_label#} \n (toNotebook nb) (toWidget child)\n if wPtr==nullPtr then return Nothing else liftM Just $\n makeNewObject mkLabel $ return $ castPtr wPtr\n\n-- @method notebookGetNthPage@ Retrieve the child widget at positon\n-- @ref arg pos@ (stating from 0).\n--\n-- * Returns Nothing if the index is out of bounds.\n--\nnotebookGetNthPage :: NotebookClass nb => nb -> Int -> IO (Maybe Widget)\nnotebookGetNthPage nb pos = do\n wPtr <- {#call unsafe notebook_get_nth_page#} \n (toNotebook nb) (fromIntegral pos)\n if wPtr==nullPtr then return Nothing else liftM Just $\n makeNewObject mkWidget $ return wPtr\n\n-- @method notebookGetTabLabel@ Extract the tab label from the given\n-- @ref arg child@.\n--\nnotebookGetTabLabel :: (NotebookClass nb, WidgetClass w) => nb -> w ->\n IO (Maybe Label)\nnotebookGetTabLabel nb child = do\n wPtr <- {#call unsafe notebook_get_tab_label#} \n (toNotebook nb) (toWidget child)\n if wPtr==nullPtr then return Nothing else liftM Just $\n makeNewObject mkLabel $ return $ castPtr wPtr\n\n-- @method notebookQueryTabLabelPacking@ Query the packing attributes of the\n-- given @ref arg child@.\n--\nnotebookQueryTabLabelPacking :: (NotebookClass nb, WidgetClass w) => nb -> w ->\n IO (Packing,PackType)\nnotebookQueryTabLabelPacking nb child = \n alloca $ \\expPtr -> alloca $ \\fillPtr -> alloca $ \\packPtr -> do\n {#call unsafe notebook_query_tab_label_packing#} (toNotebook nb)\n (toWidget child) expPtr fillPtr packPtr\n expand <- liftM toBool $ peek expPtr\n fill <- liftM toBool $ peek fillPtr\n pt <- liftM (toEnum.fromIntegral) $ peek packPtr\n return (if fill then PackFill else \n (if expand then PackExpand else PackNatural),\n\t pt)\n\n-- @method notebookSetTabLabelPacking@ Set the packing attributes of the given\n-- @ref arg child@.\n--\nnotebookSetTabLabelPacking :: (NotebookClass nb, WidgetClass w) => nb -> w ->\n Packing -> PackType -> IO ()\nnotebookSetTabLabelPacking nb child pack pt = \n {#call notebook_set_tab_label_packing#} (toNotebook nb) (toWidget child)\n (fromBool $ pack\/=PackNatural) (fromBool $ pack==PackFill) \n ((fromIntegral.fromEnum) pt)\n\n-- @method notebookSetHomogeneousTabs@ Sets whether the tabs must have all the\n-- same size or not.\n--\nnotebookSetHomogeneousTabs :: NotebookClass nb => nb -> Bool -> IO ()\nnotebookSetHomogeneousTabs nb hom = {#call notebook_set_homogeneous_tabs#}\n (toNotebook nb) (fromBool hom)\n\n\n-- @method notebookSetTabLabel@ Set a new tab label for a given\n-- @ref arg child@.\n--\nnotebookSetTabLabel :: (NotebookClass nb, WidgetClass ch, WidgetClass tab) => \n nb -> ch -> tab -> IO ()\nnotebookSetTabLabel nb child tab = {#call notebook_set_tab_label#}\n (toNotebook nb) (toWidget child) (toWidget tab)\n\n-- signals\n\n-- @signal connectToSwitchPage@ This signal is emitted when a new page is\n-- selected.\n--\nonSwitchPage, afterSwitchPage :: NotebookClass nb => nb -> (Int -> IO ()) ->\n IO (ConnectId nb)\nonSwitchPage nb fun = connect_BOXED_WORD__NONE \"switch-page\" \n\t\t (const $ return ()) False nb \n\t\t (\\_ page -> fun (fromIntegral page))\nafterSwitchPage nb fun = connect_BOXED_WORD__NONE \"switch-page\" \n\t\t\t (const $ return ()) True nb \n\t\t\t (\\_ page -> fun (fromIntegral page))\n\n\n ","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"58914389b89204a97c5cb6021940391ebbc83c88","subject":"Fix TextView signals.","message":"Fix TextView signals.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk\/Multiline\/TextView.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Multiline\/TextView.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget TextView\n--\n-- Author : Axel Simon\n--\n-- Created: 23 February 2002\n--\n-- Copyright (C) 2002-2005 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- TODO\n--\n-- If PangoTabArray is bound: \n-- Fucntions: textViewSetTabs and textViewGetTabs\n-- Properties: textViewTabs\n--\n-- All on... and after... signales had incorrect names (underscore instead of hypens). Thus\n-- they could not have been used in applications and removing them can't break anything.\n-- Thus, I've removed them. Also, all key-binding singals are now removed as there is\n-- no way to add additional key bindings programatically in a type-safe way, let alone\n-- use these signals.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Widget that displays a 'TextBuffer'\n--\nmodule Graphics.UI.Gtk.Multiline.TextView (\n-- * Detail\n-- \n-- | You may wish to begin by reading the text widget conceptual overview\n-- which gives an overview of all the objects and data types related to the\n-- text widget and how they work together.\n--\n-- Throughout we distinguish between buffer coordinates which are pixels with\n-- the origin at the upper left corner of the first character on the first\n-- line. Window coordinates are relative to the top left pixel which is visible\n-- in the current 'TextView'. Coordinates from Events are in the latter\n-- relation. The conversion can be done with 'textViewWindowToBufferCoords'.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----TextView\n-- |\n-- |\n-- | 'GObject'\n-- | +----TextChildAnchor\n-- @\n\n-- * Types\n TextView,\n TextViewClass,\n TextChildAnchor,\n TextChildAnchorClass,\n castToTextView, gTypeTextView,\n toTextView,\n DeleteType(..),\n DirectionType(..),\n Justification(..),\n MovementStep(..),\n TextWindowType(..),\n WrapMode(..),\n\n-- * Constructors\n textViewNew,\n textViewNewWithBuffer,\n\n-- * Methods\n textViewSetBuffer,\n textViewGetBuffer,\n textViewScrollToMark,\n textViewScrollToIter,\n textViewScrollMarkOnscreen,\n textViewMoveMarkOnscreen,\n textViewPlaceCursorOnscreen,\n textViewGetLineAtY,\n textViewGetLineYrange,\n textViewGetIterAtLocation,\n textViewBufferToWindowCoords,\n textViewWindowToBufferCoords,\n textViewGetWindow,\n textViewGetWindowType,\n textViewSetBorderWindowSize,\n textViewGetBorderWindowSize,\n textViewForwardDisplayLine,\n textViewBackwardDisplayLine,\n textViewForwardDisplayLineEnd,\n textViewBackwardDisplayLineStart,\n textViewStartsDisplayLine,\n textViewMoveVisually,\n textViewAddChildAtAnchor,\n textChildAnchorNew,\n textChildAnchorGetWidgets,\n textChildAnchorGetDeleted,\n textViewAddChildInWindow,\n textViewMoveChild,\n textViewSetWrapMode,\n textViewGetWrapMode,\n textViewSetEditable,\n textViewGetEditable,\n textViewSetCursorVisible,\n textViewGetCursorVisible,\n textViewSetPixelsAboveLines,\n textViewGetPixelsAboveLines,\n textViewSetPixelsBelowLines,\n textViewGetPixelsBelowLines,\n textViewSetPixelsInsideWrap,\n textViewGetPixelsInsideWrap,\n textViewSetJustification,\n textViewGetJustification,\n textViewSetLeftMargin,\n textViewGetLeftMargin,\n textViewSetRightMargin,\n textViewGetRightMargin,\n textViewSetIndent,\n textViewGetIndent,\n textViewGetDefaultAttributes,\n textViewGetVisibleRect,\n textViewGetIterLocation,\n#if GTK_CHECK_VERSION(2,6,0)\n textViewGetIterAtPosition,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n textViewSetOverwrite,\n textViewGetOverwrite,\n textViewSetAcceptsTab,\n textViewGetAcceptsTab,\n#endif\n\n-- * Attributes\n textViewPixelsAboveLines,\n textViewPixelsBelowLines,\n textViewPixelsInsideWrap,\n textViewEditable,\n textViewImModule,\n textViewWrapMode,\n textViewJustification,\n textViewLeftMargin,\n textViewRightMargin,\n textViewIndent,\n textViewCursorVisible,\n textViewBuffer,\n#if GTK_CHECK_VERSION(2,4,0)\n textViewOverwrite,\n textViewAcceptsTab,\n#endif\n\n-- * Signals\n backspace,\n copyClipboard,\n cutClipboard,\n deleteFromCursor,\n insertAtCursor,\n moveCursor,\n moveViewport,\n moveFocus,\n pageHorizontally,\n pasteClipboard,\n populatePopup,\n selectAll,\n setAnchor,\n setScrollAdjustments,\n toggleCursorVisible,\n toggleOverwrite,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\nimport System.Glib.Properties (newAttrFromStringProperty)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Multiline.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n{#import Graphics.UI.Gtk.Multiline.TextTag#}\nimport Graphics.UI.Gtk.General.Enums\t(TextWindowType(..), DeleteType(..),\n\t\t\t\t\t DirectionType(..), Justification(..),\n\t\t\t\t\t MovementStep(..), WrapMode(..),\n ScrollStep (..))\nimport System.Glib.GList\t\t(fromGList)\nimport Graphics.UI.Gtk.General.Structs\t(Rectangle(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Creates a new 'TextView'. If you don't call 'textViewSetBuffer' before\n-- using the text view, an empty default buffer will be created for you. Get\n-- the buffer with 'textViewGetBuffer'. If you want to specify your own buffer,\n-- consider 'textViewNewWithBuffer'.\n--\ntextViewNew :: IO TextView\ntextViewNew =\n makeNewObject mkTextView $\n liftM (castPtr :: Ptr Widget -> Ptr TextView) $\n {# call unsafe text_view_new #}\n\n-- | Creates a new 'TextView' widget displaying the buffer @buffer@. One\n-- buffer can be shared among many widgets.\n--\ntextViewNewWithBuffer :: TextBufferClass buffer => buffer -> IO TextView\ntextViewNewWithBuffer buffer =\n makeNewObject mkTextView $\n liftM (castPtr :: Ptr Widget -> Ptr TextView) $\n {# call text_view_new_with_buffer #}\n (toTextBuffer buffer)\n\n--------------------\n-- Methods\n\n-- | Sets the given buffer as the buffer being displayed by the text view.\n--\ntextViewSetBuffer :: (TextViewClass self, TextBufferClass buffer) => self -> buffer -> IO ()\ntextViewSetBuffer self buffer =\n {# call text_view_set_buffer #}\n (toTextView self)\n (toTextBuffer buffer)\n\n-- | Returns the 'TextBuffer' being displayed by this text view.\n--\ntextViewGetBuffer :: TextViewClass self => self -> IO TextBuffer\ntextViewGetBuffer self =\n makeNewGObject mkTextBuffer $\n {# call unsafe text_view_get_buffer #}\n (toTextView self)\n\n-- | Scrolls the text view so that @mark@ is on the screen in the position\n-- indicated by @xalign@ and @yalign@. An alignment of 0.0 indicates left or\n-- top, 1.0 indicates right or bottom, 0.5 means center. If the alignment is\n-- @Nothing@, the text scrolls the minimal distance to get the mark onscreen,\n-- possibly not scrolling at all. The effective screen for purposes of this\n-- function is reduced by a margin of size @withinMargin@.\n--\ntextViewScrollToMark :: (TextViewClass self, TextMarkClass mark) => self\n -> mark -- ^ @mark@ - a 'TextMark'\n -> Double -- ^ @withinMargin@ - margin as a [0.0,0.5) fraction of screen size\n -- and imposes an extra margin at all four sides of the window\n -- within which @xalign@ and @yalign@ are evaluated.\n -> Maybe (Double, Double) -- ^ @Just (xalign, yalign)@ - horizontal and\n -- vertical alignment of mark within visible area (if @Nothing@,\n -- scroll just enough to get the mark onscreen)\n -> IO ()\ntextViewScrollToMark self mark withinMargin align =\n let (useAlign, xalign, yalign) = case align of\n Nothing -> (False, 0, 0)\n Just (xalign, yalign) -> (True, xalign, yalign)\n in\n {# call text_view_scroll_to_mark #}\n (toTextView self)\n (toTextMark mark)\n (realToFrac withinMargin)\n (fromBool useAlign)\n (realToFrac xalign)\n (realToFrac yalign)\n\n-- | Scrolls the text view so that @iter@ is on the screen in the position\n-- indicated by @xalign@ and @yalign@. An alignment of 0.0 indicates left or\n-- top, 1.0 indicates right or bottom, 0.5 means center. If the alignment is\n-- @Nothing@, the text scrolls the minimal distance to get the mark onscreen,\n-- possibly not scrolling at all. The effective screen for purposes of this\n-- function is reduced by a margin of size @withinMargin@.\n--\n-- * This function\n-- uses the currently-computed height of the lines in the text buffer. Note\n-- that line heights are computed in an idle handler; so this function may\n-- not\n-- have the desired effect if it's called before the height computations. To\n-- avoid oddness, consider using 'textViewScrollToMark' which saves a point\n-- to be scrolled to after line validation. This is particularly important\n-- if you add new text to the buffer and immediately ask the view to scroll\n-- to it (which it can't since it is not updated until the main loop runs).\n--\ntextViewScrollToIter :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> Double -- ^ @withinMargin@ - margin as a [0.0,0.5) fraction of screen\n -- size\n -> Maybe (Double, Double) -- ^ @Just (xalign, yalign)@ - horizontal and\n -- vertical alignment of mark within visible area (if @Nothing@,\n -- scroll just enough to get the iterator onscreen)\n -> IO Bool -- ^ returns @True@ if scrolling occurred\ntextViewScrollToIter self iter withinMargin align = \n let (useAlign, xalign, yalign) = case align of\n Nothing -> (False, 0, 0)\n Just (xalign, yalign) -> (True, xalign, yalign)\n in\n liftM toBool $\n {# call text_view_scroll_to_iter #}\n (toTextView self)\n iter\n (realToFrac withinMargin)\n (fromBool useAlign)\n (realToFrac xalign)\n (realToFrac yalign)\n\n-- | Scrolls the text view the minimum distance such that @mark@ is contained\n-- within the visible area of the widget.\n--\ntextViewScrollMarkOnscreen :: (TextViewClass self, TextMarkClass mark) => self\n -> mark -- ^ @mark@ - a mark in the buffer for the text view\n -> IO ()\ntextViewScrollMarkOnscreen self mark =\n {# call text_view_scroll_mark_onscreen #}\n (toTextView self)\n (toTextMark mark)\n\n-- | Moves a mark within the buffer so that it's located within the\n-- currently-visible text area.\n--\ntextViewMoveMarkOnscreen :: (TextViewClass self, TextMarkClass mark) => self\n -> mark -- ^ @mark@ - a 'TextMark'\n -> IO Bool -- ^ returns @True@ if the mark moved (wasn't already onscreen)\ntextViewMoveMarkOnscreen self mark =\n liftM toBool $\n {# call text_view_move_mark_onscreen #}\n (toTextView self)\n (toTextMark mark)\n\n-- | Moves the cursor to the currently visible region of the buffer, it it\n-- isn't there already.\n--\ntextViewPlaceCursorOnscreen :: TextViewClass self => self\n -> IO Bool -- ^ returns @True@ if the cursor had to be moved.\ntextViewPlaceCursorOnscreen self =\n liftM toBool $\n {# call text_view_place_cursor_onscreen #}\n (toTextView self)\n\n-- | Returns the currently-visible region of the buffer, in\n-- buffer coordinates. Convert to window coordinates with\n-- 'textViewBufferToWindowCoords'.\n--\ntextViewGetVisibleRect :: TextViewClass self => self -> IO Rectangle\ntextViewGetVisibleRect self =\n alloca $ \\rectPtr -> do\n {# call unsafe text_view_get_visible_rect #}\n (toTextView self)\n (castPtr rectPtr)\n peek rectPtr\n\n-- | Gets a rectangle which roughly contains the character at @iter@. The\n-- rectangle position is in buffer coordinates; use\n-- 'textViewBufferToWindowCoords' to convert these coordinates to coordinates\n-- for one of the windows in the text view.\n--\ntextViewGetIterLocation :: TextViewClass self => self -> TextIter -> IO Rectangle\ntextViewGetIterLocation self iter =\n alloca $ \\rectPtr -> do\n {# call unsafe text_view_get_iter_location #}\n (toTextView self)\n iter\n (castPtr rectPtr)\n peek rectPtr\n\n-- | Gets the 'TextIter' at the start of the line containing the coordinate\n-- @y@. @y@ is in buffer coordinates, convert from window coordinates with\n-- 'textViewWindowToBufferCoords'. Also returns @lineTop@ the\n-- coordinate of the top edge of the line.\n--\ntextViewGetLineAtY :: TextViewClass self => self\n -> Int -- ^ @y@ - a y coordinate\n -> IO (TextIter, Int) -- ^ @(targetIter, lineTop)@ - returns the iter and the\n -- top coordinate of the line\ntextViewGetLineAtY self y =\n makeEmptyTextIter >>= \\targetIter ->\n alloca $ \\lineTopPtr -> do\n {# call unsafe text_view_get_line_at_y #}\n (toTextView self)\n targetIter\n (fromIntegral y)\n lineTopPtr\n lineTop <- peek lineTopPtr\n return (targetIter, fromIntegral lineTop)\n\n-- | Gets the y coordinate of the top of the line containing @iter@, and the\n-- height of the line. The coordinate is a buffer coordinate; convert to window\n-- coordinates with 'textViewBufferToWindowCoords'.\n--\ntextViewGetLineYrange :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO (Int, Int) -- ^ @(y, height)@ - y coordinate and height of the line\ntextViewGetLineYrange self iter =\n alloca $ \\yPtr ->\n alloca $ \\heightPtr -> do\n {# call unsafe text_view_get_line_yrange #}\n (toTextView self)\n iter\n yPtr\n heightPtr\n y <- peek yPtr\n height <- peek heightPtr\n return (fromIntegral y, fromIntegral height)\n\n-- | Retrieves the iterator at buffer coordinates @x@ and @y@. Buffer\n-- coordinates are coordinates for the entire buffer, not just the\n-- currently-displayed portion. If you have coordinates from an event, you have\n-- to convert those to buffer coordinates with 'textViewWindowToBufferCoords'.\n--\ntextViewGetIterAtLocation :: TextViewClass self => self\n -> Int -- ^ @x@ - x position, in buffer coordinates\n -> Int -- ^ @y@ - y position, in buffer coordinates\n -> IO TextIter\ntextViewGetIterAtLocation self x y = do\n iter <- makeEmptyTextIter\n {# call unsafe text_view_get_iter_at_location #}\n (toTextView self)\n iter\n (fromIntegral x)\n (fromIntegral y)\n return iter\n\n-- | Converts coordinate @(bufferX, bufferY)@ to coordinates for the window\n-- @win@\n--\n-- Note that you can't convert coordinates for a nonexisting window (see\n-- 'textViewSetBorderWindowSize').\n--\ntextViewBufferToWindowCoords :: TextViewClass self => self\n -> TextWindowType -- ^ @win@ - a 'TextWindowType' except 'TextWindowPrivate'\n -> (Int, Int) -- ^ @(bufferX, bufferY)@ - buffer x and y coordinates\n -> IO (Int, Int) -- ^ returns window x and y coordinates\ntextViewBufferToWindowCoords self win (bufferX, bufferY) =\n alloca $ \\windowXPtr ->\n alloca $ \\windowYPtr -> do\n {# call unsafe text_view_buffer_to_window_coords #}\n (toTextView self)\n ((fromIntegral . fromEnum) win)\n (fromIntegral bufferX)\n (fromIntegral bufferY)\n windowXPtr\n windowYPtr\n windowX <- peek windowXPtr\n windowY <- peek windowYPtr\n return (fromIntegral windowX, fromIntegral windowY)\n\n-- | Converts coordinates on the window identified by @win@ to buffer\n-- coordinates.\n--\n-- Note that you can't convert coordinates for a nonexisting window (see\n-- 'textViewSetBorderWindowSize').\n--\ntextViewWindowToBufferCoords :: TextViewClass self => self\n -> TextWindowType -- ^ @win@ - a 'TextWindowType' except 'TextWindowPrivate'\n -> (Int, Int) -- ^ @(windowX, windowY)@ - window x and y coordinates\n -> IO (Int, Int) -- ^ returns buffer x and y coordinates\ntextViewWindowToBufferCoords self win (windowX, windowY) =\n alloca $ \\bufferXPtr ->\n alloca $ \\bufferYPtr -> do\n {# call unsafe text_view_window_to_buffer_coords #}\n (toTextView self)\n ((fromIntegral . fromEnum) win)\n (fromIntegral windowX)\n (fromIntegral windowY)\n bufferXPtr\n bufferYPtr\n bufferX <- peek bufferXPtr\n bufferY <- peek bufferYPtr\n return (fromIntegral bufferX, fromIntegral bufferY)\n\n-- | Retrieves the 'DrawWindow' corresponding to an area of the text view;\n-- possible windows include the overall widget window, child windows on the\n-- left, right, top, bottom, and the window that displays the text buffer.\n-- Windows are @Nothing@ and nonexistent if their width or height is 0, and are\n-- nonexistent before the widget has been realized.\n--\ntextViewGetWindow :: TextViewClass self => self\n -> TextWindowType -- ^ @win@ - window to get\n -> IO (Maybe DrawWindow) -- ^ returns a 'DrawWindow', or @Nothing@\ntextViewGetWindow self win =\n maybeNull (makeNewGObject mkDrawWindow) $\n {# call unsafe text_view_get_window #}\n (toTextView self)\n ((fromIntegral . fromEnum) win)\n\n-- | Retrieve the type of window the 'TextView' widget contains.\n--\n-- Usually used to find out which window an event corresponds to. An emission\n-- of an event signal of 'TextView' yields a 'DrawWindow'. This function can be\n-- used to see if the event actually belongs to the main text window.\n--\ntextViewGetWindowType :: TextViewClass self => self\n -> DrawWindow\n -> IO TextWindowType\ntextViewGetWindowType self window =\n liftM (toEnum . fromIntegral) $\n {# call unsafe text_view_get_window_type #}\n (toTextView self)\n window\n\n-- | Sets the width of 'TextWindowLeft' or 'TextWindowRight', or the height of\n-- 'TextWindowTop' or 'TextWindowBottom'. Automatically destroys the\n-- corresponding window if the size is set to 0, and creates the window if the\n-- size is set to non-zero. This function can only be used for the \\\"border\n-- windows\\\", it doesn't work with 'TextWindowWidget', 'TextWindowText', or\n-- 'TextWindowPrivate'.\n--\ntextViewSetBorderWindowSize :: TextViewClass self => self\n -> TextWindowType -- ^ @type@ - window to affect\n -> Int -- ^ @size@ - width or height of the window\n -> IO ()\ntextViewSetBorderWindowSize self type_ size =\n {# call text_view_set_border_window_size #}\n (toTextView self)\n ((fromIntegral . fromEnum) type_)\n (fromIntegral size)\n\n-- | Gets the width of the specified border window. See\n-- 'textViewSetBorderWindowSize'.\n--\ntextViewGetBorderWindowSize :: TextViewClass self => self\n -> TextWindowType -- ^ @type@ - window to return size from\n -> IO Int -- ^ returns width of window\ntextViewGetBorderWindowSize self type_ =\n liftM fromIntegral $\n {# call unsafe text_view_get_border_window_size #}\n (toTextView self)\n ((fromIntegral . fromEnum) type_)\n\n-- | Moves the given @iter@ forward by one display (wrapped) line. A display\n-- line is different from a paragraph. Paragraphs are separated by newlines or\n-- other paragraph separator characters. Display lines are created by\n-- line-wrapping a paragraph. If wrapping is turned off, display lines and\n-- paragraphs will be the same. Display lines are divided differently for each\n-- view, since they depend on the view's width; paragraphs are the same in all\n-- views, since they depend on the contents of the 'TextBuffer'.\n--\ntextViewForwardDisplayLine :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ was moved and is not on the end\n -- iterator\ntextViewForwardDisplayLine self iter =\n liftM toBool $\n {# call unsafe text_view_forward_display_line #}\n (toTextView self)\n iter\n\n-- | Moves the given @iter@ backward by one display (wrapped) line. A display\n-- line is different from a paragraph. Paragraphs are separated by newlines or\n-- other paragraph separator characters. Display lines are created by\n-- line-wrapping a paragraph. If wrapping is turned off, display lines and\n-- paragraphs will be the same. Display lines are divided differently for each\n-- view, since they depend on the view's width; paragraphs are the same in all\n-- views, since they depend on the contents of the 'TextBuffer'.\n--\ntextViewBackwardDisplayLine :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ was moved and is not on the end\n -- iterator\ntextViewBackwardDisplayLine self iter =\n liftM toBool $\n {# call unsafe text_view_backward_display_line #}\n (toTextView self)\n iter\n\n-- | Moves the given @iter@ forward to the next display line end. A display\n-- line is different from a paragraph. Paragraphs are separated by newlines or\n-- other paragraph separator characters. Display lines are created by\n-- line-wrapping a paragraph. If wrapping is turned off, display lines and\n-- paragraphs will be the same. Display lines are divided differently for each\n-- view, since they depend on the view's width; paragraphs are the same in all\n-- views, since they depend on the contents of the 'TextBuffer'.\n--\ntextViewForwardDisplayLineEnd :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ was moved and is not on the end\n -- iterator\ntextViewForwardDisplayLineEnd self iter =\n liftM toBool $\n {# call unsafe text_view_forward_display_line_end #}\n (toTextView self)\n iter\n\n-- | Moves the given @iter@ backward to the next display line start. A display\n-- line is different from a paragraph. Paragraphs are separated by newlines or\n-- other paragraph separator characters. Display lines are created by\n-- line-wrapping a paragraph. If wrapping is turned off, display lines and\n-- paragraphs will be the same. Display lines are divided differently for each\n-- view, since they depend on the view's width; paragraphs are the same in all\n-- views, since they depend on the contents of the 'TextBuffer'.\n--\ntextViewBackwardDisplayLineStart :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ was moved and is not on the end\n -- iterator\ntextViewBackwardDisplayLineStart self iter =\n liftM toBool $\n {# call unsafe text_view_backward_display_line_start #}\n (toTextView self)\n iter\n\n-- | Determines whether @iter@ is at the start of a display line. See\n-- 'textViewForwardDisplayLine' for an explanation of display lines vs.\n-- paragraphs.\n--\ntextViewStartsDisplayLine :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ begins a wrapped line\ntextViewStartsDisplayLine self iter =\n liftM toBool $\n {# call unsafe text_view_starts_display_line #}\n (toTextView self)\n iter\n\n-- | Move the iterator a given number of characters visually, treating it as\n-- the strong cursor position. If @count@ is positive, then the new strong\n-- cursor position will be @count@ positions to the right of the old cursor\n-- position. If @count@ is negative then the new strong cursor position will be\n-- @count@ positions to the left of the old cursor position.\n--\n-- In the presence of bidirection text, the correspondence between logical\n-- and visual order will depend on the direction of the current run, and there\n-- may be jumps when the cursor is moved off of the end of a run.\n--\ntextViewMoveVisually :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> Int -- ^ @count@ - number of characters to move (negative moves left,\n -- positive moves right)\n -> IO Bool -- ^ returns @True@ if @iter@ moved and is not on the end\n -- iterator\ntextViewMoveVisually self iter count =\n liftM toBool $\n {# call unsafe text_view_move_visually #}\n (toTextView self)\n iter\n (fromIntegral count)\n\n-- | Adds a child widget in the text buffer, at the given @anchor@.\n--\ntextViewAddChildAtAnchor :: (TextViewClass self, WidgetClass child) => self\n -> child -- ^ @child@ - a 'Widget'\n -> TextChildAnchor -- ^ @anchor@ - a 'TextChildAnchor' in the 'TextBuffer'\n -- for the text view\n -> IO ()\ntextViewAddChildAtAnchor self child anchor =\n {# call text_view_add_child_at_anchor #}\n (toTextView self)\n (toWidget child)\n anchor\n\n-- | Create a new 'TextChildAnchor'.\n--\n-- * Using 'textBufferCreateChildAnchor' is usually simpler then\n-- executing this function and 'textBufferInsertChildAnchor'.\n--\ntextChildAnchorNew :: IO TextChildAnchor\ntextChildAnchorNew =\n constructNewGObject mkTextChildAnchor\n {# call unsafe text_child_anchor_new #}\n\n-- | Retrieve all 'Widget's at this\n-- 'TextChildAnchor'.\n--\n-- * The widgets in the returned list need to be upcasted to what they were.\n--\ntextChildAnchorGetWidgets :: TextChildAnchor -> IO [Widget]\ntextChildAnchorGetWidgets tca = do\n gList <- {# call text_child_anchor_get_widgets #} tca\n wList <- fromGList gList\n mapM (makeNewObject mkWidget) (map return wList)\n\n-- | Query if an anchor was deleted.\n--\ntextChildAnchorGetDeleted :: TextChildAnchor -> IO Bool\ntextChildAnchorGetDeleted tca =\n liftM toBool $\n {# call unsafe text_child_anchor_get_deleted #} tca\n\n-- | Adds a child at fixed coordinates in one of the text widget's windows.\n-- The window must have nonzero size (see 'textViewSetBorderWindowSize'). Note\n-- that the child coordinates are given relative to the 'DrawWindow' in\n-- question, and that these coordinates have no sane relationship to scrolling.\n-- When placing a child in 'TextWindowWidget', scrolling is irrelevant, the\n-- child floats above all scrollable areas. If you want the widget to move when\n-- the text view scrolls, use 'textViewAddChildAtAnchor' instead.\n--\ntextViewAddChildInWindow :: (TextViewClass self, WidgetClass child) => self\n -> child -- ^ @child@ - a 'Widget'\n -> TextWindowType -- ^ @whichWindow@ - which window the child should appear\n -- in\n -> Int -- ^ @xpos@ - X position of child in window coordinates\n -> Int -- ^ @ypos@ - Y position of child in window coordinates\n -> IO ()\ntextViewAddChildInWindow self child whichWindow xpos ypos =\n {# call text_view_add_child_in_window #}\n (toTextView self)\n (toWidget child)\n ((fromIntegral . fromEnum) whichWindow)\n (fromIntegral xpos)\n (fromIntegral ypos)\n\n-- | Move a child widget within the 'TextView'. This is really only apprpriate\n-- for \\\"floating\\\" child widgets added using 'textViewAddChildInWindow'.\n--\ntextViewMoveChild :: (TextViewClass self, WidgetClass child) => self\n -> child -- ^ @child@ - child widget already added to the text view\n -> Int -- ^ @xpos@ - new X position in window coordinates\n -> Int -- ^ @ypos@ - new Y position in window coordinates\n -> IO ()\ntextViewMoveChild self child xpos ypos =\n {# call text_view_move_child #}\n (toTextView self)\n (toWidget child)\n (fromIntegral xpos)\n (fromIntegral ypos)\n\n-- | Sets the line wrapping for the view.\n--\ntextViewSetWrapMode :: TextViewClass self => self -> WrapMode -> IO ()\ntextViewSetWrapMode self wrapMode =\n {# call text_view_set_wrap_mode #}\n (toTextView self)\n ((fromIntegral . fromEnum) wrapMode)\n\n-- | Gets the line wrapping for the view.\n--\ntextViewGetWrapMode :: TextViewClass self => self -> IO WrapMode\ntextViewGetWrapMode self =\n liftM (toEnum . fromIntegral) $\n {# call unsafe text_view_get_wrap_mode #}\n (toTextView self)\n\n-- | Sets the default editability of the 'TextView'. You can override this\n-- default setting with tags in the buffer, using the \\\"editable\\\" attribute of\n-- tags.\n--\ntextViewSetEditable :: TextViewClass self => self -> Bool -> IO ()\ntextViewSetEditable self setting =\n {# call text_view_set_editable #}\n (toTextView self)\n (fromBool setting)\n\n-- | Returns the default editability of the 'TextView'. Tags in the buffer may\n-- override this setting for some ranges of text.\n--\ntextViewGetEditable :: TextViewClass self => self -> IO Bool\ntextViewGetEditable self =\n liftM toBool $\n {# call unsafe text_view_get_editable #}\n (toTextView self)\n\n-- | Toggles whether the insertion point is displayed. A buffer with no\n-- editable text probably shouldn't have a visible cursor, so you may want to\n-- turn the cursor off.\n--\ntextViewSetCursorVisible :: TextViewClass self => self -> Bool -> IO ()\ntextViewSetCursorVisible self setting =\n {# call text_view_set_cursor_visible #}\n (toTextView self)\n (fromBool setting)\n\n-- | Find out whether the cursor is being displayed.\n--\ntextViewGetCursorVisible :: TextViewClass self => self -> IO Bool\ntextViewGetCursorVisible self =\n liftM toBool $\n {# call unsafe text_view_get_cursor_visible #}\n (toTextView self)\n\n-- | Sets the default number of blank pixels above paragraphs in the text view.\n-- Tags in the buffer for the text view may override the defaults.\n--\n-- * Tags in the buffer may override this default.\n--\ntextViewSetPixelsAboveLines :: TextViewClass self => self -> Int -> IO ()\ntextViewSetPixelsAboveLines self pixelsAboveLines =\n {# call text_view_set_pixels_above_lines #}\n (toTextView self)\n (fromIntegral pixelsAboveLines)\n\n-- | Gets the default number of pixels to put above paragraphs.\n--\ntextViewGetPixelsAboveLines :: TextViewClass self => self -> IO Int\ntextViewGetPixelsAboveLines self =\n liftM fromIntegral $\n {# call unsafe text_view_get_pixels_above_lines #}\n (toTextView self)\n\n-- | Sets the default number of pixels of blank space to put below paragraphs\n-- in the text view. May be overridden by tags applied to the text view's\n-- buffer.\n--\ntextViewSetPixelsBelowLines :: TextViewClass self => self -> Int -> IO ()\ntextViewSetPixelsBelowLines self pixelsBelowLines =\n {# call text_view_set_pixels_below_lines #}\n (toTextView self)\n (fromIntegral pixelsBelowLines)\n\n-- | Gets the default number of blank pixels below each paragraph.\n--\ntextViewGetPixelsBelowLines :: TextViewClass self => self -> IO Int\ntextViewGetPixelsBelowLines self =\n liftM fromIntegral $\n {# call unsafe text_view_get_pixels_below_lines #}\n (toTextView self)\n\n-- | Sets the default number of pixels of blank space to leave between\n-- display\\\/wrapped lines within a paragraph. May be overridden by tags in\n-- the text view's buffer.\n--\ntextViewSetPixelsInsideWrap :: TextViewClass self => self -> Int -> IO ()\ntextViewSetPixelsInsideWrap self pixelsInsideWrap =\n {# call text_view_set_pixels_inside_wrap #}\n (toTextView self)\n (fromIntegral pixelsInsideWrap)\n\n-- | Gets the default number of pixels of blank space between lines in a\n-- wrapped paragraph.\n--\ntextViewGetPixelsInsideWrap :: TextViewClass self => self -> IO Int\ntextViewGetPixelsInsideWrap self =\n liftM fromIntegral $\n {# call unsafe text_view_get_pixels_inside_wrap #}\n (toTextView self)\n\n-- | Sets the default justification of text in the text view. Tags in the\n-- view's buffer may override the default.\n--\ntextViewSetJustification :: TextViewClass self => self -> Justification -> IO ()\ntextViewSetJustification self justification =\n {# call text_view_set_justification #}\n (toTextView self)\n ((fromIntegral . fromEnum) justification)\n\n-- | Gets the default justification of paragraphs in the text view. Tags in the\n-- buffer may override the default.\n--\ntextViewGetJustification :: TextViewClass self => self -> IO Justification\ntextViewGetJustification self =\n liftM (toEnum . fromIntegral) $\n {# call unsafe text_view_get_justification #}\n (toTextView self)\n\n-- | Sets the default left margin for text in the text view. Tags in the buffer\n-- may override the default.\n--\ntextViewSetLeftMargin :: TextViewClass self => self\n -> Int -- ^ @leftMargin@ - left margin in pixels\n -> IO ()\ntextViewSetLeftMargin self leftMargin =\n {# call text_view_set_left_margin #}\n (toTextView self)\n (fromIntegral leftMargin)\n\n-- | Gets the default left margin size of paragraphs in the text view. Tags\n-- in the buffer may override the default.\n--\ntextViewGetLeftMargin :: TextViewClass self => self\n -> IO Int -- ^ returns left margin in pixels\ntextViewGetLeftMargin self =\n liftM fromIntegral $\n {# call unsafe text_view_get_left_margin #}\n (toTextView self)\n\n-- | Sets the default right margin for text in the text view. Tags in the\n-- buffer may override the default.\n--\ntextViewSetRightMargin :: TextViewClass self => self\n -> Int -- ^ @rightMargin@ - right margin in pixels\n -> IO ()\ntextViewSetRightMargin self rightMargin =\n {# call text_view_set_right_margin #}\n (toTextView self)\n (fromIntegral rightMargin)\n\n-- | Gets the default right margin for text in the text view. Tags in the\n-- buffer may override the default.\n--\ntextViewGetRightMargin :: TextViewClass self => self\n -> IO Int -- ^ returns right margin in pixels\ntextViewGetRightMargin self =\n liftM fromIntegral $\n {# call unsafe text_view_get_right_margin #}\n (toTextView self)\n\n-- | Sets the default indentation for paragraphs in the text view. Tags in the\n-- buffer may override the default.\n--\ntextViewSetIndent :: TextViewClass self => self\n -> Int -- ^ @indent@ - indentation in pixels (may be negative)\n -> IO ()\ntextViewSetIndent self indent =\n {# call text_view_set_indent #}\n (toTextView self)\n (fromIntegral indent)\n\n-- | Gets the default indentation of paragraphs in the text view. Tags in the\n-- view's buffer may override the default. The indentation may be negative.\n--\ntextViewGetIndent :: TextViewClass self => self\n -> IO Int -- ^ returns number of pixels of indentation\ntextViewGetIndent self =\n liftM fromIntegral $\n {# call unsafe text_view_get_indent #}\n (toTextView self)\n\n-- | Obtains a copy of the default text attributes. These are the attributes\n-- used for text unless a tag overrides them. You'd typically pass the default\n-- attributes in to 'textIterGetAttributes' in order to get the attributes in\n-- effect at a given text position.\n--\ntextViewGetDefaultAttributes :: TextViewClass self => self -> IO TextAttributes\ntextViewGetDefaultAttributes self =\n {# call gtk_text_view_get_default_attributes #}\n (toTextView self)\n >>= makeNewTextAttributes\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Retrieves the iterator pointing to the character at buffer coordinates\n-- @x@ and @y@. Buffer coordinates are coordinates for the entire buffer, not\n-- just the currently-displayed portion. If you have coordinates from an event,\n-- you have to convert those to buffer coordinates with\n-- 'textViewWindowToBufferCoords'.\n--\n-- Note that this is different from 'textViewGetIterAtLocation', which\n-- returns cursor locations, i.e. positions \/between\/ characters.\n--\n-- * Available since Gtk+ version 2.6\n--\ntextViewGetIterAtPosition :: TextViewClass self => self\n -> Int -- ^ @x@ - x position, in buffer coordinates\n -> Int -- ^ @y@ - y position, in buffer coordinates\n -> IO (TextIter, Int) -- ^ @(iter, trailing)@ - returns the iterator and\n -- an integer indicating where in the grapheme the\n -- user clicked. It will either be zero, or the\n -- number of characters in the grapheme. 0 represents\n -- the trailing edge of the grapheme.\ntextViewGetIterAtPosition self x y =\n alloca $ \\trailingPtr -> do\n iter <- makeEmptyTextIter\n {# call gtk_text_view_get_iter_at_position #}\n (toTextView self)\n iter\n trailingPtr\n (fromIntegral x)\n (fromIntegral y)\n trailing <- peek trailingPtr\n return (iter, fromIntegral trailing)\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Changes the 'TextView' overwrite mode.\n--\n-- * Available since Gtk+ version 2.4\n--\ntextViewSetOverwrite :: TextViewClass self => self\n -> Bool -- ^ @overwrite@ - @True@ to turn on overwrite mode, @False@ to turn\n -- it off\n -> IO ()\ntextViewSetOverwrite self overwrite =\n {# call gtk_text_view_set_overwrite #}\n (toTextView self)\n (fromBool overwrite)\n\n-- | Returns whether the 'TextView' is in overwrite mode or not.\n--\n-- * Available since Gtk+ version 2.4\n--\ntextViewGetOverwrite :: TextViewClass self => self -> IO Bool\ntextViewGetOverwrite self =\n liftM toBool $\n {# call gtk_text_view_get_overwrite #}\n (toTextView self)\n\n-- | Sets the behavior of the text widget when the Tab key is pressed. If\n-- @acceptsTab@ is @True@ a tab character is inserted. If @acceptsTab@ is\n-- @False@ the keyboard focus is moved to the next widget in the focus chain.\n--\n-- * Available since Gtk+ version 2.4\n--\ntextViewSetAcceptsTab :: TextViewClass self => self\n -> Bool -- ^ @acceptsTab@ - @True@ if pressing the Tab key should insert a\n -- tab character, @False@, if pressing the Tab key should move the\n -- keyboard focus.\n -> IO ()\ntextViewSetAcceptsTab self acceptsTab =\n {# call gtk_text_view_set_accepts_tab #}\n (toTextView self)\n (fromBool acceptsTab)\n\n-- | Returns whether pressing the Tab key inserts a tab characters.\n-- 'textViewSetAcceptsTab'.\n--\n-- * Available since Gtk+ version 2.4\n--\ntextViewGetAcceptsTab :: TextViewClass self => self\n -> IO Bool -- ^ returns @True@ if pressing the Tab key inserts a tab\n -- character, @False@ if pressing the Tab key moves the keyboard\n -- focus.\ntextViewGetAcceptsTab self =\n liftM toBool $\n {# call gtk_text_view_get_accepts_tab #}\n (toTextView self)\n#endif\n\n--------------------\n-- Attributes\n\n-- | Pixels of blank space above paragraphs.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewPixelsAboveLines :: TextViewClass self => Attr self Int\ntextViewPixelsAboveLines = newAttr\n textViewGetPixelsAboveLines\n textViewSetPixelsAboveLines\n\n-- | Pixels of blank space below paragraphs.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewPixelsBelowLines :: TextViewClass self => Attr self Int\ntextViewPixelsBelowLines = newAttr\n textViewGetPixelsBelowLines\n textViewSetPixelsBelowLines\n\n-- | Pixels of blank space between wrapped lines in a paragraph.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewPixelsInsideWrap :: TextViewClass self => Attr self Int\ntextViewPixelsInsideWrap = newAttr\n textViewGetPixelsInsideWrap\n textViewSetPixelsInsideWrap\n\n-- | Whether the text can be modified by the user.\n--\n-- Default value: @True@\n--\ntextViewEditable :: TextViewClass self => Attr self Bool\ntextViewEditable = newAttr\n textViewGetEditable\n textViewSetEditable\n\n-- | Which IM (input method) module should be used for this entry. See GtkIMContext.\n-- Setting this to a non-empty value overrides the system-wide IM module setting. \n-- See the GtkSettings \"gtk-im-module\" property.\n--\n-- Default value: \\\"\\\"\n--\ntextViewImModule :: TextViewClass self => Attr self String\ntextViewImModule = \n newAttrFromStringProperty \"im-module\"\n\n-- | Whether to wrap lines never, at word boundaries, or at character\n-- boundaries.\n--\n-- Default value: 'WrapNone'\n--\ntextViewWrapMode :: TextViewClass self => Attr self WrapMode\ntextViewWrapMode = newAttr\n textViewGetWrapMode\n textViewSetWrapMode\n\n-- | Left, right, or center justification.\n--\n-- Default value: 'JustifyLeft'\n--\ntextViewJustification :: TextViewClass self => Attr self Justification\ntextViewJustification = newAttr\n textViewGetJustification\n textViewSetJustification\n\n-- | Width of the left margin in pixels.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewLeftMargin :: TextViewClass self => Attr self Int\ntextViewLeftMargin = newAttr\n textViewGetLeftMargin\n textViewSetLeftMargin\n\n-- | Width of the right margin in pixels.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewRightMargin :: TextViewClass self => Attr self Int\ntextViewRightMargin = newAttr\n textViewGetRightMargin\n textViewSetRightMargin\n\n-- | Amount to indent the paragraph, in pixels.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewIndent :: TextViewClass self => Attr self Int\ntextViewIndent = newAttr\n textViewGetIndent\n textViewSetIndent\n\n-- | If the insertion cursor is shown.\n--\n-- Default value: @True@\n--\ntextViewCursorVisible :: TextViewClass self => Attr self Bool\ntextViewCursorVisible = newAttr\n textViewGetCursorVisible\n textViewSetCursorVisible\n\n-- | The buffer which is displayed.\n--\ntextViewBuffer :: TextViewClass self => Attr self TextBuffer\ntextViewBuffer = newAttr\n textViewGetBuffer\n textViewSetBuffer\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Whether entered text overwrites existing contents.\n--\n-- Default value: @False@\n--\ntextViewOverwrite :: TextViewClass self => Attr self Bool\ntextViewOverwrite = newAttr\n textViewGetOverwrite\n textViewSetOverwrite\n\n-- | Whether Tab will result in a tab character being entered.\n--\n-- Default value: @True@\n--\ntextViewAcceptsTab :: TextViewClass self => Attr self Bool\ntextViewAcceptsTab = newAttr\n textViewGetAcceptsTab\n textViewSetAcceptsTab\n#endif\n\n--------------------\n-- Signals\nbackspace :: TextBufferClass self => Signal self (IO ())\nbackspace = Signal (connect_NONE__NONE \"on_backspace\")\n\ncopyClipboard :: TextBufferClass self => Signal self (IO ())\ncopyClipboard = Signal (connect_NONE__NONE \"copy_clipboard\")\n\ncutClipboard :: TextBufferClass self => Signal self (IO ())\ncutClipboard = Signal (connect_NONE__NONE \"cut_clipboard\")\n\ndeleteFromCursor :: TextBufferClass self => Signal self (DeleteType -> Int -> IO ())\ndeleteFromCursor = Signal (connect_ENUM_INT__NONE \"delete_from_cursor\")\n\ninsertAtCursor :: TextBufferClass self => Signal self (String -> IO ())\ninsertAtCursor = Signal (connect_STRING__NONE \"insert_at_cursor\")\n\nmoveCursor :: TextBufferClass self => Signal self (MovementStep -> Int -> Bool -> IO ())\nmoveCursor = Signal (connect_ENUM_INT_BOOL__NONE \"move_cursor\")\n\nmoveViewport :: TextBufferClass self => Signal self (ScrollStep -> Int -> IO ())\nmoveViewport = Signal (connect_ENUM_INT__NONE \"move_viewport\")\n\nmoveFocus :: TextBufferClass self => Signal self (DirectionType -> IO ())\nmoveFocus = Signal (connect_ENUM__NONE \"move_focus\")\n\npageHorizontally :: TextBufferClass self => Signal self (Int -> Bool -> IO ())\npageHorizontally = Signal (connect_INT_BOOL__NONE \"page_horizontally\")\n\npasteClipboard :: TextBufferClass self => Signal self (IO ())\npasteClipboard = Signal (connect_NONE__NONE \"paste_clipboard\")\n\npopulatePopup :: TextBufferClass self => Signal self (Menu -> IO ())\npopulatePopup = Signal (connect_OBJECT__NONE \"populate_popup\")\n\nselectAll :: TextBufferClass self => Signal self (Bool -> IO ())\nselectAll = Signal (connect_BOOL__NONE \"select-all\")\n\nsetAnchor :: TextBufferClass self => Signal self (IO ())\nsetAnchor = Signal (connect_NONE__NONE \"set_anchor\")\n\nsetScrollAdjustments :: TextBufferClass self => Signal self (Adjustment -> Adjustment -> IO ())\nsetScrollAdjustments = Signal (connect_OBJECT_OBJECT__NONE \"set_scroll_adjustments\")\n\ntoggleCursorVisible :: TextBufferClass self => Signal self (IO ())\ntoggleCursorVisible = Signal (connect_NONE__NONE \"toggle_cursor_visible\")\n\ntoggleOverwrite :: TextBufferClass self => Signal self (IO ())\ntoggleOverwrite = Signal (connect_NONE__NONE \"toggle_overwrite\")\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget TextView\n--\n-- Author : Axel Simon\n--\n-- Created: 23 February 2002\n--\n-- Copyright (C) 2002-2005 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- TODO\n--\n-- If PangoTabArray is bound: \n-- Fucntions: textViewSetTabs and textViewGetTabs\n-- Properties: textViewTabs\n--\n-- All on... and after... signales had incorrect names (underscore instead of hypens). Thus\n-- they could not have been used in applications and removing them can't break anything.\n-- Thus, I've removed them. Also, all key-binding singals are now removed as there is\n-- no way to add additional key bindings programatically in a type-safe way, let alone\n-- use these signals.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Widget that displays a 'TextBuffer'\n--\nmodule Graphics.UI.Gtk.Multiline.TextView (\n-- * Detail\n-- \n-- | You may wish to begin by reading the text widget conceptual overview\n-- which gives an overview of all the objects and data types related to the\n-- text widget and how they work together.\n--\n-- Throughout we distinguish between buffer coordinates which are pixels with\n-- the origin at the upper left corner of the first character on the first\n-- line. Window coordinates are relative to the top left pixel which is visible\n-- in the current 'TextView'. Coordinates from Events are in the latter\n-- relation. The conversion can be done with 'textViewWindowToBufferCoords'.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----TextView\n-- |\n-- |\n-- | 'GObject'\n-- | +----TextChildAnchor\n-- @\n\n-- * Types\n TextView,\n TextViewClass,\n TextChildAnchor,\n TextChildAnchorClass,\n castToTextView, gTypeTextView,\n toTextView,\n DeleteType(..),\n DirectionType(..),\n Justification(..),\n MovementStep(..),\n TextWindowType(..),\n WrapMode(..),\n\n-- * Constructors\n textViewNew,\n textViewNewWithBuffer,\n\n-- * Methods\n textViewSetBuffer,\n textViewGetBuffer,\n textViewScrollToMark,\n textViewScrollToIter,\n textViewScrollMarkOnscreen,\n textViewMoveMarkOnscreen,\n textViewPlaceCursorOnscreen,\n textViewGetLineAtY,\n textViewGetLineYrange,\n textViewGetIterAtLocation,\n textViewBufferToWindowCoords,\n textViewWindowToBufferCoords,\n textViewGetWindow,\n textViewGetWindowType,\n textViewSetBorderWindowSize,\n textViewGetBorderWindowSize,\n textViewForwardDisplayLine,\n textViewBackwardDisplayLine,\n textViewForwardDisplayLineEnd,\n textViewBackwardDisplayLineStart,\n textViewStartsDisplayLine,\n textViewMoveVisually,\n textViewAddChildAtAnchor,\n textChildAnchorNew,\n textChildAnchorGetWidgets,\n textChildAnchorGetDeleted,\n textViewAddChildInWindow,\n textViewMoveChild,\n textViewSetWrapMode,\n textViewGetWrapMode,\n textViewSetEditable,\n textViewGetEditable,\n textViewSetCursorVisible,\n textViewGetCursorVisible,\n textViewSetPixelsAboveLines,\n textViewGetPixelsAboveLines,\n textViewSetPixelsBelowLines,\n textViewGetPixelsBelowLines,\n textViewSetPixelsInsideWrap,\n textViewGetPixelsInsideWrap,\n textViewSetJustification,\n textViewGetJustification,\n textViewSetLeftMargin,\n textViewGetLeftMargin,\n textViewSetRightMargin,\n textViewGetRightMargin,\n textViewSetIndent,\n textViewGetIndent,\n textViewGetDefaultAttributes,\n textViewGetVisibleRect,\n textViewGetIterLocation,\n#if GTK_CHECK_VERSION(2,6,0)\n textViewGetIterAtPosition,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n textViewSetOverwrite,\n textViewGetOverwrite,\n textViewSetAcceptsTab,\n textViewGetAcceptsTab,\n#endif\n\n-- * Attributes\n textViewPixelsAboveLines,\n textViewPixelsBelowLines,\n textViewPixelsInsideWrap,\n textViewEditable,\n textViewImModule,\n textViewWrapMode,\n textViewJustification,\n textViewLeftMargin,\n textViewRightMargin,\n textViewIndent,\n textViewCursorVisible,\n textViewBuffer,\n#if GTK_CHECK_VERSION(2,4,0)\n textViewOverwrite,\n textViewAcceptsTab,\n#endif\n\n-- * Signals\n populatePopup,\n setAnchor,\n setTextViewScrollAdjustments,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\nimport System.Glib.Properties (newAttrFromStringProperty)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Multiline.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n{#import Graphics.UI.Gtk.Multiline.TextTag#}\nimport Graphics.UI.Gtk.General.Enums\t(TextWindowType(..), DeleteType(..),\n\t\t\t\t\t DirectionType(..), Justification(..),\n\t\t\t\t\t MovementStep(..), WrapMode(..),\n ScrollStep (..))\nimport System.Glib.GList\t\t(fromGList)\nimport Graphics.UI.Gtk.General.Structs\t(Rectangle(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Creates a new 'TextView'. If you don't call 'textViewSetBuffer' before\n-- using the text view, an empty default buffer will be created for you. Get\n-- the buffer with 'textViewGetBuffer'. If you want to specify your own buffer,\n-- consider 'textViewNewWithBuffer'.\n--\ntextViewNew :: IO TextView\ntextViewNew =\n makeNewObject mkTextView $\n liftM (castPtr :: Ptr Widget -> Ptr TextView) $\n {# call unsafe text_view_new #}\n\n-- | Creates a new 'TextView' widget displaying the buffer @buffer@. One\n-- buffer can be shared among many widgets.\n--\ntextViewNewWithBuffer :: TextBufferClass buffer => buffer -> IO TextView\ntextViewNewWithBuffer buffer =\n makeNewObject mkTextView $\n liftM (castPtr :: Ptr Widget -> Ptr TextView) $\n {# call text_view_new_with_buffer #}\n (toTextBuffer buffer)\n\n--------------------\n-- Methods\n\n-- | Sets the given buffer as the buffer being displayed by the text view.\n--\ntextViewSetBuffer :: (TextViewClass self, TextBufferClass buffer) => self -> buffer -> IO ()\ntextViewSetBuffer self buffer =\n {# call text_view_set_buffer #}\n (toTextView self)\n (toTextBuffer buffer)\n\n-- | Returns the 'TextBuffer' being displayed by this text view.\n--\ntextViewGetBuffer :: TextViewClass self => self -> IO TextBuffer\ntextViewGetBuffer self =\n makeNewGObject mkTextBuffer $\n {# call unsafe text_view_get_buffer #}\n (toTextView self)\n\n-- | Scrolls the text view so that @mark@ is on the screen in the position\n-- indicated by @xalign@ and @yalign@. An alignment of 0.0 indicates left or\n-- top, 1.0 indicates right or bottom, 0.5 means center. If the alignment is\n-- @Nothing@, the text scrolls the minimal distance to get the mark onscreen,\n-- possibly not scrolling at all. The effective screen for purposes of this\n-- function is reduced by a margin of size @withinMargin@.\n--\ntextViewScrollToMark :: (TextViewClass self, TextMarkClass mark) => self\n -> mark -- ^ @mark@ - a 'TextMark'\n -> Double -- ^ @withinMargin@ - margin as a [0.0,0.5) fraction of screen size\n -- and imposes an extra margin at all four sides of the window\n -- within which @xalign@ and @yalign@ are evaluated.\n -> Maybe (Double, Double) -- ^ @Just (xalign, yalign)@ - horizontal and\n -- vertical alignment of mark within visible area (if @Nothing@,\n -- scroll just enough to get the mark onscreen)\n -> IO ()\ntextViewScrollToMark self mark withinMargin align =\n let (useAlign, xalign, yalign) = case align of\n Nothing -> (False, 0, 0)\n Just (xalign, yalign) -> (True, xalign, yalign)\n in\n {# call text_view_scroll_to_mark #}\n (toTextView self)\n (toTextMark mark)\n (realToFrac withinMargin)\n (fromBool useAlign)\n (realToFrac xalign)\n (realToFrac yalign)\n\n-- | Scrolls the text view so that @iter@ is on the screen in the position\n-- indicated by @xalign@ and @yalign@. An alignment of 0.0 indicates left or\n-- top, 1.0 indicates right or bottom, 0.5 means center. If the alignment is\n-- @Nothing@, the text scrolls the minimal distance to get the mark onscreen,\n-- possibly not scrolling at all. The effective screen for purposes of this\n-- function is reduced by a margin of size @withinMargin@.\n--\n-- * This function\n-- uses the currently-computed height of the lines in the text buffer. Note\n-- that line heights are computed in an idle handler; so this function may\n-- not\n-- have the desired effect if it's called before the height computations. To\n-- avoid oddness, consider using 'textViewScrollToMark' which saves a point\n-- to be scrolled to after line validation. This is particularly important\n-- if you add new text to the buffer and immediately ask the view to scroll\n-- to it (which it can't since it is not updated until the main loop runs).\n--\ntextViewScrollToIter :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> Double -- ^ @withinMargin@ - margin as a [0.0,0.5) fraction of screen\n -- size\n -> Maybe (Double, Double) -- ^ @Just (xalign, yalign)@ - horizontal and\n -- vertical alignment of mark within visible area (if @Nothing@,\n -- scroll just enough to get the iterator onscreen)\n -> IO Bool -- ^ returns @True@ if scrolling occurred\ntextViewScrollToIter self iter withinMargin align = \n let (useAlign, xalign, yalign) = case align of\n Nothing -> (False, 0, 0)\n Just (xalign, yalign) -> (True, xalign, yalign)\n in\n liftM toBool $\n {# call text_view_scroll_to_iter #}\n (toTextView self)\n iter\n (realToFrac withinMargin)\n (fromBool useAlign)\n (realToFrac xalign)\n (realToFrac yalign)\n\n-- | Scrolls the text view the minimum distance such that @mark@ is contained\n-- within the visible area of the widget.\n--\ntextViewScrollMarkOnscreen :: (TextViewClass self, TextMarkClass mark) => self\n -> mark -- ^ @mark@ - a mark in the buffer for the text view\n -> IO ()\ntextViewScrollMarkOnscreen self mark =\n {# call text_view_scroll_mark_onscreen #}\n (toTextView self)\n (toTextMark mark)\n\n-- | Moves a mark within the buffer so that it's located within the\n-- currently-visible text area.\n--\ntextViewMoveMarkOnscreen :: (TextViewClass self, TextMarkClass mark) => self\n -> mark -- ^ @mark@ - a 'TextMark'\n -> IO Bool -- ^ returns @True@ if the mark moved (wasn't already onscreen)\ntextViewMoveMarkOnscreen self mark =\n liftM toBool $\n {# call text_view_move_mark_onscreen #}\n (toTextView self)\n (toTextMark mark)\n\n-- | Moves the cursor to the currently visible region of the buffer, it it\n-- isn't there already.\n--\ntextViewPlaceCursorOnscreen :: TextViewClass self => self\n -> IO Bool -- ^ returns @True@ if the cursor had to be moved.\ntextViewPlaceCursorOnscreen self =\n liftM toBool $\n {# call text_view_place_cursor_onscreen #}\n (toTextView self)\n\n-- | Returns the currently-visible region of the buffer, in\n-- buffer coordinates. Convert to window coordinates with\n-- 'textViewBufferToWindowCoords'.\n--\ntextViewGetVisibleRect :: TextViewClass self => self -> IO Rectangle\ntextViewGetVisibleRect self =\n alloca $ \\rectPtr -> do\n {# call unsafe text_view_get_visible_rect #}\n (toTextView self)\n (castPtr rectPtr)\n peek rectPtr\n\n-- | Gets a rectangle which roughly contains the character at @iter@. The\n-- rectangle position is in buffer coordinates; use\n-- 'textViewBufferToWindowCoords' to convert these coordinates to coordinates\n-- for one of the windows in the text view.\n--\ntextViewGetIterLocation :: TextViewClass self => self -> TextIter -> IO Rectangle\ntextViewGetIterLocation self iter =\n alloca $ \\rectPtr -> do\n {# call unsafe text_view_get_iter_location #}\n (toTextView self)\n iter\n (castPtr rectPtr)\n peek rectPtr\n\n-- | Gets the 'TextIter' at the start of the line containing the coordinate\n-- @y@. @y@ is in buffer coordinates, convert from window coordinates with\n-- 'textViewWindowToBufferCoords'. Also returns @lineTop@ the\n-- coordinate of the top edge of the line.\n--\ntextViewGetLineAtY :: TextViewClass self => self\n -> Int -- ^ @y@ - a y coordinate\n -> IO (TextIter, Int) -- ^ @(targetIter, lineTop)@ - returns the iter and the\n -- top coordinate of the line\ntextViewGetLineAtY self y =\n makeEmptyTextIter >>= \\targetIter ->\n alloca $ \\lineTopPtr -> do\n {# call unsafe text_view_get_line_at_y #}\n (toTextView self)\n targetIter\n (fromIntegral y)\n lineTopPtr\n lineTop <- peek lineTopPtr\n return (targetIter, fromIntegral lineTop)\n\n-- | Gets the y coordinate of the top of the line containing @iter@, and the\n-- height of the line. The coordinate is a buffer coordinate; convert to window\n-- coordinates with 'textViewBufferToWindowCoords'.\n--\ntextViewGetLineYrange :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO (Int, Int) -- ^ @(y, height)@ - y coordinate and height of the line\ntextViewGetLineYrange self iter =\n alloca $ \\yPtr ->\n alloca $ \\heightPtr -> do\n {# call unsafe text_view_get_line_yrange #}\n (toTextView self)\n iter\n yPtr\n heightPtr\n y <- peek yPtr\n height <- peek heightPtr\n return (fromIntegral y, fromIntegral height)\n\n-- | Retrieves the iterator at buffer coordinates @x@ and @y@. Buffer\n-- coordinates are coordinates for the entire buffer, not just the\n-- currently-displayed portion. If you have coordinates from an event, you have\n-- to convert those to buffer coordinates with 'textViewWindowToBufferCoords'.\n--\ntextViewGetIterAtLocation :: TextViewClass self => self\n -> Int -- ^ @x@ - x position, in buffer coordinates\n -> Int -- ^ @y@ - y position, in buffer coordinates\n -> IO TextIter\ntextViewGetIterAtLocation self x y = do\n iter <- makeEmptyTextIter\n {# call unsafe text_view_get_iter_at_location #}\n (toTextView self)\n iter\n (fromIntegral x)\n (fromIntegral y)\n return iter\n\n-- | Converts coordinate @(bufferX, bufferY)@ to coordinates for the window\n-- @win@\n--\n-- Note that you can't convert coordinates for a nonexisting window (see\n-- 'textViewSetBorderWindowSize').\n--\ntextViewBufferToWindowCoords :: TextViewClass self => self\n -> TextWindowType -- ^ @win@ - a 'TextWindowType' except 'TextWindowPrivate'\n -> (Int, Int) -- ^ @(bufferX, bufferY)@ - buffer x and y coordinates\n -> IO (Int, Int) -- ^ returns window x and y coordinates\ntextViewBufferToWindowCoords self win (bufferX, bufferY) =\n alloca $ \\windowXPtr ->\n alloca $ \\windowYPtr -> do\n {# call unsafe text_view_buffer_to_window_coords #}\n (toTextView self)\n ((fromIntegral . fromEnum) win)\n (fromIntegral bufferX)\n (fromIntegral bufferY)\n windowXPtr\n windowYPtr\n windowX <- peek windowXPtr\n windowY <- peek windowYPtr\n return (fromIntegral windowX, fromIntegral windowY)\n\n-- | Converts coordinates on the window identified by @win@ to buffer\n-- coordinates.\n--\n-- Note that you can't convert coordinates for a nonexisting window (see\n-- 'textViewSetBorderWindowSize').\n--\ntextViewWindowToBufferCoords :: TextViewClass self => self\n -> TextWindowType -- ^ @win@ - a 'TextWindowType' except 'TextWindowPrivate'\n -> (Int, Int) -- ^ @(windowX, windowY)@ - window x and y coordinates\n -> IO (Int, Int) -- ^ returns buffer x and y coordinates\ntextViewWindowToBufferCoords self win (windowX, windowY) =\n alloca $ \\bufferXPtr ->\n alloca $ \\bufferYPtr -> do\n {# call unsafe text_view_window_to_buffer_coords #}\n (toTextView self)\n ((fromIntegral . fromEnum) win)\n (fromIntegral windowX)\n (fromIntegral windowY)\n bufferXPtr\n bufferYPtr\n bufferX <- peek bufferXPtr\n bufferY <- peek bufferYPtr\n return (fromIntegral bufferX, fromIntegral bufferY)\n\n-- | Retrieves the 'DrawWindow' corresponding to an area of the text view;\n-- possible windows include the overall widget window, child windows on the\n-- left, right, top, bottom, and the window that displays the text buffer.\n-- Windows are @Nothing@ and nonexistent if their width or height is 0, and are\n-- nonexistent before the widget has been realized.\n--\ntextViewGetWindow :: TextViewClass self => self\n -> TextWindowType -- ^ @win@ - window to get\n -> IO (Maybe DrawWindow) -- ^ returns a 'DrawWindow', or @Nothing@\ntextViewGetWindow self win =\n maybeNull (makeNewGObject mkDrawWindow) $\n {# call unsafe text_view_get_window #}\n (toTextView self)\n ((fromIntegral . fromEnum) win)\n\n-- | Retrieve the type of window the 'TextView' widget contains.\n--\n-- Usually used to find out which window an event corresponds to. An emission\n-- of an event signal of 'TextView' yields a 'DrawWindow'. This function can be\n-- used to see if the event actually belongs to the main text window.\n--\ntextViewGetWindowType :: TextViewClass self => self\n -> DrawWindow\n -> IO TextWindowType\ntextViewGetWindowType self window =\n liftM (toEnum . fromIntegral) $\n {# call unsafe text_view_get_window_type #}\n (toTextView self)\n window\n\n-- | Sets the width of 'TextWindowLeft' or 'TextWindowRight', or the height of\n-- 'TextWindowTop' or 'TextWindowBottom'. Automatically destroys the\n-- corresponding window if the size is set to 0, and creates the window if the\n-- size is set to non-zero. This function can only be used for the \\\"border\n-- windows\\\", it doesn't work with 'TextWindowWidget', 'TextWindowText', or\n-- 'TextWindowPrivate'.\n--\ntextViewSetBorderWindowSize :: TextViewClass self => self\n -> TextWindowType -- ^ @type@ - window to affect\n -> Int -- ^ @size@ - width or height of the window\n -> IO ()\ntextViewSetBorderWindowSize self type_ size =\n {# call text_view_set_border_window_size #}\n (toTextView self)\n ((fromIntegral . fromEnum) type_)\n (fromIntegral size)\n\n-- | Gets the width of the specified border window. See\n-- 'textViewSetBorderWindowSize'.\n--\ntextViewGetBorderWindowSize :: TextViewClass self => self\n -> TextWindowType -- ^ @type@ - window to return size from\n -> IO Int -- ^ returns width of window\ntextViewGetBorderWindowSize self type_ =\n liftM fromIntegral $\n {# call unsafe text_view_get_border_window_size #}\n (toTextView self)\n ((fromIntegral . fromEnum) type_)\n\n-- | Moves the given @iter@ forward by one display (wrapped) line. A display\n-- line is different from a paragraph. Paragraphs are separated by newlines or\n-- other paragraph separator characters. Display lines are created by\n-- line-wrapping a paragraph. If wrapping is turned off, display lines and\n-- paragraphs will be the same. Display lines are divided differently for each\n-- view, since they depend on the view's width; paragraphs are the same in all\n-- views, since they depend on the contents of the 'TextBuffer'.\n--\ntextViewForwardDisplayLine :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ was moved and is not on the end\n -- iterator\ntextViewForwardDisplayLine self iter =\n liftM toBool $\n {# call unsafe text_view_forward_display_line #}\n (toTextView self)\n iter\n\n-- | Moves the given @iter@ backward by one display (wrapped) line. A display\n-- line is different from a paragraph. Paragraphs are separated by newlines or\n-- other paragraph separator characters. Display lines are created by\n-- line-wrapping a paragraph. If wrapping is turned off, display lines and\n-- paragraphs will be the same. Display lines are divided differently for each\n-- view, since they depend on the view's width; paragraphs are the same in all\n-- views, since they depend on the contents of the 'TextBuffer'.\n--\ntextViewBackwardDisplayLine :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ was moved and is not on the end\n -- iterator\ntextViewBackwardDisplayLine self iter =\n liftM toBool $\n {# call unsafe text_view_backward_display_line #}\n (toTextView self)\n iter\n\n-- | Moves the given @iter@ forward to the next display line end. A display\n-- line is different from a paragraph. Paragraphs are separated by newlines or\n-- other paragraph separator characters. Display lines are created by\n-- line-wrapping a paragraph. If wrapping is turned off, display lines and\n-- paragraphs will be the same. Display lines are divided differently for each\n-- view, since they depend on the view's width; paragraphs are the same in all\n-- views, since they depend on the contents of the 'TextBuffer'.\n--\ntextViewForwardDisplayLineEnd :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ was moved and is not on the end\n -- iterator\ntextViewForwardDisplayLineEnd self iter =\n liftM toBool $\n {# call unsafe text_view_forward_display_line_end #}\n (toTextView self)\n iter\n\n-- | Moves the given @iter@ backward to the next display line start. A display\n-- line is different from a paragraph. Paragraphs are separated by newlines or\n-- other paragraph separator characters. Display lines are created by\n-- line-wrapping a paragraph. If wrapping is turned off, display lines and\n-- paragraphs will be the same. Display lines are divided differently for each\n-- view, since they depend on the view's width; paragraphs are the same in all\n-- views, since they depend on the contents of the 'TextBuffer'.\n--\ntextViewBackwardDisplayLineStart :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ was moved and is not on the end\n -- iterator\ntextViewBackwardDisplayLineStart self iter =\n liftM toBool $\n {# call unsafe text_view_backward_display_line_start #}\n (toTextView self)\n iter\n\n-- | Determines whether @iter@ is at the start of a display line. See\n-- 'textViewForwardDisplayLine' for an explanation of display lines vs.\n-- paragraphs.\n--\ntextViewStartsDisplayLine :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ begins a wrapped line\ntextViewStartsDisplayLine self iter =\n liftM toBool $\n {# call unsafe text_view_starts_display_line #}\n (toTextView self)\n iter\n\n-- | Move the iterator a given number of characters visually, treating it as\n-- the strong cursor position. If @count@ is positive, then the new strong\n-- cursor position will be @count@ positions to the right of the old cursor\n-- position. If @count@ is negative then the new strong cursor position will be\n-- @count@ positions to the left of the old cursor position.\n--\n-- In the presence of bidirection text, the correspondence between logical\n-- and visual order will depend on the direction of the current run, and there\n-- may be jumps when the cursor is moved off of the end of a run.\n--\ntextViewMoveVisually :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> Int -- ^ @count@ - number of characters to move (negative moves left,\n -- positive moves right)\n -> IO Bool -- ^ returns @True@ if @iter@ moved and is not on the end\n -- iterator\ntextViewMoveVisually self iter count =\n liftM toBool $\n {# call unsafe text_view_move_visually #}\n (toTextView self)\n iter\n (fromIntegral count)\n\n-- | Adds a child widget in the text buffer, at the given @anchor@.\n--\ntextViewAddChildAtAnchor :: (TextViewClass self, WidgetClass child) => self\n -> child -- ^ @child@ - a 'Widget'\n -> TextChildAnchor -- ^ @anchor@ - a 'TextChildAnchor' in the 'TextBuffer'\n -- for the text view\n -> IO ()\ntextViewAddChildAtAnchor self child anchor =\n {# call text_view_add_child_at_anchor #}\n (toTextView self)\n (toWidget child)\n anchor\n\n-- | Create a new 'TextChildAnchor'.\n--\n-- * Using 'textBufferCreateChildAnchor' is usually simpler then\n-- executing this function and 'textBufferInsertChildAnchor'.\n--\ntextChildAnchorNew :: IO TextChildAnchor\ntextChildAnchorNew =\n constructNewGObject mkTextChildAnchor\n {# call unsafe text_child_anchor_new #}\n\n-- | Retrieve all 'Widget's at this\n-- 'TextChildAnchor'.\n--\n-- * The widgets in the returned list need to be upcasted to what they were.\n--\ntextChildAnchorGetWidgets :: TextChildAnchor -> IO [Widget]\ntextChildAnchorGetWidgets tca = do\n gList <- {# call text_child_anchor_get_widgets #} tca\n wList <- fromGList gList\n mapM (makeNewObject mkWidget) (map return wList)\n\n-- | Query if an anchor was deleted.\n--\ntextChildAnchorGetDeleted :: TextChildAnchor -> IO Bool\ntextChildAnchorGetDeleted tca =\n liftM toBool $\n {# call unsafe text_child_anchor_get_deleted #} tca\n\n-- | Adds a child at fixed coordinates in one of the text widget's windows.\n-- The window must have nonzero size (see 'textViewSetBorderWindowSize'). Note\n-- that the child coordinates are given relative to the 'DrawWindow' in\n-- question, and that these coordinates have no sane relationship to scrolling.\n-- When placing a child in 'TextWindowWidget', scrolling is irrelevant, the\n-- child floats above all scrollable areas. If you want the widget to move when\n-- the text view scrolls, use 'textViewAddChildAtAnchor' instead.\n--\ntextViewAddChildInWindow :: (TextViewClass self, WidgetClass child) => self\n -> child -- ^ @child@ - a 'Widget'\n -> TextWindowType -- ^ @whichWindow@ - which window the child should appear\n -- in\n -> Int -- ^ @xpos@ - X position of child in window coordinates\n -> Int -- ^ @ypos@ - Y position of child in window coordinates\n -> IO ()\ntextViewAddChildInWindow self child whichWindow xpos ypos =\n {# call text_view_add_child_in_window #}\n (toTextView self)\n (toWidget child)\n ((fromIntegral . fromEnum) whichWindow)\n (fromIntegral xpos)\n (fromIntegral ypos)\n\n-- | Move a child widget within the 'TextView'. This is really only apprpriate\n-- for \\\"floating\\\" child widgets added using 'textViewAddChildInWindow'.\n--\ntextViewMoveChild :: (TextViewClass self, WidgetClass child) => self\n -> child -- ^ @child@ - child widget already added to the text view\n -> Int -- ^ @xpos@ - new X position in window coordinates\n -> Int -- ^ @ypos@ - new Y position in window coordinates\n -> IO ()\ntextViewMoveChild self child xpos ypos =\n {# call text_view_move_child #}\n (toTextView self)\n (toWidget child)\n (fromIntegral xpos)\n (fromIntegral ypos)\n\n-- | Sets the line wrapping for the view.\n--\ntextViewSetWrapMode :: TextViewClass self => self -> WrapMode -> IO ()\ntextViewSetWrapMode self wrapMode =\n {# call text_view_set_wrap_mode #}\n (toTextView self)\n ((fromIntegral . fromEnum) wrapMode)\n\n-- | Gets the line wrapping for the view.\n--\ntextViewGetWrapMode :: TextViewClass self => self -> IO WrapMode\ntextViewGetWrapMode self =\n liftM (toEnum . fromIntegral) $\n {# call unsafe text_view_get_wrap_mode #}\n (toTextView self)\n\n-- | Sets the default editability of the 'TextView'. You can override this\n-- default setting with tags in the buffer, using the \\\"editable\\\" attribute of\n-- tags.\n--\ntextViewSetEditable :: TextViewClass self => self -> Bool -> IO ()\ntextViewSetEditable self setting =\n {# call text_view_set_editable #}\n (toTextView self)\n (fromBool setting)\n\n-- | Returns the default editability of the 'TextView'. Tags in the buffer may\n-- override this setting for some ranges of text.\n--\ntextViewGetEditable :: TextViewClass self => self -> IO Bool\ntextViewGetEditable self =\n liftM toBool $\n {# call unsafe text_view_get_editable #}\n (toTextView self)\n\n-- | Toggles whether the insertion point is displayed. A buffer with no\n-- editable text probably shouldn't have a visible cursor, so you may want to\n-- turn the cursor off.\n--\ntextViewSetCursorVisible :: TextViewClass self => self -> Bool -> IO ()\ntextViewSetCursorVisible self setting =\n {# call text_view_set_cursor_visible #}\n (toTextView self)\n (fromBool setting)\n\n-- | Find out whether the cursor is being displayed.\n--\ntextViewGetCursorVisible :: TextViewClass self => self -> IO Bool\ntextViewGetCursorVisible self =\n liftM toBool $\n {# call unsafe text_view_get_cursor_visible #}\n (toTextView self)\n\n-- | Sets the default number of blank pixels above paragraphs in the text view.\n-- Tags in the buffer for the text view may override the defaults.\n--\n-- * Tags in the buffer may override this default.\n--\ntextViewSetPixelsAboveLines :: TextViewClass self => self -> Int -> IO ()\ntextViewSetPixelsAboveLines self pixelsAboveLines =\n {# call text_view_set_pixels_above_lines #}\n (toTextView self)\n (fromIntegral pixelsAboveLines)\n\n-- | Gets the default number of pixels to put above paragraphs.\n--\ntextViewGetPixelsAboveLines :: TextViewClass self => self -> IO Int\ntextViewGetPixelsAboveLines self =\n liftM fromIntegral $\n {# call unsafe text_view_get_pixels_above_lines #}\n (toTextView self)\n\n-- | Sets the default number of pixels of blank space to put below paragraphs\n-- in the text view. May be overridden by tags applied to the text view's\n-- buffer.\n--\ntextViewSetPixelsBelowLines :: TextViewClass self => self -> Int -> IO ()\ntextViewSetPixelsBelowLines self pixelsBelowLines =\n {# call text_view_set_pixels_below_lines #}\n (toTextView self)\n (fromIntegral pixelsBelowLines)\n\n-- | Gets the default number of blank pixels below each paragraph.\n--\ntextViewGetPixelsBelowLines :: TextViewClass self => self -> IO Int\ntextViewGetPixelsBelowLines self =\n liftM fromIntegral $\n {# call unsafe text_view_get_pixels_below_lines #}\n (toTextView self)\n\n-- | Sets the default number of pixels of blank space to leave between\n-- display\\\/wrapped lines within a paragraph. May be overridden by tags in\n-- the text view's buffer.\n--\ntextViewSetPixelsInsideWrap :: TextViewClass self => self -> Int -> IO ()\ntextViewSetPixelsInsideWrap self pixelsInsideWrap =\n {# call text_view_set_pixels_inside_wrap #}\n (toTextView self)\n (fromIntegral pixelsInsideWrap)\n\n-- | Gets the default number of pixels of blank space between lines in a\n-- wrapped paragraph.\n--\ntextViewGetPixelsInsideWrap :: TextViewClass self => self -> IO Int\ntextViewGetPixelsInsideWrap self =\n liftM fromIntegral $\n {# call unsafe text_view_get_pixels_inside_wrap #}\n (toTextView self)\n\n-- | Sets the default justification of text in the text view. Tags in the\n-- view's buffer may override the default.\n--\ntextViewSetJustification :: TextViewClass self => self -> Justification -> IO ()\ntextViewSetJustification self justification =\n {# call text_view_set_justification #}\n (toTextView self)\n ((fromIntegral . fromEnum) justification)\n\n-- | Gets the default justification of paragraphs in the text view. Tags in the\n-- buffer may override the default.\n--\ntextViewGetJustification :: TextViewClass self => self -> IO Justification\ntextViewGetJustification self =\n liftM (toEnum . fromIntegral) $\n {# call unsafe text_view_get_justification #}\n (toTextView self)\n\n-- | Sets the default left margin for text in the text view. Tags in the buffer\n-- may override the default.\n--\ntextViewSetLeftMargin :: TextViewClass self => self\n -> Int -- ^ @leftMargin@ - left margin in pixels\n -> IO ()\ntextViewSetLeftMargin self leftMargin =\n {# call text_view_set_left_margin #}\n (toTextView self)\n (fromIntegral leftMargin)\n\n-- | Gets the default left margin size of paragraphs in the text view. Tags\n-- in the buffer may override the default.\n--\ntextViewGetLeftMargin :: TextViewClass self => self\n -> IO Int -- ^ returns left margin in pixels\ntextViewGetLeftMargin self =\n liftM fromIntegral $\n {# call unsafe text_view_get_left_margin #}\n (toTextView self)\n\n-- | Sets the default right margin for text in the text view. Tags in the\n-- buffer may override the default.\n--\ntextViewSetRightMargin :: TextViewClass self => self\n -> Int -- ^ @rightMargin@ - right margin in pixels\n -> IO ()\ntextViewSetRightMargin self rightMargin =\n {# call text_view_set_right_margin #}\n (toTextView self)\n (fromIntegral rightMargin)\n\n-- | Gets the default right margin for text in the text view. Tags in the\n-- buffer may override the default.\n--\ntextViewGetRightMargin :: TextViewClass self => self\n -> IO Int -- ^ returns right margin in pixels\ntextViewGetRightMargin self =\n liftM fromIntegral $\n {# call unsafe text_view_get_right_margin #}\n (toTextView self)\n\n-- | Sets the default indentation for paragraphs in the text view. Tags in the\n-- buffer may override the default.\n--\ntextViewSetIndent :: TextViewClass self => self\n -> Int -- ^ @indent@ - indentation in pixels (may be negative)\n -> IO ()\ntextViewSetIndent self indent =\n {# call text_view_set_indent #}\n (toTextView self)\n (fromIntegral indent)\n\n-- | Gets the default indentation of paragraphs in the text view. Tags in the\n-- view's buffer may override the default. The indentation may be negative.\n--\ntextViewGetIndent :: TextViewClass self => self\n -> IO Int -- ^ returns number of pixels of indentation\ntextViewGetIndent self =\n liftM fromIntegral $\n {# call unsafe text_view_get_indent #}\n (toTextView self)\n\n-- | Obtains a copy of the default text attributes. These are the attributes\n-- used for text unless a tag overrides them. You'd typically pass the default\n-- attributes in to 'textIterGetAttributes' in order to get the attributes in\n-- effect at a given text position.\n--\ntextViewGetDefaultAttributes :: TextViewClass self => self -> IO TextAttributes\ntextViewGetDefaultAttributes self =\n {# call gtk_text_view_get_default_attributes #}\n (toTextView self)\n >>= makeNewTextAttributes\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Retrieves the iterator pointing to the character at buffer coordinates\n-- @x@ and @y@. Buffer coordinates are coordinates for the entire buffer, not\n-- just the currently-displayed portion. If you have coordinates from an event,\n-- you have to convert those to buffer coordinates with\n-- 'textViewWindowToBufferCoords'.\n--\n-- Note that this is different from 'textViewGetIterAtLocation', which\n-- returns cursor locations, i.e. positions \/between\/ characters.\n--\n-- * Available since Gtk+ version 2.6\n--\ntextViewGetIterAtPosition :: TextViewClass self => self\n -> Int -- ^ @x@ - x position, in buffer coordinates\n -> Int -- ^ @y@ - y position, in buffer coordinates\n -> IO (TextIter, Int) -- ^ @(iter, trailing)@ - returns the iterator and\n -- an integer indicating where in the grapheme the\n -- user clicked. It will either be zero, or the\n -- number of characters in the grapheme. 0 represents\n -- the trailing edge of the grapheme.\ntextViewGetIterAtPosition self x y =\n alloca $ \\trailingPtr -> do\n iter <- makeEmptyTextIter\n {# call gtk_text_view_get_iter_at_position #}\n (toTextView self)\n iter\n trailingPtr\n (fromIntegral x)\n (fromIntegral y)\n trailing <- peek trailingPtr\n return (iter, fromIntegral trailing)\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Changes the 'TextView' overwrite mode.\n--\n-- * Available since Gtk+ version 2.4\n--\ntextViewSetOverwrite :: TextViewClass self => self\n -> Bool -- ^ @overwrite@ - @True@ to turn on overwrite mode, @False@ to turn\n -- it off\n -> IO ()\ntextViewSetOverwrite self overwrite =\n {# call gtk_text_view_set_overwrite #}\n (toTextView self)\n (fromBool overwrite)\n\n-- | Returns whether the 'TextView' is in overwrite mode or not.\n--\n-- * Available since Gtk+ version 2.4\n--\ntextViewGetOverwrite :: TextViewClass self => self -> IO Bool\ntextViewGetOverwrite self =\n liftM toBool $\n {# call gtk_text_view_get_overwrite #}\n (toTextView self)\n\n-- | Sets the behavior of the text widget when the Tab key is pressed. If\n-- @acceptsTab@ is @True@ a tab character is inserted. If @acceptsTab@ is\n-- @False@ the keyboard focus is moved to the next widget in the focus chain.\n--\n-- * Available since Gtk+ version 2.4\n--\ntextViewSetAcceptsTab :: TextViewClass self => self\n -> Bool -- ^ @acceptsTab@ - @True@ if pressing the Tab key should insert a\n -- tab character, @False@, if pressing the Tab key should move the\n -- keyboard focus.\n -> IO ()\ntextViewSetAcceptsTab self acceptsTab =\n {# call gtk_text_view_set_accepts_tab #}\n (toTextView self)\n (fromBool acceptsTab)\n\n-- | Returns whether pressing the Tab key inserts a tab characters.\n-- 'textViewSetAcceptsTab'.\n--\n-- * Available since Gtk+ version 2.4\n--\ntextViewGetAcceptsTab :: TextViewClass self => self\n -> IO Bool -- ^ returns @True@ if pressing the Tab key inserts a tab\n -- character, @False@ if pressing the Tab key moves the keyboard\n -- focus.\ntextViewGetAcceptsTab self =\n liftM toBool $\n {# call gtk_text_view_get_accepts_tab #}\n (toTextView self)\n#endif\n\n--------------------\n-- Attributes\n\n-- | Pixels of blank space above paragraphs.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewPixelsAboveLines :: TextViewClass self => Attr self Int\ntextViewPixelsAboveLines = newAttr\n textViewGetPixelsAboveLines\n textViewSetPixelsAboveLines\n\n-- | Pixels of blank space below paragraphs.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewPixelsBelowLines :: TextViewClass self => Attr self Int\ntextViewPixelsBelowLines = newAttr\n textViewGetPixelsBelowLines\n textViewSetPixelsBelowLines\n\n-- | Pixels of blank space between wrapped lines in a paragraph.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewPixelsInsideWrap :: TextViewClass self => Attr self Int\ntextViewPixelsInsideWrap = newAttr\n textViewGetPixelsInsideWrap\n textViewSetPixelsInsideWrap\n\n-- | Whether the text can be modified by the user.\n--\n-- Default value: @True@\n--\ntextViewEditable :: TextViewClass self => Attr self Bool\ntextViewEditable = newAttr\n textViewGetEditable\n textViewSetEditable\n\n-- | Which IM (input method) module should be used for this entry. See GtkIMContext.\n-- Setting this to a non-empty value overrides the system-wide IM module setting. \n-- See the GtkSettings \"gtk-im-module\" property.\n--\n-- Default value: \\\"\\\"\n--\ntextViewImModule :: TextViewClass self => Attr self String\ntextViewImModule = \n newAttrFromStringProperty \"im-module\"\n\n-- | Whether to wrap lines never, at word boundaries, or at character\n-- boundaries.\n--\n-- Default value: 'WrapNone'\n--\ntextViewWrapMode :: TextViewClass self => Attr self WrapMode\ntextViewWrapMode = newAttr\n textViewGetWrapMode\n textViewSetWrapMode\n\n-- | Left, right, or center justification.\n--\n-- Default value: 'JustifyLeft'\n--\ntextViewJustification :: TextViewClass self => Attr self Justification\ntextViewJustification = newAttr\n textViewGetJustification\n textViewSetJustification\n\n-- | Width of the left margin in pixels.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewLeftMargin :: TextViewClass self => Attr self Int\ntextViewLeftMargin = newAttr\n textViewGetLeftMargin\n textViewSetLeftMargin\n\n-- | Width of the right margin in pixels.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewRightMargin :: TextViewClass self => Attr self Int\ntextViewRightMargin = newAttr\n textViewGetRightMargin\n textViewSetRightMargin\n\n-- | Amount to indent the paragraph, in pixels.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewIndent :: TextViewClass self => Attr self Int\ntextViewIndent = newAttr\n textViewGetIndent\n textViewSetIndent\n\n-- | If the insertion cursor is shown.\n--\n-- Default value: @True@\n--\ntextViewCursorVisible :: TextViewClass self => Attr self Bool\ntextViewCursorVisible = newAttr\n textViewGetCursorVisible\n textViewSetCursorVisible\n\n-- | The buffer which is displayed.\n--\ntextViewBuffer :: TextViewClass self => Attr self TextBuffer\ntextViewBuffer = newAttr\n textViewGetBuffer\n textViewSetBuffer\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Whether entered text overwrites existing contents.\n--\n-- Default value: @False@\n--\ntextViewOverwrite :: TextViewClass self => Attr self Bool\ntextViewOverwrite = newAttr\n textViewGetOverwrite\n textViewSetOverwrite\n\n-- | Whether Tab will result in a tab character being entered.\n--\n-- Default value: @True@\n--\ntextViewAcceptsTab :: TextViewClass self => Attr self Bool\ntextViewAcceptsTab = newAttr\n textViewGetAcceptsTab\n textViewSetAcceptsTab\n#endif\n\n--------------------\n-- Signals\n\n-- | Add menu entries to context menus.\n--\n-- * This signal is emitted if a context menu within the 'TextView' is opened.\n-- This signal can be used to add application specific menu items to this\n-- popup.\n--\n-- * If you need to add items to the context menu, connect to this signal and\n-- append your menuitems to the 'Menu'.\n--\npopulatePopup :: TextBufferClass self => Signal self (Menu -> IO ())\npopulatePopup = Signal (connect_OBJECT__NONE \"populate-popup\")\n\n-- | Inserting an anchor.\n--\n-- * This signal is emitted when anchor is inserted into the text. \n--\n-- * The action itself happens when the 'TextView' processes this\n-- signal.\n--\nsetAnchor :: TextBufferClass self => Signal self (IO ())\nsetAnchor = Signal (connect_NONE__NONE \"set-anchor\")\n\n-- | The scroll-bars changed.\n--\nsetTextViewScrollAdjustments :: TextBufferClass self => Signal self (Adjustment -> Adjustment -> IO ())\nsetTextViewScrollAdjustments = Signal (connect_OBJECT_OBJECT__NONE \"set-scroll-adjustments\")\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"8182ebf38115da4dc327b057f8565564d3a069bd","subject":"Fix the get side of all container child attributes.","message":"Fix the get side of all container child attributes.\n\nIt was accidentally calling 'set' rather than 'get'. doh! :-)\n\ndarcs-hash:20080128170816-adfee-b8b464c20847c8eeadba62f81f259f5a5ca795b6.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/ContainerChildProperties.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Abstract\/ContainerChildProperties.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Container child Properties\n--\n-- Author : Duncan Coutts\n--\n-- Created: 16 April 2005\n--\n-- Copyright (C) 2005 Duncan Coutts\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- #hide\n\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Functions for getting and setting container child properties\n--\nmodule Graphics.UI.Gtk.Abstract.ContainerChildProperties (\n containerChildGetPropertyBool,\n containerChildSetPropertyBool,\n\n newAttrFromContainerChildIntProperty,\n newAttrFromContainerChildUIntProperty,\n newAttrFromContainerChildBoolProperty,\n newAttrFromContainerChildEnumProperty,\n newAttrFromContainerChildFlagsProperty,\n newAttrFromContainerChildStringProperty,\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import Graphics.UI.Gtk.Types#}\nimport System.Glib.GType\nimport qualified System.Glib.GTypeConstants as GType\nimport System.Glib.GValueTypes\n{#import System.Glib.GValue#}\t\t(GValue(GValue), allocaGValue, valueInit)\nimport System.Glib.Attributes\t\t(Attr, newAttr)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\ncontainerChildSetPropertyInternal ::\n (ContainerClass container, WidgetClass child)\n => GType\n -> (GValue -> a -> IO ())\n -> String\n -> child\n -> container\n -> a\n -> IO ()\ncontainerChildSetPropertyInternal gtype valueSet prop child container val =\n withCString prop $ \\propertyNamePtr ->\n allocaGValue $ \\gvalue -> do\n valueInit gvalue gtype\n valueSet gvalue val\n {# call container_child_set_property #}\n (toContainer container)\n (toWidget child)\n propertyNamePtr\n gvalue\n\ncontainerChildGetPropertyInternal ::\n (ContainerClass container, WidgetClass child)\n => GType\n -> (GValue -> IO a)\n -> String\n -> child\n -> container\n -> IO a\ncontainerChildGetPropertyInternal gtype valueGet prop child container =\n withCString prop $ \\propertyNamePtr ->\n allocaGValue $ \\gvalue -> do\n valueInit gvalue gtype\n {# call container_child_get_property #}\n (toContainer container)\n (toWidget child)\n propertyNamePtr\n gvalue\n valueGet gvalue\n\n-- Versions for specific types:\n-- we actually don't use any others than bool at the moment\n--\n\ncontainerChildGetPropertyBool :: (ContainerClass container, WidgetClass child)\n => String -> child -> container -> IO Bool\ncontainerChildGetPropertyBool =\n containerChildGetPropertyInternal GType.bool valueGetBool\n\ncontainerChildSetPropertyBool :: (ContainerClass container, WidgetClass child)\n => String -> child -> container -> Bool -> IO ()\ncontainerChildSetPropertyBool =\n containerChildSetPropertyInternal GType.bool valueSetBool\n\n-- Convenience functions to make attribute implementations in the other modules\n-- shorter and more easily extensible.\n--\n\nnewAttrFromContainerChildIntProperty ::\n (ContainerClass container, WidgetClass child)\n => String -> child -> Attr container Int\nnewAttrFromContainerChildIntProperty propName child = newAttr\n (containerChildGetPropertyInternal GType.int valueGetInt propName child)\n (containerChildSetPropertyInternal GType.int valueSetInt propName child)\n\nnewAttrFromContainerChildUIntProperty ::\n (ContainerClass container, WidgetClass child)\n => String -> child -> Attr container Int\nnewAttrFromContainerChildUIntProperty propName child = newAttr\n (containerChildGetPropertyInternal GType.uint\n (\\gv -> liftM fromIntegral $ valueGetUInt gv) propName child)\n (containerChildSetPropertyInternal GType.uint\n (\\gv v -> valueSetUInt gv (fromIntegral v)) propName child)\n\nnewAttrFromContainerChildBoolProperty ::\n (ContainerClass container, WidgetClass child)\n => String -> child -> Attr container Bool\nnewAttrFromContainerChildBoolProperty propName child = newAttr\n (containerChildGetPropertyInternal GType.bool valueGetBool propName child)\n (containerChildSetPropertyInternal GType.bool valueSetBool propName child)\n\nnewAttrFromContainerChildEnumProperty ::\n (ContainerClass container, WidgetClass child, Enum enum)\n => String -> GType -> child -> Attr container enum\nnewAttrFromContainerChildEnumProperty propName gtype child = newAttr\n (containerChildGetPropertyInternal gtype valueGetEnum propName child)\n (containerChildSetPropertyInternal gtype valueSetEnum propName child)\n\nnewAttrFromContainerChildFlagsProperty ::\n (ContainerClass container, WidgetClass child, Flags flag)\n => String -> GType -> child -> Attr container [flag]\nnewAttrFromContainerChildFlagsProperty propName gtype child = newAttr\n (containerChildGetPropertyInternal gtype valueGetFlags propName child)\n (containerChildSetPropertyInternal gtype valueSetFlags propName child)\n\nnewAttrFromContainerChildStringProperty ::\n (ContainerClass container, WidgetClass child)\n => String -> child -> Attr container String\nnewAttrFromContainerChildStringProperty propName child = newAttr\n (containerChildGetPropertyInternal GType.string valueGetString propName child)\n (containerChildSetPropertyInternal GType.string valueSetString propName child)\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Container child Properties\n--\n-- Author : Duncan Coutts\n--\n-- Created: 16 April 2005\n--\n-- Copyright (C) 2005 Duncan Coutts\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- #hide\n\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Functions for getting and setting container child properties\n--\nmodule Graphics.UI.Gtk.Abstract.ContainerChildProperties (\n containerChildGetPropertyBool,\n containerChildSetPropertyBool,\n\n newAttrFromContainerChildIntProperty,\n newAttrFromContainerChildUIntProperty,\n newAttrFromContainerChildBoolProperty,\n newAttrFromContainerChildEnumProperty,\n newAttrFromContainerChildFlagsProperty,\n newAttrFromContainerChildStringProperty,\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\n{#import Graphics.UI.Gtk.Types#}\nimport System.Glib.GType\nimport qualified System.Glib.GTypeConstants as GType\nimport System.Glib.GValueTypes\n{#import System.Glib.GValue#}\t\t(GValue(GValue), allocaGValue, valueInit)\nimport System.Glib.Attributes\t\t(Attr, newAttr)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\ncontainerChildSetPropertyInternal ::\n (ContainerClass container, WidgetClass child)\n => GType\n -> (GValue -> a -> IO ())\n -> String\n -> child\n -> container\n -> a\n -> IO ()\ncontainerChildSetPropertyInternal gtype valueSet prop child container val =\n withCString prop $ \\propertyNamePtr ->\n allocaGValue $ \\gvalue -> do\n valueInit gvalue gtype\n valueSet gvalue val\n {# call container_child_set_property #}\n (toContainer container)\n (toWidget child)\n propertyNamePtr\n gvalue\n\ncontainerChildGetPropertyInternal ::\n (ContainerClass container, WidgetClass child)\n => GType\n -> (GValue -> IO a)\n -> String\n -> child\n -> container\n -> IO a\ncontainerChildGetPropertyInternal gtype valueGet prop child container =\n withCString prop $ \\propertyNamePtr ->\n allocaGValue $ \\gvalue -> do\n valueInit gvalue gtype\n {# call container_child_set_property #}\n (toContainer container)\n (toWidget child)\n propertyNamePtr\n gvalue\n valueGet gvalue\n\n-- Versions for specific types:\n-- we actually don't use any others than bool at the moment\n--\n\ncontainerChildGetPropertyBool :: (ContainerClass container, WidgetClass child)\n => String -> child -> container -> IO Bool\ncontainerChildGetPropertyBool =\n containerChildGetPropertyInternal GType.bool valueGetBool\n\ncontainerChildSetPropertyBool :: (ContainerClass container, WidgetClass child)\n => String -> child -> container -> Bool -> IO ()\ncontainerChildSetPropertyBool =\n containerChildSetPropertyInternal GType.bool valueSetBool\n\n-- Convenience functions to make attribute implementations in the other modules\n-- shorter and more easily extensible.\n--\n\nnewAttrFromContainerChildIntProperty ::\n (ContainerClass container, WidgetClass child)\n => String -> child -> Attr container Int\nnewAttrFromContainerChildIntProperty propName child = newAttr\n (containerChildGetPropertyInternal GType.int valueGetInt propName child)\n (containerChildSetPropertyInternal GType.int valueSetInt propName child)\n\nnewAttrFromContainerChildUIntProperty ::\n (ContainerClass container, WidgetClass child)\n => String -> child -> Attr container Int\nnewAttrFromContainerChildUIntProperty propName child = newAttr\n (containerChildGetPropertyInternal GType.uint\n (\\gv -> liftM fromIntegral $ valueGetUInt gv) propName child)\n (containerChildSetPropertyInternal GType.uint\n (\\gv v -> valueSetUInt gv (fromIntegral v)) propName child)\n\nnewAttrFromContainerChildBoolProperty ::\n (ContainerClass container, WidgetClass child)\n => String -> child -> Attr container Bool\nnewAttrFromContainerChildBoolProperty propName child = newAttr\n (containerChildGetPropertyInternal GType.bool valueGetBool propName child)\n (containerChildSetPropertyInternal GType.bool valueSetBool propName child)\n\nnewAttrFromContainerChildEnumProperty ::\n (ContainerClass container, WidgetClass child, Enum enum)\n => String -> GType -> child -> Attr container enum\nnewAttrFromContainerChildEnumProperty propName gtype child = newAttr\n (containerChildGetPropertyInternal gtype valueGetEnum propName child)\n (containerChildSetPropertyInternal gtype valueSetEnum propName child)\n\nnewAttrFromContainerChildFlagsProperty ::\n (ContainerClass container, WidgetClass child, Flags flag)\n => String -> GType -> child -> Attr container [flag]\nnewAttrFromContainerChildFlagsProperty propName gtype child = newAttr\n (containerChildGetPropertyInternal gtype valueGetFlags propName child)\n (containerChildSetPropertyInternal gtype valueSetFlags propName child)\n\nnewAttrFromContainerChildStringProperty ::\n (ContainerClass container, WidgetClass child)\n => String -> child -> Attr container String\nnewAttrFromContainerChildStringProperty propName child = newAttr\n (containerChildGetPropertyInternal GType.string valueGetString propName child)\n (containerChildSetPropertyInternal GType.string valueSetString propName child)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"125719627aa1523ccf755cd70ce24a2de3c3e0bb","subject":"Fixed issue #19 'blendBlit calls..'","message":"Fixed issue #19 'blendBlit calls..'\n","repos":"aleator\/CV,TomMD\/CV,BeautifulDestinations\/CV,aleator\/CV","old_file":"CV\/Image.chs","new_file":"CV\/Image.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns,ParallelListComp, FlexibleInstances, FlexibleContexts, TypeFamilies, EmptyDataDecls, ScopedTypeVariables, StandaloneDeriving, DeriveDataTypeable, UndecidableInstances #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, create\n, empty \n, emptyCopy \n, cloneImage\n, withClone\n, withCloneValue\n, CreateImage\n\n-- * Colour spaces\n, ChannelOf\n, GrayScale\n, DFT\n, RGB\n, RGBA\n, RGB_Channel(..)\n, LAB\n, LAB_Channel(..)\n, D32\n, D64\n, D8\n, Tag\n, lab\n, rgba\n, rgb\n, compose\n, composeMultichannelImage\n\n-- * IO operations\n, Loadable(..)\n, saveImage\n, loadColorImage\n, loadImage\n\n-- * Pixel level access\n, GetPixel(..)\n, SetPixel(..)\n, getAllPixels\n, getAllPixelsRowMajor\n, mapImageInplace\n\n-- * Image information\n, ImageDepth\n, Sized(..)\n, getArea\n, getChannel\n, getImageChannels\n, getImageDepth\n, getImageInfo\n\n-- * ROI's, COI's and subregions\n, setCOI\n, setROI\n, resetROI\n, getRegion\n, withIOROI\n, withROI\n\n-- * Blitting\n, blendBlit\n, blit\n, blitM\n, subPixelBlit\n, safeBlit\n, montage\n, tileImages\n\n-- * Conversions\n, rgbToGray \n, grayToRGB\n, rgbToLab \n, bgrToRgb\n, rgbToBgr\n, unsafeImageTo32F \n, unsafeImageTo8Bit \n\n-- * Low level access operations\n, BareImage(..)\n, creatingImage\n, unImage\n, unS\n, withGenBareImage\n, withBareImage\n, creatingBareImage\n, withGenImage\n, withImage\n, imageFPTR\n, ensure32F\n\n-- * Extended error handling\n, setCatch\n, CvException\n) where\n\nimport System.Mem\nimport System.Directory\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Utils\nimport Foreign.ForeignPtr hiding (newForeignPtr,unsafeForeignPtrToPtr)\nimport Foreign.Concurrent\nimport Foreign.Ptr\nimport Control.Parallel.Strategies\nimport Control.DeepSeq\nimport CV.Bindings.Error\n\nimport Data.Maybe(catMaybes)\nimport Data.List(genericLength)\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.ForeignPtr (unsafeForeignPtrToPtr)\nimport Foreign.Storable\nimport System.IO.Unsafe\nimport Data.Word\nimport Data.Complex\nimport Data.Complex\nimport Control.Monad\nimport Control.Exception\nimport Data.Data\nimport Data.Typeable\n\n\n\n\n-- Colorspaces\n\n-- | Single channel grayscale image\ndata GrayScale\n\ndata DFT\ndata RGB\ndata RGB_Channel = Red |\u00a0Green |\u00a0Blue deriving (Eq,Ord,Enum)\n\ndata BGR\n\ndata LAB\ndata RGBA\ndata LAB_Channel = LAB_L |\u00a0LAB_A |\u00a0LAB_B deriving (Eq,Ord,Enum)\n\n-- | Type family for expressing which channels a colorspace contains. This needs to be fixed wrt. the BGR color space.\ntype family ChannelOf a :: *\ntype instance ChannelOf RGB_Channel = RGB\ntype instance ChannelOf LAB_Channel = LAB\n\n-- Bit Depths\ntype D8 = Word8\ntype D32 = Float\ntype D64 = Double\n\n-- | The type for Images\nnewtype Image channels depth = S BareImage\n\n-- |\u00a0Remove typing info from an image\nunS (S i) = i -- Unsafe and ugly\n\nimageFPTR :: Image c d -> ForeignPtr BareImage\nimageFPTR (S (BareImage fptr)) = fptr\n\nwithImage :: Image c d -> (Ptr BareImage ->IO a) -> IO a\nwithImage (S i) op = withBareImage i op\n--withGenNewImage (S i) op = withGenImage i op\n\n-- Ok. this is just the example why I need image types\nwithUniPtr with x fun = with x $ \\y ->\n fun (castPtr y)\n\nwithGenImage = withUniPtr withImage\nwithGenBareImage = withUniPtr withBareImage\n\n{#pointer *IplImage as BareImage foreign newtype#}\n\nfreeBareImage ptr = with ptr {#call cvReleaseImage#}\n\n--foreign import ccall \"& wrapReleaseImage\" releaseImage :: FinalizerPtr BareImage\n\ninstance NFData (Image a b) where\n rnf a@(S (BareImage fptr)) = (unsafeForeignPtrToPtr) fptr `seq` a `seq` ()-- This might also need peek?\n\n\ncreatingImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . S . BareImage $ fptr\n\ncreatingBareImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . BareImage $ fptr\n\nunImage (S (BareImage fptr)) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\nrgba = undefined :: Tag RGBA\nlab = undefined :: Tag LAB\n\n-- | Typeclass for elements that are build from component elements. For example,\n-- RGB images can be constructed from three grayscale images.\nclass Composes a where\n type Source a :: *\n compose :: Source a -> a\n\ninstance (CreateImage (Image RGBA a)) => Composes (Image RGBA a) where\n type Source (Image RGBA a) = (Image GrayScale a, Image GrayScale a\n ,Image GrayScale a, Image GrayScale a)\n compose (r,g,b,a) = composeMultichannelImage (Just b) (Just g) (Just r) (Just a) rgba\n\ninstance (CreateImage (Image RGB a)) => Composes (Image RGB a) where\n type Source (Image RGB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (r,g,b) = composeMultichannelImage (Just b) (Just g) (Just r) Nothing rgb\n\ninstance (CreateImage (Image LAB a)) => Composes (Image LAB a) where\n type Source (Image LAB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (l,a,b) = composeMultichannelImage (Just l) (Just a) (Just b) Nothing lab\n\n{-# DEPRECATED composeMultichannelImage \"This is unsafe. Use compose instead\" #-}\ncomposeMultichannelImage :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannelImage = composeMultichannel\n\ncomposeMultichannel :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannel (c2)\n (c1)\n (c3)\n (c4)\n totag\n = unsafePerformIO $\u00a0do\n res <- create (size) -- TODO: Check channel count -- This is NOT correct\n withMaybe c1 $ \\cc1 ->\n withMaybe c2 $ \\cc2 ->\n withMaybe c3 $ \\cc3 ->\n withMaybe c4 $ \\cc4 ->\n withGenImage res $ \\cres -> {#call cvMerge#} cc1 cc2 cc3 cc4 cres\n return res\n where\n withMaybe (Just i) op = withGenImage i op\n withMaybe (Nothing) op = op nullPtr\n size = getSize . head . catMaybes $ [c1,c2,c3,c4]\n\n\n-- | Typeclass for CV items that can be read from file. Mainly images at this point.\nclass Loadable a where\n readFromFile :: FilePath -> IO a\n\n\ninstance Loadable ((Image GrayScale D32)) where\n readFromFile fp = do\n e <- loadImage fp\n case e of\n Just i -> return i\n Nothing -> fail $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D32)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ unsafeImageTo32F $ bgrToRgb i\n Nothing -> fail $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D8)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ bgrToRgb i\n Nothing -> fail $ \"Could not load \"++fp\n\ninstance Loadable ((Image GrayScale D8)) where\n readFromFile fp = do\n e <- loadImage8 fp\n case e of\n Just i -> return i\n Nothing -> fail $ \"Could not load \"++fp\n\n\n-- | This function loads and converts image to an arbitrary format. Notice that it is\n-- polymorphic enough to cause run time errors if the declared and actual types of the\n-- images do not match. Use with care.\nunsafeloadUsing x p n = do\n exists <- doesFileExist n\n if not exists then return Nothing\n else do\n i <- withCString n $ \\name ->\n creatingBareImage ({#call cvLoadImage #} name p)\n bw <- x i\n return . Just .\u00a0S $ bw\n\nloadImage :: FilePath -> IO (Maybe (Image GrayScale D32))\nloadImage = unsafeloadUsing imageTo32F 0\nloadImage8 :: FilePath -> IO (Maybe (Image GrayScale D8))\nloadImage8 = unsafeloadUsing imageTo8Bit 0\nloadColorImage :: FilePath -> IO (Maybe (Image BGR D32))\nloadColorImage = unsafeloadUsing imageTo32F 1\nloadColorImage8 :: FilePath -> IO (Maybe (Image BGR D8))\nloadColorImage8 = unsafeloadUsing imageTo8Bit 1\n\n-- | Typeclass for elements with a size, such as images and matrices.\nclass Sized a where\n type Size a :: *\n getSize :: a -> Size a\n\ninstance Sized BareImage where\n type Size BareImage = (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize image = unsafePerformIO $ withBareImage image $ \\i -> do\n w <- {#call getImageWidth#} i\n h <- {#call getImageHeight#} i\n return (fromIntegral w,fromIntegral h)\n\ninstance Sized (Image c d) where\n type Size (Image c d) = (Int,Int)\n getSize = getSize . unS\n\n\ncvRGBtoGRAY = 7 :: CInt-- NOTE: This will break.\ncvRGBtoLAB = 45 :: CInt-- NOTE: This will break.\n\n\n#c\nenum CvtFlags {\n CvtFlip = CV_CVTIMG_FLIP,\n CvtSwapRB = CV_CVTIMG_SWAP_RB\n };\n#endc\n\n#c\nenum CvtCodes {\n CV_BGR2BGRA =0,\n CV_RGB2RGBA =CV_BGR2BGRA,\n\n CV_BGRA2BGR =1,\n CV_RGBA2RGB =CV_BGRA2BGR,\n\n CV_BGR2RGBA =2,\n CV_RGB2BGRA =CV_BGR2RGBA,\n\n CV_RGBA2BGR =3,\n CV_BGRA2RGB =CV_RGBA2BGR,\n\n CV_BGR2RGB =4,\n CV_RGB2BGR =CV_BGR2RGB,\n\n CV_BGRA2RGBA =5,\n CV_RGBA2BGRA =CV_BGRA2RGBA,\n\n CV_BGR2GRAY =6,\n CV_RGB2GRAY =7,\n CV_GRAY2BGR =8,\n CV_GRAY2RGB =CV_GRAY2BGR,\n CV_GRAY2BGRA =9,\n CV_GRAY2RGBA =CV_GRAY2BGRA,\n CV_BGRA2GRAY =10,\n CV_RGBA2GRAY =11,\n\n CV_BGR2BGR565 =12,\n CV_RGB2BGR565 =13,\n CV_BGR5652BGR =14,\n CV_BGR5652RGB =15,\n CV_BGRA2BGR565 =16,\n CV_RGBA2BGR565 =17,\n CV_BGR5652BGRA =18,\n CV_BGR5652RGBA =19,\n\n CV_GRAY2BGR565 =20,\n CV_BGR5652GRAY =21,\n\n CV_BGR2BGR555 =22,\n CV_RGB2BGR555 =23,\n CV_BGR5552BGR =24,\n CV_BGR5552RGB =25,\n CV_BGRA2BGR555 =26,\n CV_RGBA2BGR555 =27,\n CV_BGR5552BGRA =28,\n CV_BGR5552RGBA =29,\n\n CV_GRAY2BGR555 =30,\n CV_BGR5552GRAY =31,\n\n CV_BGR2XYZ =32,\n CV_RGB2XYZ =33,\n CV_XYZ2BGR =34,\n CV_XYZ2RGB =35,\n\n CV_BGR2YCrCb =36,\n CV_RGB2YCrCb =37,\n CV_YCrCb2BGR =38,\n CV_YCrCb2RGB =39,\n\n CV_BGR2HSV =40,\n CV_RGB2HSV =41,\n\n CV_BGR2Lab =44,\n CV_RGB2Lab =45,\n\n CV_BayerBG2BGR =46,\n CV_BayerGB2BGR =47,\n CV_BayerRG2BGR =48,\n CV_BayerGR2BGR =49,\n\n CV_BayerBG2RGB =CV_BayerRG2BGR,\n CV_BayerGB2RGB =CV_BayerGR2BGR,\n CV_BayerRG2RGB =CV_BayerBG2BGR,\n CV_BayerGR2RGB =CV_BayerGB2BGR,\n\n CV_BGR2Luv =50,\n CV_RGB2Luv =51,\n CV_BGR2HLS =52,\n CV_RGB2HLS =53,\n\n CV_HSV2BGR =54,\n CV_HSV2RGB =55,\n\n CV_Lab2BGR =56,\n CV_Lab2RGB =57,\n CV_Luv2BGR =58,\n CV_Luv2RGB =59,\n CV_HLS2BGR =60,\n CV_HLS2RGB =61,\n\n CV_BayerBG2BGR_VNG =62,\n CV_BayerGB2BGR_VNG =63,\n CV_BayerRG2BGR_VNG =64,\n CV_BayerGR2BGR_VNG =65,\n \n CV_BayerBG2RGB_VNG =CV_BayerRG2BGR_VNG,\n CV_BayerGB2RGB_VNG =CV_BayerGR2BGR_VNG,\n CV_BayerRG2RGB_VNG =CV_BayerBG2BGR_VNG,\n CV_BayerGR2RGB_VNG =CV_BayerGB2BGR_VNG,\n \n CV_BGR2HSV_FULL = 66,\n CV_RGB2HSV_FULL = 67,\n CV_BGR2HLS_FULL = 68,\n CV_RGB2HLS_FULL = 69,\n \n CV_HSV2BGR_FULL = 70,\n CV_HSV2RGB_FULL = 71,\n CV_HLS2BGR_FULL = 72,\n CV_HLS2RGB_FULL = 73,\n \n CV_LBGR2Lab = 74,\n CV_LRGB2Lab = 75,\n CV_LBGR2Luv = 76,\n CV_LRGB2Luv = 77,\n \n CV_Lab2LBGR = 78,\n CV_Lab2LRGB = 79,\n CV_Luv2LBGR = 80,\n CV_Luv2LRGB = 81,\n \n CV_BGR2YUV = 82,\n CV_RGB2YUV = 83,\n CV_YUV2BGR = 84,\n CV_YUV2RGB = 85,\n \n CV_COLORCVT_MAX =100\n};\n#endc\n\n{#enum CvtCodes {}#}\n\n{#enum CvtFlags {}#}\n\n\nrgbToLab :: Image RGB D32 -> Image LAB D32\nrgbToLab = S . convertTo cvRGBtoLAB 3 . unS\n\nrgbToGray :: Image RGB D32 -> Image GrayScale D32\nrgbToGray = S . convertTo cvRGBtoGRAY 1 . unS\n\ngrayToRGB :: Image GrayScale D32 -> Image RGB D32\ngrayToRGB = S . convertTo (fromIntegral . fromEnum $ CV_GRAY2BGR) 3 . unS\n\n\nbgrToRgb :: Image BGR D8 -> Image RGB D8\nbgrToRgb = S . swapRB . unS\n\nrgbToBgr :: Image RGB D8 -> Image BGR D8\nrgbToBgr = S . swapRB . unS\n\nswapRB :: BareImage -> BareImage\nswapRB img = unsafePerformIO $ do\n res <- cloneBareImage img\n withBareImage img $ \\cimg ->\n withBareImage res $ \\cres ->\n {#call cvConvertImage#} (castPtr cimg) (castPtr cres) (fromIntegral . fromEnum $ CvtSwapRB)\n return res\n\n\nclass GetPixel a where\n type P a :: *\n getPixel :: (Int,Int) -> a -> P a\n\n-- #define FGET(img,x,y) (((float *)((img)->imageData + (y)*(img)->widthStep))[(x)])\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Float))):: Ptr Float)\n\ninstance GetPixel (Image GrayScale D8) where\n type P (Image GrayScale D8) = D8\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Word8))):: Ptr Word8)\n\ninstance GetPixel (Image DFT D32) where\n type P (Image DFT D32) = Complex D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n re <- peek (castPtr (d`plusPtr` (y*cs + x*2*fs)))\n im <- peek (castPtr (d`plusPtr` (y*cs +(x*2+1)*fs)))\n return (re:+im)\n\n-- #define UGETC(img,color,x,y) (((uint8_t *)((img)->imageData + (y)*(img)->widthStep))[(x)*3+(color)])\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\ninstance GetPixel (Image BGR D32) where\n type P (Image BGR D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\ninstance GetPixel (Image BGR D8) where\n type P (Image BGR D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image RGB D8) where\n type P (Image RGB D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image LAB D32) where\n type P (Image LAB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n l <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n a <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n b <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (l,a,b)\n\n-- | Perform (a destructive) inplace map of the image. This should be wrapped inside\n-- withClone or an image operation\nmapImageInplace :: (P (Image GrayScale D32) -> P (Image GrayScale D32))\n -> Image GrayScale D32\n -> IO ()\nmapImageInplace f image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let (w,h) = getSize image\n cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n forM_ [(x,y) | x<-[0..w-1], y <- [0..h-1]] $ \\(x,y) ->\u00a0do\n v <- peek (castPtr (d `plusPtr` (y*cs+x*fs)))\n poke (castPtr (d `plusPtr` (y*cs+x*fs))) (f v)\n\n\n\n\nconvertTo :: CInt -> CInt -> BareImage -> BareImage\nconvertTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage32F#} w h channels\n withBareImage img $ \\cimg ->\n {#call cvCvtColor#} (castPtr cimg) (castPtr res) code\n return res\n where\n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\n-- |\u00a0Class for images that exist.\nclass CreateImage a where\n -- | Create an image from size\n create :: (Int,Int) -> IO a\n\n\ninstance CreateImage (Image GrayScale D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image DFT D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 2\ninstance CreateImage (Image LAB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 4\n\n\n\n-- | Allocate a new empty image\nempty :: (CreateImage (Image a b)) => (Int,Int) -> (Image a b)\nempty size = unsafePerformIO $ create size\n\n-- |\u00a0Allocate a new image that of the same size and type as the exemplar image given.\nemptyCopy :: (CreateImage (Image a b)) => Image a b -> (Image a b)\nemptyCopy img = unsafePerformIO $ create (getSize img)\n\n-- | Save image. This will convert the image to 8 bit one before saving\nclass Save a where\n save :: FilePath -> a -> IO () \n\ninstance Save (Image BGR D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image) \n\ninstance Save (Image RGB D32) where\n save filename image = primitiveSave filename (swapRB . unS . unsafeImageTo8Bit $ image)\n\ninstance Save (Image RGB D8) where\n save filename image = primitiveSave filename (swapRB . unS $ image)\n\ninstance Save (Image GrayScale D8) where\n save filename image = primitiveSave filename (unS $ image)\n\ninstance Save (Image GrayScale D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image) \n \nprimitiveSave :: FilePath -> BareImage -> IO ()\nprimitiveSave filename fpi = do \n withCString filename $ \\name ->\n withGenBareImage fpi $ \\cvArr ->\n alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\nsaveImage :: (Save (Image c d)) => FilePath -> Image c d -> IO ()\nsaveImage = save\n\ngetArea :: (Sized a,Num b, Size a ~ (b,b)) => a -> b\ngetArea = uncurry (*).getSize\n\ngetRegion :: (Int,Int) -> (Int,Int) -> Image c d -> Image c d\ngetRegion (fromIntegral -> x,fromIntegral -> y) (fromIntegral -> w,fromIntegral -> h) image\n | x+w <= width && y+h <= height = S . getRegion' (x,y) (w,h) $ unS image\n | otherwise = error $ \"Region outside image:\"\n ++ show (getSize image) ++\n \"\/\"++show (x+w,y+h)\n where\n (fromIntegral -> width,fromIntegral -> height) = getSize image\n\ngetRegion' (x,y) (w,h) image = unsafePerformIO $\n withBareImage image $ \\i ->\n creatingBareImage ({#call getSubImage#}\n i x y w h)\n\n\n-- | Tile images by overlapping them on a black canvas.\ntileImages image1 image2 (x,y) = unsafePerformIO $\n withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n creatingImage ({#call simpleMergeImages#}\n i1 i2 x y)\n-- | Blit image2 onto image1.\nblitFix = blit\nblit :: Image GrayScale D32 -> Image GrayScale D32 -> (Int,Int) -> IO ()\nblit image1 image2 (x,y)\n | badSizes = error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n | otherwise = withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call plainBlit#} i1 i2 (fromIntegral y) (fromIntegral x))\n where\n ((w1,h1),(w2,h2)) = (getSize image1,getSize image2)\n badSizes = x+w2>w1 || y+h2>h1 || x<0 || y<0\n\n-- blitM :: (CreateImage (Image c d)) => (Int,Int) -> [((Int,Int),Image c d)] -> Image c d\nblitM (rw,rh) imgs = resultPic\n where\n resultPic = unsafePerformIO $ do\n r <- create (fromIntegral rw,fromIntegral rh)\n sequence_ [blit r i (fromIntegral x, fromIntegral y)\n | ((x,y),i) <- imgs ]\n return r\n\n\nsubPixelBlit\n :: Image c d -> Image c d -> (CDouble, CDouble) -> IO ()\n\nsubPixelBlit (image1) (image2) (x,y)\n | badSizes = error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n | otherwise = withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call subpixel_blit#} i1 i2 y x)\n where\n ((w1,h1),(w2,h2)) = (getSize image1,getSize image2)\n badSizes = ceiling x+w2>w1 || ceiling y+h2>h1 ||\u00a0x<0 || y<0\n\nsafeBlit i1 i2 (x,y) = unsafePerformIO $ do\n res <- cloneImage i1-- createImage32F (getSize i1) 1\n blit res i2 (x,y)\n return res\n\n-- | Blit image2 onto image1.\n-- This uses an alpha channel bitmap for determining the regions where the image should be \"blended\" with\n-- the base image.\nblendBlit image1 image1Alpha image2 image2Alpha (x,y) =\n withImage image1 $ \\i1 ->\n withImage image1Alpha $ \\i1a ->\n withImage image2Alpha $ \\i2a ->\n withImage image2 $ \\i2 ->\n ({#call alphaBlit#} i1 i1a i2 i2a y x)\n\n\n-- | Create a copy of an image\ncloneImage :: Image a b -> IO (Image a b)\ncloneImage img = withGenImage img $ \\image ->\n creatingImage ({#call cvCloneImage #} image)\n\n-- | Create a copy of a non-types image\ncloneBareImage :: BareImage -> IO BareImage\ncloneBareImage img = withGenBareImage img $ \\image ->\n creatingBareImage ({#call cvCloneImage #} image)\n\nwithClone\n :: Image channels depth\n -> (Image channels depth -> IO ())\n -> IO (Image channels depth)\nwithClone img fun = do\n result <- cloneImage img\n fun result\n return result\n\nwithCloneValue\n :: Image channels depth\n -> (Image channels depth -> IO a)\n -> IO a\nwithCloneValue img fun = do\n result <- cloneImage img\n r <- fun result\n return r\n\nunsafeImageTo32F :: Image c d -> Image c D32\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure32F #} image)\n\nunsafeImageTo8Bit :: Image cspace a -> Image cspace D8\nunsafeImageTo8Bit img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure8U #} image)\n\n--toD32 :: Image c d -> Image c D32\n--toD32 i =\n-- unsafePerformIO $\n-- withImage i $ \\i_ptr ->\n-- creatingImage\n\n\nimageTo32F img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure32F #} image)\n\nimageTo8Bit img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure8U #} image)\n#c\nenum ImageDepth {\n Depth32F = IPL_DEPTH_32F,\n Depth64F = IPL_DEPTH_64F,\n Depth8U = IPL_DEPTH_8U,\n Depth8S = IPL_DEPTH_8S,\n Depth16U = IPL_DEPTH_16U,\n Depth16S = IPL_DEPTH_16S,\n Depth32S = IPL_DEPTH_32S\n };\n#endc\n\n{#enum ImageDepth {}#}\n\nderiving instance Show ImageDepth\n\ngetImageDepth :: Image c d -> IO ImageDepth\ngetImageDepth i = withImage i $ \\c_img -> {#get IplImage->depth #} c_img >>= return.toEnum.fromIntegral\ngetImageChannels i = withImage i $ \\c_img -> {#get IplImage->nChannels #} c_img\n\ngetImageInfo x = do\n let s = getSize x\n d <- getImageDepth x\n c <- getImageChannels x\n return (s,d,c)\n\n\n-- Manipulating regions of interest:\nsetROI (fromIntegral -> x,fromIntegral -> y)\n (fromIntegral -> w,fromIntegral -> h)\n image = withImage image $ \\i ->\n {#call wrapSetImageROI#} i x y w h\n\nresetROI image = withImage image $ \\i ->\n {#call cvResetImageROI#} i\n\nsetCOI chnl image = withImage image $ \\i ->\n {#call cvSetImageCOI#} i (fromIntegral chnl)\nresetCOI image = withImage image $ \\i ->\n {#call cvSetImageCOI#} i 0\n\n\n-- #TODO: Replace the Int below with proper channel identifier\ngetChannel :: (Enum a) => a -> Image (ChannelOf a) d -> Image GrayScale d\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n setCOI (1+fromEnum no) image\n cres <- {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\n withGenImage image $ \\cimage ->\n {#call cvCopy#} cimage (castPtr cres) (nullPtr)\n resetCOI image\n return cres\n\nwithIOROI pos size image op = do\n setROI pos size image\n x <- op\n resetROI image\n return x\n\nwithROI :: (Int, Int) -> (Int, Int) -> Image c d -> (Image c d -> a) -> a\nwithROI pos size image op = unsafePerformIO $ do\n setROI pos size image\n let x = op image -- BUG\n resetROI image\n return x\n\nclass SetPixel a where\n type SP a :: *\n setPixel :: (Int,Int) -> SP a -> a -> IO ()\n\ninstance SetPixel (Image GrayScale D32) where\n type SP (Image GrayScale D32) = D32\n {-#INLINE setPixel#-}\n setPixel (x,y) v image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Float))):: Ptr Float)\n v\n\ninstance SetPixel (Image GrayScale D8) where\n type SP (Image GrayScale D8) = D8\n {-#INLINE setPixel#-}\n setPixel (x,y) v image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Word8))):: Ptr Word8)\n v\n\ninstance SetPixel (Image RGB D32) where\n type SP (Image RGB D32) = (D32,D32,D32)\n {-#INLINE setPixel#-}\n setPixel (x,y) (r,g,b) image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs +x*3*fs))) b\n poke (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs))) g \n poke (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs))) r\n\ninstance SetPixel (Image DFT D32) where\n type SP (Image DFT D32) = Complex D32\n {-#INLINE setPixel#-}\n setPixel (x,y) (re:+im) image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs + x*2*fs))) re\n poke (castPtr (d`plusPtr` (y*cs + (x*2+1)*fs))) im\n\n\n\ngetAllPixels image = [getPixel (i,j) image\n | i <- [0..width-1 ]\n , j <- [0..height-1]]\n where\n (width,height) = getSize image\n\ngetAllPixelsRowMajor image = [getPixel (i,j) image\n | j <- [0..height-1]\n , i <- [0..width-1]\n ]\n where\n (width,height) = getSize image\n\n-- |Create a montage form given images (u,v) determines the layout and space the spacing\n-- between images. Images are assumed to be the same size (determined by the first image)\nmontage :: (CreateImage (Image GrayScale D32)) => (Int,Int) -> Int -> [Image GrayScale D32] -> Image GrayScale D32\nmontage (u',v') space' imgs\n | u'*v' \/= (length imgs) = error (\"Montage mismatch: \"++show (u,v, length imgs))\n | otherwise = resultPic\n where\n space = fromIntegral space'\n (u,v) = (fromIntegral u', fromIntegral v')\n (rw,rh) = (u*xstep,v*ystep)\n (w,h) = getSize (head imgs)\n (xstep,ystep) = (fromIntegral space + w,fromIntegral space + h)\n edge = space`div`2\n resultPic = unsafePerformIO $ do\n r <- create (rw,rh)\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep)\n | y <- [0..v-1] , x <- [0..u-1]\n | i <- imgs ]\n return r\n\ndata CvException = CvException Int String String String Int\n deriving (Show, Typeable)\n\ninstance Exception CvException\n\nsetCatch = do\n let catch i cstr1 cstr2 cstr3 j = do\n func <- peekCString cstr1\n msg <- peekCString cstr2\n file <- peekCString cstr3\n throw (CvException (fromIntegral i) func msg file (fromIntegral j)) \n return 0\n cb <- mk'CvErrorCallback catch\n c'cvRedirectError cb nullPtr nullPtr\n c'cvSetErrMode c'CV_ErrModeSilent\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns,ParallelListComp, FlexibleInstances, FlexibleContexts, TypeFamilies, EmptyDataDecls, ScopedTypeVariables, StandaloneDeriving, DeriveDataTypeable, UndecidableInstances #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, create\n, empty \n, emptyCopy \n, cloneImage\n, withClone\n, withCloneValue\n, CreateImage\n\n-- * Colour spaces\n, ChannelOf\n, GrayScale\n, DFT\n, RGB\n, RGBA\n, RGB_Channel(..)\n, LAB\n, LAB_Channel(..)\n, D32\n, D64\n, D8\n, Tag\n, lab\n, rgba\n, rgb\n, compose\n, composeMultichannelImage\n\n-- * IO operations\n, Loadable(..)\n, saveImage\n, loadColorImage\n, loadImage\n\n-- * Pixel level access\n, GetPixel(..)\n, SetPixel(..)\n, getAllPixels\n, getAllPixelsRowMajor\n, mapImageInplace\n\n-- * Image information\n, ImageDepth\n, Sized(..)\n, getArea\n, getChannel\n, getImageChannels\n, getImageDepth\n, getImageInfo\n\n-- * ROI's, COI's and subregions\n, setCOI\n, setROI\n, resetROI\n, getRegion\n, withIOROI\n, withROI\n\n-- * Blitting\n, blendBlit\n, blit\n, blitM\n, subPixelBlit\n, safeBlit\n, montage\n, tileImages\n\n-- * Conversions\n, rgbToGray \n, grayToRGB\n, rgbToLab \n, bgrToRgb\n, rgbToBgr\n, unsafeImageTo32F \n, unsafeImageTo8Bit \n\n-- * Low level access operations\n, BareImage(..)\n, creatingImage\n, unImage\n, unS\n, withGenBareImage\n, withBareImage\n, creatingBareImage\n, withGenImage\n, withImage\n, imageFPTR\n, ensure32F\n\n-- * Extended error handling\n, setCatch\n, CvException\n) where\n\nimport System.Mem\nimport System.Directory\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Utils\nimport Foreign.ForeignPtr hiding (newForeignPtr,unsafeForeignPtrToPtr)\nimport Foreign.Concurrent\nimport Foreign.Ptr\nimport Control.Parallel.Strategies\nimport Control.DeepSeq\nimport CV.Bindings.Error\n\nimport Data.Maybe(catMaybes)\nimport Data.List(genericLength)\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.ForeignPtr (unsafeForeignPtrToPtr)\nimport Foreign.Storable\nimport System.IO.Unsafe\nimport Data.Word\nimport Data.Complex\nimport Data.Complex\nimport Control.Monad\nimport Control.Exception\nimport Data.Data\nimport Data.Typeable\n\n\n\n\n-- Colorspaces\n\n-- | Single channel grayscale image\ndata GrayScale\n\ndata DFT\ndata RGB\ndata RGB_Channel = Red |\u00a0Green |\u00a0Blue deriving (Eq,Ord,Enum)\n\ndata BGR\n\ndata LAB\ndata RGBA\ndata LAB_Channel = LAB_L |\u00a0LAB_A |\u00a0LAB_B deriving (Eq,Ord,Enum)\n\n-- | Type family for expressing which channels a colorspace contains. This needs to be fixed wrt. the BGR color space.\ntype family ChannelOf a :: *\ntype instance ChannelOf RGB_Channel = RGB\ntype instance ChannelOf LAB_Channel = LAB\n\n-- Bit Depths\ntype D8 = Word8\ntype D32 = Float\ntype D64 = Double\n\n-- | The type for Images\nnewtype Image channels depth = S BareImage\n\n-- |\u00a0Remove typing info from an image\nunS (S i) = i -- Unsafe and ugly\n\nimageFPTR :: Image c d -> ForeignPtr BareImage\nimageFPTR (S (BareImage fptr)) = fptr\n\nwithImage :: Image c d -> (Ptr BareImage ->IO a) -> IO a\nwithImage (S i) op = withBareImage i op\n--withGenNewImage (S i) op = withGenImage i op\n\n-- Ok. this is just the example why I need image types\nwithUniPtr with x fun = with x $ \\y ->\n fun (castPtr y)\n\nwithGenImage = withUniPtr withImage\nwithGenBareImage = withUniPtr withBareImage\n\n{#pointer *IplImage as BareImage foreign newtype#}\n\nfreeBareImage ptr = with ptr {#call cvReleaseImage#}\n\n--foreign import ccall \"& wrapReleaseImage\" releaseImage :: FinalizerPtr BareImage\n\ninstance NFData (Image a b) where\n rnf a@(S (BareImage fptr)) = (unsafeForeignPtrToPtr) fptr `seq` a `seq` ()-- This might also need peek?\n\n\ncreatingImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . S . BareImage $ fptr\n\ncreatingBareImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . BareImage $ fptr\n\nunImage (S (BareImage fptr)) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\nrgba = undefined :: Tag RGBA\nlab = undefined :: Tag LAB\n\n-- | Typeclass for elements that are build from component elements. For example,\n-- RGB images can be constructed from three grayscale images.\nclass Composes a where\n type Source a :: *\n compose :: Source a -> a\n\ninstance (CreateImage (Image RGBA a)) => Composes (Image RGBA a) where\n type Source (Image RGBA a) = (Image GrayScale a, Image GrayScale a\n ,Image GrayScale a, Image GrayScale a)\n compose (r,g,b,a) = composeMultichannelImage (Just b) (Just g) (Just r) (Just a) rgba\n\ninstance (CreateImage (Image RGB a)) => Composes (Image RGB a) where\n type Source (Image RGB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (r,g,b) = composeMultichannelImage (Just b) (Just g) (Just r) Nothing rgb\n\ninstance (CreateImage (Image LAB a)) => Composes (Image LAB a) where\n type Source (Image LAB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (l,a,b) = composeMultichannelImage (Just l) (Just a) (Just b) Nothing lab\n\n{-# DEPRECATED composeMultichannelImage \"This is unsafe. Use compose instead\" #-}\ncomposeMultichannelImage :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannelImage = composeMultichannel\n\ncomposeMultichannel :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannel (c2)\n (c1)\n (c3)\n (c4)\n totag\n = unsafePerformIO $\u00a0do\n res <- create (size) -- TODO: Check channel count -- This is NOT correct\n withMaybe c1 $ \\cc1 ->\n withMaybe c2 $ \\cc2 ->\n withMaybe c3 $ \\cc3 ->\n withMaybe c4 $ \\cc4 ->\n withGenImage res $ \\cres -> {#call cvMerge#} cc1 cc2 cc3 cc4 cres\n return res\n where\n withMaybe (Just i) op = withGenImage i op\n withMaybe (Nothing) op = op nullPtr\n size = getSize . head . catMaybes $ [c1,c2,c3,c4]\n\n\n-- | Typeclass for CV items that can be read from file. Mainly images at this point.\nclass Loadable a where\n readFromFile :: FilePath -> IO a\n\n\ninstance Loadable ((Image GrayScale D32)) where\n readFromFile fp = do\n e <- loadImage fp\n case e of\n Just i -> return i\n Nothing -> fail $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D32)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ unsafeImageTo32F $ bgrToRgb i\n Nothing -> fail $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D8)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ bgrToRgb i\n Nothing -> fail $ \"Could not load \"++fp\n\ninstance Loadable ((Image GrayScale D8)) where\n readFromFile fp = do\n e <- loadImage8 fp\n case e of\n Just i -> return i\n Nothing -> fail $ \"Could not load \"++fp\n\n\n-- | This function loads and converts image to an arbitrary format. Notice that it is\n-- polymorphic enough to cause run time errors if the declared and actual types of the\n-- images do not match. Use with care.\nunsafeloadUsing x p n = do\n exists <- doesFileExist n\n if not exists then return Nothing\n else do\n i <- withCString n $ \\name ->\n creatingBareImage ({#call cvLoadImage #} name p)\n bw <- x i\n return . Just .\u00a0S $ bw\n\nloadImage :: FilePath -> IO (Maybe (Image GrayScale D32))\nloadImage = unsafeloadUsing imageTo32F 0\nloadImage8 :: FilePath -> IO (Maybe (Image GrayScale D8))\nloadImage8 = unsafeloadUsing imageTo8Bit 0\nloadColorImage :: FilePath -> IO (Maybe (Image BGR D32))\nloadColorImage = unsafeloadUsing imageTo32F 1\nloadColorImage8 :: FilePath -> IO (Maybe (Image BGR D8))\nloadColorImage8 = unsafeloadUsing imageTo8Bit 1\n\n-- | Typeclass for elements with a size, such as images and matrices.\nclass Sized a where\n type Size a :: *\n getSize :: a -> Size a\n\ninstance Sized BareImage where\n type Size BareImage = (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize image = unsafePerformIO $ withBareImage image $ \\i -> do\n w <- {#call getImageWidth#} i\n h <- {#call getImageHeight#} i\n return (fromIntegral w,fromIntegral h)\n\ninstance Sized (Image c d) where\n type Size (Image c d) = (Int,Int)\n getSize = getSize . unS\n\n\ncvRGBtoGRAY = 7 :: CInt-- NOTE: This will break.\ncvRGBtoLAB = 45 :: CInt-- NOTE: This will break.\n\n\n#c\nenum CvtFlags {\n CvtFlip = CV_CVTIMG_FLIP,\n CvtSwapRB = CV_CVTIMG_SWAP_RB\n };\n#endc\n\n#c\nenum CvtCodes {\n CV_BGR2BGRA =0,\n CV_RGB2RGBA =CV_BGR2BGRA,\n\n CV_BGRA2BGR =1,\n CV_RGBA2RGB =CV_BGRA2BGR,\n\n CV_BGR2RGBA =2,\n CV_RGB2BGRA =CV_BGR2RGBA,\n\n CV_RGBA2BGR =3,\n CV_BGRA2RGB =CV_RGBA2BGR,\n\n CV_BGR2RGB =4,\n CV_RGB2BGR =CV_BGR2RGB,\n\n CV_BGRA2RGBA =5,\n CV_RGBA2BGRA =CV_BGRA2RGBA,\n\n CV_BGR2GRAY =6,\n CV_RGB2GRAY =7,\n CV_GRAY2BGR =8,\n CV_GRAY2RGB =CV_GRAY2BGR,\n CV_GRAY2BGRA =9,\n CV_GRAY2RGBA =CV_GRAY2BGRA,\n CV_BGRA2GRAY =10,\n CV_RGBA2GRAY =11,\n\n CV_BGR2BGR565 =12,\n CV_RGB2BGR565 =13,\n CV_BGR5652BGR =14,\n CV_BGR5652RGB =15,\n CV_BGRA2BGR565 =16,\n CV_RGBA2BGR565 =17,\n CV_BGR5652BGRA =18,\n CV_BGR5652RGBA =19,\n\n CV_GRAY2BGR565 =20,\n CV_BGR5652GRAY =21,\n\n CV_BGR2BGR555 =22,\n CV_RGB2BGR555 =23,\n CV_BGR5552BGR =24,\n CV_BGR5552RGB =25,\n CV_BGRA2BGR555 =26,\n CV_RGBA2BGR555 =27,\n CV_BGR5552BGRA =28,\n CV_BGR5552RGBA =29,\n\n CV_GRAY2BGR555 =30,\n CV_BGR5552GRAY =31,\n\n CV_BGR2XYZ =32,\n CV_RGB2XYZ =33,\n CV_XYZ2BGR =34,\n CV_XYZ2RGB =35,\n\n CV_BGR2YCrCb =36,\n CV_RGB2YCrCb =37,\n CV_YCrCb2BGR =38,\n CV_YCrCb2RGB =39,\n\n CV_BGR2HSV =40,\n CV_RGB2HSV =41,\n\n CV_BGR2Lab =44,\n CV_RGB2Lab =45,\n\n CV_BayerBG2BGR =46,\n CV_BayerGB2BGR =47,\n CV_BayerRG2BGR =48,\n CV_BayerGR2BGR =49,\n\n CV_BayerBG2RGB =CV_BayerRG2BGR,\n CV_BayerGB2RGB =CV_BayerGR2BGR,\n CV_BayerRG2RGB =CV_BayerBG2BGR,\n CV_BayerGR2RGB =CV_BayerGB2BGR,\n\n CV_BGR2Luv =50,\n CV_RGB2Luv =51,\n CV_BGR2HLS =52,\n CV_RGB2HLS =53,\n\n CV_HSV2BGR =54,\n CV_HSV2RGB =55,\n\n CV_Lab2BGR =56,\n CV_Lab2RGB =57,\n CV_Luv2BGR =58,\n CV_Luv2RGB =59,\n CV_HLS2BGR =60,\n CV_HLS2RGB =61,\n\n CV_BayerBG2BGR_VNG =62,\n CV_BayerGB2BGR_VNG =63,\n CV_BayerRG2BGR_VNG =64,\n CV_BayerGR2BGR_VNG =65,\n \n CV_BayerBG2RGB_VNG =CV_BayerRG2BGR_VNG,\n CV_BayerGB2RGB_VNG =CV_BayerGR2BGR_VNG,\n CV_BayerRG2RGB_VNG =CV_BayerBG2BGR_VNG,\n CV_BayerGR2RGB_VNG =CV_BayerGB2BGR_VNG,\n \n CV_BGR2HSV_FULL = 66,\n CV_RGB2HSV_FULL = 67,\n CV_BGR2HLS_FULL = 68,\n CV_RGB2HLS_FULL = 69,\n \n CV_HSV2BGR_FULL = 70,\n CV_HSV2RGB_FULL = 71,\n CV_HLS2BGR_FULL = 72,\n CV_HLS2RGB_FULL = 73,\n \n CV_LBGR2Lab = 74,\n CV_LRGB2Lab = 75,\n CV_LBGR2Luv = 76,\n CV_LRGB2Luv = 77,\n \n CV_Lab2LBGR = 78,\n CV_Lab2LRGB = 79,\n CV_Luv2LBGR = 80,\n CV_Luv2LRGB = 81,\n \n CV_BGR2YUV = 82,\n CV_RGB2YUV = 83,\n CV_YUV2BGR = 84,\n CV_YUV2RGB = 85,\n \n CV_COLORCVT_MAX =100\n};\n#endc\n\n{#enum CvtCodes {}#}\n\n{#enum CvtFlags {}#}\n\n\nrgbToLab :: Image RGB D32 -> Image LAB D32\nrgbToLab = S . convertTo cvRGBtoLAB 3 . unS\n\nrgbToGray :: Image RGB D32 -> Image GrayScale D32\nrgbToGray = S . convertTo cvRGBtoGRAY 1 . unS\n\ngrayToRGB :: Image GrayScale D32 -> Image RGB D32\ngrayToRGB = S . convertTo (fromIntegral . fromEnum $ CV_GRAY2BGR) 3 . unS\n\n\nbgrToRgb :: Image BGR D8 -> Image RGB D8\nbgrToRgb = S . swapRB . unS\n\nrgbToBgr :: Image RGB D8 -> Image BGR D8\nrgbToBgr = S . swapRB . unS\n\nswapRB :: BareImage -> BareImage\nswapRB img = unsafePerformIO $ do\n res <- cloneBareImage img\n withBareImage img $ \\cimg ->\n withBareImage res $ \\cres ->\n {#call cvConvertImage#} (castPtr cimg) (castPtr cres) (fromIntegral . fromEnum $ CvtSwapRB)\n return res\n\n\nclass GetPixel a where\n type P a :: *\n getPixel :: (Int,Int) -> a -> P a\n\n-- #define FGET(img,x,y) (((float *)((img)->imageData + (y)*(img)->widthStep))[(x)])\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Float))):: Ptr Float)\n\ninstance GetPixel (Image GrayScale D8) where\n type P (Image GrayScale D8) = D8\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Word8))):: Ptr Word8)\n\ninstance GetPixel (Image DFT D32) where\n type P (Image DFT D32) = Complex D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n re <- peek (castPtr (d`plusPtr` (y*cs + x*2*fs)))\n im <- peek (castPtr (d`plusPtr` (y*cs +(x*2+1)*fs)))\n return (re:+im)\n\n-- #define UGETC(img,color,x,y) (((uint8_t *)((img)->imageData + (y)*(img)->widthStep))[(x)*3+(color)])\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\ninstance GetPixel (Image BGR D32) where\n type P (Image BGR D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\ninstance GetPixel (Image BGR D8) where\n type P (Image BGR D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image RGB D8) where\n type P (Image RGB D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image LAB D32) where\n type P (Image LAB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n l <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n a <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n b <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (l,a,b)\n\n-- | Perform (a destructive) inplace map of the image. This should be wrapped inside\n-- withClone or an image operation\nmapImageInplace :: (P (Image GrayScale D32) -> P (Image GrayScale D32))\n -> Image GrayScale D32\n -> IO ()\nmapImageInplace f image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let (w,h) = getSize image\n cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n forM_ [(x,y) | x<-[0..w-1], y <- [0..h-1]] $ \\(x,y) ->\u00a0do\n v <- peek (castPtr (d `plusPtr` (y*cs+x*fs)))\n poke (castPtr (d `plusPtr` (y*cs+x*fs))) (f v)\n\n\n\n\nconvertTo :: CInt -> CInt -> BareImage -> BareImage\nconvertTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage32F#} w h channels\n withBareImage img $ \\cimg ->\n {#call cvCvtColor#} (castPtr cimg) (castPtr res) code\n return res\n where\n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\n-- |\u00a0Class for images that exist.\nclass CreateImage a where\n -- | Create an image from size\n create :: (Int,Int) -> IO a\n\n\ninstance CreateImage (Image GrayScale D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image DFT D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 2\ninstance CreateImage (Image LAB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 4\n\n\n\n-- | Allocate a new empty image\nempty :: (CreateImage (Image a b)) => (Int,Int) -> (Image a b)\nempty size = unsafePerformIO $ create size\n\n-- |\u00a0Allocate a new image that of the same size and type as the exemplar image given.\nemptyCopy :: (CreateImage (Image a b)) => Image a b -> (Image a b)\nemptyCopy img = unsafePerformIO $ create (getSize img)\n\n-- | Save image. This will convert the image to 8 bit one before saving\nclass Save a where\n save :: FilePath -> a -> IO () \n\ninstance Save (Image BGR D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image) \n\ninstance Save (Image RGB D32) where\n save filename image = primitiveSave filename (swapRB . unS . unsafeImageTo8Bit $ image)\n\ninstance Save (Image RGB D8) where\n save filename image = primitiveSave filename (swapRB . unS $ image)\n\ninstance Save (Image GrayScale D8) where\n save filename image = primitiveSave filename (unS $ image)\n\ninstance Save (Image GrayScale D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image) \n \nprimitiveSave :: FilePath -> BareImage -> IO ()\nprimitiveSave filename fpi = do \n withCString filename $ \\name ->\n withGenBareImage fpi $ \\cvArr ->\n alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\nsaveImage :: (Save (Image c d)) => FilePath -> Image c d -> IO ()\nsaveImage = save\n\ngetArea :: (Sized a,Num b, Size a ~ (b,b)) => a -> b\ngetArea = uncurry (*).getSize\n\ngetRegion :: (Int,Int) -> (Int,Int) -> Image c d -> Image c d\ngetRegion (fromIntegral -> x,fromIntegral -> y) (fromIntegral -> w,fromIntegral -> h) image\n | x+w <= width && y+h <= height = S . getRegion' (x,y) (w,h) $ unS image\n | otherwise = error $ \"Region outside image:\"\n ++ show (getSize image) ++\n \"\/\"++show (x+w,y+h)\n where\n (fromIntegral -> width,fromIntegral -> height) = getSize image\n\ngetRegion' (x,y) (w,h) image = unsafePerformIO $\n withBareImage image $ \\i ->\n creatingBareImage ({#call getSubImage#}\n i x y w h)\n\n\n-- | Tile images by overlapping them on a black canvas.\ntileImages image1 image2 (x,y) = unsafePerformIO $\n withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n creatingImage ({#call simpleMergeImages#}\n i1 i2 x y)\n-- | Blit image2 onto image1.\nblitFix = blit\nblit :: Image GrayScale D32 -> Image GrayScale D32 -> (Int,Int) -> IO ()\nblit image1 image2 (x,y)\n | badSizes = error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n | otherwise = withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call plainBlit#} i1 i2 (fromIntegral y) (fromIntegral x))\n where\n ((w1,h1),(w2,h2)) = (getSize image1,getSize image2)\n badSizes = x+w2>w1 || y+h2>h1 || x<0 || y<0\n\n-- blitM :: (CreateImage (Image c d)) => (Int,Int) -> [((Int,Int),Image c d)] -> Image c d\nblitM (rw,rh) imgs = resultPic\n where\n resultPic = unsafePerformIO $ do\n r <- create (fromIntegral rw,fromIntegral rh)\n sequence_ [blit r i (fromIntegral x, fromIntegral y)\n | ((x,y),i) <- imgs ]\n return r\n\n\nsubPixelBlit\n :: Image c d -> Image c d -> (CDouble, CDouble) -> IO ()\n\nsubPixelBlit (image1) (image2) (x,y)\n | badSizes = error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n | otherwise = withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call subpixel_blit#} i1 i2 y x)\n where\n ((w1,h1),(w2,h2)) = (getSize image1,getSize image2)\n badSizes = ceiling x+w2>w1 || ceiling y+h2>h1 ||\u00a0x<0 || y<0\n\nsafeBlit i1 i2 (x,y) = unsafePerformIO $ do\n res <- cloneImage i1-- createImage32F (getSize i1) 1\n blit res i2 (x,y)\n return res\n\n-- | Blit image2 onto image1.\n-- This uses an alpha channel bitmap for determining the regions where the image should be \"blended\" with\n-- the base image.\nblendBlit image1 image1Alpha image2 image2Alpha (x,y) =\n withImage image1 $ \\i1 ->\n withImage image1Alpha $ \\i1a ->\n withImage image2Alpha $ \\i2a ->\n withImage image2 $ \\i2 ->\n ({#call alphaBlit#} i1 i1a i2 i2a x y)\n\n\n-- | Create a copy of an image\ncloneImage :: Image a b -> IO (Image a b)\ncloneImage img = withGenImage img $ \\image ->\n creatingImage ({#call cvCloneImage #} image)\n\n-- | Create a copy of a non-types image\ncloneBareImage :: BareImage -> IO BareImage\ncloneBareImage img = withGenBareImage img $ \\image ->\n creatingBareImage ({#call cvCloneImage #} image)\n\nwithClone\n :: Image channels depth\n -> (Image channels depth -> IO ())\n -> IO (Image channels depth)\nwithClone img fun = do\n result <- cloneImage img\n fun result\n return result\n\nwithCloneValue\n :: Image channels depth\n -> (Image channels depth -> IO a)\n -> IO a\nwithCloneValue img fun = do\n result <- cloneImage img\n r <- fun result\n return r\n\nunsafeImageTo32F :: Image c d -> Image c D32\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure32F #} image)\n\nunsafeImageTo8Bit :: Image cspace a -> Image cspace D8\nunsafeImageTo8Bit img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure8U #} image)\n\n--toD32 :: Image c d -> Image c D32\n--toD32 i =\n-- unsafePerformIO $\n-- withImage i $ \\i_ptr ->\n-- creatingImage\n\n\nimageTo32F img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure32F #} image)\n\nimageTo8Bit img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure8U #} image)\n#c\nenum ImageDepth {\n Depth32F = IPL_DEPTH_32F,\n Depth64F = IPL_DEPTH_64F,\n Depth8U = IPL_DEPTH_8U,\n Depth8S = IPL_DEPTH_8S,\n Depth16U = IPL_DEPTH_16U,\n Depth16S = IPL_DEPTH_16S,\n Depth32S = IPL_DEPTH_32S\n };\n#endc\n\n{#enum ImageDepth {}#}\n\nderiving instance Show ImageDepth\n\ngetImageDepth :: Image c d -> IO ImageDepth\ngetImageDepth i = withImage i $ \\c_img -> {#get IplImage->depth #} c_img >>= return.toEnum.fromIntegral\ngetImageChannels i = withImage i $ \\c_img -> {#get IplImage->nChannels #} c_img\n\ngetImageInfo x = do\n let s = getSize x\n d <- getImageDepth x\n c <- getImageChannels x\n return (s,d,c)\n\n\n-- Manipulating regions of interest:\nsetROI (fromIntegral -> x,fromIntegral -> y)\n (fromIntegral -> w,fromIntegral -> h)\n image = withImage image $ \\i ->\n {#call wrapSetImageROI#} i x y w h\n\nresetROI image = withImage image $ \\i ->\n {#call cvResetImageROI#} i\n\nsetCOI chnl image = withImage image $ \\i ->\n {#call cvSetImageCOI#} i (fromIntegral chnl)\nresetCOI image = withImage image $ \\i ->\n {#call cvSetImageCOI#} i 0\n\n\n-- #TODO: Replace the Int below with proper channel identifier\ngetChannel :: (Enum a) => a -> Image (ChannelOf a) d -> Image GrayScale d\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n setCOI (1+fromEnum no) image\n cres <- {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\n withGenImage image $ \\cimage ->\n {#call cvCopy#} cimage (castPtr cres) (nullPtr)\n resetCOI image\n return cres\n\nwithIOROI pos size image op = do\n setROI pos size image\n x <- op\n resetROI image\n return x\n\nwithROI :: (Int, Int) -> (Int, Int) -> Image c d -> (Image c d -> a) -> a\nwithROI pos size image op = unsafePerformIO $ do\n setROI pos size image\n let x = op image -- BUG\n resetROI image\n return x\n\nclass SetPixel a where\n type SP a :: *\n setPixel :: (Int,Int) -> SP a -> a -> IO ()\n\ninstance SetPixel (Image GrayScale D32) where\n type SP (Image GrayScale D32) = D32\n {-#INLINE setPixel#-}\n setPixel (x,y) v image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Float))):: Ptr Float)\n v\n\ninstance SetPixel (Image GrayScale D8) where\n type SP (Image GrayScale D8) = D8\n {-#INLINE setPixel#-}\n setPixel (x,y) v image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Word8))):: Ptr Word8)\n v\n\ninstance SetPixel (Image RGB D32) where\n type SP (Image RGB D32) = (D32,D32,D32)\n {-#INLINE setPixel#-}\n setPixel (x,y) (r,g,b) image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs +x*3*fs))) b\n poke (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs))) g \n poke (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs))) r\n\ninstance SetPixel (Image DFT D32) where\n type SP (Image DFT D32) = Complex D32\n {-#INLINE setPixel#-}\n setPixel (x,y) (re:+im) image = withGenImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs + x*2*fs))) re\n poke (castPtr (d`plusPtr` (y*cs + (x*2+1)*fs))) im\n\n\n\ngetAllPixels image = [getPixel (i,j) image\n | i <- [0..width-1 ]\n , j <- [0..height-1]]\n where\n (width,height) = getSize image\n\ngetAllPixelsRowMajor image = [getPixel (i,j) image\n | j <- [0..height-1]\n , i <- [0..width-1]\n ]\n where\n (width,height) = getSize image\n\n-- |Create a montage form given images (u,v) determines the layout and space the spacing\n-- between images. Images are assumed to be the same size (determined by the first image)\nmontage :: (CreateImage (Image GrayScale D32)) => (Int,Int) -> Int -> [Image GrayScale D32] -> Image GrayScale D32\nmontage (u',v') space' imgs\n | u'*v' \/= (length imgs) = error (\"Montage mismatch: \"++show (u,v, length imgs))\n | otherwise = resultPic\n where\n space = fromIntegral space'\n (u,v) = (fromIntegral u', fromIntegral v')\n (rw,rh) = (u*xstep,v*ystep)\n (w,h) = getSize (head imgs)\n (xstep,ystep) = (fromIntegral space + w,fromIntegral space + h)\n edge = space`div`2\n resultPic = unsafePerformIO $ do\n r <- create (rw,rh)\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep)\n | y <- [0..v-1] , x <- [0..u-1]\n | i <- imgs ]\n return r\n\ndata CvException = CvException Int String String String Int\n deriving (Show, Typeable)\n\ninstance Exception CvException\n\nsetCatch = do\n let catch i cstr1 cstr2 cstr3 j = do\n func <- peekCString cstr1\n msg <- peekCString cstr2\n file <- peekCString cstr3\n throw (CvException (fromIntegral i) func msg file (fromIntegral j)) \n return 0\n cb <- mk'CvErrorCallback catch\n c'cvRedirectError cb nullPtr nullPtr\n c'cvSetErrMode c'CV_ErrModeSilent\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"655469d1a48b371d892dd0149077042be6e7069b","subject":"Use 'SourceStyleScheme sss => sss' replace SourceStyleScheme as function argument.","message":"Use 'SourceStyleScheme sss => sss' replace SourceStyleScheme as function argument.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceStyleScheme.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceStyleScheme.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceStyleScheme\n--\n-- Author : Peter Gavin\n-- derived from sourceview bindings by Axel Simon and Duncan Coutts\n--\n-- Created: 18 December 2008\n--\n-- Copyright (C) 2004-2008 Peter Gavin, Duncan Coutts, Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\nmodule Graphics.UI.Gtk.SourceView.SourceStyleScheme (\n-- * Description\n-- | 'SourceStyleScheme' contains all the text styles to be used in 'SourceView' and\n-- 'SourceBuffer'. For instance, it contains text styles for syntax highlighting, it may contain\n-- foreground and background color for non-highlighted text, color for the line numbers, etc.\n-- \n-- Style schemes are stored in XML files. The format of a scheme file is the documented in the style\n-- scheme reference.\n\n-- * Types\n SourceStyleScheme,\n SourceStyleSchemeClass,\n\n-- * Methods \n castToSourceStyleScheme,\n sourceStyleSchemeGetId,\n sourceStyleSchemeGetName,\n sourceStyleSchemeGetDescription,\n sourceStyleSchemeGetAuthors,\n sourceStyleSchemeGetFilename,\n sourceStyleSchemeGetStyle,\n\n-- * Attributes \n sourceStyleSchemeDescription,\n sourceStyleSchemeFilename,\n sourceStyleSchemeId,\n sourceStyleSchemeName,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(constructNewGObject)\nimport System.Glib.Attributes\n{#import System.Glib.Properties#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\nimport Graphics.UI.Gtk.SourceView.SourceStyle\n{#import Graphics.UI.Gtk.SourceView.SourceStyle.Internal#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | \n-- \nsourceStyleSchemeGetId :: SourceStyleSchemeClass sss => sss\n -> IO String -- ^ returns scheme id. \nsourceStyleSchemeGetId ss =\n {#call source_style_scheme_get_id#} (toSourceStyleScheme ss) >>= peekUTFString\n\n-- | \n-- \nsourceStyleSchemeGetName :: SourceStyleSchemeClass sss => sss \n -> IO String -- ^ returns scheme name. \nsourceStyleSchemeGetName ss =\n {#call source_style_scheme_get_name#} (toSourceStyleScheme ss) >>= peekUTFString\n\n-- | \n-- \nsourceStyleSchemeGetDescription :: SourceStyleSchemeClass sss => sss \n -> IO String -- ^ returns scheme description (if defined) or empty. \nsourceStyleSchemeGetDescription ss =\n {#call source_style_scheme_get_description#} (toSourceStyleScheme ss) >>= peekUTFString\n\n-- |\n--\nsourceStyleSchemeGetAuthors :: SourceStyleSchemeClass sss => sss \n -> IO [String] -- ^ returns an array containing the scheme authors or empty if no author is specified by the style scheme.\nsourceStyleSchemeGetAuthors ss =\n {#call source_style_scheme_get_authors#} (toSourceStyleScheme ss) >>= peekUTFStringArray0\n\n-- | \n-- \nsourceStyleSchemeGetFilename :: SourceStyleSchemeClass sss => sss \n -> IO String -- ^ returns scheme file name if the scheme was created parsing a style scheme file or empty in the other cases.\nsourceStyleSchemeGetFilename ss =\n {#call source_style_scheme_get_filename#} (toSourceStyleScheme ss) >>= peekUTFString\n\n-- | \n-- \nsourceStyleSchemeGetStyle :: SourceStyleSchemeClass sss => sss \n -> String -- ^ @styleId@ id of the style to retrieve.\n -> IO SourceStyle -- ^ returns style which corresponds to @styleId@ in the scheme\nsourceStyleSchemeGetStyle ss id = do\n styleObj <- makeNewGObject mkSourceStyleObject $\n withUTFString id ({#call source_style_scheme_get_style#} (toSourceStyleScheme ss))\n sourceStyleFromObject styleObj\n\n-- | Style scheme description.\n-- \n-- Default value: \\\"\\\"\n--\nsourceStyleSchemeDescription :: SourceStyleSchemeClass sss => ReadAttr sss String\nsourceStyleSchemeDescription = readAttrFromStringProperty \"description\"\n\n-- | Style scheme filename or 'Nothing'.\n-- \n-- Default value: \\\"\\\"\n--\nsourceStyleSchemeFilename :: SourceStyleSchemeClass sss => ReadAttr sss FilePath\nsourceStyleSchemeFilename = readAttrFromStringProperty \"filename\"\n\n-- | Style scheme id, a unique string used to identify the style scheme in 'SourceStyleSchemeManager'.\n-- \n-- Default value: \\\"\\\"\n--\nsourceStyleSchemeId :: SourceStyleSchemeClass sss => ReadAttr sss String\nsourceStyleSchemeId = readAttrFromStringProperty \"id\"\n\n-- | Style scheme name, a translatable string to present to user.\n-- \n-- Default value: \\\"\\\"\n--\nsourceStyleSchemeName :: SourceStyleSchemeClass sss => ReadAttr sss String\nsourceStyleSchemeName = readAttrFromStringProperty \"name\"\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceStyleScheme\n--\n-- Author : Peter Gavin\n-- derived from sourceview bindings by Axel Simon and Duncan Coutts\n--\n-- Created: 18 December 2008\n--\n-- Copyright (C) 2004-2008 Peter Gavin, Duncan Coutts, Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\nmodule Graphics.UI.Gtk.SourceView.SourceStyleScheme (\n-- * Description\n-- | 'SourceStyleScheme' contains all the text styles to be used in 'SourceView' and\n-- 'SourceBuffer'. For instance, it contains text styles for syntax highlighting, it may contain\n-- foreground and background color for non-highlighted text, color for the line numbers, etc.\n-- \n-- Style schemes are stored in XML files. The format of a scheme file is the documented in the style\n-- scheme reference.\n\n-- * Types\n SourceStyleScheme,\n\n-- * Methods \n castToSourceStyleScheme,\n sourceStyleSchemeGetId,\n sourceStyleSchemeGetName,\n sourceStyleSchemeGetDescription,\n sourceStyleSchemeGetAuthors,\n sourceStyleSchemeGetFilename,\n sourceStyleSchemeGetStyle,\n\n-- * Attributes \n sourceStyleSchemeDescription,\n sourceStyleSchemeFilename,\n sourceStyleSchemeId,\n sourceStyleSchemeName,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(constructNewGObject)\nimport System.Glib.Attributes\n{#import System.Glib.Properties#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\nimport Graphics.UI.Gtk.SourceView.SourceStyle\n{#import Graphics.UI.Gtk.SourceView.SourceStyle.Internal#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | \n-- \nsourceStyleSchemeGetId :: SourceStyleScheme\n -> IO String -- ^ returns scheme id. \nsourceStyleSchemeGetId ss =\n {#call source_style_scheme_get_id#} ss >>= peekUTFString\n\n-- | \n-- \nsourceStyleSchemeGetName :: SourceStyleScheme \n -> IO String -- ^ returns scheme name. \nsourceStyleSchemeGetName ss =\n {#call source_style_scheme_get_name#} ss >>= peekUTFString\n\n-- | \n-- \nsourceStyleSchemeGetDescription :: SourceStyleScheme \n -> IO String -- ^ returns scheme description (if defined) or empty. \nsourceStyleSchemeGetDescription ss =\n {#call source_style_scheme_get_description#} ss >>= peekUTFString\n\n-- |\n--\nsourceStyleSchemeGetAuthors :: SourceStyleScheme \n -> IO [String] -- ^ returns an array containing the scheme authors or empty if no author is specified by the style scheme.\nsourceStyleSchemeGetAuthors ss =\n {#call source_style_scheme_get_authors#} ss >>= peekUTFStringArray0\n\n-- | \n-- \nsourceStyleSchemeGetFilename :: SourceStyleScheme \n -> IO String -- ^ returns scheme file name if the scheme was created parsing a style scheme file or empty in the other cases.\nsourceStyleSchemeGetFilename ss =\n {#call source_style_scheme_get_filename#} ss >>= peekUTFString\n\n-- | \n-- \nsourceStyleSchemeGetStyle :: SourceStyleScheme \n -> String -- ^ @styleId@ id of the style to retrieve.\n -> IO SourceStyle -- ^ returns style which corresponds to @styleId@ in the scheme\nsourceStyleSchemeGetStyle ss id = do\n styleObj <- makeNewGObject mkSourceStyleObject $\n withUTFString id ({#call source_style_scheme_get_style#} ss)\n sourceStyleFromObject styleObj\n\n-- | Style scheme description.\n-- \n-- Default value: \\\"\\\"\n--\nsourceStyleSchemeDescription :: ReadAttr SourceStyleScheme String\nsourceStyleSchemeDescription = readAttrFromStringProperty \"description\"\n\n-- | Style scheme filename or 'Nothing'.\n-- \n-- Default value: \\\"\\\"\n--\nsourceStyleSchemeFilename :: ReadAttr SourceStyleScheme FilePath\nsourceStyleSchemeFilename = readAttrFromStringProperty \"filename\"\n\n-- | Style scheme id, a unique string used to identify the style scheme in 'SourceStyleSchemeManager'.\n-- \n-- Default value: \\\"\\\"\n--\nsourceStyleSchemeId :: ReadAttr SourceStyleScheme String\nsourceStyleSchemeId = readAttrFromStringProperty \"id\"\n\n-- | Style scheme name, a translatable string to present to user.\n-- \n-- Default value: \\\"\\\"\n--\nsourceStyleSchemeName :: ReadAttr SourceStyleScheme String\nsourceStyleSchemeName = readAttrFromStringProperty \"name\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"cffdc3c85789d7d7397f167986ee3d69d735bdc2","subject":"fix: store Tag in TAG field (was stored to SOURCE)","message":"fix: store Tag in TAG field (was stored to SOURCE)\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Control\/Parallel\/MPI\/Status.chs","new_file":"src\/Control\/Parallel\/MPI\/Status.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n\nmodule Control.Parallel.MPI.Status (Status (..), StatusPtr) where\n\nimport C2HS\nimport Control.Monad (liftM)\nimport Control.Applicative ((<$>), (<*>))\n\n{# context prefix = \"MPI\" #}\n\ndata Status = \n Status \n { status_source :: Int\n , status_tag :: Int\n , status_error :: Int\n , status_count :: Int\n , status_cancelled :: Int \n }\n deriving (Eq, Ord, Show)\n\n{#pointer *Status as StatusPtr -> Status #}\n\ninstance Storable Status where\n sizeOf _ = {#sizeof MPI_Status #}\n alignment _ = 4\n peek p = Status \n <$> liftM cIntConv ({#get MPI_Status->MPI_SOURCE #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_TAG #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_ERROR #} p)\n <*> liftM cIntConv ({#get MPI_Status->_count #} p)\n <*> liftM cIntConv ({#get MPI_Status->_cancelled #} p)\n poke p x = do\n {#set MPI_Status.MPI_SOURCE #} p (cIntConv $ status_source x)\n {#set MPI_Status.MPI_TAG #} p (cIntConv $ status_tag x)\n {#set MPI_Status.MPI_ERROR #} p (cIntConv $ status_error x)\n {#set MPI_Status._count #} p (cIntConv $ status_count x)\n {#set MPI_Status._cancelled #} p (cIntConv $ status_cancelled x)\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \n\nmodule Control.Parallel.MPI.Status (Status (..), StatusPtr) where\n\nimport C2HS\nimport Control.Monad (liftM)\nimport Control.Applicative ((<$>), (<*>))\n\n{# context prefix = \"MPI\" #}\n\ndata Status = \n Status \n { status_source :: Int\n , status_tag :: Int\n , status_error :: Int\n , status_count :: Int\n , status_cancelled :: Int \n }\n deriving (Eq, Ord, Show)\n\n{#pointer *Status as StatusPtr -> Status #}\n\ninstance Storable Status where\n sizeOf _ = {#sizeof MPI_Status #}\n alignment _ = 4\n peek p = Status \n <$> liftM cIntConv ({#get MPI_Status->MPI_SOURCE #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_TAG #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_ERROR #} p)\n <*> liftM cIntConv ({#get MPI_Status->_count #} p)\n <*> liftM cIntConv ({#get MPI_Status->_cancelled #} p)\n poke p x = do\n {#set MPI_Status.MPI_SOURCE #} p (cIntConv $ status_source x)\n {#set MPI_Status.MPI_SOURCE #} p (cIntConv $ status_tag x)\n {#set MPI_Status.MPI_ERROR #} p (cIntConv $ status_error x)\n {#set MPI_Status._count #} p (cIntConv $ status_count x)\n {#set MPI_Status._cancelled #} p (cIntConv $ status_cancelled x)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"b04c539face1a12901d95f0a4b92674eb86a2f0f","subject":"Use SourceLanguageManagerClass replace SourceLanguageManager as function argument.","message":"Use SourceLanguageManagerClass replace SourceLanguageManager as function argument.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceLanguageManager.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceLanguageManager.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceView\n--\n-- Author : Peter Gavin, Andy Stewart\n-- derived from sourceview bindings by Axel Simon and Duncan Coutts\n--\n-- Created: 18 December 2008\n--\n-- Copyright (C) 2004-2008 Peter Gavin, Duncan Coutts, Axel Simon\n-- Copyright (C) 2010 Andy Stewart\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\nmodule Graphics.UI.Gtk.SourceView.SourceLanguageManager (\n-- * Description\n-- | 'SourceLanguageManager' is an object which processes language description files and creates and\n-- stores 'SourceLanguage' objects, and provides API to access them. Use\n-- 'sourceLanguageManagerGetDefault' to retrieve the default instance of\n-- 'SourceLanguageManager', and 'sourceLanguageManagerGuessLanguage' to get a\n-- 'SourceLanguage' for given file name and content type.\n\n-- * Types\n SourceLanguageManager,\n SourceLanguageManagerClass,\n\n-- * Methods\n castToSourceLanguageManager,\n sourceLanguageManagerNew,\n sourceLanguageManagerGetDefault,\n sourceLanguageManagerSetSearchPath,\n sourceLanguageManagerGetSearchPath,\n sourceLanguageManagerGetLanguageIds,\n sourceLanguageManagerGetLanguage,\n sourceLanguageManagerGuessLanguage,\n\n-- * Attributes\n sourceLanguageManagerLanguageIds,\n sourceLanguageManagerSearchPath,\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GObject (constructNewGObject, makeNewGObject)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n{# enum SourceSmartHomeEndType {underscoreToCase} deriving (Eq, Bounded, Show, Read) #}\n\n-- | Creates a new language manager. If you do not need more than one language manager or a private\n-- language manager instance then use 'sourceLanguageManagerGetDefault' instead.\n--\nsourceLanguageManagerNew :: IO SourceLanguageManager\nsourceLanguageManagerNew = constructNewGObject mkSourceLanguageManager $ liftM castPtr\n {#call unsafe source_language_manager_new#}\n\n-- | Returns the default 'SourceLanguageManager' instance.\n--\nsourceLanguageManagerGetDefault :: IO SourceLanguageManager\nsourceLanguageManagerGetDefault = makeNewGObject mkSourceLanguageManager $ liftM castPtr\n {#call unsafe source_language_manager_new#}\n\n-- | Sets the list of directories where the lm looks for language files. If dirs is 'Nothing', the search path\n-- is reset to default.\n-- \n-- Note\n-- \n-- At the moment this function can be called only before the language files are loaded for the first\n-- time. In practice to set a custom search path for a 'SourceLanguageManager', you have to call this\n-- function right after creating it.\n--\nsourceLanguageManagerSetSearchPath :: SourceLanguageManagerClass slm => slm -> Maybe [String] -> IO ()\nsourceLanguageManagerSetSearchPath slm dirs =\n maybeWith withUTFStringArray0 dirs $ \\dirsPtr -> do\n {#call unsafe source_language_manager_set_search_path#} (toSourceLanguageManager slm) dirsPtr\n\n-- | Gets the list directories where lm looks for language files.\n--\nsourceLanguageManagerGetSearchPath :: SourceLanguageManagerClass slm => slm -> IO [String]\nsourceLanguageManagerGetSearchPath slm = do\n dirsPtr <- {#call unsafe source_language_manager_get_search_path#} (toSourceLanguageManager slm)\n liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 dirsPtr\n\n-- | Returns the ids of the available languages.\n--\nsourceLanguageManagerGetLanguageIds :: SourceLanguageManagerClass slm => slm -> IO [String]\nsourceLanguageManagerGetLanguageIds slm = do\n idsPtr <- {#call unsafe source_language_manager_get_language_ids#} (toSourceLanguageManager slm)\n liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 idsPtr\n\n-- | Gets the 'SourceLanguage' identified by the given id in the language manager.\n--\nsourceLanguageManagerGetLanguage :: SourceLanguageManagerClass slm => slm \n -> String -- ^ @id@ a language id.\n -> IO (Maybe SourceLanguage) -- ^ returns a 'SourceLanguage', or 'Nothing' if there is no language identified by the given id. \nsourceLanguageManagerGetLanguage slm id = do\n slPtr <- liftM castPtr $\n withUTFString id ({#call unsafe source_language_manager_get_language#} (toSourceLanguageManager slm))\n if slPtr \/= nullPtr\n then liftM Just $ makeNewGObject mkSourceLanguage $ return slPtr\n else return Nothing\n\n-- | Picks a 'SourceLanguage' for given file name and content type, according to the information in lang\n-- files. Either filename or @contentType@ may be 'Nothing'.\n--\nsourceLanguageManagerGuessLanguage :: SourceLanguageManagerClass slm => slm \n -> Maybe String -- ^ @filename@ a filename in Glib filename encoding, or 'Nothing'.\n -> Maybe String -- ^ @contentType@ a content type (as in GIO API), or 'Nothing'.\n -> IO (Maybe SourceLanguage) -- ^ returns a 'SourceLanguage', or 'Nothing' if there is no suitable language for given filename and\/or @contentType@. \nsourceLanguageManagerGuessLanguage slm filename contentType =\n maybeWith withUTFString filename $ \\cFilename ->\n maybeWith withUTFString contentType $ \\cContentType -> do\n slPtr <- liftM castPtr $\n {#call unsafe source_language_manager_guess_language#} (toSourceLanguageManager slm) cFilename cContentType\n if slPtr \/= nullPtr\n then liftM Just $ makeNewGObject mkSourceLanguage $ return slPtr\n else return Nothing\n\n-- | List of the ids of the available languages.\n--\nsourceLanguageManagerLanguageIds :: SourceLanguageManagerClass slm => ReadAttr slm [String]\nsourceLanguageManagerLanguageIds =\n readAttrFromBoxedOpaqueProperty (liftM (fromMaybe []) . maybePeek peekUTFStringArray0 . castPtr)\n \"language-ids\" {#call pure g_strv_get_type#}\n\n-- | List of directories where the language specification files (.lang) are located.\n--\nsourceLanguageManagerSearchPath :: SourceLanguageManagerClass slm => ReadWriteAttr slm [String] (Maybe [String])\nsourceLanguageManagerSearchPath =\n newAttr (objectGetPropertyBoxedOpaque (peekUTFStringArray0 . castPtr) gtype \"search-path\")\n (objectSetPropertyBoxedOpaque (\\dirs f -> maybeWith withUTFStringArray0 dirs (f . castPtr)) gtype \"search-path\")\n where gtype = {#call pure g_strv_get_type#}\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SourceView\n--\n-- Author : Peter Gavin, Andy Stewart\n-- derived from sourceview bindings by Axel Simon and Duncan Coutts\n--\n-- Created: 18 December 2008\n--\n-- Copyright (C) 2004-2008 Peter Gavin, Duncan Coutts, Axel Simon\n-- Copyright (C) 2010 Andy Stewart\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\nmodule Graphics.UI.Gtk.SourceView.SourceLanguageManager (\n-- * Description\n-- | 'SourceLanguageManager' is an object which processes language description files and creates and\n-- stores 'SourceLanguage' objects, and provides API to access them. Use\n-- 'sourceLanguageManagerGetDefault' to retrieve the default instance of\n-- 'SourceLanguageManager', and 'sourceLanguageManagerGuessLanguage' to get a\n-- 'SourceLanguage' for given file name and content type.\n\n-- * Types\n SourceLanguageManager,\n SourceLanguageManagerClass,\n\n-- * Methods\n castToSourceLanguageManager,\n sourceLanguageManagerNew,\n sourceLanguageManagerGetDefault,\n sourceLanguageManagerSetSearchPath,\n sourceLanguageManagerGetSearchPath,\n sourceLanguageManagerGetLanguageIds,\n sourceLanguageManagerGetLanguage,\n sourceLanguageManagerGuessLanguage,\n\n-- * Attributes\n sourceLanguageManagerLanguageIds,\n sourceLanguageManagerSearchPath,\n ) where\n\nimport Control.Monad\t(liftM)\nimport Data.Maybe (fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.GObject (constructNewGObject, makeNewGObject)\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\n{#import Graphics.UI.Gtk.SourceView.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n{# enum SourceSmartHomeEndType {underscoreToCase} deriving (Eq, Bounded, Show, Read) #}\n\n-- | Creates a new language manager. If you do not need more than one language manager or a private\n-- language manager instance then use 'sourceLanguageManagerGetDefault' instead.\n--\nsourceLanguageManagerNew :: IO SourceLanguageManager\nsourceLanguageManagerNew = constructNewGObject mkSourceLanguageManager $ liftM castPtr\n {#call unsafe source_language_manager_new#}\n\n-- | Returns the default 'SourceLanguageManager' instance.\n--\nsourceLanguageManagerGetDefault :: IO SourceLanguageManager\nsourceLanguageManagerGetDefault = makeNewGObject mkSourceLanguageManager $ liftM castPtr\n {#call unsafe source_language_manager_new#}\n\n-- | Sets the list of directories where the lm looks for language files. If dirs is 'Nothing', the search path\n-- is reset to default.\n-- \n-- Note\n-- \n-- At the moment this function can be called only before the language files are loaded for the first\n-- time. In practice to set a custom search path for a 'SourceLanguageManager', you have to call this\n-- function right after creating it.\n--\nsourceLanguageManagerSetSearchPath :: SourceLanguageManager -> Maybe [String] -> IO ()\nsourceLanguageManagerSetSearchPath slm dirs =\n maybeWith withUTFStringArray0 dirs $ \\dirsPtr -> do\n {#call unsafe source_language_manager_set_search_path#} slm dirsPtr\n\n-- | Gets the list directories where lm looks for language files.\n--\nsourceLanguageManagerGetSearchPath :: SourceLanguageManager -> IO [String]\nsourceLanguageManagerGetSearchPath slm = do\n dirsPtr <- {#call unsafe source_language_manager_get_search_path#} slm\n liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 dirsPtr\n\n-- | Returns the ids of the available languages.\n--\nsourceLanguageManagerGetLanguageIds :: SourceLanguageManager -> IO [String]\nsourceLanguageManagerGetLanguageIds slm = do\n idsPtr <- {#call unsafe source_language_manager_get_language_ids#} slm\n liftM (fromMaybe []) $ maybePeek peekUTFStringArray0 idsPtr\n\n-- | Gets the 'SourceLanguage' identified by the given id in the language manager.\n--\nsourceLanguageManagerGetLanguage :: SourceLanguageManager \n -> String -- ^ @id@ a language id.\n -> IO (Maybe SourceLanguage) -- ^ returns a 'SourceLanguage', or 'Nothing' if there is no language identified by the given id. \nsourceLanguageManagerGetLanguage slm id = do\n slPtr <- liftM castPtr $\n withUTFString id ({#call unsafe source_language_manager_get_language#} slm)\n if slPtr \/= nullPtr\n then liftM Just $ makeNewGObject mkSourceLanguage $ return slPtr\n else return Nothing\n\n-- | Picks a 'SourceLanguage' for given file name and content type, according to the information in lang\n-- files. Either filename or @contentType@ may be 'Nothing'.\n--\nsourceLanguageManagerGuessLanguage :: SourceLanguageManager \n -> Maybe String -- ^ @filename@ a filename in Glib filename encoding, or 'Nothing'.\n -> Maybe String -- ^ @contentType@ a content type (as in GIO API), or 'Nothing'.\n -> IO (Maybe SourceLanguage) -- ^ returns a 'SourceLanguage', or 'Nothing' if there is no suitable language for given filename and\/or @contentType@. \nsourceLanguageManagerGuessLanguage slm filename contentType =\n maybeWith withUTFString filename $ \\cFilename ->\n maybeWith withUTFString contentType $ \\cContentType -> do\n slPtr <- liftM castPtr $\n {#call unsafe source_language_manager_guess_language#} slm cFilename cContentType\n if slPtr \/= nullPtr\n then liftM Just $ makeNewGObject mkSourceLanguage $ return slPtr\n else return Nothing\n\n-- | List of the ids of the available languages.\n--\nsourceLanguageManagerLanguageIds :: ReadAttr SourceLanguageManager [String]\nsourceLanguageManagerLanguageIds =\n readAttrFromBoxedOpaqueProperty (liftM (fromMaybe []) . maybePeek peekUTFStringArray0 . castPtr)\n \"language-ids\" {#call pure g_strv_get_type#}\n\n-- | List of directories where the language specification files (.lang) are located.\n--\nsourceLanguageManagerSearchPath :: ReadWriteAttr SourceLanguageManager [String] (Maybe [String])\nsourceLanguageManagerSearchPath =\n newAttr (objectGetPropertyBoxedOpaque (peekUTFStringArray0 . castPtr) gtype \"search-path\")\n (objectSetPropertyBoxedOpaque (\\dirs f -> maybeWith withUTFStringArray0 dirs (f . castPtr)) gtype \"search-path\")\n where gtype = {#call pure g_strv_get_type#}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"8da868b87123f54b8750ce83e7a27c7a78c2ffc8","subject":"Fix crash bug of treeViewColumnGetWidget.","message":"Fix crash bug of treeViewColumnGetWidget.\n\nWhen you first call treeViewColumnGetWidget will got error \"main: user error (makeNewObject: object is NULL)\"\nDetails see : http:\/\/library.gnome.org\/devel\/gtk\/stable\/GtkTreeViewColumn.html#gtk-tree-view-column-get-widget\n\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk\/ModelView\/TreeViewColumn.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/ModelView\/TreeViewColumn.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) TreeViewColumn TreeView\n--\n-- Author : Axel Simon\n--\n-- Created: 9 May 2001\n--\n-- Copyright (C) 2001-2005 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- A visible column in a 'TreeView' widget\n--\nmodule Graphics.UI.Gtk.ModelView.TreeViewColumn (\n-- * Detail\n-- \n-- | The 'TreeViewColumn' object represents a visible column in a 'TreeView'\n-- widget. It allows to set properties of the column header, and functions as a\n-- holding pen for the cell renderers which determine how the data in the\n-- column is displayed.\n--\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----TreeViewColumn\n-- @\n\n-- * Types\n TreeViewColumn,\n TreeViewColumnClass,\n castToTreeViewColumn, gTypeTreeViewColumn,\n toTreeViewColumn,\n\n-- * Constructors\n treeViewColumnNew,\n\n-- * Methods\n treeViewColumnPackStart,\n treeViewColumnPackEnd,\n treeViewColumnClear,\n treeViewColumnGetCellRenderers,\n treeViewColumnSetSpacing,\n treeViewColumnGetSpacing,\n treeViewColumnSetVisible,\n treeViewColumnGetVisible,\n treeViewColumnSetResizable,\n treeViewColumnGetResizable,\n TreeViewColumnSizing(..),\n treeViewColumnSetSizing,\n treeViewColumnGetSizing,\n treeViewColumnGetWidth,\n treeViewColumnSetFixedWidth,\n treeViewColumnGetFixedWidth,\n treeViewColumnSetMinWidth,\n treeViewColumnGetMinWidth,\n treeViewColumnSetMaxWidth,\n treeViewColumnGetMaxWidth,\n treeViewColumnClicked,\n treeViewColumnSetTitle,\n treeViewColumnGetTitle,\n treeViewColumnSetClickable,\n treeViewColumnGetClickable,\n treeViewColumnSetWidget,\n treeViewColumnGetWidget,\n treeViewColumnSetAlignment,\n treeViewColumnGetAlignment,\n treeViewColumnSetReorderable,\n treeViewColumnGetReorderable,\n treeViewColumnSetSortColumnId,\n treeViewColumnGetSortColumnId,\n treeViewColumnSetSortIndicator,\n treeViewColumnGetSortIndicator,\n treeViewColumnSetSortOrder,\n treeViewColumnGetSortOrder,\n SortType(..),\n#if GTK_CHECK_VERSION(2,4,0)\n treeViewColumnSetExpand,\n treeViewColumnGetExpand,\n#endif\n treeViewColumnCellIsVisible,\n#if GTK_CHECK_VERSION(2,2,0)\n treeViewColumnFocusCell,\n#if GTK_CHECK_VERSION(2,8,0)\n treeViewColumnQueueResize,\n#endif\n#endif\n\n-- * Attributes\n treeViewColumnVisible,\n treeViewColumnResizable,\n treeViewColumnWidth,\n treeViewColumnSpacing,\n treeViewColumnSizing,\n treeViewColumnFixedWidth,\n treeViewColumnMinWidth,\n treeViewColumnMaxWidth,\n treeViewColumnTitle,\n treeViewColumnExpand,\n treeViewColumnClickable,\n treeViewColumnWidget,\n treeViewColumnAlignment,\n treeViewColumnReorderable,\n treeViewColumnSortIndicator,\n treeViewColumnSortOrder,\n treeViewColumnSortColumnId,\n\n-- * Signals\n onColClicked,\n afterColClicked\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import System.Glib.GList#}\t\t\t(fromGList)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Abstract.Object\t\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.General.Enums\t\t(TreeViewColumnSizing(..),\n\t\t\t\t\t\t SortType(..))\nimport Graphics.UI.Gtk.General.Structs (SortColumnId)\n{#import Graphics.UI.Gtk.ModelView.TreeModel#}\t()\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Generate a new TreeViewColumn widget.\n--\ntreeViewColumnNew :: IO TreeViewColumn\ntreeViewColumnNew = makeNewObject mkTreeViewColumn \n {# call tree_view_column_new #}\n\n\n--------------------\n-- Methods\n\n-- | Add a cell renderer at the beginning of a column.\n--\n-- * Excess space is divided equally among all renderers which have\n-- @expand@ set to True.\n--\ntreeViewColumnPackStart :: CellRendererClass cell => TreeViewColumn\n -> cell\n -> Bool\n -> IO ()\ntreeViewColumnPackStart self cell expand =\n {# call unsafe tree_view_column_pack_start #}\n self\n (toCellRenderer cell)\n (fromBool expand)\n\n-- | Add a cell renderer at the end of a column.\n--\n-- * Excess space is divided equally among all renderers which have\n-- @expand@ set to True.\n--\ntreeViewColumnPackEnd :: CellRendererClass cell => TreeViewColumn\n -> cell\n -> Bool\n -> IO ()\ntreeViewColumnPackEnd self cell expand =\n {# call unsafe tree_view_column_pack_end #}\n self\n (toCellRenderer cell)\n (fromBool expand)\n\n-- | Remove the associations of attributes to a store for all 'CellRenderer's.\n--\ntreeViewColumnClear :: TreeViewColumn -> IO ()\ntreeViewColumnClear self =\n {# call tree_view_column_clear #}\n self\n\n-- | Retrieve all 'CellRenderer's that are contained in this column.\n--\ntreeViewColumnGetCellRenderers :: TreeViewColumn -> IO [CellRenderer]\ntreeViewColumnGetCellRenderers self =\n {# call unsafe tree_view_column_get_cell_renderers #}\n self\n >>= fromGList\n >>= mapM (makeNewObject mkCellRenderer . return)\n\n-- | Set the number of pixels between two cell renderers.\n--\ntreeViewColumnSetSpacing :: TreeViewColumn -> Int -> IO ()\ntreeViewColumnSetSpacing self spacing =\n {# call tree_view_column_set_spacing #}\n self\n (fromIntegral spacing)\n\n\n-- | Get the number of pixels between two cell renderers.\n--\ntreeViewColumnGetSpacing :: TreeViewColumn -> IO Int\ntreeViewColumnGetSpacing self =\n liftM fromIntegral $\n {# call unsafe tree_view_column_get_spacing #}\n self\n\n-- | Set the visibility of a given column.\n--\ntreeViewColumnSetVisible :: TreeViewColumn -> Bool -> IO ()\ntreeViewColumnSetVisible self visible =\n {# call tree_view_column_set_visible #}\n self\n (fromBool visible)\n\n-- | Get the visibility of a given column.\n--\ntreeViewColumnGetVisible :: TreeViewColumn -> IO Bool\ntreeViewColumnGetVisible self =\n liftM toBool $\n {# call unsafe tree_view_column_get_visible #}\n self\n\n-- | Set if a given column is resizable by the user.\n--\ntreeViewColumnSetResizable :: TreeViewColumn -> Bool -> IO ()\ntreeViewColumnSetResizable self resizable =\n {# call tree_view_column_set_resizable #}\n self\n (fromBool resizable)\n\n-- | Get if a given column is resizable by the user.\n--\ntreeViewColumnGetResizable :: TreeViewColumn -> IO Bool\ntreeViewColumnGetResizable self =\n liftM toBool $\n {# call unsafe tree_view_column_get_resizable #}\n self\n\n-- | Set wether the column can be resized.\n--\ntreeViewColumnSetSizing :: TreeViewColumn\n -> TreeViewColumnSizing\n -> IO ()\ntreeViewColumnSetSizing self type_ =\n {# call tree_view_column_set_sizing #}\n self\n ((fromIntegral . fromEnum) type_)\n\n-- | Return the resizing type of the column.\n--\ntreeViewColumnGetSizing :: TreeViewColumn\n -> IO TreeViewColumnSizing\ntreeViewColumnGetSizing self =\n liftM (toEnum . fromIntegral) $\n {# call unsafe tree_view_column_get_sizing #}\n self\n\n-- | Query the current width of the column.\n--\ntreeViewColumnGetWidth :: TreeViewColumn -> IO Int\ntreeViewColumnGetWidth self =\n liftM fromIntegral $\n {# call unsafe tree_view_column_get_width #}\n self\n\n-- | Set the width of the column.\n--\n-- * This is meaningful only if the sizing type is 'TreeViewColumnFixed'.\n--\ntreeViewColumnSetFixedWidth :: TreeViewColumn -> Int -> IO ()\ntreeViewColumnSetFixedWidth self fixedWidth =\n {# call tree_view_column_set_fixed_width #}\n self\n (fromIntegral fixedWidth)\n\n-- | Gets the fixed width of the column.\n--\n-- * This is meaningful only if the sizing type is 'TreeViewColumnFixed'.\n--\n-- * This value is only meaning may not be the actual width of the column on the\n-- screen, just what is requested.\n--\ntreeViewColumnGetFixedWidth :: TreeViewColumn -> IO Int\ntreeViewColumnGetFixedWidth self =\n liftM fromIntegral $\n {# call unsafe tree_view_column_get_fixed_width #}\n self\n\n-- | Set minimum width of the column.\n--\ntreeViewColumnSetMinWidth :: TreeViewColumn -> Int -> IO ()\ntreeViewColumnSetMinWidth self minWidth =\n {# call tree_view_column_set_min_width #}\n self\n (fromIntegral minWidth)\n\n-- | Get the minimum width of a column. Returns -1 if this width was not set.\n--\ntreeViewColumnGetMinWidth :: TreeViewColumn -> IO Int\ntreeViewColumnGetMinWidth self =\n liftM fromIntegral $\n {# call unsafe tree_view_column_get_min_width #}\n self\n\n-- | Set maximum width of the column.\n--\ntreeViewColumnSetMaxWidth :: TreeViewColumn -> Int -> IO ()\ntreeViewColumnSetMaxWidth self maxWidth =\n {# call tree_view_column_set_max_width #}\n self\n (fromIntegral maxWidth)\n\n-- | Get the maximum width of a column. Returns -1 if this width was not set.\n--\ntreeViewColumnGetMaxWidth :: TreeViewColumn -> IO Int\ntreeViewColumnGetMaxWidth self =\n liftM fromIntegral $\n {# call unsafe tree_view_column_get_max_width #}\n self\n\n-- | Emit the @clicked@ signal on the column.\n--\ntreeViewColumnClicked :: TreeViewColumn -> IO ()\ntreeViewColumnClicked self =\n {# call tree_view_column_clicked #}\n self\n\n-- | Set the widget's title if a custom widget has not been set.\n--\ntreeViewColumnSetTitle :: TreeViewColumn -> String -> IO ()\ntreeViewColumnSetTitle self title =\n withUTFString title $ \\titlePtr ->\n {# call tree_view_column_set_title #}\n self\n titlePtr\n\n-- | Get the widget's title.\n--\ntreeViewColumnGetTitle :: TreeViewColumn -> IO (Maybe String)\ntreeViewColumnGetTitle self =\n {# call unsafe tree_view_column_get_title #}\n self\n >>= maybePeek peekUTFString\n\n-- | Set if the column should be sensitive to mouse clicks.\n--\ntreeViewColumnSetClickable :: TreeViewColumn -> Bool -> IO ()\ntreeViewColumnSetClickable self clickable =\n {# call tree_view_column_set_clickable #}\n self\n (fromBool clickable)\n\n-- | Returns True if the user can click on the header for the column.\n--\ntreeViewColumnGetClickable :: TreeViewColumn -> IO Bool\ntreeViewColumnGetClickable self =\n liftM toBool $\n {# call tree_view_column_get_clickable #}\n self\n\n-- | Set the column's title to this widget.\n--\ntreeViewColumnSetWidget :: WidgetClass widget => TreeViewColumn\n -> Maybe widget\n -> IO ()\ntreeViewColumnSetWidget self widget =\n {# call tree_view_column_set_widget #}\n self\n (maybe (Widget nullForeignPtr) toWidget widget)\n\n-- | Retrieve the widget responsible for\n-- showing the column title. In case only a text title was set this will be a\n-- 'Alignment' widget with a 'Label' inside.\n--\ntreeViewColumnGetWidget :: TreeViewColumn \n -> IO (Maybe Widget) -- ^ returns the 'Widget' in the column header, or 'Nothing'\ntreeViewColumnGetWidget self = do\n widgetPtr <- {# call unsafe tree_view_column_get_widget #} self\n if widgetPtr == nullPtr\n then return Nothing\n else liftM Just $ makeNewObject mkWidget (return widgetPtr)\n\n-- | Sets the alignment of the title or custom widget inside the column\n-- header. The alignment determines its location inside the button -- 0.0 for\n-- left, 0.5 for center, 1.0 for right.\n--\ntreeViewColumnSetAlignment :: TreeViewColumn\n -> Float -- ^ @xalign@ - The alignment, which is between [0.0 and\n -- 1.0] inclusive.\n -> IO ()\ntreeViewColumnSetAlignment self xalign =\n {# call tree_view_column_set_alignment #}\n self\n (realToFrac xalign)\n\n-- | Returns the current x alignment of the tree column. This value can range\n-- between 0.0 and 1.0.\n--\ntreeViewColumnGetAlignment :: TreeViewColumn -> IO Float\ntreeViewColumnGetAlignment self =\n liftM realToFrac $\n {# call unsafe tree_view_column_get_alignment #}\n self\n\n-- | Set if the column can be reordered by the end user dragging the header.\n--\ntreeViewColumnSetReorderable :: TreeViewColumn -> Bool -> IO ()\ntreeViewColumnSetReorderable self reorderable =\n {# call tree_view_column_set_reorderable #}\n self\n (fromBool reorderable)\n\n-- | Returns whether the column can be reordered by the user.\n--\ntreeViewColumnGetReorderable :: TreeViewColumn -> IO Bool\ntreeViewColumnGetReorderable self =\n liftM toBool $\n {# call unsafe tree_view_column_get_reorderable #}\n self\n\n-- | Set the column by which to sort.\n--\n-- * Sets the logical @columnId@ that this column sorts on when\n-- this column is selected for sorting. The selected column's header\n-- will be clickable after this call. Logical refers to the \n-- 'Graphics.UI.Gtk.ModelView.TreeSortable.SortColumnId' for which\n-- a comparison function was set.\n--\ntreeViewColumnSetSortColumnId :: TreeViewColumn -> SortColumnId -> IO ()\ntreeViewColumnSetSortColumnId self sortColumnId =\n {# call tree_view_column_set_sort_column_id #}\n self\n (fromIntegral sortColumnId)\n\n-- | Get the column by which to sort.\n--\n-- * Retrieves the logical @columnId@ that the model sorts on when this column\n-- is selected for sorting.\n--\n-- * Returns\n-- 'Graphics.UI.Gtk.ModelView.TreeSortable.treeSortableDefaultSortColumnId'\n-- if this tree view column has no\n-- 'Graphics.UI.Gtk.ModelView.TreeSortable.SortColumnId' associated with it.\n--\ntreeViewColumnGetSortColumnId :: TreeViewColumn -> IO SortColumnId\ntreeViewColumnGetSortColumnId self =\n liftM fromIntegral $\n {# call unsafe tree_view_column_get_sort_column_id #}\n self\n\n-- | Set if a given column has sorting arrows in its heading.\n--\ntreeViewColumnSetSortIndicator :: TreeViewColumn\n -> Bool -> IO ()\ntreeViewColumnSetSortIndicator self setting =\n {# call tree_view_column_set_sort_indicator #}\n self\n (fromBool setting)\n\n-- | Query if a given column has sorting arrows in its heading.\n--\ntreeViewColumnGetSortIndicator :: TreeViewColumn -> IO Bool\ntreeViewColumnGetSortIndicator self =\n liftM toBool $\n {# call unsafe tree_view_column_get_sort_indicator #}\n self\n\n-- | Set if a given column is sorted in ascending or descending order.\n--\n-- * In order for sorting to work, it is necessary to either use automatic\n-- sorting via 'treeViewColumnSetSortColumnId' or to use a\n-- user defined sorting on the elements in a 'TreeModel'.\n--\ntreeViewColumnSetSortOrder :: TreeViewColumn\n -> SortType -> IO ()\ntreeViewColumnSetSortOrder self order =\n {# call tree_view_column_set_sort_order #}\n self\n ((fromIntegral . fromEnum) order)\n\n-- | Query if a given column is sorted in ascending or descending order.\n--\ntreeViewColumnGetSortOrder :: TreeViewColumn -> IO SortType\ntreeViewColumnGetSortOrder self =\n liftM (toEnum . fromIntegral) $\n {# call unsafe tree_view_column_get_sort_order #}\n self\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:7808 d:942b\n-- | Sets the column to take available extra space. This space is shared\n-- equally amongst all columns that have the expand set to @True@. If no column\n-- has this option set, then the last column gets all extra space. By default,\n-- every column is created with this @False@.\n--\n-- * Available since Gtk+ version 2.4\n--\ntreeViewColumnSetExpand :: TreeViewColumn\n -> Bool -- ^ @expand@ - @True@ if the column should take available extra\n -- space, @False@ if not\n -> IO ()\ntreeViewColumnSetExpand self expand =\n {# call gtk_tree_view_column_set_expand #}\n self\n (fromBool expand)\n\n-- %hash c:ee41 d:f16b\n-- | Return @True@ if the column expands to take any available space.\n--\n-- * Available since Gtk+ version 2.4\n--\ntreeViewColumnGetExpand :: TreeViewColumn\n -> IO Bool -- ^ returns @True@, if the column expands\ntreeViewColumnGetExpand self =\n liftM toBool $\n {# call gtk_tree_view_column_get_expand #}\n self\n#endif\n\n-- %hash c:77e0 d:e1c7\n-- | Returns @True@ if any of the cells packed into the @treeColumn@ are\n-- visible. For this to be meaningful, you must first initialize the cells with\n-- 'treeViewColumnCellSetCellData'\n--\ntreeViewColumnCellIsVisible :: TreeViewColumn\n -> IO Bool -- ^ returns @True@, if any of the cells packed into the\n -- @treeColumn@ are currently visible\ntreeViewColumnCellIsVisible self =\n liftM toBool $\n {# call gtk_tree_view_column_cell_is_visible #}\n self\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- %hash c:a202 d:1401\n-- | Sets the current keyboard focus to be at @cell@, if the column contains 2\n-- or more editable and activatable cells.\n--\n-- * Available since Gtk+ version 2.2\n--\ntreeViewColumnFocusCell :: CellRendererClass cell => TreeViewColumn\n -> cell -- ^ @cell@ - A 'CellRenderer'\n -> IO ()\ntreeViewColumnFocusCell self cell =\n {# call gtk_tree_view_column_focus_cell #}\n self\n (toCellRenderer cell)\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:4420 d:bfde\n-- | Flags the column, and the cell renderers added to this column, to have\n-- their sizes renegotiated.\n--\n-- * Available since Gtk+ version 2.8\n--\ntreeViewColumnQueueResize :: TreeViewColumn -> IO ()\ntreeViewColumnQueueResize self =\n {# call gtk_tree_view_column_queue_resize #}\n self\n#endif\n#endif\n\n--------------------\n-- Attributes\n\n-- | Whether to display the column.\n--\n-- Default value: @True@\n--\ntreeViewColumnVisible :: Attr TreeViewColumn Bool\ntreeViewColumnVisible = newAttr\n treeViewColumnGetVisible\n treeViewColumnSetVisible\n\n-- | Column is user-resizable.\n--\n-- Default value: @False@\n--\ntreeViewColumnResizable :: Attr TreeViewColumn Bool\ntreeViewColumnResizable = newAttr\n treeViewColumnGetResizable\n treeViewColumnSetResizable\n\n-- | Current width of the column.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntreeViewColumnWidth :: ReadAttr TreeViewColumn Int\ntreeViewColumnWidth = readAttrFromIntProperty \"width\"\n\n-- | Space which is inserted between cells.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntreeViewColumnSpacing :: Attr TreeViewColumn Int\ntreeViewColumnSpacing = newAttr\n treeViewColumnGetSpacing\n treeViewColumnSetSpacing\n\n-- | Resize mode of the column.\n--\n-- Default value: 'TreeViewColumnGrowOnly'\n--\ntreeViewColumnSizing :: Attr TreeViewColumn TreeViewColumnSizing\ntreeViewColumnSizing = newAttr\n treeViewColumnGetSizing\n treeViewColumnSetSizing\n\n-- | Current fixed width of the column.\n--\n-- Allowed values: >= 1\n--\n-- Default value: 1\n--\ntreeViewColumnFixedWidth :: Attr TreeViewColumn Int\ntreeViewColumnFixedWidth = newAttr\n treeViewColumnGetFixedWidth\n treeViewColumnSetFixedWidth\n\n-- | Minimum allowed width of the column.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\ntreeViewColumnMinWidth :: Attr TreeViewColumn Int\ntreeViewColumnMinWidth = newAttr\n treeViewColumnGetMinWidth\n treeViewColumnSetMinWidth\n\n-- | Maximum allowed width of the column.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\ntreeViewColumnMaxWidth :: Attr TreeViewColumn Int\ntreeViewColumnMaxWidth = newAttr\n treeViewColumnGetMaxWidth\n treeViewColumnSetMaxWidth\n\n-- | Title to appear in column header.\n--\n-- Default value: \\\"\\\"\n--\ntreeViewColumnTitle :: ReadWriteAttr TreeViewColumn (Maybe String) String\ntreeViewColumnTitle = newAttr\n treeViewColumnGetTitle\n treeViewColumnSetTitle\n\n-- %hash c:800 d:eb1a\n-- | Column gets share of extra width allocated to the widget.\n--\n-- Default value: @False@\n--\ntreeViewColumnExpand :: Attr TreeViewColumn Bool\ntreeViewColumnExpand = newAttrFromBoolProperty \"expand\"\n\n-- | Whether the header can be clicked.\n--\n-- Default value: @False@\n--\ntreeViewColumnClickable :: Attr TreeViewColumn Bool\ntreeViewColumnClickable = newAttr\n treeViewColumnGetClickable\n treeViewColumnSetClickable\n\n-- | Widget to put in column header button instead of column title.\n--\ntreeViewColumnWidget :: WidgetClass widget => ReadWriteAttr TreeViewColumn (Maybe Widget) (Maybe widget)\ntreeViewColumnWidget = newAttr\n treeViewColumnGetWidget\n treeViewColumnSetWidget\n\n-- | X Alignment of the column header text or widget.\n--\n-- Allowed values: [0,1]\n--\n-- Default value: 0\n--\ntreeViewColumnAlignment :: Attr TreeViewColumn Float\ntreeViewColumnAlignment = newAttr\n treeViewColumnGetAlignment\n treeViewColumnSetAlignment\n\n-- | Whether the column can be reordered around the headers.\n--\n-- Default value: @False@\n--\ntreeViewColumnReorderable :: Attr TreeViewColumn Bool\ntreeViewColumnReorderable = newAttr\n treeViewColumnGetReorderable\n treeViewColumnSetReorderable\n\n-- | Whether to show a sort indicator.\n--\n-- Default value: @False@\n--\ntreeViewColumnSortIndicator :: Attr TreeViewColumn Bool\ntreeViewColumnSortIndicator = newAttr\n treeViewColumnGetSortIndicator\n treeViewColumnSetSortIndicator\n\n-- | Sort direction the sort indicator should indicate.\n--\n-- Default value: 'SortAscending'\n--\ntreeViewColumnSortOrder :: Attr TreeViewColumn SortType\ntreeViewColumnSortOrder = newAttr\n treeViewColumnGetSortOrder\n treeViewColumnSetSortOrder\n\n-- | \\'sortColumnId\\' property. See 'treeViewColumnGetSortColumnId' and\n-- 'treeViewColumnSetSortColumnId'\n--\ntreeViewColumnSortColumnId :: Attr TreeViewColumn SortColumnId\ntreeViewColumnSortColumnId = newAttr\n treeViewColumnGetSortColumnId\n treeViewColumnSetSortColumnId\n\n--------------------\n-- Signals\n\n-- | Emitted when the header of this column has been clicked on.\n--\nonColClicked, afterColClicked :: TreeViewColumnClass self => self\n -> IO ()\n -> IO (ConnectId self)\nonColClicked = connect_NONE__NONE \"clicked\" False\nafterColClicked = connect_NONE__NONE \"clicked\" True\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) TreeViewColumn TreeView\n--\n-- Author : Axel Simon\n--\n-- Created: 9 May 2001\n--\n-- Copyright (C) 2001-2005 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- A visible column in a 'TreeView' widget\n--\nmodule Graphics.UI.Gtk.ModelView.TreeViewColumn (\n-- * Detail\n-- \n-- | The 'TreeViewColumn' object represents a visible column in a 'TreeView'\n-- widget. It allows to set properties of the column header, and functions as a\n-- holding pen for the cell renderers which determine how the data in the\n-- column is displayed.\n--\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----TreeViewColumn\n-- @\n\n-- * Types\n TreeViewColumn,\n TreeViewColumnClass,\n castToTreeViewColumn, gTypeTreeViewColumn,\n toTreeViewColumn,\n\n-- * Constructors\n treeViewColumnNew,\n\n-- * Methods\n treeViewColumnPackStart,\n treeViewColumnPackEnd,\n treeViewColumnClear,\n treeViewColumnGetCellRenderers,\n treeViewColumnSetSpacing,\n treeViewColumnGetSpacing,\n treeViewColumnSetVisible,\n treeViewColumnGetVisible,\n treeViewColumnSetResizable,\n treeViewColumnGetResizable,\n TreeViewColumnSizing(..),\n treeViewColumnSetSizing,\n treeViewColumnGetSizing,\n treeViewColumnGetWidth,\n treeViewColumnSetFixedWidth,\n treeViewColumnGetFixedWidth,\n treeViewColumnSetMinWidth,\n treeViewColumnGetMinWidth,\n treeViewColumnSetMaxWidth,\n treeViewColumnGetMaxWidth,\n treeViewColumnClicked,\n treeViewColumnSetTitle,\n treeViewColumnGetTitle,\n treeViewColumnSetClickable,\n treeViewColumnGetClickable,\n treeViewColumnSetWidget,\n treeViewColumnGetWidget,\n treeViewColumnSetAlignment,\n treeViewColumnGetAlignment,\n treeViewColumnSetReorderable,\n treeViewColumnGetReorderable,\n treeViewColumnSetSortColumnId,\n treeViewColumnGetSortColumnId,\n treeViewColumnSetSortIndicator,\n treeViewColumnGetSortIndicator,\n treeViewColumnSetSortOrder,\n treeViewColumnGetSortOrder,\n SortType(..),\n#if GTK_CHECK_VERSION(2,4,0)\n treeViewColumnSetExpand,\n treeViewColumnGetExpand,\n#endif\n treeViewColumnCellIsVisible,\n#if GTK_CHECK_VERSION(2,2,0)\n treeViewColumnFocusCell,\n#if GTK_CHECK_VERSION(2,8,0)\n treeViewColumnQueueResize,\n#endif\n#endif\n\n-- * Attributes\n treeViewColumnVisible,\n treeViewColumnResizable,\n treeViewColumnWidth,\n treeViewColumnSpacing,\n treeViewColumnSizing,\n treeViewColumnFixedWidth,\n treeViewColumnMinWidth,\n treeViewColumnMaxWidth,\n treeViewColumnTitle,\n treeViewColumnExpand,\n treeViewColumnClickable,\n treeViewColumnWidget,\n treeViewColumnAlignment,\n treeViewColumnReorderable,\n treeViewColumnSortIndicator,\n treeViewColumnSortOrder,\n treeViewColumnSortColumnId,\n\n-- * Signals\n onColClicked,\n afterColClicked\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import System.Glib.GList#}\t\t\t(fromGList)\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Abstract.Object\t\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.General.Enums\t\t(TreeViewColumnSizing(..),\n\t\t\t\t\t\t SortType(..))\nimport Graphics.UI.Gtk.General.Structs (SortColumnId)\n{#import Graphics.UI.Gtk.ModelView.TreeModel#}\t()\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Generate a new TreeViewColumn widget.\n--\ntreeViewColumnNew :: IO TreeViewColumn\ntreeViewColumnNew = makeNewObject mkTreeViewColumn \n {# call tree_view_column_new #}\n\n\n--------------------\n-- Methods\n\n-- | Add a cell renderer at the beginning of a column.\n--\n-- * Excess space is divided equally among all renderers which have\n-- @expand@ set to True.\n--\ntreeViewColumnPackStart :: CellRendererClass cell => TreeViewColumn\n -> cell\n -> Bool\n -> IO ()\ntreeViewColumnPackStart self cell expand =\n {# call unsafe tree_view_column_pack_start #}\n self\n (toCellRenderer cell)\n (fromBool expand)\n\n-- | Add a cell renderer at the end of a column.\n--\n-- * Excess space is divided equally among all renderers which have\n-- @expand@ set to True.\n--\ntreeViewColumnPackEnd :: CellRendererClass cell => TreeViewColumn\n -> cell\n -> Bool\n -> IO ()\ntreeViewColumnPackEnd self cell expand =\n {# call unsafe tree_view_column_pack_end #}\n self\n (toCellRenderer cell)\n (fromBool expand)\n\n-- | Remove the associations of attributes to a store for all 'CellRenderer's.\n--\ntreeViewColumnClear :: TreeViewColumn -> IO ()\ntreeViewColumnClear self =\n {# call tree_view_column_clear #}\n self\n\n-- | Retrieve all 'CellRenderer's that are contained in this column.\n--\ntreeViewColumnGetCellRenderers :: TreeViewColumn -> IO [CellRenderer]\ntreeViewColumnGetCellRenderers self =\n {# call unsafe tree_view_column_get_cell_renderers #}\n self\n >>= fromGList\n >>= mapM (makeNewObject mkCellRenderer . return)\n\n-- | Set the number of pixels between two cell renderers.\n--\ntreeViewColumnSetSpacing :: TreeViewColumn -> Int -> IO ()\ntreeViewColumnSetSpacing self spacing =\n {# call tree_view_column_set_spacing #}\n self\n (fromIntegral spacing)\n\n\n-- | Get the number of pixels between two cell renderers.\n--\ntreeViewColumnGetSpacing :: TreeViewColumn -> IO Int\ntreeViewColumnGetSpacing self =\n liftM fromIntegral $\n {# call unsafe tree_view_column_get_spacing #}\n self\n\n-- | Set the visibility of a given column.\n--\ntreeViewColumnSetVisible :: TreeViewColumn -> Bool -> IO ()\ntreeViewColumnSetVisible self visible =\n {# call tree_view_column_set_visible #}\n self\n (fromBool visible)\n\n-- | Get the visibility of a given column.\n--\ntreeViewColumnGetVisible :: TreeViewColumn -> IO Bool\ntreeViewColumnGetVisible self =\n liftM toBool $\n {# call unsafe tree_view_column_get_visible #}\n self\n\n-- | Set if a given column is resizable by the user.\n--\ntreeViewColumnSetResizable :: TreeViewColumn -> Bool -> IO ()\ntreeViewColumnSetResizable self resizable =\n {# call tree_view_column_set_resizable #}\n self\n (fromBool resizable)\n\n-- | Get if a given column is resizable by the user.\n--\ntreeViewColumnGetResizable :: TreeViewColumn -> IO Bool\ntreeViewColumnGetResizable self =\n liftM toBool $\n {# call unsafe tree_view_column_get_resizable #}\n self\n\n-- | Set wether the column can be resized.\n--\ntreeViewColumnSetSizing :: TreeViewColumn\n -> TreeViewColumnSizing\n -> IO ()\ntreeViewColumnSetSizing self type_ =\n {# call tree_view_column_set_sizing #}\n self\n ((fromIntegral . fromEnum) type_)\n\n-- | Return the resizing type of the column.\n--\ntreeViewColumnGetSizing :: TreeViewColumn\n -> IO TreeViewColumnSizing\ntreeViewColumnGetSizing self =\n liftM (toEnum . fromIntegral) $\n {# call unsafe tree_view_column_get_sizing #}\n self\n\n-- | Query the current width of the column.\n--\ntreeViewColumnGetWidth :: TreeViewColumn -> IO Int\ntreeViewColumnGetWidth self =\n liftM fromIntegral $\n {# call unsafe tree_view_column_get_width #}\n self\n\n-- | Set the width of the column.\n--\n-- * This is meaningful only if the sizing type is 'TreeViewColumnFixed'.\n--\ntreeViewColumnSetFixedWidth :: TreeViewColumn -> Int -> IO ()\ntreeViewColumnSetFixedWidth self fixedWidth =\n {# call tree_view_column_set_fixed_width #}\n self\n (fromIntegral fixedWidth)\n\n-- | Gets the fixed width of the column.\n--\n-- * This is meaningful only if the sizing type is 'TreeViewColumnFixed'.\n--\n-- * This value is only meaning may not be the actual width of the column on the\n-- screen, just what is requested.\n--\ntreeViewColumnGetFixedWidth :: TreeViewColumn -> IO Int\ntreeViewColumnGetFixedWidth self =\n liftM fromIntegral $\n {# call unsafe tree_view_column_get_fixed_width #}\n self\n\n-- | Set minimum width of the column.\n--\ntreeViewColumnSetMinWidth :: TreeViewColumn -> Int -> IO ()\ntreeViewColumnSetMinWidth self minWidth =\n {# call tree_view_column_set_min_width #}\n self\n (fromIntegral minWidth)\n\n-- | Get the minimum width of a column. Returns -1 if this width was not set.\n--\ntreeViewColumnGetMinWidth :: TreeViewColumn -> IO Int\ntreeViewColumnGetMinWidth self =\n liftM fromIntegral $\n {# call unsafe tree_view_column_get_min_width #}\n self\n\n-- | Set maximum width of the column.\n--\ntreeViewColumnSetMaxWidth :: TreeViewColumn -> Int -> IO ()\ntreeViewColumnSetMaxWidth self maxWidth =\n {# call tree_view_column_set_max_width #}\n self\n (fromIntegral maxWidth)\n\n-- | Get the maximum width of a column. Returns -1 if this width was not set.\n--\ntreeViewColumnGetMaxWidth :: TreeViewColumn -> IO Int\ntreeViewColumnGetMaxWidth self =\n liftM fromIntegral $\n {# call unsafe tree_view_column_get_max_width #}\n self\n\n-- | Emit the @clicked@ signal on the column.\n--\ntreeViewColumnClicked :: TreeViewColumn -> IO ()\ntreeViewColumnClicked self =\n {# call tree_view_column_clicked #}\n self\n\n-- | Set the widget's title if a custom widget has not been set.\n--\ntreeViewColumnSetTitle :: TreeViewColumn -> String -> IO ()\ntreeViewColumnSetTitle self title =\n withUTFString title $ \\titlePtr ->\n {# call tree_view_column_set_title #}\n self\n titlePtr\n\n-- | Get the widget's title.\n--\ntreeViewColumnGetTitle :: TreeViewColumn -> IO (Maybe String)\ntreeViewColumnGetTitle self =\n {# call unsafe tree_view_column_get_title #}\n self\n >>= maybePeek peekUTFString\n\n-- | Set if the column should be sensitive to mouse clicks.\n--\ntreeViewColumnSetClickable :: TreeViewColumn -> Bool -> IO ()\ntreeViewColumnSetClickable self clickable =\n {# call tree_view_column_set_clickable #}\n self\n (fromBool clickable)\n\n-- | Returns True if the user can click on the header for the column.\n--\ntreeViewColumnGetClickable :: TreeViewColumn -> IO Bool\ntreeViewColumnGetClickable self =\n liftM toBool $\n {# call tree_view_column_get_clickable #}\n self\n\n-- | Set the column's title to this widget.\n--\ntreeViewColumnSetWidget :: WidgetClass widget => TreeViewColumn\n -> widget\n -> IO ()\ntreeViewColumnSetWidget self widget =\n {# call tree_view_column_set_widget #}\n self\n (toWidget widget)\n\n-- | Retrieve the widget responsible for\n-- showing the column title. In case only a text title was set this will be a\n-- 'Alignment' widget with a 'Label' inside.\n--\ntreeViewColumnGetWidget :: TreeViewColumn -> IO Widget\ntreeViewColumnGetWidget self =\n makeNewObject mkWidget $\n {# call unsafe tree_view_column_get_widget #}\n self\n\n-- | Sets the alignment of the title or custom widget inside the column\n-- header. The alignment determines its location inside the button -- 0.0 for\n-- left, 0.5 for center, 1.0 for right.\n--\ntreeViewColumnSetAlignment :: TreeViewColumn\n -> Float -- ^ @xalign@ - The alignment, which is between [0.0 and\n -- 1.0] inclusive.\n -> IO ()\ntreeViewColumnSetAlignment self xalign =\n {# call tree_view_column_set_alignment #}\n self\n (realToFrac xalign)\n\n-- | Returns the current x alignment of the tree column. This value can range\n-- between 0.0 and 1.0.\n--\ntreeViewColumnGetAlignment :: TreeViewColumn -> IO Float\ntreeViewColumnGetAlignment self =\n liftM realToFrac $\n {# call unsafe tree_view_column_get_alignment #}\n self\n\n-- | Set if the column can be reordered by the end user dragging the header.\n--\ntreeViewColumnSetReorderable :: TreeViewColumn -> Bool -> IO ()\ntreeViewColumnSetReorderable self reorderable =\n {# call tree_view_column_set_reorderable #}\n self\n (fromBool reorderable)\n\n-- | Returns whether the column can be reordered by the user.\n--\ntreeViewColumnGetReorderable :: TreeViewColumn -> IO Bool\ntreeViewColumnGetReorderable self =\n liftM toBool $\n {# call unsafe tree_view_column_get_reorderable #}\n self\n\n-- | Set the column by which to sort.\n--\n-- * Sets the logical @columnId@ that this column sorts on when\n-- this column is selected for sorting. The selected column's header\n-- will be clickable after this call. Logical refers to the \n-- 'Graphics.UI.Gtk.ModelView.TreeSortable.SortColumnId' for which\n-- a comparison function was set.\n--\ntreeViewColumnSetSortColumnId :: TreeViewColumn -> SortColumnId -> IO ()\ntreeViewColumnSetSortColumnId self sortColumnId =\n {# call tree_view_column_set_sort_column_id #}\n self\n (fromIntegral sortColumnId)\n\n-- | Get the column by which to sort.\n--\n-- * Retrieves the logical @columnId@ that the model sorts on when this column\n-- is selected for sorting.\n--\n-- * Returns\n-- 'Graphics.UI.Gtk.ModelView.TreeSortable.treeSortableDefaultSortColumnId'\n-- if this tree view column has no\n-- 'Graphics.UI.Gtk.ModelView.TreeSortable.SortColumnId' associated with it.\n--\ntreeViewColumnGetSortColumnId :: TreeViewColumn -> IO SortColumnId\ntreeViewColumnGetSortColumnId self =\n liftM fromIntegral $\n {# call unsafe tree_view_column_get_sort_column_id #}\n self\n\n-- | Set if a given column has sorting arrows in its heading.\n--\ntreeViewColumnSetSortIndicator :: TreeViewColumn\n -> Bool -> IO ()\ntreeViewColumnSetSortIndicator self setting =\n {# call tree_view_column_set_sort_indicator #}\n self\n (fromBool setting)\n\n-- | Query if a given column has sorting arrows in its heading.\n--\ntreeViewColumnGetSortIndicator :: TreeViewColumn -> IO Bool\ntreeViewColumnGetSortIndicator self =\n liftM toBool $\n {# call unsafe tree_view_column_get_sort_indicator #}\n self\n\n-- | Set if a given column is sorted in ascending or descending order.\n--\n-- * In order for sorting to work, it is necessary to either use automatic\n-- sorting via 'treeViewColumnSetSortColumnId' or to use a\n-- user defined sorting on the elements in a 'TreeModel'.\n--\ntreeViewColumnSetSortOrder :: TreeViewColumn\n -> SortType -> IO ()\ntreeViewColumnSetSortOrder self order =\n {# call tree_view_column_set_sort_order #}\n self\n ((fromIntegral . fromEnum) order)\n\n-- | Query if a given column is sorted in ascending or descending order.\n--\ntreeViewColumnGetSortOrder :: TreeViewColumn -> IO SortType\ntreeViewColumnGetSortOrder self =\n liftM (toEnum . fromIntegral) $\n {# call unsafe tree_view_column_get_sort_order #}\n self\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:7808 d:942b\n-- | Sets the column to take available extra space. This space is shared\n-- equally amongst all columns that have the expand set to @True@. If no column\n-- has this option set, then the last column gets all extra space. By default,\n-- every column is created with this @False@.\n--\n-- * Available since Gtk+ version 2.4\n--\ntreeViewColumnSetExpand :: TreeViewColumn\n -> Bool -- ^ @expand@ - @True@ if the column should take available extra\n -- space, @False@ if not\n -> IO ()\ntreeViewColumnSetExpand self expand =\n {# call gtk_tree_view_column_set_expand #}\n self\n (fromBool expand)\n\n-- %hash c:ee41 d:f16b\n-- | Return @True@ if the column expands to take any available space.\n--\n-- * Available since Gtk+ version 2.4\n--\ntreeViewColumnGetExpand :: TreeViewColumn\n -> IO Bool -- ^ returns @True@, if the column expands\ntreeViewColumnGetExpand self =\n liftM toBool $\n {# call gtk_tree_view_column_get_expand #}\n self\n#endif\n\n-- %hash c:77e0 d:e1c7\n-- | Returns @True@ if any of the cells packed into the @treeColumn@ are\n-- visible. For this to be meaningful, you must first initialize the cells with\n-- 'treeViewColumnCellSetCellData'\n--\ntreeViewColumnCellIsVisible :: TreeViewColumn\n -> IO Bool -- ^ returns @True@, if any of the cells packed into the\n -- @treeColumn@ are currently visible\ntreeViewColumnCellIsVisible self =\n liftM toBool $\n {# call gtk_tree_view_column_cell_is_visible #}\n self\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- %hash c:a202 d:1401\n-- | Sets the current keyboard focus to be at @cell@, if the column contains 2\n-- or more editable and activatable cells.\n--\n-- * Available since Gtk+ version 2.2\n--\ntreeViewColumnFocusCell :: CellRendererClass cell => TreeViewColumn\n -> cell -- ^ @cell@ - A 'CellRenderer'\n -> IO ()\ntreeViewColumnFocusCell self cell =\n {# call gtk_tree_view_column_focus_cell #}\n self\n (toCellRenderer cell)\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:4420 d:bfde\n-- | Flags the column, and the cell renderers added to this column, to have\n-- their sizes renegotiated.\n--\n-- * Available since Gtk+ version 2.8\n--\ntreeViewColumnQueueResize :: TreeViewColumn -> IO ()\ntreeViewColumnQueueResize self =\n {# call gtk_tree_view_column_queue_resize #}\n self\n#endif\n#endif\n\n--------------------\n-- Attributes\n\n-- | Whether to display the column.\n--\n-- Default value: @True@\n--\ntreeViewColumnVisible :: Attr TreeViewColumn Bool\ntreeViewColumnVisible = newAttr\n treeViewColumnGetVisible\n treeViewColumnSetVisible\n\n-- | Column is user-resizable.\n--\n-- Default value: @False@\n--\ntreeViewColumnResizable :: Attr TreeViewColumn Bool\ntreeViewColumnResizable = newAttr\n treeViewColumnGetResizable\n treeViewColumnSetResizable\n\n-- | Current width of the column.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntreeViewColumnWidth :: ReadAttr TreeViewColumn Int\ntreeViewColumnWidth = readAttrFromIntProperty \"width\"\n\n-- | Space which is inserted between cells.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntreeViewColumnSpacing :: Attr TreeViewColumn Int\ntreeViewColumnSpacing = newAttr\n treeViewColumnGetSpacing\n treeViewColumnSetSpacing\n\n-- | Resize mode of the column.\n--\n-- Default value: 'TreeViewColumnGrowOnly'\n--\ntreeViewColumnSizing :: Attr TreeViewColumn TreeViewColumnSizing\ntreeViewColumnSizing = newAttr\n treeViewColumnGetSizing\n treeViewColumnSetSizing\n\n-- | Current fixed width of the column.\n--\n-- Allowed values: >= 1\n--\n-- Default value: 1\n--\ntreeViewColumnFixedWidth :: Attr TreeViewColumn Int\ntreeViewColumnFixedWidth = newAttr\n treeViewColumnGetFixedWidth\n treeViewColumnSetFixedWidth\n\n-- | Minimum allowed width of the column.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\ntreeViewColumnMinWidth :: Attr TreeViewColumn Int\ntreeViewColumnMinWidth = newAttr\n treeViewColumnGetMinWidth\n treeViewColumnSetMinWidth\n\n-- | Maximum allowed width of the column.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\ntreeViewColumnMaxWidth :: Attr TreeViewColumn Int\ntreeViewColumnMaxWidth = newAttr\n treeViewColumnGetMaxWidth\n treeViewColumnSetMaxWidth\n\n-- | Title to appear in column header.\n--\n-- Default value: \\\"\\\"\n--\ntreeViewColumnTitle :: ReadWriteAttr TreeViewColumn (Maybe String) String\ntreeViewColumnTitle = newAttr\n treeViewColumnGetTitle\n treeViewColumnSetTitle\n\n-- %hash c:800 d:eb1a\n-- | Column gets share of extra width allocated to the widget.\n--\n-- Default value: @False@\n--\ntreeViewColumnExpand :: Attr TreeViewColumn Bool\ntreeViewColumnExpand = newAttrFromBoolProperty \"expand\"\n\n-- | Whether the header can be clicked.\n--\n-- Default value: @False@\n--\ntreeViewColumnClickable :: Attr TreeViewColumn Bool\ntreeViewColumnClickable = newAttr\n treeViewColumnGetClickable\n treeViewColumnSetClickable\n\n-- | Widget to put in column header button instead of column title.\n--\ntreeViewColumnWidget :: WidgetClass widget => ReadWriteAttr TreeViewColumn Widget widget\ntreeViewColumnWidget = newAttr\n treeViewColumnGetWidget\n treeViewColumnSetWidget\n\n-- | X Alignment of the column header text or widget.\n--\n-- Allowed values: [0,1]\n--\n-- Default value: 0\n--\ntreeViewColumnAlignment :: Attr TreeViewColumn Float\ntreeViewColumnAlignment = newAttr\n treeViewColumnGetAlignment\n treeViewColumnSetAlignment\n\n-- | Whether the column can be reordered around the headers.\n--\n-- Default value: @False@\n--\ntreeViewColumnReorderable :: Attr TreeViewColumn Bool\ntreeViewColumnReorderable = newAttr\n treeViewColumnGetReorderable\n treeViewColumnSetReorderable\n\n-- | Whether to show a sort indicator.\n--\n-- Default value: @False@\n--\ntreeViewColumnSortIndicator :: Attr TreeViewColumn Bool\ntreeViewColumnSortIndicator = newAttr\n treeViewColumnGetSortIndicator\n treeViewColumnSetSortIndicator\n\n-- | Sort direction the sort indicator should indicate.\n--\n-- Default value: 'SortAscending'\n--\ntreeViewColumnSortOrder :: Attr TreeViewColumn SortType\ntreeViewColumnSortOrder = newAttr\n treeViewColumnGetSortOrder\n treeViewColumnSetSortOrder\n\n-- | \\'sortColumnId\\' property. See 'treeViewColumnGetSortColumnId' and\n-- 'treeViewColumnSetSortColumnId'\n--\ntreeViewColumnSortColumnId :: Attr TreeViewColumn SortColumnId\ntreeViewColumnSortColumnId = newAttr\n treeViewColumnGetSortColumnId\n treeViewColumnSetSortColumnId\n\n--------------------\n-- Signals\n\n-- | Emitted when the header of this column has been clicked on.\n--\nonColClicked, afterColClicked :: TreeViewColumnClass self => self\n -> IO ()\n -> IO (ConnectId self)\nonColClicked = connect_NONE__NONE \"clicked\" False\nafterColClicked = connect_NONE__NONE \"clicked\" True\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"b4e1094051069b00af35f49189a14170b6d18447","subject":"Add instances for NativeFileChooserUserAction.","message":"Add instances for NativeFileChooserUserAction.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/NativeFileChooser.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/NativeFileChooser.chs","new_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.NativeFileChooser\n (\n NativeFileChooserType(..),\n NativeFileChooserOption(..),\n NativeFileChooserUserAction(..),\n allNativeFileChooserOptions,\n -- * Constructor\n nativeFileChooserNew\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Native_File_Chooser\n --\n -- $functions\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_Native_File_ChooserC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\n\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\n\n#c\nenum NativeFileChooserType {\n BrowseFile = BROWSE_FILE,\n BrowseDirectory = BROWSE_DIRECTORY,\n BrowseMultiFile = BROWSE_MULTI_FILE,\n BrowseMultiDirectory = BROWSE_MULTI_DIRECTORY,\n BrowseSaveFile = BROWSE_SAVE_FILE,\n BrowseSaveDirectory = BROWSE_SAVE_DIRECTORY\n};\n\nenum NativeFileChooserOption {\n NoOptions = NO_OPTIONS,\n SaveasConfirm = SAVEAS_CONFIRM,\n NewFolder = NEW_FOLDER,\n Preview = PREVIEW,\n UseFilterExt = USE_FILTER_EXT\n};\n#endc\n\n{#enum NativeFileChooserType {} deriving (Show, Eq, Ord) #}\n{#enum NativeFileChooserOption {} deriving (Show, Eq, Ord) #}\n\ndata NativeFileChooserUserAction =\n NativeFileChooserPicked |\n NativeFileChooserCancelled |\n NativeFileChooserError deriving (Show, Eq, Ord)\n\nallNativeFileChooserOptions :: [NativeFileChooserOption]\nallNativeFileChooserOptions =\n [\n NoOptions,\n SaveasConfirm,\n NewFolder,\n Preview,\n UseFilterExt\n ]\n\n{# fun Fl_Native_File_Chooser_New_WithVal as newWithVal' { `Int' } -> `Ptr ()' id #}\n{# fun Fl_Native_File_Chooser_New as new' { } -> `Ptr ()' id #}\nnativeFileChooserNew :: Maybe NativeFileChooserType -> IO (Ref NativeFileChooser)\nnativeFileChooserNew t =\n case t of\n (Just t') -> newWithVal' (fromEnum t') >>= toRef\n Nothing -> new' >>= toRef\n\n{# fun Fl_Native_File_Chooser_Destroy as nativeFileChooserDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ IO ()) => Op (Destroy ()) NativeFileChooser orig impl where\n runOp _ _ chooser = swapRef chooser $ \\chooserPtr -> do\n nativeFileChooserDestroy' chooserPtr\n return nullPtr\n{# fun Fl_Native_File_Chooser_set_type as setType' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (NativeFileChooserType -> IO ())) => Op (SetType ()) NativeFileChooser orig impl where\n runOp _ _ chooser type'' = withRef chooser $ \\chooserPtr -> setType' chooserPtr (fromEnum type'')\n{# fun Fl_Native_File_Chooser_type as type' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (NativeFileChooserType))) => Op (GetType_ ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> type' chooserPtr >>= return . toEnum\n{# fun Fl_Native_File_Chooser_set_options as setOptions' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ ([NativeFileChooserOption] -> IO ())) => Op (SetOptions ()) NativeFileChooser orig impl where\n runOp _ _ chooser options = withRef chooser $ \\chooserPtr -> setOptions' chooserPtr (combine options)\n{# fun Fl_Native_File_Chooser_options as options' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO ([NativeFileChooserOption]))) => Op (GetOptions ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> do\n opts <- options' chooserPtr\n if (opts == 0)\n then return []\n else return (extract allNativeFileChooserOptions $ fromIntegral opts)\n{# fun Fl_Native_File_Chooser_count as count' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetCount ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> count' chooserPtr\n{# fun Fl_Native_File_Chooser_filename as filename' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO (Maybe T.Text))) => Op (GetFilename ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> filename' chooserPtr >>= \\s -> cStringToText s >>= \\s ->\n if (T.null s) then return Nothing else return (Just s)\n{# fun Fl_Native_File_Chooser_filename_with_i as filenameWithI' { id `Ptr ()',`Int' } -> `CString' #}\ninstance (impl ~ (AtIndex -> IO (Maybe T.Text))) => Op (GetFilenameAt ()) NativeFileChooser orig impl where\n runOp _ _ chooser (AtIndex i) = withRef chooser $ \\chooserPtr -> filenameWithI' chooserPtr i >>= \\s -> cStringToText s >>= \\s ->\n if (T.null s) then return Nothing else return (Just s)\n{# fun Fl_Native_File_Chooser_set_directory as setDirectory' { id `Ptr ()',`CString' } -> `()' #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetDirectory ()) NativeFileChooser orig impl where\n runOp _ _ chooser val = withRef chooser $ \\chooserPtr -> copyTextToCString val >>= setDirectory' chooserPtr\n{# fun Fl_Native_File_Chooser_directory as directory' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO (Maybe T.Text))) => Op (GetDirectory ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> directory' chooserPtr >>= \\s -> cStringToText s >>= \\s ->\n if (T.null s) then return Nothing else return (Just s)\n{# fun Fl_Native_File_Chooser_set_title as setTitle' { id `Ptr ()',`CString' } -> `()' #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetTitle ()) NativeFileChooser orig impl where\n runOp _ _ chooser title'' = withRef chooser $ \\chooserPtr -> copyTextToCString title'' >>= setTitle' chooserPtr\n{# fun Fl_Native_File_Chooser_title as title' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO (Maybe T.Text))) => Op (GetTitle ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> title' chooserPtr >>= \\s -> cStringToText s >>= \\s ->\n if (T.null s) then return Nothing else return (Just s)\n{# fun Fl_Native_File_Chooser_filter as filter' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO (Maybe T.Text))) => Op (GetFilter ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> filter' chooserPtr >>= \\s -> cStringToText s >>= \\s ->\n if (T.null s) then return Nothing else return (Just s)\n{# fun Fl_Native_File_Chooser_set_filter as setFilter' { id `Ptr ()', `CString' } -> `()' #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetFilter ()) NativeFileChooser orig impl where\n runOp _ _ chooser filter'' = withRef chooser $ \\chooserPtr -> copyTextToCString filter'' >>= setFilter' chooserPtr\n{# fun Fl_Native_File_Chooser_filters as filters' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (Filters ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> filters' chooserPtr\n{# fun Fl_Native_File_Chooser_set_filter_value as setFilterValue' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (AtIndex -> IO ())) => Op (SetFilterValue ()) NativeFileChooser orig impl where\n runOp _ _ chooser (AtIndex i) = withRef chooser $ \\chooserPtr -> setFilterValue' chooserPtr i\n{# fun Fl_Native_File_Chooser_filter_value as filterValue' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (AtIndex))) => Op (GetFilterValue ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> filterValue' chooserPtr >>= return . AtIndex\n{# fun Fl_Native_File_Chooser_set_preset_file as setPresetFile' { id `Ptr ()',`CString' } -> `()' #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetPresetFile ()) NativeFileChooser orig impl where\n runOp _ _ chooser preset' = withRef chooser $ \\chooserPtr -> copyTextToCString preset' >>= setPresetFile' chooserPtr\n{# fun Fl_Native_File_Chooser_preset_file as presetFile' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO (Maybe T.Text))) => Op (GetPresetFile ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> presetFile' chooserPtr >>= \\s -> cStringToText s >>= \\s ->\n if (T.null s) then return Nothing else return (Just s)\n{# fun Fl_Native_File_Chooser_errmsg as errmsg' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO (Maybe T.Text))) => Op (GetErrmsg ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> errmsg' chooserPtr >>= \\s -> cStringToText s >>= \\s ->\n if (T.null s) then return Nothing else return (Just s)\n{# fun Fl_Native_File_Chooser_show as show' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (NativeFileChooserUserAction))) => Op (ShowWidget ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> do\n res' <- show' chooserPtr\n return $ case res' of\n 0 -> NativeFileChooserPicked\n 1 -> NativeFileChooserCancelled\n (-1) -> NativeFileChooserError\n x'' -> error $ \"NativeFileChooser::showWidget, unknown option:\" ++ (show x'')\n\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.NativeFileChooser\"\n-- @\n\n-- $functions\n-- @\n-- destroy :: 'Ref' 'NativeFileChooser' -> 'IO' ()\n--\n-- filters :: 'Ref' 'NativeFileChooser' -> 'IO' ('Int')\n--\n-- getCount :: 'Ref' 'NativeFileChooser' -> 'IO' ('Int')\n--\n-- getDirectory :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')\n--\n-- getErrmsg :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')\n--\n-- getFilename :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')\n--\n-- getFilenameAt :: 'Ref' 'NativeFileChooser' -> 'AtIndex' -> 'IO' ('Maybe' 'T.Text')\n--\n-- getFilter :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')\n--\n-- getFilterValue :: 'Ref' 'NativeFileChooser' -> 'IO' ('AtIndex')\n--\n-- getOptions :: 'Ref' 'NativeFileChooser' -> 'IO' (['NativeFileChooserOption')]\n--\n-- getPresetFile :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')\n--\n-- getTitle :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')\n--\n-- getType_ :: 'Ref' 'NativeFileChooser' -> 'IO' ('NativeFileChooserType')\n--\n-- setDirectory :: 'Ref' 'NativeFileChooser' -> 'T.Text' -> 'IO' ()\n--\n-- setFilter :: 'Ref' 'NativeFileChooser' -> 'T.Text' -> 'IO' ()\n--\n-- setFilterValue :: 'Ref' 'NativeFileChooser' -> 'AtIndex' -> 'IO' ()\n--\n-- setOptions :: 'Ref' 'NativeFileChooser' -> ['NativeFileChooserOption'] -> 'IO' ()\n--\n-- setPresetFile :: 'Ref' 'NativeFileChooser' -> 'T.Text' -> 'IO' ()\n--\n-- setTitle :: 'Ref' 'NativeFileChooser' -> 'T.Text' -> 'IO' ()\n--\n-- setType :: 'Ref' 'NativeFileChooser' -> 'NativeFileChooserType' -> 'IO' ()\n--\n-- showWidget :: 'Ref' 'NativeFileChooser' -> 'IO' ('NativeFileChooserUserAction')\n-- @\n","old_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.NativeFileChooser\n (\n NativeFileChooserType(..),\n NativeFileChooserOption(..),\n NativeFileChooserUserAction(..),\n allNativeFileChooserOptions,\n -- * Constructor\n nativeFileChooserNew\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Native_File_Chooser\n --\n -- $functions\n )\nwhere\n#include \"Fl_ExportMacros.h\"\n#include \"Fl_Types.h\"\n#include \"Fl_Native_File_ChooserC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\n\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\n\n#c\nenum NativeFileChooserType {\n BrowseFile = BROWSE_FILE,\n BrowseDirectory = BROWSE_DIRECTORY,\n BrowseMultiFile = BROWSE_MULTI_FILE,\n BrowseMultiDirectory = BROWSE_MULTI_DIRECTORY,\n BrowseSaveFile = BROWSE_SAVE_FILE,\n BrowseSaveDirectory = BROWSE_SAVE_DIRECTORY\n};\n\nenum NativeFileChooserOption {\n NoOptions = NO_OPTIONS,\n SaveasConfirm = SAVEAS_CONFIRM,\n NewFolder = NEW_FOLDER,\n Preview = PREVIEW,\n UseFilterExt = USE_FILTER_EXT\n};\n#endc\n\n{#enum NativeFileChooserType {} deriving (Show, Eq, Ord) #}\n{#enum NativeFileChooserOption {} deriving (Show, Eq, Ord) #}\n\ndata NativeFileChooserUserAction =\n NativeFileChooserPicked |\n NativeFileChooserCancelled |\n NativeFileChooserError\n\nallNativeFileChooserOptions :: [NativeFileChooserOption]\nallNativeFileChooserOptions =\n [\n NoOptions,\n SaveasConfirm,\n NewFolder,\n Preview,\n UseFilterExt\n ]\n\n{# fun Fl_Native_File_Chooser_New_WithVal as newWithVal' { `Int' } -> `Ptr ()' id #}\n{# fun Fl_Native_File_Chooser_New as new' { } -> `Ptr ()' id #}\nnativeFileChooserNew :: Maybe NativeFileChooserType -> IO (Ref NativeFileChooser)\nnativeFileChooserNew t =\n case t of\n (Just t') -> newWithVal' (fromEnum t') >>= toRef\n Nothing -> new' >>= toRef\n\n{# fun Fl_Native_File_Chooser_Destroy as nativeFileChooserDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ IO ()) => Op (Destroy ()) NativeFileChooser orig impl where\n runOp _ _ chooser = swapRef chooser $ \\chooserPtr -> do\n nativeFileChooserDestroy' chooserPtr\n return nullPtr\n{# fun Fl_Native_File_Chooser_set_type as setType' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (NativeFileChooserType -> IO ())) => Op (SetType ()) NativeFileChooser orig impl where\n runOp _ _ chooser type'' = withRef chooser $ \\chooserPtr -> setType' chooserPtr (fromEnum type'')\n{# fun Fl_Native_File_Chooser_type as type' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (NativeFileChooserType))) => Op (GetType_ ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> type' chooserPtr >>= return . toEnum\n{# fun Fl_Native_File_Chooser_set_options as setOptions' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ ([NativeFileChooserOption] -> IO ())) => Op (SetOptions ()) NativeFileChooser orig impl where\n runOp _ _ chooser options = withRef chooser $ \\chooserPtr -> setOptions' chooserPtr (combine options)\n{# fun Fl_Native_File_Chooser_options as options' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO ([NativeFileChooserOption]))) => Op (GetOptions ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> do\n opts <- options' chooserPtr\n if (opts == 0)\n then return []\n else return (extract allNativeFileChooserOptions $ fromIntegral opts)\n{# fun Fl_Native_File_Chooser_count as count' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetCount ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> count' chooserPtr\n{# fun Fl_Native_File_Chooser_filename as filename' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO (Maybe T.Text))) => Op (GetFilename ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> filename' chooserPtr >>= \\s -> cStringToText s >>= \\s ->\n if (T.null s) then return Nothing else return (Just s)\n{# fun Fl_Native_File_Chooser_filename_with_i as filenameWithI' { id `Ptr ()',`Int' } -> `CString' #}\ninstance (impl ~ (AtIndex -> IO (Maybe T.Text))) => Op (GetFilenameAt ()) NativeFileChooser orig impl where\n runOp _ _ chooser (AtIndex i) = withRef chooser $ \\chooserPtr -> filenameWithI' chooserPtr i >>= \\s -> cStringToText s >>= \\s ->\n if (T.null s) then return Nothing else return (Just s)\n{# fun Fl_Native_File_Chooser_set_directory as setDirectory' { id `Ptr ()',`CString' } -> `()' #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetDirectory ()) NativeFileChooser orig impl where\n runOp _ _ chooser val = withRef chooser $ \\chooserPtr -> copyTextToCString val >>= setDirectory' chooserPtr\n{# fun Fl_Native_File_Chooser_directory as directory' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO (Maybe T.Text))) => Op (GetDirectory ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> directory' chooserPtr >>= \\s -> cStringToText s >>= \\s ->\n if (T.null s) then return Nothing else return (Just s)\n{# fun Fl_Native_File_Chooser_set_title as setTitle' { id `Ptr ()',`CString' } -> `()' #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetTitle ()) NativeFileChooser orig impl where\n runOp _ _ chooser title'' = withRef chooser $ \\chooserPtr -> copyTextToCString title'' >>= setTitle' chooserPtr\n{# fun Fl_Native_File_Chooser_title as title' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO (Maybe T.Text))) => Op (GetTitle ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> title' chooserPtr >>= \\s -> cStringToText s >>= \\s ->\n if (T.null s) then return Nothing else return (Just s)\n{# fun Fl_Native_File_Chooser_filter as filter' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO (Maybe T.Text))) => Op (GetFilter ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> filter' chooserPtr >>= \\s -> cStringToText s >>= \\s ->\n if (T.null s) then return Nothing else return (Just s)\n{# fun Fl_Native_File_Chooser_set_filter as setFilter' { id `Ptr ()', `CString' } -> `()' #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetFilter ()) NativeFileChooser orig impl where\n runOp _ _ chooser filter'' = withRef chooser $ \\chooserPtr -> copyTextToCString filter'' >>= setFilter' chooserPtr\n{# fun Fl_Native_File_Chooser_filters as filters' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (Filters ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> filters' chooserPtr\n{# fun Fl_Native_File_Chooser_set_filter_value as setFilterValue' { id `Ptr ()',`Int' } -> `()' #}\ninstance (impl ~ (AtIndex -> IO ())) => Op (SetFilterValue ()) NativeFileChooser orig impl where\n runOp _ _ chooser (AtIndex i) = withRef chooser $ \\chooserPtr -> setFilterValue' chooserPtr i\n{# fun Fl_Native_File_Chooser_filter_value as filterValue' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (AtIndex))) => Op (GetFilterValue ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> filterValue' chooserPtr >>= return . AtIndex\n{# fun Fl_Native_File_Chooser_set_preset_file as setPresetFile' { id `Ptr ()',`CString' } -> `()' #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetPresetFile ()) NativeFileChooser orig impl where\n runOp _ _ chooser preset' = withRef chooser $ \\chooserPtr -> copyTextToCString preset' >>= setPresetFile' chooserPtr\n{# fun Fl_Native_File_Chooser_preset_file as presetFile' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO (Maybe T.Text))) => Op (GetPresetFile ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> presetFile' chooserPtr >>= \\s -> cStringToText s >>= \\s ->\n if (T.null s) then return Nothing else return (Just s)\n{# fun Fl_Native_File_Chooser_errmsg as errmsg' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO (Maybe T.Text))) => Op (GetErrmsg ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> errmsg' chooserPtr >>= \\s -> cStringToText s >>= \\s ->\n if (T.null s) then return Nothing else return (Just s)\n{# fun Fl_Native_File_Chooser_show as show' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (NativeFileChooserUserAction))) => Op (ShowWidget ()) NativeFileChooser orig impl where\n runOp _ _ chooser = withRef chooser $ \\chooserPtr -> do\n res' <- show' chooserPtr\n return $ case res' of\n 0 -> NativeFileChooserPicked\n 1 -> NativeFileChooserCancelled\n (-1) -> NativeFileChooserError\n x'' -> error $ \"NativeFileChooser::showWidget, unknown option:\" ++ (show x'')\n\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.NativeFileChooser\"\n-- @\n\n-- $functions\n-- @\n-- destroy :: 'Ref' 'NativeFileChooser' -> 'IO' ()\n--\n-- filters :: 'Ref' 'NativeFileChooser' -> 'IO' ('Int')\n--\n-- getCount :: 'Ref' 'NativeFileChooser' -> 'IO' ('Int')\n--\n-- getDirectory :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')\n--\n-- getErrmsg :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')\n--\n-- getFilename :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')\n--\n-- getFilenameAt :: 'Ref' 'NativeFileChooser' -> 'AtIndex' -> 'IO' ('Maybe' 'T.Text')\n--\n-- getFilter :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')\n--\n-- getFilterValue :: 'Ref' 'NativeFileChooser' -> 'IO' ('AtIndex')\n--\n-- getOptions :: 'Ref' 'NativeFileChooser' -> 'IO' (['NativeFileChooserOption')]\n--\n-- getPresetFile :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')\n--\n-- getTitle :: 'Ref' 'NativeFileChooser' -> 'IO' ('Maybe' 'T.Text')\n--\n-- getType_ :: 'Ref' 'NativeFileChooser' -> 'IO' ('NativeFileChooserType')\n--\n-- setDirectory :: 'Ref' 'NativeFileChooser' -> 'T.Text' -> 'IO' ()\n--\n-- setFilter :: 'Ref' 'NativeFileChooser' -> 'T.Text' -> 'IO' ()\n--\n-- setFilterValue :: 'Ref' 'NativeFileChooser' -> 'AtIndex' -> 'IO' ()\n--\n-- setOptions :: 'Ref' 'NativeFileChooser' -> ['NativeFileChooserOption'] -> 'IO' ()\n--\n-- setPresetFile :: 'Ref' 'NativeFileChooser' -> 'T.Text' -> 'IO' ()\n--\n-- setTitle :: 'Ref' 'NativeFileChooser' -> 'T.Text' -> 'IO' ()\n--\n-- setType :: 'Ref' 'NativeFileChooser' -> 'NativeFileChooserType' -> 'IO' ()\n--\n-- showWidget :: 'Ref' 'NativeFileChooser' -> 'IO' ('NativeFileChooserUserAction')\n-- @\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"}
{"commit":"78074117a70df0281796e0a49cda4179847bb737","subject":"added nullDevPtr to Driver API","message":"added nullDevPtr to Driver API\n\nIgnore-this: 189a37a7feb6bc81462d75feffc40121\n\ndarcs-hash:20100212042424-879de-eb204d44749e5f29225464b0a30091ac7f29dc97.gz\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Marshal.chs","new_file":"Foreign\/CUDA\/Driver\/Marshal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Marshal\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Memory management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Marshal\n (\n -- * Host Allocation\n HostPtr(..), AllocFlag(..),\n withHostPtr, mallocHostArray, freeHost,\n\n -- * Device Allocation\n DevicePtr,\n mallocArray, allocaArray, free, nullDevPtr,\n\n -- * Marshalling\n peekArray, peekArrayAsync, peekListArray,\n pokeArray, pokeArrayAsync, pokeListArray,\n copyArrayAsync,\n\n -- * Combined Allocation and Marshalling\n newListArray, withListArray, withListArrayLen,\n\n -- * Utility\n memset, getDevicePtr\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Stream (Stream(..))\n\n-- System\nimport Unsafe.Coerce\nimport Control.Monad (liftM)\nimport Control.Exception.Extensible\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.Storable\nimport qualified Foreign.Marshal as F\n\n#c\ntypedef enum CUmemhostalloc_option_enum {\n CU_MEMHOSTALLOC_OPTION_PORTABLE = CU_MEMHOSTALLOC_PORTABLE,\n CU_MEMHOSTALLOC_OPTION_DEVICE_MAPPED = CU_MEMHOSTALLOC_DEVICEMAP,\n CU_MEMHOSTALLOC_OPTION_WRITE_COMBINED = CU_MEMHOSTALLOC_WRITECOMBINED\n} CUmemhostalloc_option;\n#endc\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A reference to memory allocated on the device\n--\nnewtype DevicePtr a = DevicePtr { useDevicePtr :: {# type CUdeviceptr #}}\n\ninstance Storable (DevicePtr a) where\n sizeOf _ = sizeOf (undefined :: {# type CUdeviceptr #})\n alignment _ = alignment (undefined :: {# type CUdeviceptr #})\n peek p = DevicePtr `fmap` peek (castPtr p)\n poke p v = poke (castPtr p) (useDevicePtr v)\n\n\n-- |\n-- A reference to memory on the host that is page-locked and directly-accessible\n-- from the device. Since the memory can be accessed directly, it can be read or\n-- written at a much higher bandwidth than pageable memory from the traditional\n-- malloc.\n--\n-- The driver automatically accelerates calls to functions such as `memcpy'\n-- which reference page-locked memory.\n--\nnewtype HostPtr a = HostPtr { useHostPtr :: Ptr a }\n\n-- |\n-- Unwrap a host pointer and execute a computation using the base pointer object\n--\nwithHostPtr :: HostPtr a -> (Ptr a -> IO b) -> IO b\nwithHostPtr p f = f (useHostPtr p)\n\n-- |\n-- Options for host allocation\n--\n{# enum CUmemhostalloc_option as AllocFlag\n { underscoreToCase }\n with prefix=\"CU_MEMHOSTALLOC_OPTION\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------------------\n-- Host Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a section of linear memory on the host which is page-locked and\n-- directly accessible from the device. The storage is sufficient to hold the\n-- given number of elements of a storable type.\n--\n-- Note that since the amount of pageable memory is thusly reduced, overall\n-- system performance may suffer. This is best used sparingly to allocate\n-- staging areas for data exchange.\n--\nmallocHostArray :: Storable a => [AllocFlag] -> Int -> IO (HostPtr a)\nmallocHostArray flags = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (HostPtr a')\n doMalloc x n = resultIfOk =<< cuMemHostAlloc (n * sizeOf x) flags\n\n{# fun unsafe cuMemHostAlloc\n { alloca'- `HostPtr a' peekHP*\n , `Int'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n peekHP p = (HostPtr . castPtr) `fmap` peek p\n\n\n-- |\n-- Free a section of page-locked host memory\n--\nfreeHost :: HostPtr a -> IO ()\nfreeHost p = nothingIfOk =<< cuMemFreeHost p\n\n{# fun unsafe cuMemFreeHost\n { useHP `HostPtr a' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n--------------------------------------------------------------------------------\n-- Device Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a section of linear memory on the device, and return a reference to\n-- it. The memory is sufficient to hold the given number of elements of storable\n-- type. It is suitably aligned for any type, and is not cleared.\n--\nmallocArray :: Storable a => Int -> IO (DevicePtr a)\nmallocArray = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')\n doMalloc x n = resultIfOk =<< cuMemAlloc (n * sizeOf x)\n\n{# fun unsafe cuMemAlloc\n { alloca'- `DevicePtr a' peekDP*\n , `Int' } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n peekDP = liftM DevicePtr . peek\n\n\n-- |\n-- Execute a computation on the device, passing a pointer to a temporarily\n-- allocated block of memory sufficient to hold the given number of elements of\n-- storable type. The memory is freed when the computation terminates (normally\n-- or via an exception), so the pointer must not be used after this.\n--\n-- Note that kernel launches can be asynchronous, so you may want to add a\n-- synchronisation point using 'sync' as part of the computation.\n--\nallocaArray :: Storable a => Int -> (DevicePtr a -> IO b) -> IO b\nallocaArray n = bracket (mallocArray n) free\n\n\n-- |\n-- Release a section of device memory\n--\nfree :: DevicePtr a -> IO ()\nfree dp = nothingIfOk =<< cuMemFree dp\n\n{# fun unsafe cuMemFree\n { useDevicePtr `DevicePtr a' } -> `Status' cToEnum #}\n\n-- |\n-- The constant 'nullDevPtr' contains the distinguished memory location that is\n-- not associated with a valid memory location\n--\nnullDevPtr :: DevicePtr a\nnullDevPtr = DevicePtr 0\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Copy a number of elements from the device to host memory. This is a\n-- synchronous operation\n--\npeekArray :: Storable a => Int -> DevicePtr a -> Ptr a -> IO ()\npeekArray n dptr hptr = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ = nothingIfOk =<< cuMemcpyDtoH hptr dptr (n * sizeOf x)\n\n{# fun unsafe cuMemcpyDtoH\n { castPtr `Ptr a'\n , useDevicePtr `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy memory from the device asynchronously, possibly associated with a\n-- particular stream. The destination host memory must be page-locked.\n--\npeekArrayAsync :: Storable a => Int -> DevicePtr a -> HostPtr a -> Maybe Stream -> IO ()\npeekArrayAsync n dptr hptr mst = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ =\n nothingIfOk =<< case mst of\n Nothing -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) (Stream nullPtr)\n Just st -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) st\n\n{# fun unsafe cuMemcpyDtoHAsync\n { useHP `HostPtr a'\n , useDevicePtr `DevicePtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Copy a number of elements from the device into a new Haskell list. Note that\n-- this requires two memory copies: firstly from the device into a heap\n-- allocated array, and from there marshalled into a list.\n--\npeekListArray :: Storable a => Int -> DevicePtr a -> IO [a]\npeekListArray n dptr =\n F.allocaArray n $ \\p -> do\n peekArray n dptr p\n F.peekArray n p\n\n\n-- |\n-- Copy a number of elements onto the device. This is a synchronous operation\n--\npokeArray :: Storable a => Int -> Ptr a -> DevicePtr a -> IO ()\npokeArray n hptr dptr = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPoke x _ = nothingIfOk =<< cuMemcpyHtoD dptr hptr (n * sizeOf x)\n\n{# fun unsafe cuMemcpyHtoD\n { useDevicePtr `DevicePtr a'\n , castPtr `Ptr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy memory onto the device asynchronously, possibly associated with a\n-- particular stream. The source host memory must be page-locked.\n--\npokeArrayAsync :: Storable a => Int -> HostPtr a -> DevicePtr a -> Maybe Stream -> IO ()\npokeArrayAsync n hptr dptr mst = dopoke undefined dptr\n where\n dopoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n dopoke x _ =\n nothingIfOk =<< case mst of\n Nothing -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) (Stream nullPtr)\n Just st -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) st\n\n{# fun unsafe cuMemcpyHtoDAsync\n { useDevicePtr `DevicePtr a'\n , useHP `HostPtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Write a list of storable elements into a device array. The device array must\n-- be sufficiently large to hold the entire list. This requires two marshalling\n-- operations.\n--\npokeListArray :: Storable a => [a] -> DevicePtr a -> IO ()\npokeListArray xs dptr = F.withArrayLen xs $ \\len p -> pokeArray len p dptr\n\n\n-- |\n-- Copy the given number of elements from the first device array (source) to the\n-- second (destination). The copied areas may not overlap. This operation is\n-- asynchronous with respect to the host, but will never overlap with kernel\n-- execution.\n--\ncopyArrayAsync :: Storable a => Int -> DevicePtr a -> DevicePtr a -> IO ()\ncopyArrayAsync n = docopy undefined\n where\n docopy :: Storable a' => a' -> DevicePtr a' -> DevicePtr a' -> IO ()\n docopy x src dst = nothingIfOk =<< cuMemcpyDtoD dst src (n * sizeOf x)\n\n{# fun unsafe cuMemcpyDtoD\n { useDevicePtr `DevicePtr a'\n , useDevicePtr `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Combined Allocation and Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Write a list of storable elements into a newly allocated device array. Note\n-- that this requires two memory copies: firstly from a Haskell list to a heap\n-- allocated array, and from there onto the graphics device. The memory should\n-- be 'free'd when no longer required.\n--\nnewListArray :: Storable a => [a] -> IO (DevicePtr a)\nnewListArray xs =\n F.withArrayLen xs $ \\len p ->\n bracketOnError (mallocArray len) free $ \\d_xs -> do\n pokeArray len p d_xs\n return d_xs\n\n\n-- |\n-- Temporarily store a list of elements into a newly allocated device array. An\n-- IO action is applied to to the array, the result of which is returned.\n-- Similar to 'newListArray', this requires copying the data twice.\n--\n-- As with 'allocaArray', the memory is freed once the action completes, so you\n-- should not return the pointer from the action, and be wary of asynchronous\n-- kernel execution.\n--\nwithListArray :: Storable a => [a] -> (DevicePtr a -> IO b) -> IO b\nwithListArray xs = withListArrayLen xs . const\n\n\n-- |\n-- A variant of 'withListArray' which also supplies the number of elements in\n-- the array to the applied function\n--\nwithListArrayLen :: Storable a => [a] -> (Int -> DevicePtr a -> IO b) -> IO b\nwithListArrayLen xs f =\n allocaArray len $ \\d_xs -> do\n F.allocaArray len $ \\h_xs -> do\n F.pokeArray h_xs xs\n pokeArray len h_xs d_xs\n f len d_xs\n where\n len = length xs\n\n\n--------------------------------------------------------------------------------\n-- Utility\n--------------------------------------------------------------------------------\n\n-- |\n-- Set a number of data elements to the specified value, which may be either 8-,\n-- 16-, or 32-bits wide.\n--\nmemset :: Storable a => DevicePtr a -> Int -> a -> IO ()\nmemset dptr n val = case sizeOf val of\n 1 -> nothingIfOk =<< cuMemsetD8 dptr val n\n 2 -> nothingIfOk =<< cuMemsetD16 dptr val n\n 4 -> nothingIfOk =<< cuMemsetD32 dptr val n\n _ -> cudaError \"can only memset 8-, 16-, and 32-bit values\"\n\n--\n-- We use unsafe coerce below to reinterpret the bits of the value to memset as,\n-- into the integer type required by the setting functions.\n--\n{# fun unsafe cuMemsetD8\n { useDevicePtr `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuMemsetD16\n { useDevicePtr `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuMemsetD32\n { useDevicePtr `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the device pointer associated with a mapped, pinned host buffer, which\n-- was allocated with the 'DeviceMapped' option by 'mallocHostArray'.\n--\n-- Currently, no options are supported and this must be empty.\n--\ngetDevicePtr :: [AllocFlag] -> HostPtr a -> IO (DevicePtr a)\ngetDevicePtr flags hp = resultIfOk =<< cuMemHostGetDevicePointer hp flags\n\n{# fun unsafe cuMemHostGetDevicePointer\n { alloca'- `DevicePtr a' peekDP*\n , useHP `HostPtr a'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n useHP = castPtr . useHostPtr\n peekDP = liftM DevicePtr . peek\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Marshal\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Memory management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Marshal\n (\n -- * Host Allocation\n HostPtr(..), AllocFlag(..),\n withHostPtr, mallocHostArray, freeHost,\n\n -- * Device Allocation\n DevicePtr,\n mallocArray, allocaArray, free,\n\n -- * Marshalling\n peekArray, peekArrayAsync, peekListArray,\n pokeArray, pokeArrayAsync, pokeListArray,\n copyArrayAsync,\n\n -- * Combined Allocation and Marshalling\n newListArray, withListArray, withListArrayLen,\n\n -- * Utility\n memset, getDevicePtr\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Stream (Stream(..))\n\n-- System\nimport Unsafe.Coerce\nimport Control.Monad (liftM)\nimport Control.Exception.Extensible\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.Storable\nimport qualified Foreign.Marshal as F\n\n#c\ntypedef enum CUmemhostalloc_option_enum {\n CU_MEMHOSTALLOC_OPTION_PORTABLE = CU_MEMHOSTALLOC_PORTABLE,\n CU_MEMHOSTALLOC_OPTION_DEVICE_MAPPED = CU_MEMHOSTALLOC_DEVICEMAP,\n CU_MEMHOSTALLOC_OPTION_WRITE_COMBINED = CU_MEMHOSTALLOC_WRITECOMBINED\n} CUmemhostalloc_option;\n#endc\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A reference to memory allocated on the device\n--\nnewtype DevicePtr a = DevicePtr { useDevicePtr :: {# type CUdeviceptr #}}\n\ninstance Storable (DevicePtr a) where\n sizeOf _ = sizeOf (undefined :: {# type CUdeviceptr #})\n alignment _ = alignment (undefined :: {# type CUdeviceptr #})\n peek p = DevicePtr `fmap` peek (castPtr p)\n poke p v = poke (castPtr p) (useDevicePtr v)\n\n\n-- |\n-- A reference to memory on the host that is page-locked and directly-accessible\n-- from the device. Since the memory can be accessed directly, it can be read or\n-- written at a much higher bandwidth than pageable memory from the traditional\n-- malloc.\n--\n-- The driver automatically accelerates calls to functions such as `memcpy'\n-- which reference page-locked memory.\n--\nnewtype HostPtr a = HostPtr { useHostPtr :: Ptr a }\n\n-- |\n-- Unwrap a host pointer and execute a computation using the base pointer object\n--\nwithHostPtr :: HostPtr a -> (Ptr a -> IO b) -> IO b\nwithHostPtr p f = f (useHostPtr p)\n\n-- |\n-- Options for host allocation\n--\n{# enum CUmemhostalloc_option as AllocFlag\n { underscoreToCase }\n with prefix=\"CU_MEMHOSTALLOC_OPTION\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------------------\n-- Host Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a section of linear memory on the host which is page-locked and\n-- directly accessible from the device. The storage is sufficient to hold the\n-- given number of elements of a storable type.\n--\n-- Note that since the amount of pageable memory is thusly reduced, overall\n-- system performance may suffer. This is best used sparingly to allocate\n-- staging areas for data exchange.\n--\nmallocHostArray :: Storable a => [AllocFlag] -> Int -> IO (HostPtr a)\nmallocHostArray flags = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (HostPtr a')\n doMalloc x n = resultIfOk =<< cuMemHostAlloc (n * sizeOf x) flags\n\n{# fun unsafe cuMemHostAlloc\n { alloca'- `HostPtr a' peekHP*\n , `Int'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n peekHP p = (HostPtr . castPtr) `fmap` peek p\n\n\n-- |\n-- Free a section of page-locked host memory\n--\nfreeHost :: HostPtr a -> IO ()\nfreeHost p = nothingIfOk =<< cuMemFreeHost p\n\n{# fun unsafe cuMemFreeHost\n { useHP `HostPtr a' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n--------------------------------------------------------------------------------\n-- Device Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a section of linear memory on the device, and return a reference to\n-- it. The memory is sufficient to hold the given number of elements of storable\n-- type. It is suitably aligned for any type, and is not cleared.\n--\nmallocArray :: Storable a => Int -> IO (DevicePtr a)\nmallocArray = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')\n doMalloc x n = resultIfOk =<< cuMemAlloc (n * sizeOf x)\n\n{# fun unsafe cuMemAlloc\n { alloca'- `DevicePtr a' peekDP*\n , `Int' } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n peekDP = liftM DevicePtr . peek\n\n\n-- |\n-- Execute a computation on the device, passing a pointer to a temporarily\n-- allocated block of memory sufficient to hold the given number of elements of\n-- storable type. The memory is freed when the computation terminates (normally\n-- or via an exception), so the pointer must not be used after this.\n--\n-- Note that kernel launches can be asynchronous, so you may want to add a\n-- synchronisation point using 'sync' as part of the computation.\n--\nallocaArray :: Storable a => Int -> (DevicePtr a -> IO b) -> IO b\nallocaArray n = bracket (mallocArray n) free\n\n\n-- |\n-- Release a section of device memory\n--\nfree :: DevicePtr a -> IO ()\nfree dp = nothingIfOk =<< cuMemFree dp\n\n{# fun unsafe cuMemFree\n { useDevicePtr `DevicePtr a' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Copy a number of elements from the device to host memory. This is a\n-- synchronous operation\n--\npeekArray :: Storable a => Int -> DevicePtr a -> Ptr a -> IO ()\npeekArray n dptr hptr = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ = nothingIfOk =<< cuMemcpyDtoH hptr dptr (n * sizeOf x)\n\n{# fun unsafe cuMemcpyDtoH\n { castPtr `Ptr a'\n , useDevicePtr `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy memory from the device asynchronously, possibly associated with a\n-- particular stream. The destination host memory must be page-locked.\n--\npeekArrayAsync :: Storable a => Int -> DevicePtr a -> HostPtr a -> Maybe Stream -> IO ()\npeekArrayAsync n dptr hptr mst = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ =\n nothingIfOk =<< case mst of\n Nothing -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) (Stream nullPtr)\n Just st -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) st\n\n{# fun unsafe cuMemcpyDtoHAsync\n { useHP `HostPtr a'\n , useDevicePtr `DevicePtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Copy a number of elements from the device into a new Haskell list. Note that\n-- this requires two memory copies: firstly from the device into a heap\n-- allocated array, and from there marshalled into a list.\n--\npeekListArray :: Storable a => Int -> DevicePtr a -> IO [a]\npeekListArray n dptr =\n F.allocaArray n $ \\p -> do\n peekArray n dptr p\n F.peekArray n p\n\n\n-- |\n-- Copy a number of elements onto the device. This is a synchronous operation\n--\npokeArray :: Storable a => Int -> Ptr a -> DevicePtr a -> IO ()\npokeArray n hptr dptr = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPoke x _ = nothingIfOk =<< cuMemcpyHtoD dptr hptr (n * sizeOf x)\n\n{# fun unsafe cuMemcpyHtoD\n { useDevicePtr `DevicePtr a'\n , castPtr `Ptr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy memory onto the device asynchronously, possibly associated with a\n-- particular stream. The source host memory must be page-locked.\n--\npokeArrayAsync :: Storable a => Int -> HostPtr a -> DevicePtr a -> Maybe Stream -> IO ()\npokeArrayAsync n hptr dptr mst = dopoke undefined dptr\n where\n dopoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n dopoke x _ =\n nothingIfOk =<< case mst of\n Nothing -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) (Stream nullPtr)\n Just st -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) st\n\n{# fun unsafe cuMemcpyHtoDAsync\n { useDevicePtr `DevicePtr a'\n , useHP `HostPtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Write a list of storable elements into a device array. The device array must\n-- be sufficiently large to hold the entire list. This requires two marshalling\n-- operations.\n--\npokeListArray :: Storable a => [a] -> DevicePtr a -> IO ()\npokeListArray xs dptr = F.withArrayLen xs $ \\len p -> pokeArray len p dptr\n\n\n-- |\n-- Copy the given number of elements from the first device array (source) to the\n-- second (destination). The copied areas may not overlap. This operation is\n-- asynchronous with respect to the host, but will never overlap with kernel\n-- execution.\n--\ncopyArrayAsync :: Storable a => Int -> DevicePtr a -> DevicePtr a -> IO ()\ncopyArrayAsync n = docopy undefined\n where\n docopy :: Storable a' => a' -> DevicePtr a' -> DevicePtr a' -> IO ()\n docopy x src dst = nothingIfOk =<< cuMemcpyDtoD dst src (n * sizeOf x)\n\n{# fun unsafe cuMemcpyDtoD\n { useDevicePtr `DevicePtr a'\n , useDevicePtr `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Combined Allocation and Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Write a list of storable elements into a newly allocated device array. Note\n-- that this requires two memory copies: firstly from a Haskell list to a heap\n-- allocated array, and from there onto the graphics device. The memory should\n-- be 'free'd when no longer required.\n--\nnewListArray :: Storable a => [a] -> IO (DevicePtr a)\nnewListArray xs =\n F.withArrayLen xs $ \\len p ->\n bracketOnError (mallocArray len) free $ \\d_xs -> do\n pokeArray len p d_xs\n return d_xs\n\n\n-- |\n-- Temporarily store a list of elements into a newly allocated device array. An\n-- IO action is applied to to the array, the result of which is returned.\n-- Similar to 'newListArray', this requires copying the data twice.\n--\n-- As with 'allocaArray', the memory is freed once the action completes, so you\n-- should not return the pointer from the action, and be wary of asynchronous\n-- kernel execution.\n--\nwithListArray :: Storable a => [a] -> (DevicePtr a -> IO b) -> IO b\nwithListArray xs = withListArrayLen xs . const\n\n\n-- |\n-- A variant of 'withListArray' which also supplies the number of elements in\n-- the array to the applied function\n--\nwithListArrayLen :: Storable a => [a] -> (Int -> DevicePtr a -> IO b) -> IO b\nwithListArrayLen xs f =\n allocaArray len $ \\d_xs -> do\n F.allocaArray len $ \\h_xs -> do\n F.pokeArray h_xs xs\n pokeArray len h_xs d_xs\n f len d_xs\n where\n len = length xs\n\n\n--------------------------------------------------------------------------------\n-- Utility\n--------------------------------------------------------------------------------\n\n-- |\n-- Set a number of data elements to the specified value, which may be either 8-,\n-- 16-, or 32-bits wide.\n--\nmemset :: Storable a => DevicePtr a -> Int -> a -> IO ()\nmemset dptr n val = case sizeOf val of\n 1 -> nothingIfOk =<< cuMemsetD8 dptr val n\n 2 -> nothingIfOk =<< cuMemsetD16 dptr val n\n 4 -> nothingIfOk =<< cuMemsetD32 dptr val n\n _ -> cudaError \"can only memset 8-, 16-, and 32-bit values\"\n\n--\n-- We use unsafe coerce below to reinterpret the bits of the value to memset as,\n-- into the integer type required by the setting functions.\n--\n{# fun unsafe cuMemsetD8\n { useDevicePtr `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuMemsetD16\n { useDevicePtr `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuMemsetD32\n { useDevicePtr `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the device pointer associated with a mapped, pinned host buffer, which\n-- was allocated with the 'DeviceMapped' option by 'mallocHostArray'.\n--\n-- Currently, no options are supported and this must be empty.\n--\ngetDevicePtr :: [AllocFlag] -> HostPtr a -> IO (DevicePtr a)\ngetDevicePtr flags hp = resultIfOk =<< cuMemHostGetDevicePointer hp flags\n\n{# fun unsafe cuMemHostGetDevicePointer\n { alloca'- `DevicePtr a' peekDP*\n , useHP `HostPtr a'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n useHP = castPtr . useHostPtr\n peekDP = liftM DevicePtr . peek\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"6d8a621a3dfa22e1a108fe03df745f3af2f7265e","subject":"gstreamer: M.S.G.Core.Clock: a few small doc fixes","message":"gstreamer: M.S.G.Core.Clock: a few small doc fixes\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Clock.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Clock.chs","new_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gstreamer -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GStreamer, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GStreamer documentation.\n-- \n-- |\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\n-- \n-- Abstract class of global clocks.\nmodule Media.Streaming.GStreamer.Core.Clock (\n \n-- * Detail\n -- | GStreamer uses a global clock to synchronize the plugins in a\n -- pipeline. Different clock implementations are possible by\n -- implementing this abstract base class.\n -- \n -- The 'Clock' returns a monotonically increasing time with the\n -- method 'clockGetTime'. Its accuracy and base time depend\n -- on the specific clock implementation but time is always\n -- expressed in nanoseconds. Since the baseline of the clock is\n -- undefined, the clock time returned is not meaningful in itself,\n -- what matters are the deltas between two clock times. The time\n -- returned by a clock is called the absolute time.\n -- \n -- The pipeline uses the clock to calculate the stream\n -- time. Usually all renderers synchronize to the global clock\n -- using the buffer timestamps, the newsegment events and the\n -- element's base time, see GstPipeline.\n -- \n -- A clock implementation can support periodic and single shot\n -- clock notifications both synchronous and asynchronous.\n -- \n -- One first needs to create a 'ClockID' for the periodic or\n -- single shot notification using 'clockNewSingleShotID' or\n -- 'clockNewPeriodicID'.\n -- \n -- To perform a blocking wait for the specific time of the\n -- 'ClockID' use 'clockIDWait'. This calls can be interrupted with\n -- the 'clockIDUnschedule' call. If the blocking wait is\n -- unscheduled a return value of 'ClockUnscheduled' is returned.\n -- \n -- Periodic callbacks scheduled async will be repeadedly called\n -- automatically until it is unscheduled. To schedule a sync\n -- periodic callback, 'clockIDWait' should be called repeatedly.\n -- \n -- The async callbacks can happen from any thread, either provided\n -- by the core or from a streaming thread. The application should\n -- be prepared for this.\n -- \n -- A 'ClockID' that has been unscheduled cannot be used again for\n -- any wait operation; a new 'ClockID' should be created.\n -- \n -- It is possible to perform a blocking wait on the same 'ClockID'\n -- from multiple threads. However, registering the same 'ClockID'\n -- for multiple async notifications is not possible, the callback\n -- will only be called for the thread registering the entry last.\n -- \n -- These clock operations do not operate on the stream time, so\n -- the callbacks will also occur when not in the playing state as\n -- if the clock just keeps on running. Some clocks however do not\n -- progress when the element that provided the clock is not\n -- playing.\n -- \n -- When a clock has the 'ClockFlagCanSetMaster' flag set, it can\n -- be slaved to another 'Clock' with 'clockSetMaster'. The clock\n -- will then automatically be synchronized to this master clock by\n -- repeatedly sampling the master clock and the slave clock and\n -- recalibrating the slave clock with 'clockSetCalibration'. This\n -- feature is mostly useful for plugins that have an internal\n -- clock but must operate with another clock selected by the\n -- GstPipeline. They can track the offset and rate difference of\n -- their internal clock relative to the master clock by using the\n -- 'clockGetCalibration' function.\n -- \n -- The master\\\/slave synchronisation can be tuned with the\n -- the 'clockTimeout', 'clockWindowSize' and 'clockWindowThreshold' properties.\n -- The 'clockTimeout' property defines the interval to\n -- sample the master clock and run the calibration\n -- functions. 'clockWindowSize' defines the number of samples to\n -- use when calibrating and 'clockWindowThreshold' defines the\n -- minimum number of samples before the calibration is performed.\n\n-- * Types\n Clock,\n ClockClass,\n castToClock,\n toClock,\n \n -- | A time value measured in nanoseconds.\n ClockTime,\n \n -- | The 'ClockTime' value representing an invalid time.\n clockTimeNone,\n clockTimeIsValid,\n \n -- | The 'ClockTime' value representing 1 second, i.e. 1e9.\n second,\n -- | The 'ClockTime' value representing 1 millisecond, i.e. 1e6.\n msecond,\n -- | The 'ClockTime' value representing 1 microsecond, i.e. 1e3.\n usecond,\n -- | The 'ClockTime' value representing 1 nanosecond, i.e. 1.\n nsecond,\n -- | A value holding the difference between two 'ClockTime's.\n ClockTimeDiff,\n -- | An opaque identifier for a timer event.\n ClockID,\n -- | An enumeration type returned by 'clockIDWait'.\n ClockReturn(..),\n -- | The flags a 'Clock' may have.\n ClockFlags(..),\n clockGetFlags,\n clockSetFlags,\n clockUnsetFlags,\n\n-- * Clock Operations \n clockAddObservation,\n clockSetMaster,\n clockGetMaster,\n clockSetResolution,\n clockGetResolution,\n clockGetTime,\n clockNewSingleShotID,\n clockNewPeriodicID,\n clockGetInternalTime,\n clockGetCalibration,\n clockSetCalibration,\n clockIDGetTime,\n clockIDWait,\n clockIDUnschedule,\n \n-- * Clock Properties\n clockTimeout,\n clockWindowSize,\n clockWindowThreshold\n \n ) where\n\nimport Data.Ratio ( Ratio\n , (%)\n , numerator\n , denominator )\nimport Control.Monad ( liftM\n , liftM4)\n{#import Media.Streaming.GStreamer.Core.Types#}\nimport System.Glib.FFI\nimport System.Glib.Attributes ( Attr\n , newAttr )\nimport System.Glib.Properties\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\n-- | Get the flags set on the clock.\nclockGetFlags :: ClockClass clockT\n => clockT -- ^ @clock@\n -> IO [ClockFlags] -- ^ the flags currently set on the clock\nclockGetFlags = mkObjectGetFlags\n\n-- | Set the given flags on the clock.\nclockSetFlags :: ClockClass clockT\n => clockT -- ^ @clock@\n -> [ClockFlags] -- ^ @flags@ - the flags to be set\n -> IO ()\nclockSetFlags = mkObjectSetFlags\n\n-- | Unset the given flags on the clock.\nclockUnsetFlags :: ClockClass clockT\n => clockT -- ^ @clock@\n -> [ClockFlags] -- ^ @flags@ - the flags to be unset\n -> IO ()\nclockUnsetFlags = mkObjectUnsetFlags\n\n-- | Returns 'True' if the given 'ClockTime' is valid, and 'False'\n-- otherwise.\nclockTimeIsValid :: ClockTime -- ^ @clockTime@\n -> Bool -- ^ 'True' if @clockTime@ is valid, 'False' otherwise\nclockTimeIsValid = (\/= clockTimeNone)\n\n-- | The time master of the master clock and the time slave of the\n-- slave clock are added to the list of observations. If enough\n-- observations are available, a linear regression algorithm is run\n-- on the observations and clock is recalibrated.\n-- \n-- If a calibration is performed, the correlation coefficient of the\n-- interpolation will be returned. A value of 1.0 means the clocks\n-- are in perfect sync. This value can be used to control the\n-- sampling frequency of the master and slave clocks.\nclockAddObservation :: ClockClass clock\n => clock\n -> ClockTime\n -> ClockTime\n -> IO (Maybe Double)\nclockAddObservation clock slave master =\n alloca $ \\rSquaredPtr ->\n do success <- {# call clock_add_observation #} (toClock clock)\n (fromIntegral slave)\n (fromIntegral master)\n rSquaredPtr\n if toBool success\n then liftM (Just . realToFrac) $ peek rSquaredPtr\n else return Nothing\n\n-- | Set @master@ as the master clock for @clock@. The @clock@ will\n-- automatically be calibrated so that 'clockGetTime' reports the\n-- same time as the @master@ clock.\n-- \n-- A clock provider that slaves its clock to a master can get the\n-- current calibration values with 'clockGetCalibration'.\n-- \n-- The @master@ clock can be 'Nothing' in which case @clock@ will\n-- not be slaved any longer. It will, however, continue to report\n-- its time adjusted using the last configured rate and time\n-- offsets.\n-- \n-- Note that if @clock@ does not have the 'ClockFlagCanSetMaster'\n-- flag set, this function will not succeed and return 'False'.\nclockSetMaster :: (ClockClass clock, ClockClass master)\n => clock -- ^ @clock@\n -> Maybe master -- ^ @master@\n -> IO Bool -- ^ 'True' if @clock@ is capable of\n -- being slaved to the @master@ clock, otherwise 'False'\nclockSetMaster clock master =\n withObject (toClock clock) $ \\clockPtr ->\n maybeWith withObject (liftM toClock $ master) $ \\masterPtr ->\n liftM toBool $ gst_clock_set_master clockPtr masterPtr\n where\n _ = {# call clock_set_master #}\n\n-- | Return the master that @clock@ is slaved to, or 'Nothing' if\n-- @clock@ is not slaved.\nclockGetMaster :: ClockClass clock\n => clock -- ^ @clock@\n -> IO (Maybe Clock) -- ^ the master that @clock@ is slaved to, or 'Nothing'\nclockGetMaster clock =\n {# call clock_get_master #} (toClock clock) >>= maybePeek takeObject\n\n-- | Set the resolution of @clock@. Some clocks have the possibility\n-- to operate with different resolution at the expense of more\n-- resource usage. There is normally no need to change the default\n-- resolution of a clock. The resolution of a clock can only be\n-- changed if the clock has the 'ClockFlagCanSetResolution' flag\n-- set.\nclockSetResolution :: ClockClass clock\n => clock\n -> ClockTime\n -> IO ClockTime\nclockSetResolution clock resolution =\n liftM fromIntegral $\n {# call clock_set_resolution #} (toClock clock)\n (fromIntegral resolution)\n\n-- | Get the resolution of the @clock@. The resolution of the clock is\n-- the granularity of the values returned by 'clockGetTime'.\nclockGetResolution :: ClockClass clock\n => clock -- ^ @clock@\n -> IO ClockTime -- ^ the resolution currently set in @clock@\nclockGetResolution clock =\n liftM fromIntegral $\n {# call clock_get_resolution #} (toClock clock)\n\n-- | Gets the current time of @clock@. The time is always\n-- monotonically increasing and adjusted according to the current\n-- offset and rate.\nclockGetTime :: ClockClass clock\n => clock -- ^ @clock@\n -> IO ClockTime -- ^ the current time in @clock@\nclockGetTime clock =\n liftM fromIntegral $\n {# call clock_get_time #} (toClock clock)\n\n-- | Get a 'ClockID' from @clock@ to trigger a single shot\n-- notification at the requested time.\nclockNewSingleShotID :: ClockClass clock\n => clock -- ^ @clock@\n -> ClockTime -- ^ @clockTime@\n -> IO ClockID -- ^ a single shot notification id triggered at @clockTime@\nclockNewSingleShotID clock time =\n {# call clock_new_single_shot_id #} (toClock clock)\n (fromIntegral time) >>=\n takeClockID . castPtr\n\n-- | Get a 'ClockID' from @clock@ to trigger periodic\n-- notifications. The notifications will start at time @startTime@\n-- and then be fired at each @interval@ after.\nclockNewPeriodicID :: ClockClass clock\n => clock -- ^ @clock@\n -> ClockTime -- ^ @startTime@\n -> ClockTime -- ^ @interval@\n -> IO ClockID -- ^ a periodic notification id\nclockNewPeriodicID clock startTime interval =\n {# call clock_new_periodic_id #} (toClock clock)\n (fromIntegral startTime)\n (fromIntegral interval) >>=\n takeClockID . castPtr\n\n-- | Gets the current internal time of @clock@. The time is\n-- returned unadjusted in the offset and rate.\nclockGetInternalTime :: ClockClass clock\n => clock -- ^ @clock@\n -> IO ClockTime -- ^ the clock's internal time value\nclockGetInternalTime clock =\n liftM fromIntegral $\n {# call clock_get_internal_time #} (toClock clock)\n\n-- | Gets the internal rate and reference time of @clock@. See\n-- 'clockSetCalibration' for more information.\nclockGetCalibration :: ClockClass clock\n => clock -- ^ @clock@\n -> IO (ClockTime, ClockTime, Ratio ClockTime)\n -- ^ the clock's internal time, external (adjusted) time, and skew rate\nclockGetCalibration clock =\n alloca $ \\internalPtr ->\n alloca $ \\externalPtr ->\n alloca $ \\rateNumPtr ->\n alloca $ \\rateDenomPtr ->\n do {# call clock_get_calibration #} (toClock clock)\n internalPtr\n externalPtr\n rateNumPtr\n rateDenomPtr\n liftM4 (\\a b c d ->\n (fromIntegral a,\n fromIntegral b,\n fromIntegral c % fromIntegral d))\n (peek internalPtr)\n (peek externalPtr)\n (peek rateNumPtr)\n (peek rateDenomPtr)\n\n-- | Adjusts the rate and time of clock. A rate of @1 % 1@ is the\n-- normal speed of the clock. Larger values make the clock go\n-- faster.\n-- \n-- The parameters @internal@ and @external@ specifying that\n-- 'clockGetTime' should have returned @external@ when the clock had\n-- internal time @internal@. The parameter @internal@ should not be\n-- in the future; that is, it should be less than the value returned\n-- by 'clockGetInternalTime' when this function is called.\n-- \n-- Subsequent calls to 'clockGetTime' will return clock times\n-- computed as follows:\n-- \n-- > (clock_internal - internal) * rate + external\n-- \n-- Note that 'clockGetTime' always returns increasing values, so if\n-- the clock is moved backwards, 'clockGetTime' will report the\n-- previous value until the clock catches up.\nclockSetCalibration :: ClockClass clock\n => clock -- ^ @clock@\n -> ClockTime -- ^ @internal@\n -> ClockTime -- ^ @external@\n -> Ratio ClockTime -- ^ @rate@\n -> IO ()\nclockSetCalibration clock internal external rate =\n {# call clock_set_calibration #} (toClock clock)\n (fromIntegral internal)\n (fromIntegral external)\n (fromIntegral $ numerator rate)\n (fromIntegral $ denominator rate)\n\n-- | Get the time of @clockID@.\nclockIDGetTime :: ClockID -- ^ @clockID@\n -> IO ClockTime\nclockIDGetTime clockID =\n liftM fromIntegral $ withClockID clockID $\n {# call clock_id_get_time #} . castPtr\n\n-- | Perform a blocking wait on @clockID@. The parameter @clockID@\n-- should have been created with 'clockNewSingleShotID' or\n-- 'clockNewPeriodicID', and should not been unscheduled with a call\n-- to 'clockIDUnschedule'.\n-- \n-- If second value in the returned pair is not 'Nothing', it will\n-- contain the difference against the clock and the time of\n-- @clockID@ when this method was called. Positive values indicate\n-- how late @clockID@ was relative to the clock. Negative values\n-- indicate how much time was spend waiting on the clock before the\n-- function returned.\nclockIDWait :: ClockID -- ^ @clockID@\n -> IO (ClockReturn, Maybe ClockTimeDiff)\nclockIDWait clockID =\n alloca $ \\jitterPtr ->\n do result <- liftM cToEnum $ withClockID clockID $ \\clockIDPtr ->\n {# call clock_id_wait #} (castPtr clockIDPtr) jitterPtr\n jitter <- let peekJitter = liftM (Just . fromIntegral) $ peek jitterPtr\n in case result of\n ClockOk -> peekJitter\n ClockEarly -> peekJitter\n _ -> return Nothing\n return (result, jitter)\n\n-- | Cancel an outstanding request with @clockID@. After this call,\n-- @clockID@ cannot be used anymore to recieve notifications; you\n-- must create a new 'ClockID'.\nclockIDUnschedule :: ClockID -- ^ @clockID@\n -> IO ()\nclockIDUnschedule clockID =\n withClockID clockID $ {# call clock_id_unschedule #} . castPtr\n\nclockTimeout :: ClockClass clockT\n => Attr clockT ClockTime\nclockTimeout = newAttr\n (objectGetPropertyUInt64 \"timeout\")\n (objectSetPropertyUInt64 \"timeout\")\n\nclockWindowSize :: ClockClass clockT\n => Attr clockT Int\nclockWindowSize =\n newAttrFromIntProperty \"window-size\"\n\nclockWindowThreshold :: ClockClass clockT\n => Attr clockT Int\nclockWindowThreshold =\n newAttrFromIntProperty \"window-threshold\"\n","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gstreamer -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GStreamer, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GStreamer documentation.\n-- \n-- |\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\n-- \n-- Abstract class of global clocks.\nmodule Media.Streaming.GStreamer.Core.Clock (\n \n-- * Detail\n -- | GStreamer uses a global clock to synchronize the plugins in a\n -- pipeline. Different clock implementations are possible by\n -- implementing this abstract base class.\n -- \n -- The 'Clock' returns a monotonically increasing time with the\n -- method 'clockGetTime'. Its accuracy and base time depend\n -- on the specific clock implementation but time is always\n -- expressed in nanoseconds. Since the baseline of the clock is\n -- undefined, the clock time returned is not meaningful in itself,\n -- what matters are the deltas between two clock times. The time\n -- returned by a clock is called the absolute time.\n -- \n -- The pipeline uses the clock to calculate the stream\n -- time. Usually all renderers synchronize to the global clock\n -- using the buffer timestamps, the newsegment events and the\n -- element's base time, see GstPipeline.\n -- \n -- A clock implementation can support periodic and single shot\n -- clock notifications both synchronous and asynchronous.\n -- \n -- One first needs to create a 'ClockID' for the periodic or\n -- single shot notification using 'clockNewSingleShotID' or\n -- 'clockNewPeriodicID'.\n -- \n -- To perform a blocking wait for the specific time of the\n -- 'ClockID' use 'clockIDWait'. This calls can be interrupted with\n -- the 'clockIDUnschedule' call. If the blocking wait is\n -- unscheduled a return value of 'ClockUnscheduled' is returned.\n -- \n -- Periodic callbacks scheduled async will be repeadedly called\n -- automatically until it is unscheduled. To schedule a sync\n -- periodic callback, 'clockIDWait' should be called repeatedly.\n -- \n -- The async callbacks can happen from any thread, either provided\n -- by the core or from a streaming thread. The application should\n -- be prepared for this.\n -- \n -- A 'ClockID' that has been unscheduled cannot be used again for\n -- any wait operation; a new 'ClockID' should be created.\n -- \n -- It is possible to perform a blocking wait on the same 'ClockID'\n -- from multiple threads. However, registering the same 'ClockID'\n -- for multiple async notifications is not possible, the callback\n -- will only be called for the thread registering the entry last.\n -- \n -- These clock operations do not operate on the stream time, so\n -- the callbacks will also occur when not in the playing state as\n -- if the clock just keeps on running. Some clocks however do not\n -- progress when the element that provided the clock is not\n -- playing.\n -- \n -- When a clock has the 'ClockFlagCanSetMaster' flag set, it can\n -- be slaved to another 'Clock' with 'clockSetMaster'. The clock\n -- will then automatically be synchronized to this master clock by\n -- repeatedly sampling the master clock and the slave clock and\n -- recalibrating the slave clock with 'clockSetCalibration'. This\n -- feature is mostly useful for plugins that have an internal\n -- clock but must operate with another clock selected by the\n -- GstPipeline. They can track the offset and rate difference of\n -- their internal clock relative to the master clock by using the\n -- 'clockGetCalibration' function.\n -- \n -- The master\\\/slave synchronisation can be tuned with the\n -- the 'clockTimeout', 'clockWindowSize' and 'clockWindowThreshold' properties.\n -- The 'clockTimeout' property defines the interval to\n -- sample the master clock and run the calibration\n -- functions. 'clockWindowSize' defines the number of samples to\n -- use when calibrating and 'clockWindowThreshold' defines the\n -- minimum number of samples before the calibration is performed.\n\n-- * Types\n Clock,\n ClockClass,\n castToClock,\n toClock,\n \n -- | A time value measured in nanoseconds.\n ClockTime,\n \n -- | The 'ClockTime' value representing an invalid time.\n clockTimeNone,\n clockTimeIsValid,\n \n -- | The 'ClockTime' value representing 1 second, i.e. 1e9.\n second,\n -- | The 'ClockTime' value representing 1 millisecond, i.e. 1e6.\n msecond,\n -- | The 'ClockTime' value representing 1 microsecond, i.e. 1e3.\n usecond,\n -- | The 'ClockTime' value representing 1 nanosecond, i.e. 1.\n nsecond,\n -- | A value holding the difference between two 'ClockTime's.\n ClockTimeDiff,\n -- | An opaque identifier for a timer event.\n ClockID,\n -- | An enumeration type returned by 'clockIDWait'.\n ClockReturn(..),\n -- | The flags a 'Clock' may have.\n ClockFlags(..),\n clockGetFlags,\n clockSetFlags,\n clockUnsetFlags,\n\n-- * Clock Operations \n clockAddObservation,\n clockSetMaster,\n clockGetMaster,\n clockSetResolution,\n clockGetResolution,\n clockGetTime,\n clockNewSingleShotID,\n clockNewPeriodicID,\n clockGetInternalTime,\n clockGetCalibration,\n clockSetCalibration,\n clockIDGetTime,\n clockIDWait,\n clockIDUnschedule,\n \n-- * Clock Properties\n clockTimeout,\n clockWindowSize,\n clockWindowThreshold\n \n ) where\n\nimport Data.Ratio ( Ratio\n , (%)\n , numerator\n , denominator )\nimport Control.Monad ( liftM\n , liftM4)\n{#import Media.Streaming.GStreamer.Core.Types#}\nimport System.Glib.FFI\nimport System.Glib.Attributes ( Attr\n , newAttr )\nimport System.Glib.Properties\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\n-- | Gets the flags set on the clock.\nclockGetFlags :: ClockClass clockT\n => clockT -- ^ @clock@\n -> IO [ClockFlags] -- ^ the flags currently set on the clock\nclockGetFlags = mkObjectGetFlags\n\n-- | Sets the given flags on the clock.\nclockSetFlags :: ClockClass clockT\n => clockT -- ^ @clock@\n -> [ClockFlags] -- ^ @flags@ - the flags to be set\n -> IO ()\nclockSetFlags = mkObjectSetFlags\n\n-- | Unsets the given flags on the clock.\nclockUnsetFlags :: ClockClass clockT\n => clockT -- ^ @clock@\n -> [ClockFlags] -- ^ @flags@ - the flags to be unset\n -> IO ()\nclockUnsetFlags = mkObjectUnsetFlags\n\n-- | Returns 'True' if the given 'ClockTime' is valid, and 'False'\n-- otherwise.\nclockTimeIsValid :: ClockTime -- ^ @clockTime@\n -> Bool -- ^ 'True' if @clockTime@ is valid, 'False' otherwise\nclockTimeIsValid = (\/= clockTimeNone)\n\n-- | The time master of the master clock and the time slave of the\n-- slave clock are added to the list of observations. If enough\n-- observations are available, a linear regression algorithm is run\n-- on the observations and clock is recalibrated.\n-- \n-- If a calibration is performed, the correlation coefficient of the\n-- interpolation will be returned. A value of 1.0 means the clocks\n-- are in perfect sync. This value can be used to control the\n-- sampling frequency of the master and slave clocks.\nclockAddObservation :: ClockClass clock\n => clock\n -> ClockTime\n -> ClockTime\n -> IO (Maybe Double)\nclockAddObservation clock slave master =\n alloca $ \\rSquaredPtr ->\n do success <- {# call clock_add_observation #} (toClock clock)\n (fromIntegral slave)\n (fromIntegral master)\n rSquaredPtr\n if toBool success\n then liftM (Just . realToFrac) $ peek rSquaredPtr\n else return Nothing\n\n-- | Set @master@ as the master clock for @clock@. The @clock@ will\n-- automatically be calibrated so that 'clockGetTime' reports the\n-- same time as the @master@ clock.\n-- \n-- A clock provider that slaves its clock to a master can get the\n-- current calibration values with 'clockGetCalibration'.\n-- \n-- The @master@ clock can be 'Nothing' in which case @clock@ will\n-- not be slaved any longer. It will, however, continue to report\n-- its time adjusted using the last configured rate and time\n-- offsets.\n-- \n-- Note that if @clock@ does not have the 'ClockFlagCanSetMaster'\n-- flag set, this function will not succeed and return 'False'.\nclockSetMaster :: (ClockClass clock, ClockClass master)\n => clock -- ^ @clock@\n -> Maybe master -- ^ @master@\n -> IO Bool -- ^ 'True' if @clock@ is capable of\n -- being slaved to the @master@ clock, otherwise 'False'\nclockSetMaster clock master =\n withObject (toClock clock) $ \\clockPtr ->\n maybeWith withObject (liftM toClock $ master) $ \\masterPtr ->\n liftM toBool $ gst_clock_set_master clockPtr masterPtr\n where\n _ = {# call clock_set_master #}\n\n-- | Return the master that @clock@ is slaved to, or 'Nothing' if\n-- @clock@ is not slaved.\nclockGetMaster :: ClockClass clock\n => clock -- ^ @clock@\n -> IO (Maybe Clock) -- ^ the master that @clock@ is slaved to, or 'Nothing'\nclockGetMaster clock =\n {# call clock_get_master #} (toClock clock) >>= maybePeek takeObject\n\n-- | Set the resolution of @clock@. Some clocks have the possibility\n-- to operate with different resolution at the expense of more\n-- resource usage. There is normally no need to change the default\n-- resolution of a clock. The resolution of a clock can only be\n-- changed if the clock has the 'ClockFlagCanSetResolution' flag\n-- set.\nclockSetResolution :: ClockClass clock\n => clock\n -> ClockTime\n -> IO ClockTime\nclockSetResolution clock resolution =\n liftM fromIntegral $\n {# call clock_set_resolution #} (toClock clock)\n (fromIntegral resolution)\n\n-- | Get the resolution of the @clock@. The resolution of the clock is\n-- the granularity of the values returned by 'clockGetTime'.\nclockGetResolution :: ClockClass clock\n => clock -- ^ @clock@\n -> IO ClockTime -- ^ the resolution currently set in @clock@\nclockGetResolution clock =\n liftM fromIntegral $\n {# call clock_get_resolution #} (toClock clock)\n\n-- | Gets the current time of @clock@. The time is always\n-- monotonically increasing and adjusted according to the current\n-- offset and rate.\nclockGetTime :: ClockClass clock\n => clock -- ^ @clock@\n -> IO ClockTime -- ^ the current time in @clock@\nclockGetTime clock =\n liftM fromIntegral $\n {# call clock_get_time #} (toClock clock)\n\n-- | Get a 'ClockID' from @clock@ to trigger a single shot\n-- notification at the requested time.\nclockNewSingleShotID :: ClockClass clock\n => clock -- ^ @clock@\n -> ClockTime -- ^ @clockTime@\n -> IO ClockID -- ^ a single shot notification id triggered at @clockTime@\nclockNewSingleShotID clock time =\n {# call clock_new_single_shot_id #} (toClock clock)\n (fromIntegral time) >>=\n takeClockID . castPtr\n\n-- | Get a 'ClockID' from @clock@ to trigger periodic\n-- notifications. The notifications will start at time @startTime@\n-- and then be fired at each @interval@ after.\nclockNewPeriodicID :: ClockClass clock\n => clock -- ^ @clock@\n -> ClockTime -- ^ @startTime@\n -> ClockTime -- ^ @interval@\n -> IO ClockID -- ^ a periodic notification id\nclockNewPeriodicID clock startTime interval =\n {# call clock_new_periodic_id #} (toClock clock)\n (fromIntegral startTime)\n (fromIntegral interval) >>=\n takeClockID . castPtr\n\n-- | Gets the current internal time of @clock@. The time is\n-- returned unadjusted in the offset and rate.\nclockGetInternalTime :: ClockClass clock\n => clock -- ^ @clock@\n -> IO ClockTime -- ^ the clock's internal time value\nclockGetInternalTime clock =\n liftM fromIntegral $\n {# call clock_get_internal_time #} (toClock clock)\n\n-- | Gets the internal rate and reference time of @clock@. See\n-- 'clockSetCalibration' for more information.\nclockGetCalibration :: ClockClass clock\n => clock -- ^ @clock@\n -> IO (ClockTime, ClockTime, Ratio ClockTime)\n -- ^ the clock's internal time, external (adjusted) time, and skew rate\nclockGetCalibration clock =\n alloca $ \\internalPtr ->\n alloca $ \\externalPtr ->\n alloca $ \\rateNumPtr ->\n alloca $ \\rateDenomPtr ->\n do {# call clock_get_calibration #} (toClock clock)\n internalPtr\n externalPtr\n rateNumPtr\n rateDenomPtr\n liftM4 (\\a b c d ->\n (fromIntegral a,\n fromIntegral b,\n fromIntegral c % fromIntegral d))\n (peek internalPtr)\n (peek externalPtr)\n (peek rateNumPtr)\n (peek rateDenomPtr)\n\n-- | Adjusts the rate and time of clock. A rate of @1 % 1@ is the\n-- normal speed of the clock. Larger values make the clock go\n-- faster.\n-- \n-- The parameters @internal@ and @external@ specifying that\n-- 'clockGetTime' should have returned @external@ when the clock had\n-- internal time @internal@. The parameter @internal@ should not be\n-- in the future; that is, it should be less than the value returned\n-- by 'clockGetInternalTime' when this function is called.\n-- \n-- Subsequent calls to 'clockGetTime' will return clock times\n-- computed as follows:\n-- \n-- > (clock_internal - internal) * rate + external\n-- \n-- Note that 'clockGetTime' always returns increasing values, so if\n-- the clock is moved backwards, 'clockGetTime' will report the\n-- previous value until the clock catches up.\nclockSetCalibration :: ClockClass clock\n => clock -- ^ @clock@\n -> ClockTime -- ^ @internal@\n -> ClockTime -- ^ @external@\n -> Ratio ClockTime -- ^ @rate@\n -> IO ()\nclockSetCalibration clock internal external rate =\n {# call clock_set_calibration #} (toClock clock)\n (fromIntegral internal)\n (fromIntegral external)\n (fromIntegral $ numerator rate)\n (fromIntegral $ denominator rate)\n\n-- | Get the time of @clockID@.\nclockIDGetTime :: ClockID -- ^ @clockID@\n -> IO ClockTime\nclockIDGetTime clockID =\n liftM fromIntegral $ withClockID clockID $\n {# call clock_id_get_time #} . castPtr\n\n-- | Perform a blocking wait on @clockID@. The parameter @clockID@\n-- should have been created with 'clockNewSingleShotID' or\n-- 'clockNewPeriodicID', and should not been unscheduled with a call\n-- to 'clockIDUnschedule'.\n-- \n-- If second value in the returned pair is not 'Nothing', it will\n-- contain the difference against the clock and the time of\n-- @clockID@ when this method was called. Positive values indicate\n-- how late @clockID@ was relative to the clock. Negative values\n-- indicate how much time was spend waiting on the clock before the\n-- function returned.\nclockIDWait :: ClockID -- ^ @clockID@\n -> IO (ClockReturn, Maybe ClockTimeDiff)\nclockIDWait clockID =\n alloca $ \\jitterPtr ->\n do result <- liftM cToEnum $ withClockID clockID $ \\clockIDPtr ->\n {# call clock_id_wait #} (castPtr clockIDPtr) jitterPtr\n jitter <- let peekJitter = liftM (Just . fromIntegral) $ peek jitterPtr\n in case result of\n ClockOk -> peekJitter\n ClockEarly -> peekJitter\n _ -> return Nothing\n return (result, jitter)\n\n-- | Cancel an outstanding request with @clockID@. After this call,\n-- @clockID@ cannot be used anymore to recieve notifications; you\n-- must create a new 'ClockID'.\nclockIDUnschedule :: ClockID -- ^ @clockID@\n -> IO ()\nclockIDUnschedule clockID =\n withClockID clockID $ {# call clock_id_unschedule #} . castPtr\n\nclockTimeout :: ClockClass clockT\n => Attr clockT ClockTime\nclockTimeout = newAttr\n (objectGetPropertyUInt64 \"timeout\")\n (objectSetPropertyUInt64 \"timeout\")\n\nclockWindowSize :: ClockClass clockT\n => Attr clockT Int\nclockWindowSize =\n newAttrFromIntProperty \"window-size\"\n\nclockWindowThreshold :: ClockClass clockT\n => Attr clockT Int\nclockWindowThreshold =\n newAttrFromIntProperty \"window-threshold\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"6718b252e8f9947b2cd3bf1de0d24abb7279e990","subject":"[project @ 2003-05-17 14:53:11 by as49] Doc fix.","message":"[project @ 2003-05-17 14:53:11 by as49]\nDoc fix.\n","repos":"vincenthz\/webkit","old_file":"gtk\/pango\/PangoLayout.chs","new_file":"gtk\/pango\/PangoLayout.chs","new_contents":"-- GIMP Toolkit (GTK) - text layout functions @entry PangoLayout@\n--\n-- Author : Axel Simon\n-- \n-- Created: 8 Feburary 2003\n--\n-- Version $Revision: 1.4 $ from $Date: 2003\/05\/17 14:53:11 $\n--\n-- Copyright (c) 1999..2003 Axel Simon\n--\n-- This file is free software; you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation; either version 2 of the License, or\n-- (at your option) any later version.\n--\n-- This file is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- * Functions to run the rendering pipeline.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * The Pango rendering pipeline takes a string of Unicode characters\n-- and converts it into glyphs. The functions described in this module\n-- accomplish various steps of this process.\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * Functions that are missing:\n-- pango_layout_set_attributes, pango_layout_get_attributes,\n-- pango_layout_set_font_description, pango_layout_set_tabs,\n-- pango_layout_get_tabs, pango_layout_get_log_attrs, \n-- pango_layout_iter_get_run\n--\n-- * The following functions cannot be bound easily due to Unicode\/UTF8 issues:\n-- pango_layout_xy_to_index, pango_layout_index_to_pos,\n-- pango_layout_get_cursor_pos, pango_layout_move_cursor_visually,\n-- pango_layout_iter_get_index, pango_layout_line_index_to_x,\n-- pango_layout_line_x_to_index, pango_layout_line_get_x_ranges\n--\n-- * These functions are not bound, because they're too easy:\n-- pango_layout_get_size, pango_layout_get_pixel_size,\n-- pango_layout_get_line \n--\nmodule PangoLayout(\n PangoLayout,\n layoutCopy,\n layoutGetContext,\n layoutContextChanged,\n layoutSetText,\n layoutGetText,\n layoutSetMarkup,\n layoutSetMarkupWithAccel,\n layoutSetWidth,\n layoutGetWidth,\n LayoutWrapMode(..),\n layoutSetWrap,\n layoutGetWrap,\n layoutSetIndent,\n layoutGetIndent,\n layoutSetSpacing,\n layoutGetSpacing,\n layoutSetJustify,\n layoutGetJustify,\n LayoutAlignment(..),\n layoutSetAlignment,\n layoutGetAlignment,\n layoutSetSingleParagraphMode,\n layoutGetSingleParagraphMode,\n layoutGetExtents,\n layoutGetPixelExtents,\n layoutGetLineCount,\n layoutGetLines,\n LayoutIter,\n layoutGetIter,\n layoutIterNextRun,\n layoutIterNextChar,\n layoutIterNextCluster,\n layoutIterNextLine,\n layoutIterAtLastLine,\n layoutIterGetBaseline,\n layoutIterGetLine,\n layoutIterGetCharExtents,\n layoutIterGetClusterExtents,\n layoutIterGetRunExtents,\n layoutIterGetLineYRange,\n layoutIterGetLineExtents,\n LayoutLine,\n layoutLineGetExtents,\n layoutLineGetPixelExtents\n ) where\n\nimport Monad (liftM)\nimport Foreign\nimport UTFCForeign\n{#import Hierarchy#}\nimport GObject (makeNewGObject)\nimport Markup\t(Markup)\nimport Char\t(ord, chr)\nimport Enums\nimport Structs\t(Rectangle)\nimport GList\t(readGSList)\n{#import PangoTypes#}\n\n{# context lib=\"pango\" prefix=\"pango\" #}\n\n-- @method layoutCopy@ Create a copy of the @ref data layout@.\n--\nlayoutCopy :: PangoLayout -> IO PangoLayout\nlayoutCopy pl = makeNewGObject mkPangoLayout \n\t\t ({#call unsafe layout_copy#} (toPangoLayout pl))\n\n-- @method layoutGetContext@ Retrieves the @ref data PangoContext@ from this\n-- layout.\n--\nlayoutGetContext :: PangoLayout -> IO PangoContext\nlayoutGetContext pl = makeNewGObject mkPangoContext\n\t\t ({#call unsafe layout_get_context#} pl)\n\n-- @method layoutContextChanged@ Signal a @ref data Context@ change.\n--\n-- * Forces recomputation of any state in the @ref data PangoLayout@ that\n-- might depend on the layout's context. This function should\n-- be called if you make changes to the context subsequent\n-- to creating the layout.\n--\nlayoutContextChanged :: PangoLayout -> IO ()\nlayoutContextChanged pl = {#call unsafe layout_context_changed#} pl\n\n-- @method layoutSetText@ Set the string in the layout.\n--\nlayoutSetText :: PangoLayout -> String -> IO ()\nlayoutSetText pl txt = withCStringLen txt $ \\(strPtr,len) ->\n {#call unsafe layout_set_text#} pl strPtr (fromIntegral len)\n\n-- @method layoutGetText@ Retrieve the string in the layout.\n--\nlayoutGetText :: PangoLayout -> IO String\nlayoutGetText pl = {#call unsafe layout_get_text#} pl >>= peekCString\n\n-- @method layoutSetMarkup@ Set the string in the layout.\n--\n-- * The string may include @ref data Markup@.\n--\nlayoutSetMarkup :: PangoLayout -> Markup -> IO ()\nlayoutSetMarkup pl txt = withCStringLen txt $ \\(strPtr,len) ->\n {#call unsafe layout_set_markup#} pl strPtr (fromIntegral len)\n\n-- @method layoutSetMarkupWithAccel@ Set the string in the layout.\n--\n-- * The string may include @ref data Markup@. Furthermore, any underscore\n-- character indicates that the next character should be\n-- marked as accelerator (i.e. underlined). A literal underscore character\n-- can be produced by placing it twice in the string.\n--\n-- * The character which follows the underscore is\n-- returned so it can be used to add the actual keyboard shortcut. \n--\nlayoutSetMarkupWithAccel :: PangoLayout -> Markup -> IO Char\nlayoutSetMarkupWithAccel pl txt =\n alloca $ \\chrPtr -> \n withCStringLen txt $ \\(strPtr,len) -> do\n {#call unsafe layout_set_markup_with_accel#} pl strPtr (fromIntegral len)\n (fromIntegral (ord '_')) chrPtr\n liftM (chr.fromIntegral) $ peek chrPtr\n\n\n-- there are a couple of functions missing here\n\n-- @method layoutSetWidth@ Set the width of this paragraph.\n--\n-- * Sets the width to which the lines of the @ref data PangoLayout@\n-- should be wrapped.\n--\n-- * @ref arg width@ is the desired width, or @literal -1@ to indicate that\n-- no wrapping should be performed.\n--\nlayoutSetWidth :: PangoLayout -> Int -> IO ()\nlayoutSetWidth pl width =\n {#call unsafe layout_set_width#} pl (fromIntegral width)\n\n-- @method layoutGetWidth@ Gets the width of this paragraph.\n--\n-- * Gets the width to which the lines of the @ref data PangoLayout@\n-- should be wrapped.\n--\n-- * Returns is the current width, or @literal -1@ to indicate that\n-- no wrapping is performed.\n--\nlayoutGetWidth :: PangoLayout -> IO Int\nlayoutGetWidth pl = liftM fromIntegral $ {#call unsafe layout_get_width#} pl\n\n\n-- @data LayoutWarpMode@ Enumerates how a line can be wrapped.\n--\n-- @variant WrapWholeWords@ Breaks lines only between words.\n--\n-- * This variant does not guarantee that the requested width is not\n-- exceeded. A word that is longer than the paragraph width is not\n-- split.\n\n-- @variant WrapAnywhere@ Break lines anywhere.\n--\n-- @variant WrapPartialWords@ Wrap within a word if it is the only one on\n-- this line.\n--\n-- * This option acts like @ref variant WrapWholeWords@ but will split\n-- a word if it is the only one on this line and it exceeds the\n-- specified width.\n--\n{#enum PangoWrapMode as LayoutWrapMode \n {underscoreToCase,\n PANGO_WRAP_WORD as WrapWholeWords,\n PANGO_WRAP_CHAR as WrapAnywhere,\n PANGO_WRAP_WORD_CHAR as WrapPartialWords}#}\n\n-- @method layoutSetWrap@ Set how this paragraph is wrapped.\n--\n-- * Sets the wrap style; the wrap style only has an effect if a width\n-- is set on the layout with @ref method layoutSetWidth@. To turn off\n-- wrapping, set the width to -1.\n--\nlayoutSetWrap :: PangoLayout -> LayoutWrapMode -> IO ()\nlayoutSetWrap pl wm =\n {#call unsafe layout_set_wrap#} pl ((fromIntegral.fromEnum) wm)\n\n\n-- @method layoutGetWrap@ Get the wrap mode for the layout.\n--\nlayoutGetWrap :: PangoLayout -> IO LayoutWrapMode\nlayoutGetWrap pl = liftM (toEnum.fromIntegral) $\n {#call unsafe layout_get_wrap#} pl\n\n-- @method layoutSetIndent@ Set the indentation of this paragraph.\n--\n-- * Sets the amount by which the first line should be shorter than\n-- the rest of the lines. This may be negative, in which case the\n-- subsequent lines will be shorter than the first line. (However, in\n-- either case, the entire width of the layout will be given by the\n-- value.\n--\nlayoutSetIndent :: PangoLayout -> Int -> IO ()\nlayoutSetIndent pl indent =\n {#call unsafe layout_set_indent#} pl (fromIntegral indent)\n\n-- @method layoutGetIndent@ Gets the indentation of this paragraph.\n--\n-- * Gets the amount by which the first line should be shorter than \n-- the rest of the lines.\n--\nlayoutGetIndent :: PangoLayout -> IO Int\nlayoutGetIndent pl = liftM fromIntegral $ {#call unsafe layout_get_indent#} pl\n\n\n-- @method layoutSetSpacing@ Set the spacing between lines of this paragraph.\n--\nlayoutSetSpacing :: PangoLayout -> Int -> IO ()\nlayoutSetSpacing pl spacing =\n {#call unsafe layout_set_spacing#} pl (fromIntegral spacing)\n\n-- @method layoutGetSpacing@ Gets the spacing between the lines.\n--\nlayoutGetSpacing :: PangoLayout -> IO Int\nlayoutGetSpacing pl = \n liftM fromIntegral $ {#call unsafe layout_get_spacing#} pl\n\n-- @method layoutSetJustify@ Set if text should be streched to fit width.\n--\n-- * Sets whether or not each complete line should be stretched to\n-- fill the entire width of the layout. This stretching is typically\n-- done by adding whitespace, but for some scripts (such as Arabic),\n-- the justification is done by extending the characters.\n--\nlayoutSetJustify :: PangoLayout -> Bool -> IO ()\nlayoutSetJustify pl j = {#call unsafe layout_set_justify#} pl (fromBool j)\n\n-- @method layoutGetJustify@ Retrieve the justification flag.\n--\n-- * See @ref method layoutSetJustify@.\n--\nlayoutGetJustify :: PangoLayout -> IO Bool\nlayoutGetJustify pl = liftM toBool $ {#call unsafe layout_get_justify#} pl\n\n-- @data LayoutAlignment@ Enumerate to which side incomplete lines are flushed.\n--\n{#enum PangoAlignment as LayoutAlignment {underscoreToCase}#}\n\n-- @method layoutSetAlignment@ Set how this paragraph is aligned.\n--\n-- * Sets the alignment for the layout (how partial lines are\n-- positioned within the horizontal space available.)\n--\nlayoutSetAlignment :: PangoLayout -> LayoutAlignment -> IO ()\nlayoutSetAlignment pl am =\n {#call unsafe layout_set_alignment#} pl ((fromIntegral.fromEnum) am)\n\n\n-- @method layoutGetAlignment@ Get the alignment for the layout.\n--\nlayoutGetAlignment :: PangoLayout -> IO LayoutAlignment\nlayoutGetAlignment pl = liftM (toEnum.fromIntegral) $\n {#call unsafe layout_get_alignment#} pl\n\n-- functions are missing here\n\n-- @method layoutSetSingleParagraphMode@ Honor newlines or not.\n--\n-- * If @ref arg honor@ is @literal True@, do not treat newlines and\n-- similar characters as paragraph separators; instead, keep all text in\n-- a single paragraph, and display a glyph for paragraph separator\n-- characters. Used when you want to allow editing of newlines on a\n-- single text line.\n--\nlayoutSetSingleParagraphMode :: PangoLayout -> Bool -> IO ()\nlayoutSetSingleParagraphMode pl honor = \n {#call unsafe layout_set_single_paragraph_mode#} pl (fromBool honor)\n\n-- @method layoutGetSingleParagraphMode@ Retrieve if newlines are honored.\n--\n-- * See @ref method layoutSetSingleParagraphMode@.\n--\nlayoutGetSingleParagraphMode :: PangoLayout -> IO Bool\nlayoutGetSingleParagraphMode pl = \n liftM toBool $ {#call unsafe layout_get_single_paragraph_mode#} pl\n\n-- a function is missing here\n\n-- @method layoutGetExtents@ Compute the physical size of the layout.\n--\n-- * Computes the logical and the ink size of the @ref data Layout@. The\n-- logical layout is used for positioning, the ink size is the smallest\n-- bounding box that includes all character pixels. The ink size can be\n-- smaller or larger that the logical layout.\n--\n-- * All values are in layout units. To get to device units (pixel for\n-- @ref data Drawable@s) divide by @ref constant pangoScale@.\n--\nlayoutGetExtents :: PangoLayout -> IO (Rectangle, Rectangle)\nlayoutGetExtents pl = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_get_extents#} pl (castPtr logPtr) (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n\n-- @method layoutGetPixelExtents@ Compute the physical size of the layout.\n--\n-- * Computes the logical and the ink size of the @ref data Layout@. The\n-- logical layout is used for positioning, the ink size is the smallest\n-- bounding box that includes all character pixels. The ink size can be\n-- smaller or larger that the logical layout.\n--\n-- * All values are in device units. This function is a wrapper around\n-- @ref method layoutGetExtents@ with scaling.\n--\nlayoutGetPixelExtents :: PangoLayout -> IO (Rectangle, Rectangle)\nlayoutGetPixelExtents pl = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_get_pixel_extents#} pl (castPtr logPtr) (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n-- @method layoutGetLineCount@ Ask for the number of lines in this layout.\n--\nlayoutGetLineCount :: PangoLayout -> IO Int\nlayoutGetLineCount pl = liftM fromIntegral $\n {#call unsafe layout_get_line_count#} pl\n\n-- @method layoutGetLines@ Extract the single lines of the layout.\n--\n-- * The lines of each layout are regenerated if any attribute changes.\n-- Thus the returned list does not reflect the current state of lines\n-- after a change has been made.\n--\nlayoutGetLines :: PangoLayout -> IO [LayoutLine]\nlayoutGetLines pl = do\n listPtr <- {#call unsafe layout_get_lines#} pl\n list <- readGSList listPtr\n mapM mkLayoutLine list\n\n-- @constructor layoutGetIter@ Create an iterator to examine a layout.\n--\nlayoutGetIter :: PangoLayout -> IO LayoutIter\nlayoutGetIter pl = do\n iterPtr <- {#call unsafe layout_get_iter#} pl\n liftM LayoutIter $ newForeignPtr iterPtr (layout_iter_free iterPtr)\n\n-- @method layoutNextRun@ Move to the next run.\n--\n-- * Returns @literal False@ if this was the last run in the layout.\n--\nlayoutIterNextRun :: LayoutIter -> IO Bool\nlayoutIterNextRun = liftM toBool . {#call unsafe layout_iter_next_run#}\n\n-- @method layoutNextChar@ Move to the next char.\n--\n-- * Returns @literal False@ if this was the last char in the layout.\n--\nlayoutIterNextChar :: LayoutIter -> IO Bool\nlayoutIterNextChar = liftM toBool . {#call unsafe layout_iter_next_char#}\n\n-- @method layoutNextCluster@ Move to the next cluster.\n--\n-- * Returns @literal False@ if this was the last cluster in the layout.\n--\nlayoutIterNextCluster :: LayoutIter -> IO Bool\nlayoutIterNextCluster = liftM toBool . {#call unsafe layout_iter_next_cluster#}\n\n-- @method layoutNextLine@ Move to the next line.\n--\n-- * Returns @literal False@ if this was the last line in the layout.\n--\nlayoutIterNextLine :: LayoutIter -> IO Bool\nlayoutIterNextLine = liftM toBool . {#call unsafe layout_iter_next_line#}\n\n-- @method layoutAtLastLine@ Check if the iterator is on the last line.\n--\n-- * Returns @literal True@ if the iterator is on the last line of this\n-- paragraph.\n--\nlayoutIterAtLastLine :: LayoutIter -> IO Bool\nlayoutIterAtLastLine = liftM toBool . {#call unsafe layout_iter_at_last_line#}\n\n-- @method layoutIterGetBaseline@ Query the vertical position within the\n-- layout.\n--\n-- * Gets the y position of the current line's baseline, in layout\n-- coordinates (origin at top left of the entire layout).\n--\nlayoutIterGetBaseline :: LayoutIter -> IO Int\nlayoutIterGetBaseline = \n liftM fromIntegral . {#call unsafe pango_layout_iter_get_baseline#}\n\n-- pango_layout_iter_get_run goes here\n\n-- @method layoutIterGetLine@ Extract the line under the iterator.\n--\nlayoutIterGetLine :: LayoutIter -> IO (Maybe LayoutLine)\nlayoutIterGetLine li = do\n llPtr <- liftM castPtr $ {#call unsafe pango_layout_iter_get_line#} li\n if (llPtr==nullPtr) then return Nothing else \n liftM Just $ mkLayoutLine llPtr\n\n-- @method layoutIterGetCharExtents@ Retrieve a rectangle surrounding\n-- a character.\n--\n-- * Get the extents of the current character in layout cooridnates\n-- (origin is the top left of the entire layout). Only logical extents\n-- can sensibly be obtained for characters. \n--\nlayoutIterGetCharExtents :: LayoutIter -> IO Rectangle\nlayoutIterGetCharExtents li = alloca $ \\logPtr -> \n {#call unsafe layout_iter_get_char_extents#} li (castPtr logPtr) >>\n peek logPtr\n\n-- @method layoutIterGetClusterExtents@ Compute the physical size of the\n-- cluster.\n--\n-- * Computes the logical and the ink size of the cluster pointed to by\n-- @ref data LayoutIter@.\n--\n-- * All values are in layoutIter units. To get to device units (pixel for\n-- @ref data Drawable@s) divide by @ref constant pangoScale@.\n--\nlayoutIterGetClusterExtents :: LayoutIter -> IO (Rectangle, Rectangle)\nlayoutIterGetClusterExtents li = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_iter_get_cluster_extents#} li (castPtr logPtr)\n (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n-- @method layoutIterGetRunExtents@ Compute the physical size of the run.\n--\n-- * Computes the logical and the ink size of the run pointed to by\n-- @ref data LayoutIter@.\n--\n-- * All values are in layoutIter units. To get to device units (pixel for\n-- @ref data Drawable@s) divide by @ref constant pangoScale@.\n--\nlayoutIterGetRunExtents :: LayoutIter -> IO (Rectangle, Rectangle)\nlayoutIterGetRunExtents li = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_iter_get_run_extents#} li (castPtr logPtr)\n (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n-- @method layoutIterGetLineYRange@ Retrieve vertical extent of this\n-- line.\n--\n-- * Divides the vertical space in the @ref data PangoLayout@ being\n-- iterated over between the lines in the layout, and returns the\n-- space belonging to the current line. A line's range includes the\n-- line's logical extents, plus half of the spacing above and below\n-- the line, if @ref method pangoLayoutSetSpacing@ has been called\n-- to set layout spacing. The y positions are in layout coordinates\n-- (origin at top left of the entire layout).\n--\n-- * The first element in the returned tuple is the start, the second is\n-- the end of this line.\n--\nlayoutIterGetLineYRange :: LayoutIter -> IO (Int,Int)\nlayoutIterGetLineYRange li = alloca $ \\sPtr -> alloca $ \\ePtr -> do\n {#call unsafe layout_iter_get_line_extents#} li (castPtr sPtr) (castPtr ePtr)\n start <- peek sPtr\n end <- peek ePtr\n return (start,end)\n\n-- @method layoutIterGetLineExtents@ Compute the physical size of the line.\n--\n-- * Computes the logical and the ink size of the line pointed to by\n-- @ref data LayoutIter@.\n--\n-- * Extents are in layout coordinates (origin is the top-left corner\n-- of the entire @ref data PangoLayout@). Thus the extents returned\n-- by this function will be the same width\/height but not at the\n-- same x\/y as the extents returned from @ref method\n-- pangoLayoutLineGetExtents@.\n--\nlayoutIterGetLineExtents :: LayoutIter -> IO (Rectangle, Rectangle)\nlayoutIterGetLineExtents li = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_iter_get_line_extents#} li (castPtr logPtr)\n (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n\n-- @method layoutLineGetExtents@ Compute the physical size of the line.\n--\n-- * Computes the logical and the ink size of the @ref data LayoutLine@. The\n-- logical layout is used for positioning, the ink size is the smallest\n-- bounding box that includes all character pixels. The ink size can be\n-- smaller or larger that the logical layout.\n--\n-- * All values are in layout units. To get to device units (pixel for\n-- @ref data Drawable@s) divide by @ref constant pangoScale@.\n--\nlayoutLineGetExtents :: LayoutLine -> IO (Rectangle, Rectangle)\nlayoutLineGetExtents pl = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_line_get_extents#} pl (castPtr logPtr) (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n-- @method layoutLineGetPixelExtents@ Compute the physical size of the line.\n--\n-- * Computes the logical and the ink size of the @ref data LayoutLine@. The\n-- logical layout is used for positioning, the ink size is the smallest\n-- bounding box that includes all character pixels. The ink size can be\n-- smaller or larger that the logical layout.\n--\n-- * All values are in device units. This function is a wrapper around\n-- @ref method layoutLineGetExtents@ with scaling.\n--\nlayoutLineGetPixelExtents :: LayoutLine -> IO (Rectangle, Rectangle)\nlayoutLineGetPixelExtents pl = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_line_get_pixel_extents#} pl\n (castPtr logPtr) (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n","old_contents":"-- GIMP Toolkit (GTK) - text layout functions @entry layout@\n--\n-- Author : Axel Simon\n-- \n-- Created: 8 Feburary 2003\n--\n-- Version $Revision: 1.3 $ from $Date: 2003\/05\/16 05:53:33 $\n--\n-- Copyright (c) 1999..2003 Axel Simon\n--\n-- This file is free software; you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation; either version 2 of the License, or\n-- (at your option) any later version.\n--\n-- This file is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- * Functions to run the rendering pipeline.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * The Pango rendering pipeline takes a string of Unicode characters\n-- and converts it into glyphs. The functions described in this module\n-- accomplish various steps of this process.\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * Functions that are missing:\n-- pango_layout_set_attributes, pango_layout_get_attributes,\n-- pango_layout_set_font_description, pango_layout_set_tabs,\n-- pango_layout_get_tabs, pango_layout_get_log_attrs, \n-- pango_layout_iter_get_run\n--\n-- * The following functions cannot be bound easily due to Unicode\/UTF8 issues:\n-- pango_layout_xy_to_index, pango_layout_index_to_pos,\n-- pango_layout_get_cursor_pos, pango_layout_move_cursor_visually,\n-- pango_layout_iter_get_index, pango_layout_line_index_to_x,\n-- pango_layout_line_x_to_index, pango_layout_line_get_x_ranges\n--\n-- * These functions are not bound, because they're too easy:\n-- pango_layout_get_size, pango_layout_get_pixel_size,\n-- pango_layout_get_line \n--\nmodule PangoLayout(\n PangoLayout,\n layoutCopy,\n layoutGetContext,\n layoutContextChanged,\n layoutSetText,\n layoutGetText,\n layoutSetMarkup,\n layoutSetMarkupWithAccel,\n layoutSetWidth,\n layoutGetWidth,\n LayoutWrapMode(..),\n layoutSetWrap,\n layoutGetWrap,\n layoutSetIndent,\n layoutGetIndent,\n layoutSetSpacing,\n layoutGetSpacing,\n layoutSetJustify,\n layoutGetJustify,\n LayoutAlignment(..),\n layoutSetAlignment,\n layoutGetAlignment,\n layoutSetSingleParagraphMode,\n layoutGetSingleParagraphMode,\n layoutGetExtents,\n layoutGetPixelExtents,\n layoutGetLineCount,\n layoutGetLines,\n LayoutIter,\n layoutGetIter,\n layoutIterNextRun,\n layoutIterNextChar,\n layoutIterNextCluster,\n layoutIterNextLine,\n layoutIterAtLastLine,\n layoutIterGetBaseline,\n layoutIterGetLine,\n layoutIterGetCharExtents,\n layoutIterGetClusterExtents,\n layoutIterGetRunExtents,\n layoutIterGetLineYRange,\n layoutIterGetLineExtents,\n LayoutLine,\n layoutLineGetExtents,\n layoutLineGetPixelExtents\n ) where\n\nimport Monad (liftM)\nimport Foreign\nimport UTFCForeign\n{#import Hierarchy#}\nimport GObject (makeNewGObject)\nimport Markup\t(Markup)\nimport Char\t(ord, chr)\nimport Enums\nimport Structs\t(Rectangle)\nimport GList\t(readGSList)\n{#import PangoTypes#}\n\n{# context lib=\"pango\" prefix=\"pango\" #}\n\n-- @method layoutCopy@ Create a copy of the @ref data layout@.\n--\nlayoutCopy :: PangoLayout -> IO PangoLayout\nlayoutCopy pl = makeNewGObject mkPangoLayout \n\t\t ({#call unsafe layout_copy#} (toPangoLayout pl))\n\n-- @method layoutGetContext@ Retrieves the @ref data PangoContext@ from this\n-- layout.\n--\nlayoutGetContext :: PangoLayout -> IO PangoContext\nlayoutGetContext pl = makeNewGObject mkPangoContext\n\t\t ({#call unsafe layout_get_context#} pl)\n\n-- @method layoutContextChanged@ Signal a @ref data Context@ change.\n--\n-- * Forces recomputation of any state in the @ref data PangoLayout@ that\n-- might depend on the layout's context. This function should\n-- be called if you make changes to the context subsequent\n-- to creating the layout.\n--\nlayoutContextChanged :: PangoLayout -> IO ()\nlayoutContextChanged pl = {#call unsafe layout_context_changed#} pl\n\n-- @method layoutSetText@ Set the string in the layout.\n--\nlayoutSetText :: PangoLayout -> String -> IO ()\nlayoutSetText pl txt = withCStringLen txt $ \\(strPtr,len) ->\n {#call unsafe layout_set_text#} pl strPtr (fromIntegral len)\n\n-- @method layoutGetText@ Retrieve the string in the layout.\n--\nlayoutGetText :: PangoLayout -> IO String\nlayoutGetText pl = {#call unsafe layout_get_text#} pl >>= peekCString\n\n-- @method layoutSetMarkup@ Set the string in the layout.\n--\n-- * The string may include @ref data Markup@.\n--\nlayoutSetMarkup :: PangoLayout -> Markup -> IO ()\nlayoutSetMarkup pl txt = withCStringLen txt $ \\(strPtr,len) ->\n {#call unsafe layout_set_markup#} pl strPtr (fromIntegral len)\n\n-- @method layoutSetMarkupWithAccel@ Set the string in the layout.\n--\n-- * The string may include @ref data Markup@. Furthermore, any underscore\n-- character indicates that the next character should be\n-- marked as accelerator (i.e. underlined). A literal underscore character\n-- can be produced by placing it twice in the string.\n--\n-- * The character which follows the underscore is\n-- returned so it can be used to add the actual keyboard shortcut. \n--\nlayoutSetMarkupWithAccel :: PangoLayout -> Markup -> IO Char\nlayoutSetMarkupWithAccel pl txt =\n alloca $ \\chrPtr -> \n withCStringLen txt $ \\(strPtr,len) -> do\n {#call unsafe layout_set_markup_with_accel#} pl strPtr (fromIntegral len)\n (fromIntegral (ord '_')) chrPtr\n liftM (chr.fromIntegral) $ peek chrPtr\n\n\n-- there are a couple of functions missing here\n\n-- @method layoutSetWidth@ Set the width of this paragraph.\n--\n-- * Sets the width to which the lines of the @ref data PangoLayout@\n-- should be wrapped.\n--\n-- * @ref arg width@ is the desired width, or @literal -1@ to indicate that\n-- no wrapping should be performed.\n--\nlayoutSetWidth :: PangoLayout -> Int -> IO ()\nlayoutSetWidth pl width =\n {#call unsafe layout_set_width#} pl (fromIntegral width)\n\n-- @method layoutGetWidth@ Gets the width of this paragraph.\n--\n-- * Gets the width to which the lines of the @ref data PangoLayout@\n-- should be wrapped.\n--\n-- * Returns is the current width, or @literal -1@ to indicate that\n-- no wrapping is performed.\n--\nlayoutGetWidth :: PangoLayout -> IO Int\nlayoutGetWidth pl = liftM fromIntegral $ {#call unsafe layout_get_width#} pl\n\n\n-- @data LayoutWarpMode@ Enumerates how a line can be wrapped.\n--\n-- @variant WrapWholeWords@ Breaks lines only between words.\n--\n-- * This variant does not guarantee that the requested width is not\n-- exceeded. A word that is longer than the paragraph width is not\n-- split.\n\n-- @variant WrapAnywhere@ Break lines anywhere.\n--\n-- @variant WrapPartialWords@ Wrap within a word if it is the only one on\n-- this line.\n--\n-- * This option acts like @ref variant WrapWholeWords@ but will split\n-- a word if it is the only one on this line and it exceeds the\n-- specified width.\n--\n{#enum PangoWrapMode as LayoutWrapMode \n {underscoreToCase,\n PANGO_WRAP_WORD as WrapWholeWords,\n PANGO_WRAP_CHAR as WrapAnywhere,\n PANGO_WRAP_WORD_CHAR as WrapPartialWords}#}\n\n-- @method layoutSetWrap@ Set how this paragraph is wrapped.\n--\n-- * Sets the wrap style; the wrap style only has an effect if a width\n-- is set on the layout with @ref method layoutSetWidth@. To turn off\n-- wrapping, set the width to -1.\n--\nlayoutSetWrap :: PangoLayout -> LayoutWrapMode -> IO ()\nlayoutSetWrap pl wm =\n {#call unsafe layout_set_wrap#} pl ((fromIntegral.fromEnum) wm)\n\n\n-- @method layoutGetWrap@ Get the wrap mode for the layout.\n--\nlayoutGetWrap :: PangoLayout -> IO LayoutWrapMode\nlayoutGetWrap pl = liftM (toEnum.fromIntegral) $\n {#call unsafe layout_get_wrap#} pl\n\n-- @method layoutSetIndent@ Set the indentation of this paragraph.\n--\n-- * Sets the amount by which the first line should be shorter than\n-- the rest of the lines. This may be negative, in which case the\n-- subsequent lines will be shorter than the first line. (However, in\n-- either case, the entire width of the layout will be given by the\n-- value.\n--\nlayoutSetIndent :: PangoLayout -> Int -> IO ()\nlayoutSetIndent pl indent =\n {#call unsafe layout_set_indent#} pl (fromIntegral indent)\n\n-- @method layoutGetIndent@ Gets the indentation of this paragraph.\n--\n-- * Gets the amount by which the first line should be shorter than \n-- the rest of the lines.\n--\nlayoutGetIndent :: PangoLayout -> IO Int\nlayoutGetIndent pl = liftM fromIntegral $ {#call unsafe layout_get_indent#} pl\n\n\n-- @method layoutSetSpacing@ Set the spacing between lines of this paragraph.\n--\nlayoutSetSpacing :: PangoLayout -> Int -> IO ()\nlayoutSetSpacing pl spacing =\n {#call unsafe layout_set_spacing#} pl (fromIntegral spacing)\n\n-- @method layoutGetSpacing@ Gets the spacing between the lines.\n--\nlayoutGetSpacing :: PangoLayout -> IO Int\nlayoutGetSpacing pl = \n liftM fromIntegral $ {#call unsafe layout_get_spacing#} pl\n\n-- @method layoutSetJustify@ Set if text should be streched to fit width.\n--\n-- * Sets whether or not each complete line should be stretched to\n-- fill the entire width of the layout. This stretching is typically\n-- done by adding whitespace, but for some scripts (such as Arabic),\n-- the justification is done by extending the characters.\n--\nlayoutSetJustify :: PangoLayout -> Bool -> IO ()\nlayoutSetJustify pl j = {#call unsafe layout_set_justify#} pl (fromBool j)\n\n-- @method layoutGetJustify@ Retrieve the justification flag.\n--\n-- * See @ref method layoutSetJustify@.\n--\nlayoutGetJustify :: PangoLayout -> IO Bool\nlayoutGetJustify pl = liftM toBool $ {#call unsafe layout_get_justify#} pl\n\n-- @data LayoutAlignment@ Enumerate to which side incomplete lines are flushed.\n--\n{#enum PangoAlignment as LayoutAlignment {underscoreToCase}#}\n\n-- @method layoutSetAlignment@ Set how this paragraph is aligned.\n--\n-- * Sets the alignment for the layout (how partial lines are\n-- positioned within the horizontal space available.)\n--\nlayoutSetAlignment :: PangoLayout -> LayoutAlignment -> IO ()\nlayoutSetAlignment pl am =\n {#call unsafe layout_set_alignment#} pl ((fromIntegral.fromEnum) am)\n\n\n-- @method layoutGetAlignment@ Get the alignment for the layout.\n--\nlayoutGetAlignment :: PangoLayout -> IO LayoutAlignment\nlayoutGetAlignment pl = liftM (toEnum.fromIntegral) $\n {#call unsafe layout_get_alignment#} pl\n\n-- functions are missing here\n\n-- @method layoutSetSingleParagraphMode@ Honor newlines or not.\n--\n-- * If @ref arg honor@ is @literal True@, do not treat newlines and\n-- similar characters as paragraph separators; instead, keep all text in\n-- a single paragraph, and display a glyph for paragraph separator\n-- characters. Used when you want to allow editing of newlines on a\n-- single text line.\n--\nlayoutSetSingleParagraphMode :: PangoLayout -> Bool -> IO ()\nlayoutSetSingleParagraphMode pl honor = \n {#call unsafe layout_set_single_paragraph_mode#} pl (fromBool honor)\n\n-- @method layoutGetSingleParagraphMode@ Retrieve if newlines are honored.\n--\n-- * See @ref method layoutSetSingleParagraphMode@.\n--\nlayoutGetSingleParagraphMode :: PangoLayout -> IO Bool\nlayoutGetSingleParagraphMode pl = \n liftM toBool $ {#call unsafe layout_get_single_paragraph_mode#} pl\n\n-- a function is missing here\n\n-- @method layoutGetExtents@ Compute the physical size of the layout.\n--\n-- * Computes the logical and the ink size of the @ref data Layout@. The\n-- logical layout is used for positioning, the ink size is the smallest\n-- bounding box that includes all character pixels. The ink size can be\n-- smaller or larger that the logical layout.\n--\n-- * All values are in layout units. To get to device units (pixel for\n-- @ref data Drawable@s) divide by @ref constant pangoScale@.\n--\nlayoutGetExtents :: PangoLayout -> IO (Rectangle, Rectangle)\nlayoutGetExtents pl = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_get_extents#} pl (castPtr logPtr) (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n\n-- @method layoutGetPixelExtents@ Compute the physical size of the layout.\n--\n-- * Computes the logical and the ink size of the @ref data Layout@. The\n-- logical layout is used for positioning, the ink size is the smallest\n-- bounding box that includes all character pixels. The ink size can be\n-- smaller or larger that the logical layout.\n--\n-- * All values are in device units. This function is a wrapper around\n-- @ref method layoutGetExtents@ with scaling.\n--\nlayoutGetPixelExtents :: PangoLayout -> IO (Rectangle, Rectangle)\nlayoutGetPixelExtents pl = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_get_pixel_extents#} pl (castPtr logPtr) (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n-- @method layoutGetLineCount@ Ask for the number of lines in this layout.\n--\nlayoutGetLineCount :: PangoLayout -> IO Int\nlayoutGetLineCount pl = liftM fromIntegral $\n {#call unsafe layout_get_line_count#} pl\n\n-- @method layoutGetLines@ Extract the single lines of the layout.\n--\n-- * The lines of each layout are regenerated if any attribute changes.\n-- Thus the returned list does not reflect the current state of lines\n-- after a change has been made.\n--\nlayoutGetLines :: PangoLayout -> IO [LayoutLine]\nlayoutGetLines pl = do\n listPtr <- {#call unsafe layout_get_lines#} pl\n list <- readGSList listPtr\n mapM mkLayoutLine list\n\n-- @constructor layoutGetIter@ Create an iterator to examine a layout.\n--\nlayoutGetIter :: PangoLayout -> IO LayoutIter\nlayoutGetIter pl = do\n iterPtr <- {#call unsafe layout_get_iter#} pl\n liftM LayoutIter $ newForeignPtr iterPtr (layout_iter_free iterPtr)\n\n-- @method layoutNextRun@ Move to the next run.\n--\n-- * Returns @literal False@ if this was the last run in the layout.\n--\nlayoutIterNextRun :: LayoutIter -> IO Bool\nlayoutIterNextRun = liftM toBool . {#call unsafe layout_iter_next_run#}\n\n-- @method layoutNextChar@ Move to the next char.\n--\n-- * Returns @literal False@ if this was the last char in the layout.\n--\nlayoutIterNextChar :: LayoutIter -> IO Bool\nlayoutIterNextChar = liftM toBool . {#call unsafe layout_iter_next_char#}\n\n-- @method layoutNextCluster@ Move to the next cluster.\n--\n-- * Returns @literal False@ if this was the last cluster in the layout.\n--\nlayoutIterNextCluster :: LayoutIter -> IO Bool\nlayoutIterNextCluster = liftM toBool . {#call unsafe layout_iter_next_cluster#}\n\n-- @method layoutNextLine@ Move to the next line.\n--\n-- * Returns @literal False@ if this was the last line in the layout.\n--\nlayoutIterNextLine :: LayoutIter -> IO Bool\nlayoutIterNextLine = liftM toBool . {#call unsafe layout_iter_next_line#}\n\n-- @method layoutAtLastLine@ Check if the iterator is on the last line.\n--\n-- * Returns @literal True@ if the iterator is on the last line of this\n-- paragraph.\n--\nlayoutIterAtLastLine :: LayoutIter -> IO Bool\nlayoutIterAtLastLine = liftM toBool . {#call unsafe layout_iter_at_last_line#}\n\n-- @method layoutIterGetBaseline@ Query the vertical position within the\n-- layout.\n--\n-- * Gets the y position of the current line's baseline, in layout\n-- coordinates (origin at top left of the entire layout).\n--\nlayoutIterGetBaseline :: LayoutIter -> IO Int\nlayoutIterGetBaseline = \n liftM fromIntegral . {#call unsafe pango_layout_iter_get_baseline#}\n\n-- pango_layout_iter_get_run goes here\n\n-- @method layoutIterGetLine@ Extract the line under the iterator.\n--\nlayoutIterGetLine :: LayoutIter -> IO (Maybe LayoutLine)\nlayoutIterGetLine li = do\n llPtr <- liftM castPtr $ {#call unsafe pango_layout_iter_get_line#} li\n if (llPtr==nullPtr) then return Nothing else \n liftM Just $ mkLayoutLine llPtr\n\n-- @method layoutIterGetCharExtents@ Retrieve a rectangle surrounding\n-- a character.\n--\n-- * Get the extents of the current character in layout cooridnates\n-- (origin is the top left of the entire layout). Only logical extents\n-- can sensibly be obtained for characters. \n--\nlayoutIterGetCharExtents :: LayoutIter -> IO Rectangle\nlayoutIterGetCharExtents li = alloca $ \\logPtr -> \n {#call unsafe layout_iter_get_char_extents#} li (castPtr logPtr) >>\n peek logPtr\n\n-- @method layoutIterGetClusterExtents@ Compute the physical size of the\n-- cluster.\n--\n-- * Computes the logical and the ink size of the cluster pointed to by\n-- @ref data LayoutIter@.\n--\n-- * All values are in layoutIter units. To get to device units (pixel for\n-- @ref data Drawable@s) divide by @ref constant pangoScale@.\n--\nlayoutIterGetClusterExtents :: LayoutIter -> IO (Rectangle, Rectangle)\nlayoutIterGetClusterExtents li = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_iter_get_cluster_extents#} li (castPtr logPtr)\n (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n-- @method layoutIterGetRunExtents@ Compute the physical size of the run.\n--\n-- * Computes the logical and the ink size of the run pointed to by\n-- @ref data LayoutIter@.\n--\n-- * All values are in layoutIter units. To get to device units (pixel for\n-- @ref data Drawable@s) divide by @ref constant pangoScale@.\n--\nlayoutIterGetRunExtents :: LayoutIter -> IO (Rectangle, Rectangle)\nlayoutIterGetRunExtents li = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_iter_get_run_extents#} li (castPtr logPtr)\n (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n-- @method layoutIterGetLineYRange@ Retrieve vertical extent of this\n-- line.\n--\n-- * Divides the vertical space in the @ref data PangoLayout@ being\n-- iterated over between the lines in the layout, and returns the\n-- space belonging to the current line. A line's range includes the\n-- line's logical extents, plus half of the spacing above and below\n-- the line, if @ref method pangoLayoutSetSpacing@ has been called\n-- to set layout spacing. The y positions are in layout coordinates\n-- (origin at top left of the entire layout).\n--\n-- * The first element in the returned tuple is the start, the second is\n-- the end of this line.\n--\nlayoutIterGetLineYRange :: LayoutIter -> IO (Int,Int)\nlayoutIterGetLineYRange li = alloca $ \\sPtr -> alloca $ \\ePtr -> do\n {#call unsafe layout_iter_get_line_extents#} li (castPtr sPtr) (castPtr ePtr)\n start <- peek sPtr\n end <- peek ePtr\n return (start,end)\n\n-- @method layoutIterGetLineExtents@ Compute the physical size of the line.\n--\n-- * Computes the logical and the ink size of the line pointed to by\n-- @ref data LayoutIter@.\n--\n-- * Extents are in layout coordinates (origin is the top-left corner\n-- of the entire @ref data PangoLayout@). Thus the extents returned\n-- by this function will be the same width\/height but not at the\n-- same x\/y as the extents returned from @ref method\n-- pangoLayoutLineGetExtents@.\n--\nlayoutIterGetLineExtents :: LayoutIter -> IO (Rectangle, Rectangle)\nlayoutIterGetLineExtents li = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_iter_get_line_extents#} li (castPtr logPtr)\n (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n\n-- @method layoutLineGetExtents@ Compute the physical size of the line.\n--\n-- * Computes the logical and the ink size of the @ref data LayoutLine@. The\n-- logical layout is used for positioning, the ink size is the smallest\n-- bounding box that includes all character pixels. The ink size can be\n-- smaller or larger that the logical layout.\n--\n-- * All values are in layout units. To get to device units (pixel for\n-- @ref data Drawable@s) divide by @ref constant pangoScale@.\n--\nlayoutLineGetExtents :: LayoutLine -> IO (Rectangle, Rectangle)\nlayoutLineGetExtents pl = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_line_get_extents#} pl (castPtr logPtr) (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n-- @method layoutLineGetPixelExtents@ Compute the physical size of the line.\n--\n-- * Computes the logical and the ink size of the @ref data LayoutLine@. The\n-- logical layout is used for positioning, the ink size is the smallest\n-- bounding box that includes all character pixels. The ink size can be\n-- smaller or larger that the logical layout.\n--\n-- * All values are in device units. This function is a wrapper around\n-- @ref method layoutLineGetExtents@ with scaling.\n--\nlayoutLineGetPixelExtents :: LayoutLine -> IO (Rectangle, Rectangle)\nlayoutLineGetPixelExtents pl = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_line_get_pixel_extents#} pl\n (castPtr logPtr) (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"b5317e7569ca2fba00c3a8e829e3c2bb832f3c1b","subject":"separate cl 1.1 code","message":"separate cl 1.1 code\n","repos":"IFCA\/opencl,IFCA\/opencl,Delan90\/opencl,Delan90\/opencl","old_file":"src\/Control\/Parallel\/OpenCL\/Context.chs","new_file":"src\/Control\/Parallel\/OpenCL\/Context.chs","new_contents":"{- Copyright (c) 2011 Luis Cabellos,\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided\n with the distribution.\n\n * Neither the name of nor the names of other\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables, CPP #-}\nmodule Control.Parallel.OpenCL.Context(\n -- * Types\n CLContext, CLContextProperty(..),\n -- * Context Functions\n clCreateContext, clCreateContextFromType, clRetainContext, clReleaseContext,\n clGetContextReferenceCount, clGetContextDevices, clGetContextProperties )\n where\n\n-- -----------------------------------------------------------------------------\nimport Foreign( \n Ptr, FunPtr, nullPtr, castPtr, alloca, allocaArray, peek, peekArray, \n ptrToIntPtr, intPtrToPtr, withArray )\nimport Foreign.C.Types( CSize )\nimport Foreign.C.String( CString, peekCString )\nimport Foreign.Storable( sizeOf )\nimport Control.Parallel.OpenCL.Types( \n CLuint, CLint, CLDeviceType_, CLContextInfo_, CLContextProperty_, CLDeviceID, \n CLContext, CLDeviceType, CLPlatformID, bitmaskFromFlags, getCLValue, getEnumCL,\n whenSuccess, wrapCheckSuccess, wrapPError, wrapGetInfo )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#include \n#endif\n\n-- -----------------------------------------------------------------------------\ntype ContextCallback = CString -> Ptr () -> CSize -> Ptr () -> IO ()\nforeign import CALLCONV \"wrapper\" wrapContextCallback :: \n ContextCallback -> IO (FunPtr ContextCallback)\nforeign import CALLCONV \"clCreateContext\" raw_clCreateContext ::\n Ptr CLContextProperty_ -> CLuint -> Ptr CLDeviceID -> FunPtr ContextCallback -> \n Ptr () -> Ptr CLint -> IO CLContext\nforeign import CALLCONV \"clCreateContextFromType\" raw_clCreateContextFromType :: \n Ptr CLContextProperty_ -> CLDeviceType_ -> FunPtr ContextCallback -> \n Ptr () -> Ptr CLint -> IO CLContext\nforeign import CALLCONV \"clRetainContext\" raw_clRetainContext :: \n CLContext -> IO CLint\nforeign import CALLCONV \"clReleaseContext\" raw_clReleaseContext :: \n CLContext -> IO CLint\nforeign import CALLCONV \"clGetContextInfo\" raw_clGetContextInfo :: \n CLContext -> CLContextInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLContextProperties {\n cL_CONTEXT_PLATFORM_=CL_CONTEXT_PLATFORM,\n#ifdef CL_VERSION_1_1\n#ifdef __APPLE__\n cL_CGL_SHAREGROUP_KHR_=CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE\n#else\n cL_GL_CONTEXT_KHR_=CL_GL_CONTEXT_KHR,\n cL_EGL_DISPLAY_KHR_=CL_EGL_DISPLAY_KHR,\n cL_GLX_DISPLAY_KHR_=CL_GLX_DISPLAY_KHR,\n cL_WGL_HDC_KHR_=CL_WGL_HDC_KHR,\n cL_CGL_SHAREGROUP_KHR_=CL_CGL_SHAREGROUP_KHR\n#endif\n#endif\n };\n#endc\n{#enum CLContextProperties {upcaseFirstLetter} #}\n\n-- | Specifies a context property name and its corresponding value.\ndata CLContextProperty = CL_CONTEXT_PLATFORM CLPlatformID \n -- ^ Specifies the platform to use.\n#ifdef CL_VERSION_1_1\n | CL_CGL_SHAREGROUP_KHR (Ptr ())\n -- ^ Specifies the CGL share group to use.\n#ifndef __APPLE__\n | CL_GL_CONTEXT_KHR (Ptr ())\n | CL_EGL_DISPLAY_KHR (Ptr ())\n | CL_GLX_DISPLAY_KHR (Ptr ())\n | CL_WGL_HDC_KHR (Ptr ())\n#endif\n#endif\n deriving( Show )\n\npackProperty :: CLContextProperty -> [CLContextProperty_]\npackProperty (CL_CONTEXT_PLATFORM pid) = [ getCLValue CL_CONTEXT_PLATFORM_\n , fromIntegral . ptrToIntPtr $ pid ]\n#ifdef CL_VERSION_1_1\npackProperty (CL_CGL_SHAREGROUP_KHR ptr) = [ getCLValue CL_CGL_SHAREGROUP_KHR_\n , fromIntegral . ptrToIntPtr $ ptr ]\n#ifndef __APPLE__\npackProperty (CL_GL_CONTEXT_KHR ptr) = [ getCLValue CL_GL_CONTEXT_KHR_\n , fromIntegral . ptrToIntPtr $ ptr ]\npackProperty (CL_EGL_DISPLAY_KHR ptr) = [ getCLValue CL_EGL_DISPLAY_KHR_\n , fromIntegral . ptrToIntPtr $ ptr ]\npackProperty (CL_GLX_DISPLAY_KHR ptr) = [ getCLValue CL_GLX_DISPLAY_KHR_\n , fromIntegral . ptrToIntPtr $ ptr ]\npackProperty (CL_WGL_HDC_KHR ptr) = [ getCLValue CL_WGL_HDC_KHR_\n , fromIntegral . ptrToIntPtr $ ptr ]\n#endif\n#endif\n\npackContextProperties :: [CLContextProperty] -> [CLContextProperty_]\npackContextProperties [] = [0]\npackContextProperties (x:xs) = packProperty x ++ packContextProperties xs\n\nunpackContextProperties :: [CLContextProperty_] -> [CLContextProperty]\nunpackContextProperties [] = error \"non-exhaustive Context Property list\"\nunpackContextProperties [x] \n | x == 0 = []\n | otherwise = error \"non-exhaustive Context Property list\"\nunpackContextProperties (x:y:xs) = let ys = unpackContextProperties xs \n in case getEnumCL x of\n CL_CONTEXT_PLATFORM_ \n -> CL_CONTEXT_PLATFORM \n (intPtrToPtr . fromIntegral $ y) : ys\n#ifdef CL_VERSION_1_1\n CL_CGL_SHAREGROUP_KHR_ \n -> CL_CGL_SHAREGROUP_KHR \n (intPtrToPtr . fromIntegral $ y) : ys\n#endif\n \n-- -----------------------------------------------------------------------------\nmkContextCallback :: (String -> IO ()) -> ContextCallback\nmkContextCallback f msg _ _ _ = peekCString msg >>= f\n\n-- | Creates an OpenCL context.\n-- An OpenCL context is created with one or more devices. Contexts are used by \n-- the OpenCL runtime for managing objects such as command-queues, memory, \n-- program and kernel objects and for executing kernels on one or more devices \n-- specified in the context.\nclCreateContext :: [CLContextProperty] -> [CLDeviceID] -> (String -> IO ()) \n -> IO CLContext\nclCreateContext [] devs f = withArray devs $ \\pdevs ->\n wrapPError $ \\perr -> do\n fptr <- wrapContextCallback $ mkContextCallback f\n raw_clCreateContext nullPtr cndevs pdevs fptr nullPtr perr\n where\n cndevs = fromIntegral . length $ devs\nclCreateContext props devs f = withArray devs $ \\pdevs ->\n wrapPError $ \\perr -> do\n fptr <- wrapContextCallback $ mkContextCallback f\n withArray (packContextProperties props) $ \\pprops ->\n raw_clCreateContext pprops cndevs pdevs fptr nullPtr perr \n where\n cndevs = fromIntegral . length $ devs\n\n-- | Create an OpenCL context from a device type that identifies the specific \n-- device(s) to use.\nclCreateContextFromType :: [CLContextProperty] -> [CLDeviceType] \n -> (String -> IO ()) -> IO CLContext\nclCreateContextFromType [] xs f = wrapPError $ \\perr -> do\n fptr <- wrapContextCallback $ mkContextCallback f\n raw_clCreateContextFromType nullPtr types fptr nullPtr perr\n where\n types = bitmaskFromFlags xs\nclCreateContextFromType props xs f = wrapPError $ \\perr -> do\n fptr <- wrapContextCallback $ mkContextCallback f\n withArray (packContextProperties props) $ \\pprops -> \n raw_clCreateContextFromType pprops types fptr nullPtr perr\n where\n types = bitmaskFromFlags xs\n\n-- | Increment the context reference count.\n-- 'clCreateContext' and 'clCreateContextFromType' perform an implicit retain. \n-- This is very helpful for 3rd party libraries, which typically get a context \n-- passed to them by the application. However, it is possible that the \n-- application may delete the context without informing the library. Allowing \n-- functions to attach to (i.e. retain) and release a context solves the \n-- problem of a context being used by a library no longer being valid.\n-- Returns 'True' if the function is executed successfully, or 'False' if \n-- context is not a valid OpenCL context.\nclRetainContext :: CLContext -> IO Bool\nclRetainContext ctx = wrapCheckSuccess $ raw_clRetainContext ctx \n\n-- | Decrement the context reference count.\n-- After the context reference count becomes zero and all the objects attached \n-- to context (such as memory objects, command-queues) are released, the \n-- context is deleted.\n-- Returns 'True' if the function is executed successfully, or 'False' if \n-- context is not a valid OpenCL context.\nclReleaseContext :: CLContext -> IO Bool\nclReleaseContext ctx = wrapCheckSuccess $ raw_clReleaseContext ctx \n\ngetContextInfoSize :: CLContext -> CLContextInfo_ -> IO CSize\ngetContextInfoSize ctx infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n whenSuccess (raw_clGetContextInfo ctx infoid 0 nullPtr value_size)\n $ peek value_size\n\n#c\nenum CLContextInfo {\n cL_CONTEXT_REFERENCE_COUNT=CL_CONTEXT_REFERENCE_COUNT,\n cL_CONTEXT_DEVICES=CL_CONTEXT_DEVICES,\n cL_CONTEXT_PROPERTIES=CL_CONTEXT_PROPERTIES\n };\n#endc\n{#enum CLContextInfo {upcaseFirstLetter} #}\n\n-- | Return the context reference count. The reference count returned should be \n-- considered immediately stale. It is unsuitable for general use in \n-- applications. This feature is provided for identifying memory leaks.\n--\n-- This function execute OpenCL clGetContextInfo with 'CL_CONTEXT_REFERENCE_COUNT'.\nclGetContextReferenceCount :: CLContext -> IO CLuint\nclGetContextReferenceCount ctx =\n wrapGetInfo (\\(dat :: Ptr CLuint) ->\n raw_clGetContextInfo ctx infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_CONTEXT_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the list of devices in context.\n--\n-- This function execute OpenCL clGetContextInfo with 'CL_CONTEXT_DEVICES'.\nclGetContextDevices :: CLContext -> IO [CLDeviceID]\nclGetContextDevices ctx = do\n size <- getContextInfoSize ctx infoid\n let n = (fromIntegral size) `div` elemSize \n \n allocaArray n $ \\(buff :: Ptr CLDeviceID) -> do\n whenSuccess (raw_clGetContextInfo ctx infoid size (castPtr buff) nullPtr)\n $ peekArray n buff\n where\n infoid = getCLValue CL_CONTEXT_DEVICES\n elemSize = sizeOf (nullPtr :: CLDeviceID)\n\nclGetContextProperties :: CLContext -> IO [CLContextProperty]\nclGetContextProperties ctx = do\n size <- getContextInfoSize ctx infoid\n let n = (fromIntegral size) `div` elemSize \n \n if n == 0 \n then return []\n else allocaArray n $ \\(buff :: Ptr CLContextProperty_) ->\n whenSuccess (raw_clGetContextInfo ctx infoid size (castPtr buff) nullPtr)\n $ fmap unpackContextProperties $ peekArray n buff\n where\n infoid = getCLValue CL_CONTEXT_PROPERTIES\n elemSize = sizeOf (nullPtr :: CLDeviceID)\n \n-- -----------------------------------------------------------------------------\n","old_contents":"{- Copyright (c) 2011 Luis Cabellos,\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided\n with the distribution.\n\n * Neither the name of nor the names of other\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables, CPP #-}\nmodule Control.Parallel.OpenCL.Context(\n -- * Types\n CLContext, CLContextProperty(..),\n -- * Context Functions\n clCreateContext, clCreateContextFromType, clRetainContext, clReleaseContext,\n clGetContextReferenceCount, clGetContextDevices, clGetContextProperties )\n where\n\n-- -----------------------------------------------------------------------------\nimport Foreign( \n Ptr, FunPtr, nullPtr, castPtr, alloca, allocaArray, peek, peekArray, \n ptrToIntPtr, intPtrToPtr, withArray )\nimport Foreign.C.Types( CSize )\nimport Foreign.C.String( CString, peekCString )\nimport Foreign.Storable( sizeOf )\nimport Control.Parallel.OpenCL.Types( \n CLuint, CLint, CLDeviceType_, CLContextInfo_, CLContextProperty_, CLDeviceID, \n CLContext, CLDeviceType, CLPlatformID, bitmaskFromFlags, getCLValue, getEnumCL,\n whenSuccess, wrapCheckSuccess, wrapPError, wrapGetInfo )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#include \n#endif\n\n-- -----------------------------------------------------------------------------\ntype ContextCallback = CString -> Ptr () -> CSize -> Ptr () -> IO ()\nforeign import CALLCONV \"wrapper\" wrapContextCallback :: \n ContextCallback -> IO (FunPtr ContextCallback)\nforeign import CALLCONV \"clCreateContext\" raw_clCreateContext ::\n Ptr CLContextProperty_ -> CLuint -> Ptr CLDeviceID -> FunPtr ContextCallback -> \n Ptr () -> Ptr CLint -> IO CLContext\nforeign import CALLCONV \"clCreateContextFromType\" raw_clCreateContextFromType :: \n Ptr CLContextProperty_ -> CLDeviceType_ -> FunPtr ContextCallback -> \n Ptr () -> Ptr CLint -> IO CLContext\nforeign import CALLCONV \"clRetainContext\" raw_clRetainContext :: \n CLContext -> IO CLint\nforeign import CALLCONV \"clReleaseContext\" raw_clReleaseContext :: \n CLContext -> IO CLint\nforeign import CALLCONV \"clGetContextInfo\" raw_clGetContextInfo :: \n CLContext -> CLContextInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLContextProperties {\n cL_CONTEXT_PLATFORM_=CL_CONTEXT_PLATFORM,\n#ifdef __APPLE__\n cL_CGL_SHAREGROUP_KHR_=CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE\n#else\n cL_GL_CONTEXT_KHR_=CL_GL_CONTEXT_KHR,\n cL_EGL_DISPLAY_KHR_=CL_EGL_DISPLAY_KHR,\n cL_GLX_DISPLAY_KHR_=CL_GLX_DISPLAY_KHR,\n cL_WGL_HDC_KHR_=CL_WGL_HDC_KHR,\n cL_CGL_SHAREGROUP_KHR_=CL_CGL_SHAREGROUP_KHR\n#endif\n };\n#endc\n{#enum CLContextProperties {upcaseFirstLetter} #}\n\n-- | Specifies a context property name and its corresponding value.\ndata CLContextProperty = CL_CONTEXT_PLATFORM CLPlatformID \n -- ^ Specifies the platform to use.\n | CL_CGL_SHAREGROUP_KHR (Ptr ())\n -- ^ Specifies the CGL share group to use.\n#ifndef __APPLE__\n | CL_GL_CONTEXT_KHR (Ptr ())\n | CL_EGL_DISPLAY_KHR (Ptr ())\n | CL_GLX_DISPLAY_KHR (Ptr ())\n | CL_WGL_HDC_KHR (Ptr ())\n#endif\n deriving( Show )\n\npackProperty :: CLContextProperty -> [CLContextProperty_]\npackProperty (CL_CONTEXT_PLATFORM pid) = [ getCLValue CL_CONTEXT_PLATFORM_\n , fromIntegral . ptrToIntPtr $ pid ]\npackProperty (CL_CGL_SHAREGROUP_KHR ptr) = [ getCLValue CL_CGL_SHAREGROUP_KHR_\n , fromIntegral . ptrToIntPtr $ ptr ]\n#ifndef __APPLE__\npackProperty (CL_GL_CONTEXT_KHR ptr) = [ getCLValue CL_GL_CONTEXT_KHR_\n , fromIntegral . ptrToIntPtr $ ptr ]\npackProperty (CL_EGL_DISPLAY_KHR ptr) = [ getCLValue CL_EGL_DISPLAY_KHR_\n , fromIntegral . ptrToIntPtr $ ptr ]\npackProperty (CL_GLX_DISPLAY_KHR ptr) = [ getCLValue CL_GLX_DISPLAY_KHR_\n , fromIntegral . ptrToIntPtr $ ptr ]\npackProperty (CL_WGL_HDC_KHR ptr) = [ getCLValue CL_WGL_HDC_KHR_\n , fromIntegral . ptrToIntPtr $ ptr ]\n#endif\n\npackContextProperties :: [CLContextProperty] -> [CLContextProperty_]\npackContextProperties [] = [0]\npackContextProperties (x:xs) = packProperty x ++ packContextProperties xs\n\nunpackContextProperties :: [CLContextProperty_] -> [CLContextProperty]\nunpackContextProperties [] = error \"non-exhaustive Context Property list\"\nunpackContextProperties [x] \n | x == 0 = []\n | otherwise = error \"non-exhaustive Context Property list\"\nunpackContextProperties (x:y:xs) = let ys = unpackContextProperties xs \n in case getEnumCL x of\n CL_CONTEXT_PLATFORM_ \n -> CL_CONTEXT_PLATFORM \n (intPtrToPtr . fromIntegral $ y) : ys\n CL_CGL_SHAREGROUP_KHR_ \n -> CL_CGL_SHAREGROUP_KHR \n (intPtrToPtr . fromIntegral $ y) : ys\n \n-- -----------------------------------------------------------------------------\nmkContextCallback :: (String -> IO ()) -> ContextCallback\nmkContextCallback f msg _ _ _ = peekCString msg >>= f\n\n-- | Creates an OpenCL context.\n-- An OpenCL context is created with one or more devices. Contexts are used by \n-- the OpenCL runtime for managing objects such as command-queues, memory, \n-- program and kernel objects and for executing kernels on one or more devices \n-- specified in the context.\nclCreateContext :: [CLContextProperty] -> [CLDeviceID] -> (String -> IO ()) \n -> IO CLContext\nclCreateContext [] devs f = withArray devs $ \\pdevs ->\n wrapPError $ \\perr -> do\n fptr <- wrapContextCallback $ mkContextCallback f\n raw_clCreateContext nullPtr cndevs pdevs fptr nullPtr perr\n where\n cndevs = fromIntegral . length $ devs\nclCreateContext props devs f = withArray devs $ \\pdevs ->\n wrapPError $ \\perr -> do\n fptr <- wrapContextCallback $ mkContextCallback f\n withArray (packContextProperties props) $ \\pprops ->\n raw_clCreateContext pprops cndevs pdevs fptr nullPtr perr \n where\n cndevs = fromIntegral . length $ devs\n\n-- | Create an OpenCL context from a device type that identifies the specific \n-- device(s) to use.\nclCreateContextFromType :: [CLContextProperty] -> [CLDeviceType] \n -> (String -> IO ()) -> IO CLContext\nclCreateContextFromType [] xs f = wrapPError $ \\perr -> do\n fptr <- wrapContextCallback $ mkContextCallback f\n raw_clCreateContextFromType nullPtr types fptr nullPtr perr\n where\n types = bitmaskFromFlags xs\nclCreateContextFromType props xs f = wrapPError $ \\perr -> do\n fptr <- wrapContextCallback $ mkContextCallback f\n withArray (packContextProperties props) $ \\pprops -> \n raw_clCreateContextFromType pprops types fptr nullPtr perr\n where\n types = bitmaskFromFlags xs\n\n-- | Increment the context reference count.\n-- 'clCreateContext' and 'clCreateContextFromType' perform an implicit retain. \n-- This is very helpful for 3rd party libraries, which typically get a context \n-- passed to them by the application. However, it is possible that the \n-- application may delete the context without informing the library. Allowing \n-- functions to attach to (i.e. retain) and release a context solves the \n-- problem of a context being used by a library no longer being valid.\n-- Returns 'True' if the function is executed successfully, or 'False' if \n-- context is not a valid OpenCL context.\nclRetainContext :: CLContext -> IO Bool\nclRetainContext ctx = wrapCheckSuccess $ raw_clRetainContext ctx \n\n-- | Decrement the context reference count.\n-- After the context reference count becomes zero and all the objects attached \n-- to context (such as memory objects, command-queues) are released, the \n-- context is deleted.\n-- Returns 'True' if the function is executed successfully, or 'False' if \n-- context is not a valid OpenCL context.\nclReleaseContext :: CLContext -> IO Bool\nclReleaseContext ctx = wrapCheckSuccess $ raw_clReleaseContext ctx \n\ngetContextInfoSize :: CLContext -> CLContextInfo_ -> IO CSize\ngetContextInfoSize ctx infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n whenSuccess (raw_clGetContextInfo ctx infoid 0 nullPtr value_size)\n $ peek value_size\n\n#c\nenum CLContextInfo {\n cL_CONTEXT_REFERENCE_COUNT=CL_CONTEXT_REFERENCE_COUNT,\n cL_CONTEXT_DEVICES=CL_CONTEXT_DEVICES,\n cL_CONTEXT_PROPERTIES=CL_CONTEXT_PROPERTIES\n };\n#endc\n{#enum CLContextInfo {upcaseFirstLetter} #}\n\n-- | Return the context reference count. The reference count returned should be \n-- considered immediately stale. It is unsuitable for general use in \n-- applications. This feature is provided for identifying memory leaks.\n--\n-- This function execute OpenCL clGetContextInfo with 'CL_CONTEXT_REFERENCE_COUNT'.\nclGetContextReferenceCount :: CLContext -> IO CLuint\nclGetContextReferenceCount ctx =\n wrapGetInfo (\\(dat :: Ptr CLuint) ->\n raw_clGetContextInfo ctx infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_CONTEXT_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the list of devices in context.\n--\n-- This function execute OpenCL clGetContextInfo with 'CL_CONTEXT_DEVICES'.\nclGetContextDevices :: CLContext -> IO [CLDeviceID]\nclGetContextDevices ctx = do\n size <- getContextInfoSize ctx infoid\n let n = (fromIntegral size) `div` elemSize \n \n allocaArray n $ \\(buff :: Ptr CLDeviceID) -> do\n whenSuccess (raw_clGetContextInfo ctx infoid size (castPtr buff) nullPtr)\n $ peekArray n buff\n where\n infoid = getCLValue CL_CONTEXT_DEVICES\n elemSize = sizeOf (nullPtr :: CLDeviceID)\n\nclGetContextProperties :: CLContext -> IO [CLContextProperty]\nclGetContextProperties ctx = do\n size <- getContextInfoSize ctx infoid\n let n = (fromIntegral size) `div` elemSize \n \n if n == 0 \n then return []\n else allocaArray n $ \\(buff :: Ptr CLContextProperty_) ->\n whenSuccess (raw_clGetContextInfo ctx infoid size (castPtr buff) nullPtr)\n $ fmap unpackContextProperties $ peekArray n buff\n where\n infoid = getCLValue CL_CONTEXT_PROPERTIES\n elemSize = sizeOf (nullPtr :: CLDeviceID)\n \n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"45aff6a9d66a4b380f09c5e8a27b4a6cb5c52d82","subject":"binding to select device for executions","message":"binding to select device for executions\n\nIgnore-this: a95d048b62a825d5160daf33d79d5fb\n\ndarcs-hash:20090718052809-115f9-e8754b21a3cb34a8eaed00381ddb75b8b59df7cb.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Runtime.chs","new_file":"Foreign\/CUDA\/Runtime.chs","new_contents":"{-\n - Haskell bindings to the CUDA library\n -\n - This uses the higher-level \"C for CUDA\" interface and runtime API, which\n - itself is implemented with the lower-level driver API.\n -}\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Foreign.CUDA.Runtime\n (\n --\n -- Device management\n --\n getDeviceCount, getDeviceProperties,\n setDevice,\n\n --\n -- Memory management\n --\n malloc\n ) where\n\nimport Foreign.CUDA.Types\nimport Foreign.CUDA.Utils\n\nimport Foreign.CUDA.Internal.C2HS hiding (malloc)\n\n\n#include \n{#context lib=\"cudart\" prefix=\"cuda\"#}\n\n{# pointer *cudaDeviceProp as ^ foreign -> DeviceProperties nocode #}\n\n--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n--\n-- Returns the number of compute-capable devices\n--\ngetDeviceCount :: IO (Either String Int)\ngetDeviceCount = resultIfOk `fmap` cudaGetDeviceCount\n\n{# fun unsafe cudaGetDeviceCount\n { alloca- `Int' peekIntConv* } -> `Result' cToEnum #}\n\n--\n-- Return information about the selected compute device\n--\ngetDeviceProperties :: Int -> IO (Either String DeviceProperties)\ngetDeviceProperties n = resultIfOk `fmap` cudaGetDeviceProperties n\n\n{# fun unsafe cudaGetDeviceProperties\n { alloca- `DeviceProperties' peek*,\n `Int' } -> `Result' cToEnum #}\n\n--\n-- Set device to be used for GPU execution\n--\nsetDevice :: Int -> IO (Maybe String)\nsetDevice n = nothingIfOk `fmap` cudaSetDevice n\n\n{# fun unsafe cudaSetDevice\n { `Int' } -> `Result' cToEnum #}\n\n--------------------------------------------------------------------------------\n-- Memory Management\n--------------------------------------------------------------------------------\n\n--\n-- Allocate the specified number of bytes in linear memory on the device. The\n-- memory is suitably aligned for any kind of variable, and is not cleared.\n--\nmalloc :: Integer -> IO (Either String DevicePtr)\nmalloc bytes = do\n (rv,ptr) <- cudaMalloc bytes\n case rv of\n Success -> doAutoRelease cudaFree_ >>= \\fp ->\n newDevicePtr fp ptr >>= (return.Right)\n _ -> return (Left (getErrorString rv))\n\n{# fun unsafe cudaMalloc\n { alloca- `Ptr ()' peek*,\n cIntConv `Integer' } -> `Result' cToEnum #}\n\n\n--\n-- Free previously allocated memory on the device\n--\ncudaFree_ :: Ptr () -> IO ()\ncudaFree_ p = throwIf_ (\/= Success) (getErrorString) (cudaFree p)\n\n{# fun unsafe cudaFree\n { id `Ptr ()' } -> `Result' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr () -> IO ()) -> IO (FunPtr (Ptr () -> IO ()))\n","old_contents":"{-\n - Haskell bindings to the CUDA library\n -\n - This uses the higher-level \"C for CUDA\" interface and runtime API, which\n - itself is implemented with the lower-level driver API.\n -}\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Foreign.CUDA.Runtime\n (\n --\n -- Device management\n --\n getDeviceCount, getDeviceProperties,\n\n --\n -- Memory management\n --\n malloc\n ) where\n\nimport Foreign.CUDA.Types\nimport Foreign.CUDA.Utils\n\nimport Foreign.CUDA.Internal.C2HS hiding (malloc)\n\n\n#include \n{#context lib=\"cudart\" prefix=\"cuda\"#}\n\n{# pointer *cudaDeviceProp as ^ foreign -> DeviceProperties nocode #}\n\n--------------------------------------------------------------------------------\n-- Device Management\n--------------------------------------------------------------------------------\n\n--\n-- Returns the number of compute-capable devices\n--\ngetDeviceCount :: IO (Either String Int)\ngetDeviceCount = resultIfOk `fmap` cudaGetDeviceCount\n\n{# fun unsafe cudaGetDeviceCount\n { alloca- `Int' peekIntConv* } -> `Result' cToEnum #}\n\n--\n-- Return information about the selected compute device\n--\ngetDeviceProperties :: Int -> IO (Either String DeviceProperties)\ngetDeviceProperties n = resultIfOk `fmap` cudaGetDeviceProperties n\n\n{# fun unsafe cudaGetDeviceProperties\n { alloca- `DeviceProperties' peek*,\n `Int' } -> `Result' cToEnum #}\n\n--------------------------------------------------------------------------------\n-- Memory Management\n--------------------------------------------------------------------------------\n\n--\n-- Allocate the specified number of bytes in linear memory on the device. The\n-- memory is suitably aligned for any kind of variable, and is not cleared.\n--\nmalloc :: Integer -> IO (Either String DevicePtr)\nmalloc bytes = do\n (rv,ptr) <- cudaMalloc bytes\n case rv of\n Success -> doAutoRelease cudaFree_ >>= \\fp ->\n newDevicePtr fp ptr >>= (return.Right)\n _ -> return (Left (getErrorString rv))\n\n{# fun unsafe cudaMalloc\n { alloca- `Ptr ()' peek*,\n cIntConv `Integer' } -> `Result' cToEnum #}\n\n\n--\n-- Free previously allocated memory on the device\n--\ncudaFree_ :: Ptr () -> IO ()\ncudaFree_ p = throwIf_ (\/= Success) (getErrorString) (cudaFree p)\n\n{# fun unsafe cudaFree\n { id `Ptr ()' } -> `Result' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr () -> IO ()) -> IO (FunPtr (Ptr () -> IO ()))\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"c3388d11df8c9365aac0ceb8228854c276526e21","subject":"removed debug prints","message":"removed debug prints\n","repos":"denisenkom\/hspkcs11,denisenkom\/hspkcs11","old_file":"System\/Crypto\/Pkcs11.chs","new_file":"System\/Crypto\/Pkcs11.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\nmodule System.Crypto.Pkcs11 (\n -- * Library\n Library,\n loadLibrary,\n releaseLibrary,\n\n -- ** Reading library information\n Info,\n getInfo,\n infoCryptokiVersion,\n infoManufacturerId,\n infoFlags,\n infoLibraryDescription,\n infoLibraryVersion,\n\n -- * Slots\n SlotId,\n getSlotList,\n\n -- ** Reading slot information\n SlotInfo,\n getSlotInfo,\n slotInfoDescription,\n slotInfoManufacturerId,\n slotInfoFlags,\n slotInfoHardwareVersion,\n slotInfoFirmwareVersion,\n\n -- ** Reading token information\n TokenInfo,\n getTokenInfo,\n tokenInfoLabel,\n tokenInfoManufacturerId,\n tokenInfoModel,\n tokenInfoSerialNumber,\n tokenInfoFlags,\n\n -- * Mechanisms\n MechType(RsaPkcsKeyPairGen,RsaPkcs,AesEcb,AesCbc,AesMac,AesMacGeneral,AesCbcPad,AesCtr),\n MechInfo,\n getMechanismList,\n getMechanismInfo,\n mechInfoMinKeySize,\n mechInfoMaxKeySize,\n mechInfoFlags,\n\n -- * Session management\n Session,\n UserType(User,SecurityOfficer,ContextSpecific),\n withSession,\n login,\n logout,\n\n -- * Object attributes\n ObjectHandle,\n Attribute(Class,Label,KeyType,Modulus,ModulusBits,PublicExponent,Token,Decrypt),\n ClassType(PrivateKey,SecretKey),\n KeyTypeValue(RSA,DSA,DH,ECDSA,EC,AES),\n -- ** Searching objects\n findObjects,\n -- ** Reading object attributes\n getTokenFlag,\n getPrivateFlag,\n getSensitiveFlag,\n getEncryptFlag,\n getDecryptFlag,\n getWrapFlag,\n getUnwrapFlag,\n getSignFlag,\n getModulus,\n getPublicExponent,\n\n -- * Key generation\n generateKeyPair,\n\n -- * Key wrapping\/unwrapping\n unwrapKey,\n\n -- * Encryption\/decryption\n decrypt,\n encrypt,\n\n -- * Misc\n Version,\n versionMajor,\n versionMinor,\n) where\nimport Foreign\nimport Foreign.Marshal.Utils\nimport Foreign.Marshal.Alloc\nimport Foreign.C\nimport Foreign.Ptr\nimport System.Posix.DynamicLinker\nimport Control.Monad\nimport Control.Exception\nimport qualified Data.ByteString.UTF8 as BU8\nimport qualified Data.ByteString as BS\nimport Data.ByteString.Unsafe\n\n#include \"pkcs11import.h\"\n\n{-\n Currently cannot use c2hs structure alignment and offset detector since it does not support pragma pack\n which is required by PKCS11, which is using 1 byte packing\n https:\/\/github.com\/haskell\/c2hs\/issues\/172\n-}\n\n_serialSession = {#const CKF_SERIAL_SESSION#} :: Int\n_rwSession = {#const CKF_RW_SESSION#} :: Int\n\nrsaPkcsKeyPairGen = {#const CKM_RSA_PKCS_KEY_PAIR_GEN#} :: Int\n\ntype ObjectHandle = {#type CK_OBJECT_HANDLE#}\ntype SlotId = Int\ntype Rv = {#type CK_RV#}\ntype CK_BBOOL = {#type CK_BBOOL#}\ntype CK_BYTE = {#type CK_BYTE#}\ntype CK_FLAGS = {#type CK_FLAGS#}\ntype GetFunctionListFunPtr = {#type CK_C_GetFunctionList#}\ntype GetSlotListFunPtr = {#type CK_C_GetSlotList#}\ntype NotifyFunPtr = {#type CK_NOTIFY#}\ntype SessionHandle = {#type CK_SESSION_HANDLE#}\n\n{#pointer *CK_FUNCTION_LIST as FunctionListPtr#}\n{#pointer *CK_INFO as InfoPtr -> Info#}\n{#pointer *CK_SLOT_INFO as SlotInfoPtr -> SlotInfo#}\n{#pointer *CK_TOKEN_INFO as TokenInfoPtr -> TokenInfo#}\n{#pointer *CK_ATTRIBUTE as LlAttributePtr -> LlAttribute#}\n{#pointer *CK_MECHANISM_INFO as MechInfoPtr -> MechInfo#}\n{#pointer *CK_MECHANISM as MechPtr -> Mech#}\n\n-- defined this one manually because I don't know how to make c2hs to define it yet\ntype GetFunctionListFun = (C2HSImp.Ptr (FunctionListPtr)) -> (IO C2HSImp.CULong)\n\nforeign import ccall unsafe \"dynamic\"\n getFunctionList'_ :: GetFunctionListFunPtr -> GetFunctionListFun\n\ndata Version = Version {\n versionMajor :: Int,\n versionMinor :: Int\n} deriving (Show)\n\ninstance Storable Version where\n sizeOf _ = {#sizeof CK_VERSION#}\n alignment _ = {#alignof CK_VERSION#}\n peek p = Version\n <$> liftM fromIntegral ({#get CK_VERSION->major#} p)\n <*> liftM fromIntegral ({#get CK_VERSION->minor#} p)\n poke p x = do\n {#set CK_VERSION->major#} p (fromIntegral $ versionMajor x)\n {#set CK_VERSION->minor#} p (fromIntegral $ versionMinor x)\n\ndata Info = Info {\n -- | Cryptoki interface version number, for compatibility with future revisions of this interface\n infoCryptokiVersion :: Version,\n -- | ID of the Cryptoki library manufacturer\n infoManufacturerId :: String,\n -- | bit flags reserved for future versions. Must be zero for this version\n infoFlags :: Int,\n infoLibraryDescription :: String,\n -- | Cryptoki library version number\n infoLibraryVersion :: Version\n} deriving (Show)\n\ninstance Storable Info where\n sizeOf _ = (2+32+4+32+10+2)\n alignment _ = 1\n peek p = do\n ver <- peek (p `plusPtr` {#offsetof CK_INFO->cryptokiVersion#}) :: IO Version\n manufacturerId <- peekCStringLen ((p `plusPtr` 2), 32)\n flags <- (\\ptr -> do {C2HSImp.peekByteOff ptr (2+32) :: IO C2HSImp.CULong}) p\n --flags <- {#get CK_INFO->flags#} p\n libraryDescription <- peekCStringLen ((p `plusPtr` (2+32+4+10)), 32)\n --libraryDescription <- {# get CK_INFO->libraryDescription #} p\n libVer <- peek (p `plusPtr` (2+32+4+32+10)) :: IO Version\n return Info {infoCryptokiVersion=ver,\n infoManufacturerId=manufacturerId,\n infoFlags=fromIntegral flags,\n infoLibraryDescription=libraryDescription,\n infoLibraryVersion=libVer\n }\n poke p v = do\n error \"not implemented\"\n\n\npeekInfo :: Ptr Info -> IO Info\npeekInfo ptr = peek ptr\n\n\ndata SlotInfo = SlotInfo {\n slotInfoDescription :: String,\n slotInfoManufacturerId :: String,\n -- | bit flags indicating capabilities and status of the slot as defined in https:\/\/www.cryptsoft.com\/pkcs11doc\/v220\/pkcs11__all_8h.html#aCK_SLOT_INFO\n slotInfoFlags :: Int,\n slotInfoHardwareVersion :: Version,\n slotInfoFirmwareVersion :: Version\n} deriving (Show)\n\ninstance Storable SlotInfo where\n sizeOf _ = (64+32+4+2+2)\n alignment _ = 1\n peek p = do\n description <- peekCStringLen ((p `plusPtr` 0), 64)\n manufacturerId <- peekCStringLen ((p `plusPtr` 64), 32)\n flags <- C2HSImp.peekByteOff p (64+32) :: IO C2HSImp.CULong\n hwVer <- peek (p `plusPtr` (64+32+4)) :: IO Version\n fwVer <- peek (p `plusPtr` (64+32+4+2)) :: IO Version\n return SlotInfo {slotInfoDescription=description,\n slotInfoManufacturerId=manufacturerId,\n slotInfoFlags=fromIntegral flags,\n slotInfoHardwareVersion=hwVer,\n slotInfoFirmwareVersion=fwVer\n }\n poke p v = do\n error \"not implemented\"\n\n\ndata TokenInfo = TokenInfo {\n tokenInfoLabel :: String,\n tokenInfoManufacturerId :: String,\n tokenInfoModel :: String,\n tokenInfoSerialNumber :: String,\n -- | bit flags indicating capabilities and status of the device as defined in https:\/\/www.cryptsoft.com\/pkcs11doc\/v220\/pkcs11__all_8h.html#aCK_TOKEN_INFO\n tokenInfoFlags :: Int--,\n --tokenInfoHardwareVersion :: Version,\n --tokenInfoFirmwareVersion :: Version\n} deriving (Show)\n\ninstance Storable TokenInfo where\n sizeOf _ = (64+32+4+2+2)\n alignment _ = 1\n peek p = do\n label <- peekCStringLen ((p `plusPtr` 0), 32)\n manufacturerId <- peekCStringLen ((p `plusPtr` 32), 32)\n model <- peekCStringLen ((p `plusPtr` (32+32)), 16)\n serialNumber <- peekCStringLen ((p `plusPtr` (32+32+16)), 16)\n flags <- C2HSImp.peekByteOff p (32+32+16+16) :: IO C2HSImp.CULong\n --hwVer <- peek (p `plusPtr` (64+32+4)) :: IO Version\n --fwVer <- peek (p `plusPtr` (64+32+4+2)) :: IO Version\n return TokenInfo {tokenInfoLabel=label,\n tokenInfoManufacturerId=manufacturerId,\n tokenInfoModel=model,\n tokenInfoSerialNumber=serialNumber,\n tokenInfoFlags=fromIntegral flags--,\n --tokenInfoHardwareVersion=hwVer,\n --tokenInfoFirmwareVersion=fwVer\n }\n\n poke p v = do\n error \"not implemented\"\n\n\ndata MechInfo = MechInfo {\n mechInfoMinKeySize :: Int,\n mechInfoMaxKeySize :: Int,\n mechInfoFlags :: Int\n} deriving (Show)\n\ninstance Storable MechInfo where\n sizeOf _ = {#sizeof CK_MECHANISM_INFO#}\n alignment _ = 1\n peek p = MechInfo\n <$> liftM fromIntegral ({#get CK_MECHANISM_INFO->ulMinKeySize#} p)\n <*> liftM fromIntegral ({#get CK_MECHANISM_INFO->ulMaxKeySize#} p)\n <*> liftM fromIntegral ({#get CK_MECHANISM_INFO->flags#} p)\n poke p x = do\n {#set CK_MECHANISM_INFO->ulMinKeySize#} p (fromIntegral $ mechInfoMinKeySize x)\n {#set CK_MECHANISM_INFO->ulMaxKeySize#} p (fromIntegral $ mechInfoMaxKeySize x)\n {#set CK_MECHANISM_INFO->flags#} p (fromIntegral $ mechInfoFlags x)\n\n\ndata Mech = Mech {\n mechType :: MechType,\n mechParamPtr :: Ptr (),\n mechParamSize :: Int\n}\n\ninstance Storable Mech where\n sizeOf _ = {#sizeof CK_MECHANISM_TYPE#} + {#sizeof CK_VOID_PTR#} + {#sizeof CK_ULONG#}\n alignment _ = 1\n peek p = do\n error \"not implemented\"\n poke p x = do\n poke (p `plusPtr` 0) (fromEnum $ mechType x)\n poke (p `plusPtr` {#sizeof CK_MECHANISM_TYPE#}) (mechParamPtr x :: {#type CK_VOID_PTR#})\n poke (p `plusPtr` ({#sizeof CK_MECHANISM_TYPE#} + {#sizeof CK_VOID_PTR#})) (mechParamSize x)\n\n\n\n{#fun unsafe CK_FUNCTION_LIST.C_Initialize as initialize\n {`FunctionListPtr',\n alloca- `()' } -> `Rv' fromIntegral#}\n\n{#fun unsafe CK_FUNCTION_LIST.C_GetInfo as getInfo'\n {`FunctionListPtr',\n alloca- `Info' peekInfo* } -> `Rv' fromIntegral#}\n\n\ngetSlotList' functionListPtr active num = do\n alloca $ \\arrayLenPtr -> do\n poke arrayLenPtr (fromIntegral num)\n allocaArray num $ \\array -> do\n res <- {#call unsafe CK_FUNCTION_LIST.C_GetSlotList#} functionListPtr (fromBool active) array arrayLenPtr\n arrayLen <- peek arrayLenPtr\n slots <- peekArray (fromIntegral arrayLen) array\n return (fromIntegral res, slots)\n\n\n{#fun unsafe CK_FUNCTION_LIST.C_GetSlotInfo as getSlotInfo'\n {`FunctionListPtr',\n `Int',\n alloca- `SlotInfo' peek* } -> `Rv' fromIntegral\n#}\n\n\n{#fun unsafe CK_FUNCTION_LIST.C_GetTokenInfo as getTokenInfo'\n {`FunctionListPtr',\n `Int',\n alloca- `TokenInfo' peek* } -> `Rv' fromIntegral\n#}\n\n\nopenSession' functionListPtr slotId flags =\n alloca $ \\slotIdPtr -> do\n res <- {#call unsafe CK_FUNCTION_LIST.C_OpenSession#} functionListPtr (fromIntegral slotId) (fromIntegral flags) nullPtr nullFunPtr slotIdPtr\n slotId <- peek slotIdPtr\n return (fromIntegral res, fromIntegral slotId)\n\n\n{#fun unsafe CK_FUNCTION_LIST.C_CloseSession as closeSession'\n {`FunctionListPtr',\n `CULong' } -> `Rv' fromIntegral#}\n\n\n{#fun unsafe CK_FUNCTION_LIST.C_Finalize as finalize\n {`FunctionListPtr',\n alloca- `()' } -> `Rv' fromIntegral#}\n\n\ngetFunctionList :: GetFunctionListFunPtr -> IO ((Rv), (FunctionListPtr))\ngetFunctionList getFunctionListPtr =\n alloca $ \\funcListPtrPtr -> do\n res <- (getFunctionList'_ getFunctionListPtr) funcListPtrPtr\n funcListPtr <- peek funcListPtrPtr\n return (fromIntegral res, funcListPtr)\n\n\nfindObjectsInit' functionListPtr session attribs = do\n _withAttribs attribs $ \\attribsPtr -> do\n res <- {#call unsafe CK_FUNCTION_LIST.C_FindObjectsInit#} functionListPtr session attribsPtr (fromIntegral $ length attribs)\n return (fromIntegral res)\n\n\nfindObjects' functionListPtr session maxObjects = do\n alloca $ \\arrayLenPtr -> do\n poke arrayLenPtr (fromIntegral 0)\n allocaArray maxObjects $ \\array -> do\n res <- {#call unsafe CK_FUNCTION_LIST.C_FindObjects#} functionListPtr session array (fromIntegral maxObjects) arrayLenPtr\n arrayLen <- peek arrayLenPtr\n objectHandles <- peekArray (fromIntegral arrayLen) array\n return (fromIntegral res, objectHandles)\n\n\n{#fun unsafe CK_FUNCTION_LIST.C_FindObjectsFinal as findObjectsFinal'\n {`FunctionListPtr',\n `CULong' } -> `Rv' fromIntegral#}\n\n\n{#enum define UserType {CKU_USER as User, CKU_SO as SecurityOfficer, CKU_CONTEXT_SPECIFIC as ContextSpecific} deriving (Eq) #}\n\n\n_login :: FunctionListPtr -> SessionHandle -> UserType -> BU8.ByteString -> IO (Rv)\n_login functionListPtr session userType pin = do\n unsafeUseAsCStringLen pin $ \\(pinPtr, pinLen) -> do\n res <- {#call unsafe CK_FUNCTION_LIST.C_Login#} functionListPtr session (fromIntegral $ fromEnum userType) (castPtr pinPtr) (fromIntegral pinLen)\n return (fromIntegral res)\n\n\n_generateKeyPair :: FunctionListPtr -> SessionHandle -> MechType -> [Attribute] -> [Attribute] -> IO (Rv, ObjectHandle, ObjectHandle)\n_generateKeyPair functionListPtr session mechType pubAttrs privAttrs = do\n alloca $ \\pubKeyHandlePtr -> do\n alloca $ \\privKeyHandlePtr -> do\n alloca $ \\mechPtr -> do\n poke mechPtr (Mech {mechType = mechType, mechParamPtr = nullPtr, mechParamSize = 0})\n _withAttribs pubAttrs $ \\pubAttrsPtr -> do\n _withAttribs privAttrs $ \\privAttrsPtr -> do\n res <- {#call unsafe CK_FUNCTION_LIST.C_GenerateKeyPair#} functionListPtr session mechPtr pubAttrsPtr (fromIntegral $ length pubAttrs) privAttrsPtr (fromIntegral $ length privAttrs) pubKeyHandlePtr privKeyHandlePtr\n pubKeyHandle <- peek pubKeyHandlePtr\n privKeyHandle <- peek privKeyHandlePtr\n return (fromIntegral res, fromIntegral pubKeyHandle, fromIntegral privKeyHandle)\n\n\n\n_getMechanismList :: FunctionListPtr -> Int -> Int -> IO (Rv, [Int])\n_getMechanismList functionListPtr slotId maxMechanisms = do\n alloca $ \\arrayLenPtr -> do\n poke arrayLenPtr (fromIntegral maxMechanisms)\n allocaArray maxMechanisms $ \\array -> do\n res <- {#call unsafe CK_FUNCTION_LIST.C_GetMechanismList#} functionListPtr (fromIntegral slotId) array arrayLenPtr\n arrayLen <- peek arrayLenPtr\n objectHandles <- peekArray (fromIntegral arrayLen) array\n return (fromIntegral res, map (fromIntegral) objectHandles)\n\n\n{#fun unsafe CK_FUNCTION_LIST.C_GetMechanismInfo as _getMechanismInfo\n {`FunctionListPtr',\n `Int',\n `Int',\n alloca- `MechInfo' peek* } -> `Rv' fromIntegral\n#}\n\n\nrvToStr :: Rv -> String\nrvToStr {#const CKR_OK#} = \"ok\"\nrvToStr {#const CKR_ARGUMENTS_BAD#} = \"bad arguments\"\nrvToStr {#const CKR_ATTRIBUTE_READ_ONLY#} = \"attribute is read-only\"\nrvToStr {#const CKR_ATTRIBUTE_TYPE_INVALID#} = \"invalid attribute type specified in template\"\nrvToStr {#const CKR_ATTRIBUTE_VALUE_INVALID#} = \"invalid attribute value specified in template\"\nrvToStr {#const CKR_BUFFER_TOO_SMALL#} = \"buffer too small\"\nrvToStr {#const CKR_CRYPTOKI_NOT_INITIALIZED#} = \"cryptoki not initialized\"\nrvToStr {#const CKR_DATA_INVALID#} = \"data invalid\"\nrvToStr {#const CKR_DEVICE_ERROR#} = \"device error\"\nrvToStr {#const CKR_DEVICE_MEMORY#} = \"device memory\"\nrvToStr {#const CKR_DEVICE_REMOVED#} = \"device removed\"\nrvToStr {#const CKR_DOMAIN_PARAMS_INVALID#} = \"invalid domain parameters\"\nrvToStr {#const CKR_ENCRYPTED_DATA_INVALID#} = \"encrypted data is invalid\"\nrvToStr {#const CKR_ENCRYPTED_DATA_LEN_RANGE#} = \"encrypted data length not in range\"\nrvToStr {#const CKR_FUNCTION_CANCELED#} = \"function canceled\"\nrvToStr {#const CKR_FUNCTION_FAILED#} = \"function failed\"\nrvToStr {#const CKR_GENERAL_ERROR#} = \"general error\"\nrvToStr {#const CKR_HOST_MEMORY#} = \"host memory\"\nrvToStr {#const CKR_KEY_FUNCTION_NOT_PERMITTED#} = \"key function not permitted\"\nrvToStr {#const CKR_KEY_HANDLE_INVALID#} = \"key handle invalid\"\nrvToStr {#const CKR_KEY_SIZE_RANGE#} = \"key size range\"\nrvToStr {#const CKR_KEY_TYPE_INCONSISTENT#} = \"key type inconsistent\"\nrvToStr {#const CKR_MECHANISM_INVALID#} = \"invalid mechanism\"\nrvToStr {#const CKR_MECHANISM_PARAM_INVALID#} = \"invalid mechanism parameter\"\nrvToStr {#const CKR_OPERATION_ACTIVE#} = \"there is already an active operation in-progress\"\nrvToStr {#const CKR_OPERATION_NOT_INITIALIZED#} = \"operation was not initialized\"\nrvToStr {#const CKR_PIN_EXPIRED#} = \"PIN is expired, you need to setup a new PIN\"\nrvToStr {#const CKR_PIN_INCORRECT#} = \"PIN is incorrect, authentication failed\"\nrvToStr {#const CKR_PIN_LOCKED#} = \"PIN is locked, authentication failed\"\nrvToStr {#const CKR_SESSION_CLOSED#} = \"session was closed in a middle of operation\"\nrvToStr {#const CKR_SESSION_COUNT#} = \"session count\"\nrvToStr {#const CKR_SESSION_HANDLE_INVALID#} = \"session handle is invalid\"\nrvToStr {#const CKR_SESSION_PARALLEL_NOT_SUPPORTED#} = \"parallel session not supported\"\nrvToStr {#const CKR_SESSION_READ_ONLY#} = \"session is read-only\"\nrvToStr {#const CKR_SESSION_READ_ONLY_EXISTS#} = \"read-only session exists, SO cannot login\"\nrvToStr {#const CKR_SESSION_READ_WRITE_SO_EXISTS#} = \"read-write SO session exists\"\nrvToStr {#const CKR_SLOT_ID_INVALID#} = \"slot id invalid\"\nrvToStr {#const CKR_TEMPLATE_INCOMPLETE#} = \"provided template is incomplete\"\nrvToStr {#const CKR_TEMPLATE_INCONSISTENT#} = \"provided template is inconsistent\"\nrvToStr {#const CKR_TOKEN_NOT_PRESENT#} = \"token not present\"\nrvToStr {#const CKR_TOKEN_NOT_RECOGNIZED#} = \"token not recognized\"\nrvToStr {#const CKR_TOKEN_WRITE_PROTECTED#} = \"token is write protected\"\nrvToStr {#const CKR_UNWRAPPING_KEY_HANDLE_INVALID#} = \"unwrapping key handle invalid\"\nrvToStr {#const CKR_UNWRAPPING_KEY_SIZE_RANGE#} = \"unwrapping key size not in range\"\nrvToStr {#const CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT#} = \"unwrapping key type inconsistent\"\nrvToStr {#const CKR_USER_NOT_LOGGED_IN#} = \"user needs to be logged in to perform this operation\"\nrvToStr {#const CKR_USER_ALREADY_LOGGED_IN#} = \"user already logged in\"\nrvToStr {#const CKR_USER_ANOTHER_ALREADY_LOGGED_IN#} = \"another user already logged in, first another user should be logged out\"\nrvToStr {#const CKR_USER_PIN_NOT_INITIALIZED#} = \"user PIN not initialized, need to setup PIN first\"\nrvToStr {#const CKR_USER_TOO_MANY_TYPES#} = \"cannot login user, somebody should logout first\"\nrvToStr {#const CKR_USER_TYPE_INVALID#} = \"invalid value for user type\"\nrvToStr {#const CKR_WRAPPED_KEY_INVALID#} = \"wrapped key invalid\"\nrvToStr {#const CKR_WRAPPED_KEY_LEN_RANGE#} = \"wrapped key length not in range\"\nrvToStr rv = \"unknown value for error \" ++ (show rv)\n\n\n-- Attributes\n\n{#enum define ClassType {\n CKO_DATA as Data,\n CKO_CERTIFICATE as Certificate,\n CKO_PUBLIC_KEY as PublicKey,\n CKO_PRIVATE_KEY as PrivateKey,\n CKO_SECRET_KEY as SecretKey,\n CKO_HW_FEATURE as HWFeature,\n CKO_DOMAIN_PARAMETERS as DomainParameters,\n CKO_MECHANISM as Mechanism\n} deriving (Show, Eq)\n#}\n\n{#enum define KeyTypeValue {\n CKK_RSA as RSA,\n CKK_DSA as DSA,\n CKK_DH as DH,\n CKK_ECDSA as ECDSA,\n CKK_EC as EC,\n CKK_AES as AES\n } deriving (Show, Eq) #}\n\n{#enum define AttributeType {\n CKA_CLASS as ClassType,\n CKA_TOKEN as TokenType,\n CKA_PRIVATE as PrivateType,\n CKA_LABEL as LabelType,\n CKA_APPLICATION as ApplicationType,\n CKA_VALUE as ValueType,\n CKA_OBJECT_ID as ObjectType,\n CKA_CERTIFICATE_TYPE as CertificateType,\n CKA_ISSUER as IssuerType,\n CKA_SERIAL_NUMBER as SerialNumberType,\n CKA_AC_ISSUER as AcIssuerType,\n CKA_OWNER as OwnerType,\n CKA_ATTR_TYPES as AttrTypesType,\n CKA_TRUSTED as TrustedType,\n CKA_CERTIFICATE_CATEGORY as CertificateCategoryType,\n CKA_JAVA_MIDP_SECURITY_DOMAIN as JavaMidpSecurityDomainType,\n CKA_URL as UrlType,\n CKA_HASH_OF_SUBJECT_PUBLIC_KEY as HashOfSubjectPublicKeyType,\n CKA_HASH_OF_ISSUER_PUBLIC_KEY as HashOfIssuerPublicKeyType,\n CKA_CHECK_VALUE as CheckValueType,\n\n CKA_KEY_TYPE as KeyTypeType,\n CKA_SUBJECT as SubjectType,\n CKA_ID as IdType,\n CKA_SENSITIVE as SensitiveType,\n CKA_ENCRYPT as EncryptType,\n CKA_DECRYPT as DecryptType,\n CKA_WRAP as WrapType,\n CKA_UNWRAP as UnwrapType,\n CKA_SIGN as SignType,\n CKA_SIGN_RECOVER as SignRecoverType,\n CKA_VERIFY as VerifyType,\n CKA_VERIFY_RECOVER as VerifyRecoverType,\n CKA_DERIVE as DeriveType,\n CKA_START_DATE as StartDateType,\n CKA_END_DATE as EndDataType,\n CKA_PUBLIC_EXPONENT as PublicExponentType,\n CKA_PRIVATE_EXPONENT as PrivateExponentType,\n CKA_MODULUS as ModulusType,\n CKA_MODULUS_BITS as ModulusBitsType,\n CKA_PRIME_1 as Prime1Type,\n CKA_PRIME_2 as Prime2Type,\n CKA_EXPONENT_1 as Exponent1Type,\n CKA_EXPONENT_2 as Exponent2Type,\n CKA_COEFFICIENT as CoefficientType,\n\n CKA_PRIME_BITS as PrimeBitsType,\n CKA_SUBPRIME_BITS as SubPrimeBitsType,\n\n CKA_VALUE_BITS as ValueBitsType,\n CKA_VALUE_LEN as ValueLenType,\n CKA_EXTRACTABLE as ExtractableType,\n CKA_LOCAL as LocalType,\n CKA_NEVER_EXTRACTABLE as NeverExtractableType,\n CKA_ALWAYS_SENSITIVE as AlwaysSensitiveType,\n CKA_KEY_GEN_MECHANISM as KeyGenMechanismType,\n\n CKA_MODIFIABLE as ModifiableType,\n\n -- CKA_ECDSA_PARAMS is deprecated in v2.11,\n -- CKA_EC_PARAMS is preferred.\n CKA_ECDSA_PARAMS as EcdsaParamsType,\n CKA_EC_PARAMS as EcParamsType,\n\n CKA_EC_POINT as EcPointType,\n\n -- CKA_SECONDARY_AUTH, CKA_AUTH_PIN_FLAGS,\n -- are new for v2.10. Deprecated in v2.11 and onwards.\n CKA_SECONDARY_AUTH as SecondaryAuthType,\n CKA_AUTH_PIN_FLAGS as AuthPinFlagsType,\n\n CKA_ALWAYS_AUTHENTICATE as AlwaysAuthenticateType,\n\n CKA_WRAP_WITH_TRUSTED as WrapWithTrustedType,\n CKA_WRAP_TEMPLATE as WrapTemplateType,\n CKA_UNWRAP_TEMPLATE as UnwrapTemplateType,\n CKA_DERIVE_TEMPLATE as DeriveTemplateType,\n\n CKA_OTP_FORMAT as OtpFormatType,\n CKA_OTP_LENGTH as OtpLengthType,\n CKA_OTP_TIME_INTERVAL as OtpTimeIntervalType,\n CKA_OTP_USER_FRIENDLY_MODE as OtpUserFriendlyModeType,\n CKA_OTP_CHALLENGE_REQUIREMENT as OtpChallengeRequirementType,\n CKA_OTP_TIME_REQUIREMENT as OtpTimeRequirementType,\n CKA_OTP_COUNTER_REQUIREMENT as OtpCounterRequirementType,\n CKA_OTP_PIN_REQUIREMENT as OtpPinRequirementType,\n CKA_OTP_COUNTER as OtpCounterType,\n CKA_OTP_TIME as OtpTimeType,\n CKA_OTP_USER_IDENTIFIER as OtpUserIdentifierType,\n CKA_OTP_SERVICE_IDENTIFIER as OtpServiceIdentifierType,\n CKA_OTP_SERVICE_LOGO as OtpServiceLogoType,\n CKA_OTP_SERVICE_LOGO_TYPE as OtpServiceLogoTypeType,\n\n CKA_GOSTR3410_PARAMS as GostR3410ParamsType,\n CKA_GOSTR3411_PARAMS as GostR3411ParamsType,\n CKA_GOST28147_PARAMS as Gost28147ParamsType,\n\n CKA_HW_FEATURE_TYPE as HwFeatureTypeType,\n CKA_RESET_ON_INIT as ResetOnInitType,\n CKA_HAS_RESET as HasResetType,\n\n CKA_PIXEL_X as PixelXType,\n CKA_PIXEL_Y as PixelYType,\n CKA_RESOLUTION as ResolutionType,\n CKA_CHAR_ROWS as CharRowsType,\n CKA_CHAR_COLUMNS as CharColumnsType,\n CKA_COLOR as ColorType,\n CKA_BITS_PER_PIXEL as BitPerPixelType,\n CKA_CHAR_SETS as CharSetsType,\n CKA_ENCODING_METHODS as EncodingMethodsType,\n CKA_MIME_TYPES as MimeTypesType,\n CKA_MECHANISM_TYPE as MechanismTypeType,\n CKA_REQUIRED_CMS_ATTRIBUTES as RequiredCmsAttributesType,\n CKA_DEFAULT_CMS_ATTRIBUTES as DefaultCmsAttributesType,\n CKA_SUPPORTED_CMS_ATTRIBUTES as SupportedCmsAttributesType,\n CKA_ALLOWED_MECHANISMS as AllowedMechanismsType,\n\n CKA_VENDOR_DEFINED as VendorDefinedType\n } deriving (Show, Eq) #}\n\ndata Attribute = Class ClassType\n | KeyType KeyTypeValue\n | Label String\n | ModulusBits Int\n | Token Bool\n | Decrypt Bool\n | Sign Bool\n | Modulus Integer\n | PublicExponent Integer\n deriving (Show)\n\ndata LlAttribute = LlAttribute {\n attributeType :: AttributeType,\n attributeValuePtr :: Ptr (),\n attributeSize :: {#type CK_ULONG#}\n}\n\ninstance Storable LlAttribute where\n sizeOf _ = {#sizeof CK_ATTRIBUTE_TYPE#} + {#sizeof CK_VOID_PTR#} + {#sizeof CK_ULONG#}\n alignment _ = 1\n poke p x = do\n poke (p `plusPtr` 0) (fromEnum $ attributeType x)\n poke (p `plusPtr` {#sizeof CK_ATTRIBUTE_TYPE#}) (attributeValuePtr x :: {#type CK_VOID_PTR#})\n poke (p `plusPtr` ({#sizeof CK_ATTRIBUTE_TYPE#} + {#sizeof CK_VOID_PTR#})) (attributeSize x)\n peek p = do\n attrType <- peek (p `plusPtr` 0) :: IO {#type CK_ATTRIBUTE_TYPE#}\n valPtr <- peek (p `plusPtr` {#sizeof CK_ATTRIBUTE_TYPE#})\n valSize <- peek (p `plusPtr` ({#sizeof CK_ATTRIBUTE_TYPE#} + {#sizeof CK_VOID_PTR#}))\n return $ LlAttribute (toEnum $ fromIntegral attrType) valPtr valSize\n\n\n_attrType :: Attribute -> AttributeType\n_attrType (Class _) = ClassType\n_attrType (KeyType _) = KeyTypeType\n_attrType (Label _) = LabelType\n_attrType (ModulusBits _) = ModulusBitsType\n_attrType (Token _) = TokenType\n\n\n_valueSize :: Attribute -> Int\n_valueSize (Class _) = {#sizeof CK_OBJECT_CLASS#}\n_valueSize (KeyType _) = {#sizeof CK_KEY_TYPE#}\n_valueSize (Label l) = BU8.length $ BU8.fromString l\n_valueSize (ModulusBits _) = {#sizeof CK_ULONG#}\n_valueSize (Token _) = {#sizeof CK_BBOOL#}\n\n\n_pokeValue :: Attribute -> Ptr () -> IO ()\n_pokeValue (Class c) ptr = poke (castPtr ptr :: Ptr {#type CK_OBJECT_CLASS#}) (fromIntegral $ fromEnum c)\n_pokeValue (KeyType k) ptr = poke (castPtr ptr :: Ptr {#type CK_KEY_TYPE#}) (fromIntegral $ fromEnum k)\n_pokeValue (Label l) ptr = unsafeUseAsCStringLen (BU8.fromString l) $ \\(src, len) -> copyBytes ptr (castPtr src :: Ptr ()) len\n_pokeValue (ModulusBits l) ptr = poke (castPtr ptr :: Ptr {#type CK_ULONG#}) (fromIntegral l :: {#type CK_KEY_TYPE#})\n_pokeValue (Token b) ptr = poke (castPtr ptr :: Ptr {#type CK_BBOOL#}) (fromBool b :: {#type CK_BBOOL#})\n\n\n_pokeValues :: [Attribute] -> Ptr () -> IO ()\n_pokeValues [] p = return ()\n_pokeValues (a:rem) p = do\n _pokeValue a p\n _pokeValues rem (p `plusPtr` (_valueSize a))\n\n\n_valuesSize :: [Attribute] -> Int\n_valuesSize attribs = foldr (+) 0 (map (_valueSize) attribs)\n\n\n_makeLowLevelAttrs :: [Attribute] -> Ptr () -> [LlAttribute]\n_makeLowLevelAttrs [] valuePtr = []\n_makeLowLevelAttrs (a:rem) valuePtr =\n let valuePtr' = valuePtr `plusPtr` (_valueSize a)\n llAttr = LlAttribute {attributeType=_attrType a, attributeValuePtr=valuePtr, attributeSize=(fromIntegral $ _valueSize a)}\n in\n llAttr:(_makeLowLevelAttrs rem valuePtr')\n\n\n_withAttribs :: [Attribute] -> (Ptr LlAttribute -> IO a) -> IO a\n_withAttribs attribs f = do\n allocaBytes (_valuesSize attribs) $ \\valuesPtr -> do\n _pokeValues attribs valuesPtr\n allocaArray (length attribs) $ \\attrsPtr -> do\n pokeArray attrsPtr (_makeLowLevelAttrs attribs valuesPtr)\n f attrsPtr\n\n\n_peekBigInt :: Ptr () -> CULong -> IO Integer\n_peekBigInt ptr len = do\n arr <- peekArray (fromIntegral len) (castPtr ptr :: Ptr Word8)\n return $ foldl (\\acc v -> (fromIntegral v) + (acc * 256)) 0 arr\n\n\n_llAttrToAttr :: LlAttribute -> IO Attribute\n_llAttrToAttr (LlAttribute ClassType ptr len) = do\n val <- peek (castPtr ptr :: Ptr {#type CK_OBJECT_CLASS#})\n return (Class $ toEnum $ fromIntegral val)\n_llAttrToAttr (LlAttribute ModulusType ptr len) = do\n val <- _peekBigInt ptr len\n return (Modulus val)\n_llAttrToAttr (LlAttribute PublicExponentType ptr len) = do\n val <- _peekBigInt ptr len\n return (PublicExponent val)\n_llAttrToAttr (LlAttribute DecryptType ptr len) = do\n val <- peek (castPtr ptr :: Ptr {#type CK_BBOOL#})\n return $ Decrypt(val \/= 0)\n_llAttrToAttr (LlAttribute SignType ptr len) = do\n val <- peek (castPtr ptr :: Ptr {#type CK_BBOOL#})\n return $ Sign(val \/= 0)\n\n\n-- High level API starts here\n\n\ndata Library = Library {\n libraryHandle :: DL,\n functionListPtr :: FunctionListPtr\n}\n\n\ndata Session = Session SessionHandle FunctionListPtr\n\n\n-- | Load PKCS#11 dynamically linked library\n--\n-- > lib <- loadLibrary \"\/path\/to\/dll.so\"\nloadLibrary :: String -> IO Library\nloadLibrary libraryPath = do\n lib <- dlopen libraryPath []\n getFunctionListFunPtr <- dlsym lib \"C_GetFunctionList\"\n (rv, functionListPtr) <- getFunctionList getFunctionListFunPtr\n if rv \/= 0\n then fail $ \"failed to get list of functions \" ++ (rvToStr rv)\n else do\n rv <- initialize functionListPtr\n if rv \/= 0\n then fail $ \"failed to initialize library \" ++ (rvToStr rv)\n else return Library { libraryHandle = lib, functionListPtr = functionListPtr }\n\n\nreleaseLibrary lib = do\n rv <- finalize $ functionListPtr lib\n dlclose $ libraryHandle lib\n\n\n-- | Returns general information about Cryptoki\ngetInfo :: Library -> IO Info\ngetInfo (Library _ functionListPtr) = do\n (rv, info) <- getInfo' functionListPtr\n if rv \/= 0\n then fail $ \"failed to get library information \" ++ (rvToStr rv)\n else return info\n\n\n-- | Allows to obtain a list of slots in the system\n--\n-- > slotsIds <- getSlotList lib True 10\n--\n-- In this example retrieves list of, at most 10 (third parameter) slot identifiers with tokens present (second parameter is set to True)\ngetSlotList :: Library -> Bool -> Int -> IO [SlotId]\ngetSlotList (Library _ functionListPtr) active num = do\n (rv, slots) <- getSlotList' functionListPtr active num\n if rv \/= 0\n then fail $ \"failed to get list of slots \" ++ (rvToStr rv)\n else return $ map (fromIntegral) slots\n\n\n-- | Obtains information about a particular slot in the system\n--\n-- > slotInfo <- getSlotInfo lib slotId\ngetSlotInfo :: Library -> SlotId -> IO SlotInfo\ngetSlotInfo (Library _ functionListPtr) slotId = do\n (rv, slotInfo) <- getSlotInfo' functionListPtr slotId\n if rv \/= 0\n then fail $ \"failed to get slot information \" ++ (rvToStr rv)\n else return slotInfo\n\n\n-- | Obtains information about a particular token in the system\n--\n-- > tokenInfo <- getTokenInfo lib slotId\ngetTokenInfo :: Library -> SlotId -> IO TokenInfo\ngetTokenInfo (Library _ functionListPtr) slotId = do\n (rv, slotInfo) <- getTokenInfo' functionListPtr slotId\n if rv \/= 0\n then fail $ \"failed to get token information \" ++ (rvToStr rv)\n else return slotInfo\n\n\n_openSessionEx :: Library -> SlotId -> Int -> IO Session\n_openSessionEx (Library _ functionListPtr) slotId flags = do\n (rv, sessionHandle) <- openSession' functionListPtr slotId flags\n if rv \/= 0\n then fail $ \"failed to open slot: \" ++ (rvToStr rv)\n else return $ Session sessionHandle functionListPtr\n\n\n_closeSessionEx :: Session -> IO ()\n_closeSessionEx (Session sessionHandle functionListPtr) = do\n rv <- closeSession' functionListPtr sessionHandle\n if rv \/= 0\n then fail $ \"failed to close slot: \" ++ (rvToStr rv)\n else return ()\n\n\nwithSession :: Library -> SlotId -> Bool -> (Session -> IO a) -> IO a\nwithSession lib slotId writable f = do\n let flags = if writable then _rwSession else 0\n bracket\n (_openSessionEx lib slotId (flags .|. _serialSession))\n (_closeSessionEx)\n (f)\n\n\n\n_findObjectsInitEx :: Session -> [Attribute] -> IO ()\n_findObjectsInitEx (Session sessionHandle functionListPtr) attribs = do\n rv <- findObjectsInit' functionListPtr sessionHandle attribs\n if rv \/= 0\n then fail $ \"failed to initialize search: \" ++ (rvToStr rv)\n else return ()\n\n\n_findObjectsEx :: Session -> IO [ObjectHandle]\n_findObjectsEx (Session sessionHandle functionListPtr) = do\n (rv, objectsHandles) <- findObjects' functionListPtr sessionHandle 10\n if rv \/= 0\n then fail $ \"failed to execute search: \" ++ (rvToStr rv)\n else return objectsHandles\n\n\n_findObjectsFinalEx :: Session -> IO ()\n_findObjectsFinalEx (Session sessionHandle functionListPtr) = do\n rv <- findObjectsFinal' functionListPtr sessionHandle\n if rv \/= 0\n then fail $ \"failed to finalize search: \" ++ (rvToStr rv)\n else return ()\n\n\nfindObjects :: Session -> [Attribute] -> IO [ObjectHandle]\nfindObjects session attribs = do\n _findObjectsInitEx session attribs\n finally (_findObjectsEx session) (_findObjectsFinalEx session)\n\n\ngenerateKeyPair :: Session -> MechType -> [Attribute] -> [Attribute] -> IO (ObjectHandle, ObjectHandle)\ngenerateKeyPair (Session sessionHandle functionListPtr) mechType pubKeyAttrs privKeyAttrs = do\n (rv, pubKeyHandle, privKeyHandle) <- _generateKeyPair functionListPtr sessionHandle mechType pubKeyAttrs privKeyAttrs\n if rv \/= 0\n then fail $ \"failed to generate key pair: \" ++ (rvToStr rv)\n else return (pubKeyHandle, privKeyHandle)\n\n\n_getAttr :: Session -> ObjectHandle -> AttributeType -> Ptr x -> IO ()\n_getAttr (Session sessionHandle functionListPtr) objHandle attrType valPtr = do\n alloca $ \\attrPtr -> do\n poke attrPtr (LlAttribute attrType (castPtr valPtr) (fromIntegral $ sizeOf valPtr))\n rv <- {#call unsafe CK_FUNCTION_LIST.C_GetAttributeValue#} functionListPtr sessionHandle objHandle attrPtr 1\n if rv \/= 0\n then fail $ \"failed to get attribute: \" ++ (rvToStr rv)\n else return ()\n\n\ngetBoolAttr :: Session -> ObjectHandle -> AttributeType -> IO Bool\ngetBoolAttr sess objHandle attrType = do\n alloca $ \\valuePtr -> do\n _getAttr sess objHandle attrType (valuePtr :: Ptr CK_BBOOL)\n val <- peek valuePtr\n return $ toBool val\n\n\ngetObjectAttr :: Session -> ObjectHandle -> AttributeType -> IO Attribute\ngetObjectAttr (Session sessionHandle functionListPtr) objHandle attrType = do\n alloca $ \\attrPtr -> do\n poke attrPtr (LlAttribute attrType nullPtr 0)\n rv <- {#call unsafe CK_FUNCTION_LIST.C_GetAttributeValue#} functionListPtr sessionHandle objHandle attrPtr 1\n attrWithLen <- peek attrPtr\n allocaBytes (fromIntegral $ attributeSize attrWithLen) $ \\attrVal -> do\n poke attrPtr (LlAttribute attrType attrVal (attributeSize attrWithLen))\n rv <- {#call unsafe CK_FUNCTION_LIST.C_GetAttributeValue#} functionListPtr sessionHandle objHandle attrPtr 1\n if rv \/= 0\n then fail $ \"failed to get attribute: \" ++ (rvToStr rv)\n else do\n llAttr <- peek attrPtr\n _llAttrToAttr llAttr\n\n\ngetTokenFlag sess objHandle = getBoolAttr sess objHandle TokenType\ngetPrivateFlag sess objHandle = getBoolAttr sess objHandle PrivateType\ngetSensitiveFlag sess objHandle = getBoolAttr sess objHandle SensitiveType\ngetEncryptFlag sess objHandle = getBoolAttr sess objHandle EncryptType\ngetDecryptFlag sess objHandle = getBoolAttr sess objHandle DecryptType\ngetWrapFlag sess objHandle = getBoolAttr sess objHandle WrapType\ngetUnwrapFlag sess objHandle = getBoolAttr sess objHandle UnwrapType\ngetSignFlag sess objHandle = getBoolAttr sess objHandle SignType\n\ngetModulus :: Session -> ObjectHandle -> IO Integer\ngetModulus sess objHandle = do\n (Modulus m) <- getObjectAttr sess objHandle ModulusType\n return m\n\ngetPublicExponent :: Session -> ObjectHandle -> IO Integer\ngetPublicExponent sess objHandle = do\n (PublicExponent v) <- getObjectAttr sess objHandle PublicExponentType\n return v\n\n\nlogin :: Session -> UserType -> BU8.ByteString -> IO ()\nlogin (Session sessionHandle functionListPtr) userType pin = do\n rv <- _login functionListPtr sessionHandle userType pin\n if rv \/= 0\n then fail $ \"login failed: \" ++ (rvToStr rv)\n else return ()\n\n\nlogout :: Session -> IO ()\nlogout (Session sessionHandle functionListPtr) = do\n rv <- {#call unsafe CK_FUNCTION_LIST.C_Logout#} functionListPtr sessionHandle\n if rv \/= 0\n then fail $ \"logout failed: \" ++ (rvToStr rv)\n else return ()\n\n\n{#enum define MechType {\n CKM_RSA_PKCS_KEY_PAIR_GEN as RsaPkcsKeyPairGen,\n CKM_RSA_PKCS as RsaPkcs,\n CKM_RSA_9796 as Rsa9796,\n CKM_RSA_X_509 as RsaX509,\n CKM_MD2_RSA_PKCS as Md2RsaPkcs,-- 0x00000004\n CKM_MD5_RSA_PKCS as Md5RsaPkcs,-- 0x00000005\n CKM_SHA1_RSA_PKCS as Sha1RsaPkcs,-- 0x00000006\n CKM_RIPEMD128_RSA_PKCS as RipeMd128RsaPkcs,-- 0x00000007\n CKM_RIPEMD160_RSA_PKCS as RipeMd160RsaPkcs,-- 0x00000008\n CKM_RSA_PKCS_OAEP as RsaPkcsOaep,-- 0x00000009\n CKM_RSA_X9_31_KEY_PAIR_GEN as RsaX931KeyPairGen,-- 0x0000000A\n CKM_RSA_X9_31 as RsaX931,-- 0x0000000B\n CKM_SHA1_RSA_X9_31 as Sha1RsaX931,-- 0x0000000C\n CKM_RSA_PKCS_PSS as RsaPkcsPss,-- 0x0000000D\n CKM_SHA1_RSA_PKCS_PSS as Sha1RsaPkcsPss,-- 0x0000000E\n CKM_DSA_KEY_PAIR_GEN as DsaKeyPairGen,-- 0x00000010\n CKM_DSA as Dsa,-- 0x00000011\n CKM_DSA_SHA1 as DsaSha1,-- 0x00000012\n CKM_DH_PKCS_KEY_PAIR_GEN as DhPkcsKeyPairGen,-- 0x00000020\n CKM_DH_PKCS_DERIVE as DhPkcsDerive,-- 0x00000021\n CKM_X9_42_DH_KEY_PAIR_GEN as X942DhKeyPairGen,-- 0x00000030\n CKM_X9_42_DH_DERIVE as X942DhDerive,-- 0x00000031\n CKM_X9_42_DH_HYBRID_DERIVE as X942DhHybridDerive,-- 0x00000032\n CKM_X9_42_MQV_DERIVE as X942MqvDerive,-- 0x00000033\n CKM_SHA256_RSA_PKCS as Sha256RsaPkcs,-- 0x00000040\n CKM_SHA384_RSA_PKCS as Sha384RsaPkcs,-- 0x00000041\n CKM_SHA512_RSA_PKCS as Sha512RsaPkcs,-- 0x00000042\n CKM_SHA256_RSA_PKCS_PSS as Sha256RsaPkcsPss,-- 0x00000043\n CKM_SHA384_RSA_PKCS_PSS as Sha384RsaPkcsPss,-- 0x00000044\n CKM_SHA512_RSA_PKCS_PSS as Sha512RsaPkcsPss,-- 0x00000045\n\n -- SHA-224 RSA mechanisms are new for PKCS #11 v2.20 amendment 3\n CKM_SHA224_RSA_PKCS as Sha224RsaPkcs,-- 0x00000046\n CKM_SHA224_RSA_PKCS_PSS as Sha224RsaPkcsPss,-- 0x00000047\n\n CKM_RC2_KEY_GEN as Rc2KeyGen,-- 0x00000100\n CKM_RC2_ECB as Rc2Ecb,-- 0x00000101\n CKM_RC2_CBC as Rc2Cbc,-- 0x00000102\n CKM_RC2_MAC as Rc2Mac,-- 0x00000103\n\n -- CKM_RC2_MAC_GENERAL and CKM_RC2_CBC_PAD are new for v2.0\n CKM_RC2_MAC_GENERAL as Rc2MacGeneral,-- 0x00000104\n CKM_RC2_CBC_PAD as Rc2CbcPad,--0x00000105\n\n CKM_RC4_KEY_GEN as Rc4KeyGen,--0x00000110\n CKM_RC4 as Rc4,--0x00000111\n CKM_DES_KEY_GEN as DesKeyGen,--0x00000120\n CKM_DES_ECB as DesEcb,--0x00000121\n CKM_DES_CBC as DesCbc,--0x00000122\n CKM_DES_MAC as DesMac,--0x00000123\n\n -- CKM_DES_MAC_GENERAL and CKM_DES_CBC_PAD are new for v2.0\n CKM_DES_MAC_GENERAL as DesMacGeneral,--0x00000124\n CKM_DES_CBC_PAD as DesCbcPad,--0x00000125\n\n CKM_DES2_KEY_GEN as Des2KeyGen,--0x00000130\n CKM_DES3_KEY_GEN as Des3KeyGen,--0x00000131\n CKM_DES3_ECB as Des3Ecb,--0x00000132\n CKM_DES3_CBC as Des3Cbc,--0x00000133\n CKM_DES3_MAC as Des3Mac,--0x00000134\n\n -- CKM_DES3_MAC_GENERAL, CKM_DES3_CBC_PAD, CKM_CDMF_KEY_GEN,\n -- CKM_CDMF_ECB, CKM_CDMF_CBC, CKM_CDMF_MAC,\n -- CKM_CDMF_MAC_GENERAL, and CKM_CDMF_CBC_PAD are new for v2.0\n CKM_DES3_MAC_GENERAL as Des3MacGeneral,--0x00000135\n CKM_DES3_CBC_PAD as Des3CbcPad,--0x00000136\n CKM_CDMF_KEY_GEN as CdmfKeyGen,--0x00000140\n CKM_CDMF_ECB as CdmfEcb,--0x00000141\n CKM_CDMF_CBC as CdmfCbc,--0x00000142\n CKM_CDMF_MAC as CdmfMac,--0x00000143\n CKM_CDMF_MAC_GENERAL as CdmfMacGeneral,--0x00000144\n CKM_CDMF_CBC_PAD as CdmfCbcPad,--0x00000145\n\n -- the following four DES mechanisms are new for v2.20\n CKM_DES_OFB64 as DesOfb64,--0x00000150\n CKM_DES_OFB8 as DesOfb8,--0x00000151\n CKM_DES_CFB64 as DesCfb64,--0x00000152\n CKM_DES_CFB8 as DesCfb8,--0x00000153\n\n CKM_MD2 as Md2,--0x00000200\n\n -- CKM_MD2_HMAC and CKM_MD2_HMAC_GENERAL are new for v2.0\n CKM_MD2_HMAC as Md2Hmac,--0x00000201\n CKM_MD2_HMAC_GENERAL as Md2HmacGeneral,--0x00000202\n\n CKM_MD5 as Md5,--0x00000210\n\n -- CKM_MD5_HMAC and CKM_MD5_HMAC_GENERAL are new for v2.0\n CKM_MD5_HMAC as Md5Hmac,--0x00000211\n CKM_MD5_HMAC_GENERAL as Md5HmacGeneral,--0x00000212\n\n CKM_SHA_1 as Sha1,--0x00000220\n\n -- CKM_SHA_1_HMAC and CKM_SHA_1_HMAC_GENERAL are new for v2.0\n CKM_SHA_1_HMAC as Sha1Hmac,--0x00000221\n CKM_SHA_1_HMAC_GENERAL as Sha1HmacGeneral,--0x00000222\n\n -- CKM_RIPEMD128, CKM_RIPEMD128_HMAC,\n -- CKM_RIPEMD128_HMAC_GENERAL, CKM_RIPEMD160, CKM_RIPEMD160_HMAC,\n -- and CKM_RIPEMD160_HMAC_GENERAL are new for v2.10\n CKM_RIPEMD128 as RipeMd128,--0x00000230\n CKM_RIPEMD128_HMAC as RipeMd128Hmac,--0x00000231\n CKM_RIPEMD128_HMAC_GENERAL as RipeMd128HmacGeneral,--0x00000232\n CKM_RIPEMD160 as Ripe160,--0x00000240\n CKM_RIPEMD160_HMAC as Ripe160Hmac,--0x00000241\n CKM_RIPEMD160_HMAC_GENERAL as Ripe160HmacGeneral,--0x00000242\n\n -- CKM_SHA256\/384\/512 are new for v2.20\n CKM_SHA256 as Sha256,--0x00000250\n CKM_SHA256_HMAC as Sha256Hmac,--0x00000251\n CKM_SHA256_HMAC_GENERAL as Sha256HmacGeneral,--0x00000252\n\n -- SHA-224 is new for PKCS #11 v2.20 amendment 3\n CKM_SHA224 as Sha224,--0x00000255\n CKM_SHA224_HMAC as Sha224Hmac,--0x00000256\n CKM_SHA224_HMAC_GENERAL as Sha224HmacGeneral,--0x00000257\n\n CKM_SHA384 as Sha384,--0x00000260\n CKM_SHA384_HMAC as Sha384Hmac,--0x00000261\n CKM_SHA384_HMAC_GENERAL as Sha384HmacGeneral,--0x00000262\n CKM_SHA512 as Sha512,--0x00000270\n CKM_SHA512_HMAC as Sha512Hmac,--0x00000271\n CKM_SHA512_HMAC_GENERAL as Sha512HmacGeneral,--0x00000272\n\n -- SecurID is new for PKCS #11 v2.20 amendment 1\n --CKM_SECURID_KEY_GEN 0x00000280\n --CKM_SECURID 0x00000282\n\n -- HOTP is new for PKCS #11 v2.20 amendment 1\n --CKM_HOTP_KEY_GEN 0x00000290\n --CKM_HOTP 0x00000291\n\n -- ACTI is new for PKCS #11 v2.20 amendment 1\n --CKM_ACTI 0x000002A0\n --CKM_ACTI_KEY_GEN 0x000002A1\n\n -- All of the following mechanisms are new for v2.0\n -- Note that CAST128 and CAST5 are the same algorithm\n CKM_CAST_KEY_GEN as CastKeyGen,--0x00000300\n CKM_CAST_ECB as CastEcb,--0x00000301\n CKM_CAST_CBC as CastCbc,--0x00000302\n CKM_CAST_MAC as CastMac,--0x00000303\n CKM_CAST_MAC_GENERAL as CastMacGeneral,--0x00000304\n CKM_CAST_CBC_PAD as CastCbcPad,--0x00000305\n CKM_CAST3_KEY_GEN as Cast3KeyGen,--0x00000310\n CKM_CAST3_ECB as Cast3Ecb,--0x00000311\n CKM_CAST3_CBC as Cast3Cbc,--0x00000312\n CKM_CAST3_MAC as Cast3Mac,--0x00000313\n CKM_CAST3_MAC_GENERAL as Cast3MacGeneral,--0x00000314\n CKM_CAST3_CBC_PAD as Cast3CbcPad,--0x00000315\n CKM_CAST5_KEY_GEN as Cast5KeyGen,--0x00000320\n CKM_CAST128_KEY_GEN as Cast128KeyGen,--0x00000320\n CKM_CAST5_ECB as Cast5Ecb,--0x00000321\n CKM_CAST128_ECB as Cast128Ecb,--0x00000321\n CKM_CAST5_CBC as Cast5Cbc,--0x00000322\n CKM_CAST128_CBC as Cast128Cbc,--0x00000322\n CKM_CAST5_MAC as Cast5Mac,--0x00000323\n CKM_CAST128_MAC as Cast128Mac,--0x00000323\n CKM_CAST5_MAC_GENERAL as Cast5MacGeneral,--0x00000324\n CKM_CAST128_MAC_GENERAL as Cast128MacGeneral,--0x00000324\n CKM_CAST5_CBC_PAD as Cast5CbcPad,--0x00000325\n CKM_CAST128_CBC_PAD as Cast128CbcPad,--0x00000325\n CKM_RC5_KEY_GEN as Rc5KeyGen,--0x00000330\n CKM_RC5_ECB as Rc5Ecb,--0x00000331\n CKM_RC5_CBC as Rc5Cbc,--0x00000332\n CKM_RC5_MAC as Rc5Mac,--0x00000333\n CKM_RC5_MAC_GENERAL as Rc5MacGeneral,--0x00000334\n CKM_RC5_CBC_PAD as Rc5CbcPad,--0x00000335\n CKM_IDEA_KEY_GEN as IdeaKeyGen,--0x00000340\n CKM_IDEA_ECB as IdeaEcb,--0x00000341\n CKM_IDEA_CBC as IdeaCbc,--0x00000342\n CKM_IDEA_MAC as IdeaMac,--0x00000343\n CKM_IDEA_MAC_GENERAL as IdeaMacGeneral,--0x00000344\n CKM_IDEA_CBC_PAD as IdeaCbcPad,--0x00000345\n CKM_GENERIC_SECRET_KEY_GEN as GeneralSecretKeyGen,--0x00000350\n CKM_CONCATENATE_BASE_AND_KEY as ConcatenateBaseAndKey,--0x00000360\n CKM_CONCATENATE_BASE_AND_DATA as ConcatenateBaseAndData,--0x00000362\n CKM_CONCATENATE_DATA_AND_BASE as ConcatenateDataAndBase,--0x00000363\n CKM_XOR_BASE_AND_DATA as XorBaseAndData,--0x00000364\n CKM_EXTRACT_KEY_FROM_KEY as ExtractKeyFromKey,--0x00000365\n CKM_SSL3_PRE_MASTER_KEY_GEN as Ssl3PreMasterKeyGen,--0x00000370\n CKM_SSL3_MASTER_KEY_DERIVE as Ssl3MasterKeyDerive,--0x00000371\n CKM_SSL3_KEY_AND_MAC_DERIVE as Ssl3KeyAndMacDerive,--0x00000372\n\n -- CKM_SSL3_MASTER_KEY_DERIVE_DH, CKM_TLS_PRE_MASTER_KEY_GEN,\n -- CKM_TLS_MASTER_KEY_DERIVE, CKM_TLS_KEY_AND_MAC_DERIVE, and\n -- CKM_TLS_MASTER_KEY_DERIVE_DH are new for v2.11\n --CKM_SSL3_MASTER_KEY_DERIVE_DH 0x00000373\n --CKM_TLS_PRE_MASTER_KEY_GEN 0x00000374\n --CKM_TLS_MASTER_KEY_DERIVE 0x00000375\n --CKM_TLS_KEY_AND_MAC_DERIVE 0x00000376\n --CKM_TLS_MASTER_KEY_DERIVE_DH 0x00000377\n\n -- CKM_TLS_PRF is new for v2.20\n --CKM_TLS_PRF 0x00000378\n\n --CKM_SSL3_MD5_MAC 0x00000380\n --CKM_SSL3_SHA1_MAC 0x00000381\n --CKM_MD5_KEY_DERIVATION 0x00000390\n --CKM_MD2_KEY_DERIVATION 0x00000391\n --CKM_SHA1_KEY_DERIVATION 0x00000392\n\n -- CKM_SHA256\/384\/512 are new for v2.20\n --CKM_SHA256_KEY_DERIVATION 0x00000393\n --CKM_SHA384_KEY_DERIVATION 0x00000394\n --CKM_SHA512_KEY_DERIVATION 0x00000395\n\n -- SHA-224 key derivation is new for PKCS #11 v2.20 amendment 3\n CKM_SHA224_KEY_DERIVATION as Sha224KeyDerivation,--0x00000396\n\n CKM_PBE_MD2_DES_CBC as PbeMd2DesCbc,--0x000003A0\n CKM_PBE_MD5_DES_CBC as PbeMd5DesCbc,--0x000003A1\n CKM_PBE_MD5_CAST_CBC as PbeMd5CastCbc,--0x000003A2\n CKM_PBE_MD5_CAST3_CBC as PbeMd5Cast3Cbc,--0x000003A3\n CKM_PBE_MD5_CAST5_CBC as PbeMd5Cast5Cbc,--0x000003A4\n CKM_PBE_MD5_CAST128_CBC as PbeMd5Cast128Cbc,--0x000003A4\n CKM_PBE_SHA1_CAST5_CBC as PbeSha1Cast5Cbc,--0x000003A5\n CKM_PBE_SHA1_CAST128_CBC as PbeSha1Cast128Cbc,--0x000003A5\n CKM_PBE_SHA1_RC4_128 as PbeSha1Rc4128,--0x000003A6\n CKM_PBE_SHA1_RC4_40 as PbeSha1Rc440,--0x000003A7\n CKM_PBE_SHA1_DES3_EDE_CBC as PbeSha1Des3EdeCbc,--0x000003A8\n CKM_PBE_SHA1_DES2_EDE_CBC as PbeSha1Des2EdeCbc,--0x000003A9\n CKM_PBE_SHA1_RC2_128_CBC as PbeSha1Rc2128Cbc,--0x000003AA\n CKM_PBE_SHA1_RC2_40_CBC as PbeSha1Rc240Cbc,--0x000003AB\n\n -- CKM_PKCS5_PBKD2 is new for v2.10\n CKM_PKCS5_PBKD2 as Pkcs5Pbkd2,--0x000003B0\n\n CKM_PBA_SHA1_WITH_SHA1_HMAC as PbaSha1WithSha1Hmac,--0x000003C0\n\n -- WTLS mechanisms are new for v2.20\n --CKM_WTLS_PRE_MASTER_KEY_GEN 0x000003D0\n --CKM_WTLS_MASTER_KEY_DERIVE 0x000003D1\n --CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC 0x000003D2\n --CKM_WTLS_PRF 0x000003D3\n --CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE 0x000003D4\n --CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE 0x000003D5\n\n --CKM_KEY_WRAP_LYNKS 0x00000400\n --CKM_KEY_WRAP_SET_OAEP 0x00000401\n\n -- CKM_CMS_SIG is new for v2.20\n --CKM_CMS_SIG 0x00000500\n\n -- CKM_KIP mechanisms are new for PKCS #11 v2.20 amendment 2\n --CKM_KIP_DERIVE\t 0x00000510\n --CKM_KIP_WRAP\t 0x00000511\n --CKM_KIP_MAC\t 0x00000512\n\n -- Camellia is new for PKCS #11 v2.20 amendment 3\n --CKM_CAMELLIA_KEY_GEN 0x00000550\n --CKM_CAMELLIA_ECB 0x00000551\n --CKM_CAMELLIA_CBC 0x00000552\n --CKM_CAMELLIA_MAC 0x00000553\n --CKM_CAMELLIA_MAC_GENERAL 0x00000554\n --CKM_CAMELLIA_CBC_PAD 0x00000555\n --CKM_CAMELLIA_ECB_ENCRYPT_DATA 0x00000556\n --CKM_CAMELLIA_CBC_ENCRYPT_DATA 0x00000557\n --CKM_CAMELLIA_CTR 0x00000558\n\n -- ARIA is new for PKCS #11 v2.20 amendment 3\n --CKM_ARIA_KEY_GEN 0x00000560\n --CKM_ARIA_ECB 0x00000561\n --CKM_ARIA_CBC 0x00000562\n --CKM_ARIA_MAC 0x00000563\n --CKM_ARIA_MAC_GENERAL 0x00000564\n --CKM_ARIA_CBC_PAD 0x00000565\n --CKM_ARIA_ECB_ENCRYPT_DATA 0x00000566\n --CKM_ARIA_CBC_ENCRYPT_DATA 0x00000567\n\n -- Fortezza mechanisms\n --CKM_SKIPJACK_KEY_GEN 0x00001000\n --CKM_SKIPJACK_ECB64 0x00001001\n --CKM_SKIPJACK_CBC64 0x00001002\n --CKM_SKIPJACK_OFB64 0x00001003\n --CKM_SKIPJACK_CFB64 0x00001004\n --CKM_SKIPJACK_CFB32 0x00001005\n --CKM_SKIPJACK_CFB16 0x00001006\n --CKM_SKIPJACK_CFB8 0x00001007\n --CKM_SKIPJACK_WRAP 0x00001008\n --CKM_SKIPJACK_PRIVATE_WRAP 0x00001009\n --CKM_SKIPJACK_RELAYX 0x0000100a\n --CKM_KEA_KEY_PAIR_GEN 0x00001010\n --CKM_KEA_KEY_DERIVE 0x00001011\n --CKM_FORTEZZA_TIMESTAMP 0x00001020\n --CKM_BATON_KEY_GEN 0x00001030\n --CKM_BATON_ECB128 0x00001031\n --CKM_BATON_ECB96 0x00001032\n --CKM_BATON_CBC128 0x00001033\n --CKM_BATON_COUNTER 0x00001034\n --CKM_BATON_SHUFFLE 0x00001035\n --CKM_BATON_WRAP 0x00001036\n\n -- CKM_ECDSA_KEY_PAIR_GEN is deprecated in v2.11,\n -- CKM_EC_KEY_PAIR_GEN is preferred\n CKM_ECDSA_KEY_PAIR_GEN as EcdsaKeyPairGen,--0x00001040\n CKM_EC_KEY_PAIR_GEN as EcKeyPairGen,--0x00001040\n\n CKM_ECDSA as Ecdsa,--0x00001041\n CKM_ECDSA_SHA1 as EcdsaSha1,--0x00001042\n\n -- CKM_ECDH1_DERIVE, CKM_ECDH1_COFACTOR_DERIVE, and CKM_ECMQV_DERIVE\n -- are new for v2.11\n CKM_ECDH1_DERIVE as Ecdh1Derive,--0x00001050\n CKM_ECDH1_COFACTOR_DERIVE as Ecdh1CofactorDerive,--0x00001051\n CKM_ECMQV_DERIVE as DcmqvDerive,--0x00001052\n\n CKM_JUNIPER_KEY_GEN as JuniperKeyGen,--0x00001060\n CKM_JUNIPER_ECB128 as JuniperEcb128,--0x00001061\n CKM_JUNIPER_CBC128 as JuniperCbc128,--0x00001062\n CKM_JUNIPER_COUNTER as JuniperCounter,--0x00001063\n CKM_JUNIPER_SHUFFLE as JuniperShuffle,--0x00001064\n CKM_JUNIPER_WRAP as JuniperWrap,--0x00001065\n CKM_FASTHASH as FastHash,--0x00001070\n\n -- CKM_AES_KEY_GEN, CKM_AES_ECB, CKM_AES_CBC, CKM_AES_MAC,\n -- CKM_AES_MAC_GENERAL, CKM_AES_CBC_PAD, CKM_DSA_PARAMETER_GEN,\n -- CKM_DH_PKCS_PARAMETER_GEN, and CKM_X9_42_DH_PARAMETER_GEN are\n -- new for v2.11\n CKM_AES_KEY_GEN as AesKeyGen,--0x00001080\n CKM_AES_ECB as AesEcb,\n CKM_AES_CBC as AesCbc,\n CKM_AES_MAC as AesMac,\n CKM_AES_MAC_GENERAL as AesMacGeneral,\n CKM_AES_CBC_PAD as AesCbcPad,\n\n -- AES counter mode is new for PKCS #11 v2.20 amendment 3\n CKM_AES_CTR as AesCtr,\n\n CKM_AES_GCM as AesGcm,--0x00001087\n CKM_AES_CCM as AesCcm,--0x00001088\n CKM_AES_KEY_WRAP as AesKeyWrap,--0x00001090\n CKM_AES_KEY_WRAP_PAD as AesKeyWrapPad,--0x00001091\n\n -- BlowFish and TwoFish are new for v2.20\n CKM_BLOWFISH_KEY_GEN as BlowfishKeyGen,\n CKM_BLOWFISH_CBC as BlowfishCbc,\n CKM_TWOFISH_KEY_GEN as TwoFishKeyGen,\n CKM_TWOFISH_CBC as TwoFishCbc,\n\n -- CKM_xxx_ENCRYPT_DATA mechanisms are new for v2.20\n CKM_DES_ECB_ENCRYPT_DATA as DesEcbEncryptData,\n CKM_DES_CBC_ENCRYPT_DATA as DesCbcEncryptData,\n CKM_DES3_ECB_ENCRYPT_DATA as Des3EcbEncryptData,\n CKM_DES3_CBC_ENCRYPT_DATA as Des3CbcEncryptData,\n CKM_AES_ECB_ENCRYPT_DATA as AesEcbEncryptData,\n CKM_AES_CBC_ENCRYPT_DATA as AesCbcEncryptData,\n\n CKM_DSA_PARAMETER_GEN as DsaParameterGen,\n CKM_DH_PKCS_PARAMETER_GEN as DhPkcsParameterGen,\n CKM_X9_42_DH_PARAMETER_GEN as X9_42DhParameterGen,\n\n CKM_VENDOR_DEFINED as VendorDefined\n } deriving (Eq,Show) #}\n\n\n_decryptInit :: MechType -> Session -> ObjectHandle -> IO ()\n_decryptInit mechType (Session sessionHandle functionListPtr) obj = do\n alloca $ \\mechPtr -> do\n poke mechPtr (Mech {mechType = mechType, mechParamPtr = nullPtr, mechParamSize = 0})\n rv <- {#call unsafe CK_FUNCTION_LIST.C_DecryptInit#} functionListPtr sessionHandle mechPtr obj\n if rv \/= 0\n then fail $ \"failed to initiate decryption: \" ++ (rvToStr rv)\n else return ()\n\n\ndecrypt :: MechType -> Session -> ObjectHandle -> BS.ByteString -> IO BS.ByteString\ndecrypt mechType (Session sessionHandle functionListPtr) obj encData = do\n _decryptInit mechType (Session sessionHandle functionListPtr) obj\n unsafeUseAsCStringLen encData $ \\(encDataPtr, encDataLen) -> do\n allocaBytes encDataLen $ \\outDataPtr -> do\n alloca $ \\outDataLenPtr -> do\n poke outDataLenPtr (fromIntegral encDataLen)\n rv <- {#call unsafe CK_FUNCTION_LIST.C_Decrypt#} functionListPtr sessionHandle (castPtr encDataPtr) (fromIntegral encDataLen) outDataPtr outDataLenPtr\n if rv \/= 0\n then fail $ \"failed to decrypt: \" ++ (rvToStr rv)\n else do\n outDataLen <- peek outDataLenPtr\n res <- BS.packCStringLen (castPtr outDataPtr, fromIntegral outDataLen)\n return res\n\n\n_encryptInit :: MechType -> Session -> ObjectHandle -> IO ()\n_encryptInit mechType (Session sessionHandle functionListPtr) obj = do\n alloca $ \\mechPtr -> do\n poke mechPtr (Mech {mechType = mechType, mechParamPtr = nullPtr, mechParamSize = 0})\n rv <- {#call unsafe CK_FUNCTION_LIST.C_EncryptInit#} functionListPtr sessionHandle mechPtr obj\n if rv \/= 0\n then fail $ \"failed to initiate decryption: \" ++ (rvToStr rv)\n else return ()\n\n\nencrypt :: MechType -> Session -> ObjectHandle -> BS.ByteString -> IO BS.ByteString\nencrypt mechType (Session sessionHandle functionListPtr) obj encData = do\n _encryptInit mechType (Session sessionHandle functionListPtr) obj\n let outLen = 1000\n unsafeUseAsCStringLen encData $ \\(encDataPtr, encDataLen) -> do\n allocaBytes outLen $ \\outDataPtr -> do\n alloca $ \\outDataLenPtr -> do\n poke outDataLenPtr (fromIntegral outLen)\n rv <- {#call unsafe CK_FUNCTION_LIST.C_Encrypt#} functionListPtr sessionHandle (castPtr encDataPtr) (fromIntegral encDataLen) outDataPtr outDataLenPtr\n if rv \/= 0\n then fail $ \"failed to decrypt: \" ++ (rvToStr rv)\n else do\n outDataLen <- peek outDataLenPtr\n res <- BS.packCStringLen (castPtr outDataPtr, fromIntegral outDataLen)\n return res\n\n\nunwrapKey :: MechType -> Session -> ObjectHandle -> BS.ByteString -> [Attribute] -> IO ObjectHandle\nunwrapKey mechType (Session sessionHandle functionListPtr) key wrappedKey template = do\n _withAttribs template $ \\attribsPtr -> do\n alloca $ \\mechPtr -> do\n poke mechPtr (Mech {mechType = mechType, mechParamPtr = nullPtr, mechParamSize = 0})\n unsafeUseAsCStringLen wrappedKey $ \\(wrappedKeyPtr, wrappedKeyLen) -> do\n alloca $ \\unwrappedKeyPtr -> do\n rv <- {#call unsafe CK_FUNCTION_LIST.C_UnwrapKey#} functionListPtr sessionHandle mechPtr key (castPtr wrappedKeyPtr) (fromIntegral wrappedKeyLen) attribsPtr (fromIntegral $ length template) unwrappedKeyPtr\n if rv \/= 0\n then fail $ \"failed to unwrap key: \" ++ (rvToStr rv)\n else do\n unwrappedKey <- peek unwrappedKeyPtr\n return unwrappedKey\n\n\n-- | Obtains a list of mechanism types supported by a token\ngetMechanismList :: Library -> SlotId -> Int -> IO [Int]\ngetMechanismList (Library _ functionListPtr) slotId maxMechanisms = do\n (rv, types) <- _getMechanismList functionListPtr slotId maxMechanisms\n if rv \/= 0\n then fail $ \"failed to get list of mechanisms: \" ++ (rvToStr rv)\n else return $ map (fromIntegral) types\n\n\n-- | Obtains information about a particular mechanism possibly supported by a token\ngetMechanismInfo :: Library -> SlotId -> MechType -> IO MechInfo\ngetMechanismInfo (Library _ functionListPtr) slotId mechId = do\n (rv, types) <- _getMechanismInfo functionListPtr slotId (fromEnum mechId)\n if rv \/= 0\n then fail $ \"failed to get mechanism information: \" ++ (rvToStr rv)\n else return types\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\nmodule System.Crypto.Pkcs11 (\n -- * Library\n Library,\n loadLibrary,\n releaseLibrary,\n\n -- ** Reading library information\n Info,\n getInfo,\n infoCryptokiVersion,\n infoManufacturerId,\n infoFlags,\n infoLibraryDescription,\n infoLibraryVersion,\n\n -- * Slots\n SlotId,\n getSlotList,\n\n -- ** Reading slot information\n SlotInfo,\n getSlotInfo,\n slotInfoDescription,\n slotInfoManufacturerId,\n slotInfoFlags,\n slotInfoHardwareVersion,\n slotInfoFirmwareVersion,\n\n -- ** Reading token information\n TokenInfo,\n getTokenInfo,\n tokenInfoLabel,\n tokenInfoManufacturerId,\n tokenInfoModel,\n tokenInfoSerialNumber,\n tokenInfoFlags,\n\n -- * Mechanisms\n MechType(RsaPkcsKeyPairGen,RsaPkcs,AesEcb,AesCbc,AesMac,AesMacGeneral,AesCbcPad,AesCtr),\n MechInfo,\n getMechanismList,\n getMechanismInfo,\n mechInfoMinKeySize,\n mechInfoMaxKeySize,\n mechInfoFlags,\n\n -- * Session management\n Session,\n UserType(User,SecurityOfficer,ContextSpecific),\n withSession,\n login,\n logout,\n\n -- * Object attributes\n ObjectHandle,\n Attribute(Class,Label,KeyType,Modulus,ModulusBits,PublicExponent,Token,Decrypt),\n ClassType(PrivateKey,SecretKey),\n KeyTypeValue(RSA,DSA,DH,ECDSA,EC,AES),\n -- ** Searching objects\n findObjects,\n -- ** Reading object attributes\n getTokenFlag,\n getPrivateFlag,\n getSensitiveFlag,\n getEncryptFlag,\n getDecryptFlag,\n getWrapFlag,\n getUnwrapFlag,\n getSignFlag,\n getModulus,\n getPublicExponent,\n\n -- * Key generation\n generateKeyPair,\n\n -- * Key wrapping\/unwrapping\n unwrapKey,\n\n -- * Encryption\/decryption\n decrypt,\n encrypt,\n\n -- * Misc\n Version,\n versionMajor,\n versionMinor,\n) where\nimport Foreign\nimport Foreign.Marshal.Utils\nimport Foreign.Marshal.Alloc\nimport Foreign.C\nimport Foreign.Ptr\nimport System.Posix.DynamicLinker\nimport Control.Monad\nimport Control.Exception\nimport qualified Data.ByteString.UTF8 as BU8\nimport qualified Data.ByteString as BS\nimport Data.ByteString.Unsafe\n\n#include \"pkcs11import.h\"\n\n{-\n Currently cannot use c2hs structure alignment and offset detector since it does not support pragma pack\n which is required by PKCS11, which is using 1 byte packing\n https:\/\/github.com\/haskell\/c2hs\/issues\/172\n-}\n\n_serialSession = {#const CKF_SERIAL_SESSION#} :: Int\n_rwSession = {#const CKF_RW_SESSION#} :: Int\n\nrsaPkcsKeyPairGen = {#const CKM_RSA_PKCS_KEY_PAIR_GEN#} :: Int\n\ntype ObjectHandle = {#type CK_OBJECT_HANDLE#}\ntype SlotId = Int\ntype Rv = {#type CK_RV#}\ntype CK_BBOOL = {#type CK_BBOOL#}\ntype CK_BYTE = {#type CK_BYTE#}\ntype CK_FLAGS = {#type CK_FLAGS#}\ntype GetFunctionListFunPtr = {#type CK_C_GetFunctionList#}\ntype GetSlotListFunPtr = {#type CK_C_GetSlotList#}\ntype NotifyFunPtr = {#type CK_NOTIFY#}\ntype SessionHandle = {#type CK_SESSION_HANDLE#}\n\n{#pointer *CK_FUNCTION_LIST as FunctionListPtr#}\n{#pointer *CK_INFO as InfoPtr -> Info#}\n{#pointer *CK_SLOT_INFO as SlotInfoPtr -> SlotInfo#}\n{#pointer *CK_TOKEN_INFO as TokenInfoPtr -> TokenInfo#}\n{#pointer *CK_ATTRIBUTE as LlAttributePtr -> LlAttribute#}\n{#pointer *CK_MECHANISM_INFO as MechInfoPtr -> MechInfo#}\n{#pointer *CK_MECHANISM as MechPtr -> Mech#}\n\n-- defined this one manually because I don't know how to make c2hs to define it yet\ntype GetFunctionListFun = (C2HSImp.Ptr (FunctionListPtr)) -> (IO C2HSImp.CULong)\n\nforeign import ccall unsafe \"dynamic\"\n getFunctionList'_ :: GetFunctionListFunPtr -> GetFunctionListFun\n\ndata Version = Version {\n versionMajor :: Int,\n versionMinor :: Int\n} deriving (Show)\n\ninstance Storable Version where\n sizeOf _ = {#sizeof CK_VERSION#}\n alignment _ = {#alignof CK_VERSION#}\n peek p = Version\n <$> liftM fromIntegral ({#get CK_VERSION->major#} p)\n <*> liftM fromIntegral ({#get CK_VERSION->minor#} p)\n poke p x = do\n {#set CK_VERSION->major#} p (fromIntegral $ versionMajor x)\n {#set CK_VERSION->minor#} p (fromIntegral $ versionMinor x)\n\ndata Info = Info {\n -- | Cryptoki interface version number, for compatibility with future revisions of this interface\n infoCryptokiVersion :: Version,\n -- | ID of the Cryptoki library manufacturer\n infoManufacturerId :: String,\n -- | bit flags reserved for future versions. Must be zero for this version\n infoFlags :: Int,\n infoLibraryDescription :: String,\n -- | Cryptoki library version number\n infoLibraryVersion :: Version\n} deriving (Show)\n\ninstance Storable Info where\n sizeOf _ = (2+32+4+32+10+2)\n alignment _ = 1\n peek p = do\n ver <- peek (p `plusPtr` {#offsetof CK_INFO->cryptokiVersion#}) :: IO Version\n manufacturerId <- peekCStringLen ((p `plusPtr` 2), 32)\n flags <- (\\ptr -> do {C2HSImp.peekByteOff ptr (2+32) :: IO C2HSImp.CULong}) p\n --flags <- {#get CK_INFO->flags#} p\n libraryDescription <- peekCStringLen ((p `plusPtr` (2+32+4+10)), 32)\n --libraryDescription <- {# get CK_INFO->libraryDescription #} p\n libVer <- peek (p `plusPtr` (2+32+4+32+10)) :: IO Version\n return Info {infoCryptokiVersion=ver,\n infoManufacturerId=manufacturerId,\n infoFlags=fromIntegral flags,\n infoLibraryDescription=libraryDescription,\n infoLibraryVersion=libVer\n }\n poke p v = do\n error \"not implemented\"\n\n\npeekInfo :: Ptr Info -> IO Info\npeekInfo ptr = peek ptr\n\n\ndata SlotInfo = SlotInfo {\n slotInfoDescription :: String,\n slotInfoManufacturerId :: String,\n -- | bit flags indicating capabilities and status of the slot as defined in https:\/\/www.cryptsoft.com\/pkcs11doc\/v220\/pkcs11__all_8h.html#aCK_SLOT_INFO\n slotInfoFlags :: Int,\n slotInfoHardwareVersion :: Version,\n slotInfoFirmwareVersion :: Version\n} deriving (Show)\n\ninstance Storable SlotInfo where\n sizeOf _ = (64+32+4+2+2)\n alignment _ = 1\n peek p = do\n description <- peekCStringLen ((p `plusPtr` 0), 64)\n manufacturerId <- peekCStringLen ((p `plusPtr` 64), 32)\n flags <- C2HSImp.peekByteOff p (64+32) :: IO C2HSImp.CULong\n hwVer <- peek (p `plusPtr` (64+32+4)) :: IO Version\n fwVer <- peek (p `plusPtr` (64+32+4+2)) :: IO Version\n return SlotInfo {slotInfoDescription=description,\n slotInfoManufacturerId=manufacturerId,\n slotInfoFlags=fromIntegral flags,\n slotInfoHardwareVersion=hwVer,\n slotInfoFirmwareVersion=fwVer\n }\n poke p v = do\n error \"not implemented\"\n\n\ndata TokenInfo = TokenInfo {\n tokenInfoLabel :: String,\n tokenInfoManufacturerId :: String,\n tokenInfoModel :: String,\n tokenInfoSerialNumber :: String,\n -- | bit flags indicating capabilities and status of the device as defined in https:\/\/www.cryptsoft.com\/pkcs11doc\/v220\/pkcs11__all_8h.html#aCK_TOKEN_INFO\n tokenInfoFlags :: Int--,\n --tokenInfoHardwareVersion :: Version,\n --tokenInfoFirmwareVersion :: Version\n} deriving (Show)\n\ninstance Storable TokenInfo where\n sizeOf _ = (64+32+4+2+2)\n alignment _ = 1\n peek p = do\n label <- peekCStringLen ((p `plusPtr` 0), 32)\n manufacturerId <- peekCStringLen ((p `plusPtr` 32), 32)\n model <- peekCStringLen ((p `plusPtr` (32+32)), 16)\n serialNumber <- peekCStringLen ((p `plusPtr` (32+32+16)), 16)\n flags <- C2HSImp.peekByteOff p (32+32+16+16) :: IO C2HSImp.CULong\n --hwVer <- peek (p `plusPtr` (64+32+4)) :: IO Version\n --fwVer <- peek (p `plusPtr` (64+32+4+2)) :: IO Version\n return TokenInfo {tokenInfoLabel=label,\n tokenInfoManufacturerId=manufacturerId,\n tokenInfoModel=model,\n tokenInfoSerialNumber=serialNumber,\n tokenInfoFlags=fromIntegral flags--,\n --tokenInfoHardwareVersion=hwVer,\n --tokenInfoFirmwareVersion=fwVer\n }\n\n poke p v = do\n error \"not implemented\"\n\n\ndata MechInfo = MechInfo {\n mechInfoMinKeySize :: Int,\n mechInfoMaxKeySize :: Int,\n mechInfoFlags :: Int\n} deriving (Show)\n\ninstance Storable MechInfo where\n sizeOf _ = {#sizeof CK_MECHANISM_INFO#}\n alignment _ = 1\n peek p = MechInfo\n <$> liftM fromIntegral ({#get CK_MECHANISM_INFO->ulMinKeySize#} p)\n <*> liftM fromIntegral ({#get CK_MECHANISM_INFO->ulMaxKeySize#} p)\n <*> liftM fromIntegral ({#get CK_MECHANISM_INFO->flags#} p)\n poke p x = do\n {#set CK_MECHANISM_INFO->ulMinKeySize#} p (fromIntegral $ mechInfoMinKeySize x)\n {#set CK_MECHANISM_INFO->ulMaxKeySize#} p (fromIntegral $ mechInfoMaxKeySize x)\n {#set CK_MECHANISM_INFO->flags#} p (fromIntegral $ mechInfoFlags x)\n\n\ndata Mech = Mech {\n mechType :: MechType,\n mechParamPtr :: Ptr (),\n mechParamSize :: Int\n}\n\ninstance Storable Mech where\n sizeOf _ = {#sizeof CK_MECHANISM_TYPE#} + {#sizeof CK_VOID_PTR#} + {#sizeof CK_ULONG#}\n alignment _ = 1\n peek p = do\n error \"not implemented\"\n poke p x = do\n poke (p `plusPtr` 0) (fromEnum $ mechType x)\n poke (p `plusPtr` {#sizeof CK_MECHANISM_TYPE#}) (mechParamPtr x :: {#type CK_VOID_PTR#})\n poke (p `plusPtr` ({#sizeof CK_MECHANISM_TYPE#} + {#sizeof CK_VOID_PTR#})) (mechParamSize x)\n\n\n\n{#fun unsafe CK_FUNCTION_LIST.C_Initialize as initialize\n {`FunctionListPtr',\n alloca- `()' } -> `Rv' fromIntegral#}\n\n{#fun unsafe CK_FUNCTION_LIST.C_GetInfo as getInfo'\n {`FunctionListPtr',\n alloca- `Info' peekInfo* } -> `Rv' fromIntegral#}\n\n\ngetSlotList' functionListPtr active num = do\n alloca $ \\arrayLenPtr -> do\n poke arrayLenPtr (fromIntegral num)\n allocaArray num $ \\array -> do\n res <- {#call unsafe CK_FUNCTION_LIST.C_GetSlotList#} functionListPtr (fromBool active) array arrayLenPtr\n arrayLen <- peek arrayLenPtr\n slots <- peekArray (fromIntegral arrayLen) array\n return (fromIntegral res, slots)\n\n\n{#fun unsafe CK_FUNCTION_LIST.C_GetSlotInfo as getSlotInfo'\n {`FunctionListPtr',\n `Int',\n alloca- `SlotInfo' peek* } -> `Rv' fromIntegral\n#}\n\n\n{#fun unsafe CK_FUNCTION_LIST.C_GetTokenInfo as getTokenInfo'\n {`FunctionListPtr',\n `Int',\n alloca- `TokenInfo' peek* } -> `Rv' fromIntegral\n#}\n\n\nopenSession' functionListPtr slotId flags =\n alloca $ \\slotIdPtr -> do\n res <- {#call unsafe CK_FUNCTION_LIST.C_OpenSession#} functionListPtr (fromIntegral slotId) (fromIntegral flags) nullPtr nullFunPtr slotIdPtr\n slotId <- peek slotIdPtr\n return (fromIntegral res, fromIntegral slotId)\n\n\n{#fun unsafe CK_FUNCTION_LIST.C_CloseSession as closeSession'\n {`FunctionListPtr',\n `CULong' } -> `Rv' fromIntegral#}\n\n\n{#fun unsafe CK_FUNCTION_LIST.C_Finalize as finalize\n {`FunctionListPtr',\n alloca- `()' } -> `Rv' fromIntegral#}\n\n\ngetFunctionList :: GetFunctionListFunPtr -> IO ((Rv), (FunctionListPtr))\ngetFunctionList getFunctionListPtr =\n alloca $ \\funcListPtrPtr -> do\n res <- (getFunctionList'_ getFunctionListPtr) funcListPtrPtr\n funcListPtr <- peek funcListPtrPtr\n return (fromIntegral res, funcListPtr)\n\n\nfindObjectsInit' functionListPtr session attribs = do\n _withAttribs attribs $ \\attribsPtr -> do\n res <- {#call unsafe CK_FUNCTION_LIST.C_FindObjectsInit#} functionListPtr session attribsPtr (fromIntegral $ length attribs)\n return (fromIntegral res)\n\n\nfindObjects' functionListPtr session maxObjects = do\n alloca $ \\arrayLenPtr -> do\n poke arrayLenPtr (fromIntegral 0)\n allocaArray maxObjects $ \\array -> do\n res <- {#call unsafe CK_FUNCTION_LIST.C_FindObjects#} functionListPtr session array (fromIntegral maxObjects) arrayLenPtr\n arrayLen <- peek arrayLenPtr\n objectHandles <- peekArray (fromIntegral arrayLen) array\n return (fromIntegral res, objectHandles)\n\n\n{#fun unsafe CK_FUNCTION_LIST.C_FindObjectsFinal as findObjectsFinal'\n {`FunctionListPtr',\n `CULong' } -> `Rv' fromIntegral#}\n\n\n{#enum define UserType {CKU_USER as User, CKU_SO as SecurityOfficer, CKU_CONTEXT_SPECIFIC as ContextSpecific} deriving (Eq) #}\n\n\n_login :: FunctionListPtr -> SessionHandle -> UserType -> BU8.ByteString -> IO (Rv)\n_login functionListPtr session userType pin = do\n unsafeUseAsCStringLen pin $ \\(pinPtr, pinLen) -> do\n res <- {#call unsafe CK_FUNCTION_LIST.C_Login#} functionListPtr session (fromIntegral $ fromEnum userType) (castPtr pinPtr) (fromIntegral pinLen)\n return (fromIntegral res)\n\n\n_generateKeyPair :: FunctionListPtr -> SessionHandle -> MechType -> [Attribute] -> [Attribute] -> IO (Rv, ObjectHandle, ObjectHandle)\n_generateKeyPair functionListPtr session mechType pubAttrs privAttrs = do\n alloca $ \\pubKeyHandlePtr -> do\n alloca $ \\privKeyHandlePtr -> do\n alloca $ \\mechPtr -> do\n poke mechPtr (Mech {mechType = mechType, mechParamPtr = nullPtr, mechParamSize = 0})\n _withAttribs pubAttrs $ \\pubAttrsPtr -> do\n _withAttribs privAttrs $ \\privAttrsPtr -> do\n res <- {#call unsafe CK_FUNCTION_LIST.C_GenerateKeyPair#} functionListPtr session mechPtr pubAttrsPtr (fromIntegral $ length pubAttrs) privAttrsPtr (fromIntegral $ length privAttrs) pubKeyHandlePtr privKeyHandlePtr\n pubKeyHandle <- peek pubKeyHandlePtr\n privKeyHandle <- peek privKeyHandlePtr\n return (fromIntegral res, fromIntegral pubKeyHandle, fromIntegral privKeyHandle)\n\n\n\n_getMechanismList :: FunctionListPtr -> Int -> Int -> IO (Rv, [Int])\n_getMechanismList functionListPtr slotId maxMechanisms = do\n alloca $ \\arrayLenPtr -> do\n poke arrayLenPtr (fromIntegral maxMechanisms)\n allocaArray maxMechanisms $ \\array -> do\n res <- {#call unsafe CK_FUNCTION_LIST.C_GetMechanismList#} functionListPtr (fromIntegral slotId) array arrayLenPtr\n arrayLen <- peek arrayLenPtr\n objectHandles <- peekArray (fromIntegral arrayLen) array\n return (fromIntegral res, map (fromIntegral) objectHandles)\n\n\n{#fun unsafe CK_FUNCTION_LIST.C_GetMechanismInfo as _getMechanismInfo\n {`FunctionListPtr',\n `Int',\n `Int',\n alloca- `MechInfo' peek* } -> `Rv' fromIntegral\n#}\n\n\nrvToStr :: Rv -> String\nrvToStr {#const CKR_OK#} = \"ok\"\nrvToStr {#const CKR_ARGUMENTS_BAD#} = \"bad arguments\"\nrvToStr {#const CKR_ATTRIBUTE_READ_ONLY#} = \"attribute is read-only\"\nrvToStr {#const CKR_ATTRIBUTE_TYPE_INVALID#} = \"invalid attribute type specified in template\"\nrvToStr {#const CKR_ATTRIBUTE_VALUE_INVALID#} = \"invalid attribute value specified in template\"\nrvToStr {#const CKR_BUFFER_TOO_SMALL#} = \"buffer too small\"\nrvToStr {#const CKR_CRYPTOKI_NOT_INITIALIZED#} = \"cryptoki not initialized\"\nrvToStr {#const CKR_DATA_INVALID#} = \"data invalid\"\nrvToStr {#const CKR_DEVICE_ERROR#} = \"device error\"\nrvToStr {#const CKR_DEVICE_MEMORY#} = \"device memory\"\nrvToStr {#const CKR_DEVICE_REMOVED#} = \"device removed\"\nrvToStr {#const CKR_DOMAIN_PARAMS_INVALID#} = \"invalid domain parameters\"\nrvToStr {#const CKR_ENCRYPTED_DATA_INVALID#} = \"encrypted data is invalid\"\nrvToStr {#const CKR_ENCRYPTED_DATA_LEN_RANGE#} = \"encrypted data length not in range\"\nrvToStr {#const CKR_FUNCTION_CANCELED#} = \"function canceled\"\nrvToStr {#const CKR_FUNCTION_FAILED#} = \"function failed\"\nrvToStr {#const CKR_GENERAL_ERROR#} = \"general error\"\nrvToStr {#const CKR_HOST_MEMORY#} = \"host memory\"\nrvToStr {#const CKR_KEY_FUNCTION_NOT_PERMITTED#} = \"key function not permitted\"\nrvToStr {#const CKR_KEY_HANDLE_INVALID#} = \"key handle invalid\"\nrvToStr {#const CKR_KEY_SIZE_RANGE#} = \"key size range\"\nrvToStr {#const CKR_KEY_TYPE_INCONSISTENT#} = \"key type inconsistent\"\nrvToStr {#const CKR_MECHANISM_INVALID#} = \"invalid mechanism\"\nrvToStr {#const CKR_MECHANISM_PARAM_INVALID#} = \"invalid mechanism parameter\"\nrvToStr {#const CKR_OPERATION_ACTIVE#} = \"there is already an active operation in-progress\"\nrvToStr {#const CKR_OPERATION_NOT_INITIALIZED#} = \"operation was not initialized\"\nrvToStr {#const CKR_PIN_EXPIRED#} = \"PIN is expired, you need to setup a new PIN\"\nrvToStr {#const CKR_PIN_INCORRECT#} = \"PIN is incorrect, authentication failed\"\nrvToStr {#const CKR_PIN_LOCKED#} = \"PIN is locked, authentication failed\"\nrvToStr {#const CKR_SESSION_CLOSED#} = \"session was closed in a middle of operation\"\nrvToStr {#const CKR_SESSION_COUNT#} = \"session count\"\nrvToStr {#const CKR_SESSION_HANDLE_INVALID#} = \"session handle is invalid\"\nrvToStr {#const CKR_SESSION_PARALLEL_NOT_SUPPORTED#} = \"parallel session not supported\"\nrvToStr {#const CKR_SESSION_READ_ONLY#} = \"session is read-only\"\nrvToStr {#const CKR_SESSION_READ_ONLY_EXISTS#} = \"read-only session exists, SO cannot login\"\nrvToStr {#const CKR_SESSION_READ_WRITE_SO_EXISTS#} = \"read-write SO session exists\"\nrvToStr {#const CKR_SLOT_ID_INVALID#} = \"slot id invalid\"\nrvToStr {#const CKR_TEMPLATE_INCOMPLETE#} = \"provided template is incomplete\"\nrvToStr {#const CKR_TEMPLATE_INCONSISTENT#} = \"provided template is inconsistent\"\nrvToStr {#const CKR_TOKEN_NOT_PRESENT#} = \"token not present\"\nrvToStr {#const CKR_TOKEN_NOT_RECOGNIZED#} = \"token not recognized\"\nrvToStr {#const CKR_TOKEN_WRITE_PROTECTED#} = \"token is write protected\"\nrvToStr {#const CKR_UNWRAPPING_KEY_HANDLE_INVALID#} = \"unwrapping key handle invalid\"\nrvToStr {#const CKR_UNWRAPPING_KEY_SIZE_RANGE#} = \"unwrapping key size not in range\"\nrvToStr {#const CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT#} = \"unwrapping key type inconsistent\"\nrvToStr {#const CKR_USER_NOT_LOGGED_IN#} = \"user needs to be logged in to perform this operation\"\nrvToStr {#const CKR_USER_ALREADY_LOGGED_IN#} = \"user already logged in\"\nrvToStr {#const CKR_USER_ANOTHER_ALREADY_LOGGED_IN#} = \"another user already logged in, first another user should be logged out\"\nrvToStr {#const CKR_USER_PIN_NOT_INITIALIZED#} = \"user PIN not initialized, need to setup PIN first\"\nrvToStr {#const CKR_USER_TOO_MANY_TYPES#} = \"cannot login user, somebody should logout first\"\nrvToStr {#const CKR_USER_TYPE_INVALID#} = \"invalid value for user type\"\nrvToStr {#const CKR_WRAPPED_KEY_INVALID#} = \"wrapped key invalid\"\nrvToStr {#const CKR_WRAPPED_KEY_LEN_RANGE#} = \"wrapped key length not in range\"\nrvToStr rv = \"unknown value for error \" ++ (show rv)\n\n\n-- Attributes\n\n{#enum define ClassType {\n CKO_DATA as Data,\n CKO_CERTIFICATE as Certificate,\n CKO_PUBLIC_KEY as PublicKey,\n CKO_PRIVATE_KEY as PrivateKey,\n CKO_SECRET_KEY as SecretKey,\n CKO_HW_FEATURE as HWFeature,\n CKO_DOMAIN_PARAMETERS as DomainParameters,\n CKO_MECHANISM as Mechanism\n} deriving (Show, Eq)\n#}\n\n{#enum define KeyTypeValue {\n CKK_RSA as RSA,\n CKK_DSA as DSA,\n CKK_DH as DH,\n CKK_ECDSA as ECDSA,\n CKK_EC as EC,\n CKK_AES as AES\n } deriving (Show, Eq) #}\n\n{#enum define AttributeType {\n CKA_CLASS as ClassType,\n CKA_TOKEN as TokenType,\n CKA_PRIVATE as PrivateType,\n CKA_LABEL as LabelType,\n CKA_APPLICATION as ApplicationType,\n CKA_VALUE as ValueType,\n CKA_OBJECT_ID as ObjectType,\n CKA_CERTIFICATE_TYPE as CertificateType,\n CKA_ISSUER as IssuerType,\n CKA_SERIAL_NUMBER as SerialNumberType,\n CKA_AC_ISSUER as AcIssuerType,\n CKA_OWNER as OwnerType,\n CKA_ATTR_TYPES as AttrTypesType,\n CKA_TRUSTED as TrustedType,\n CKA_CERTIFICATE_CATEGORY as CertificateCategoryType,\n CKA_JAVA_MIDP_SECURITY_DOMAIN as JavaMidpSecurityDomainType,\n CKA_URL as UrlType,\n CKA_HASH_OF_SUBJECT_PUBLIC_KEY as HashOfSubjectPublicKeyType,\n CKA_HASH_OF_ISSUER_PUBLIC_KEY as HashOfIssuerPublicKeyType,\n CKA_CHECK_VALUE as CheckValueType,\n\n CKA_KEY_TYPE as KeyTypeType,\n CKA_SUBJECT as SubjectType,\n CKA_ID as IdType,\n CKA_SENSITIVE as SensitiveType,\n CKA_ENCRYPT as EncryptType,\n CKA_DECRYPT as DecryptType,\n CKA_WRAP as WrapType,\n CKA_UNWRAP as UnwrapType,\n CKA_SIGN as SignType,\n CKA_SIGN_RECOVER as SignRecoverType,\n CKA_VERIFY as VerifyType,\n CKA_VERIFY_RECOVER as VerifyRecoverType,\n CKA_DERIVE as DeriveType,\n CKA_START_DATE as StartDateType,\n CKA_END_DATE as EndDataType,\n CKA_PUBLIC_EXPONENT as PublicExponentType,\n CKA_PRIVATE_EXPONENT as PrivateExponentType,\n CKA_MODULUS as ModulusType,\n CKA_MODULUS_BITS as ModulusBitsType,\n CKA_PRIME_1 as Prime1Type,\n CKA_PRIME_2 as Prime2Type,\n CKA_EXPONENT_1 as Exponent1Type,\n CKA_EXPONENT_2 as Exponent2Type,\n CKA_COEFFICIENT as CoefficientType,\n\n CKA_PRIME_BITS as PrimeBitsType,\n CKA_SUBPRIME_BITS as SubPrimeBitsType,\n\n CKA_VALUE_BITS as ValueBitsType,\n CKA_VALUE_LEN as ValueLenType,\n CKA_EXTRACTABLE as ExtractableType,\n CKA_LOCAL as LocalType,\n CKA_NEVER_EXTRACTABLE as NeverExtractableType,\n CKA_ALWAYS_SENSITIVE as AlwaysSensitiveType,\n CKA_KEY_GEN_MECHANISM as KeyGenMechanismType,\n\n CKA_MODIFIABLE as ModifiableType,\n\n -- CKA_ECDSA_PARAMS is deprecated in v2.11,\n -- CKA_EC_PARAMS is preferred.\n CKA_ECDSA_PARAMS as EcdsaParamsType,\n CKA_EC_PARAMS as EcParamsType,\n\n CKA_EC_POINT as EcPointType,\n\n -- CKA_SECONDARY_AUTH, CKA_AUTH_PIN_FLAGS,\n -- are new for v2.10. Deprecated in v2.11 and onwards.\n CKA_SECONDARY_AUTH as SecondaryAuthType,\n CKA_AUTH_PIN_FLAGS as AuthPinFlagsType,\n\n CKA_ALWAYS_AUTHENTICATE as AlwaysAuthenticateType,\n\n CKA_WRAP_WITH_TRUSTED as WrapWithTrustedType,\n CKA_WRAP_TEMPLATE as WrapTemplateType,\n CKA_UNWRAP_TEMPLATE as UnwrapTemplateType,\n CKA_DERIVE_TEMPLATE as DeriveTemplateType,\n\n CKA_OTP_FORMAT as OtpFormatType,\n CKA_OTP_LENGTH as OtpLengthType,\n CKA_OTP_TIME_INTERVAL as OtpTimeIntervalType,\n CKA_OTP_USER_FRIENDLY_MODE as OtpUserFriendlyModeType,\n CKA_OTP_CHALLENGE_REQUIREMENT as OtpChallengeRequirementType,\n CKA_OTP_TIME_REQUIREMENT as OtpTimeRequirementType,\n CKA_OTP_COUNTER_REQUIREMENT as OtpCounterRequirementType,\n CKA_OTP_PIN_REQUIREMENT as OtpPinRequirementType,\n CKA_OTP_COUNTER as OtpCounterType,\n CKA_OTP_TIME as OtpTimeType,\n CKA_OTP_USER_IDENTIFIER as OtpUserIdentifierType,\n CKA_OTP_SERVICE_IDENTIFIER as OtpServiceIdentifierType,\n CKA_OTP_SERVICE_LOGO as OtpServiceLogoType,\n CKA_OTP_SERVICE_LOGO_TYPE as OtpServiceLogoTypeType,\n\n CKA_GOSTR3410_PARAMS as GostR3410ParamsType,\n CKA_GOSTR3411_PARAMS as GostR3411ParamsType,\n CKA_GOST28147_PARAMS as Gost28147ParamsType,\n\n CKA_HW_FEATURE_TYPE as HwFeatureTypeType,\n CKA_RESET_ON_INIT as ResetOnInitType,\n CKA_HAS_RESET as HasResetType,\n\n CKA_PIXEL_X as PixelXType,\n CKA_PIXEL_Y as PixelYType,\n CKA_RESOLUTION as ResolutionType,\n CKA_CHAR_ROWS as CharRowsType,\n CKA_CHAR_COLUMNS as CharColumnsType,\n CKA_COLOR as ColorType,\n CKA_BITS_PER_PIXEL as BitPerPixelType,\n CKA_CHAR_SETS as CharSetsType,\n CKA_ENCODING_METHODS as EncodingMethodsType,\n CKA_MIME_TYPES as MimeTypesType,\n CKA_MECHANISM_TYPE as MechanismTypeType,\n CKA_REQUIRED_CMS_ATTRIBUTES as RequiredCmsAttributesType,\n CKA_DEFAULT_CMS_ATTRIBUTES as DefaultCmsAttributesType,\n CKA_SUPPORTED_CMS_ATTRIBUTES as SupportedCmsAttributesType,\n CKA_ALLOWED_MECHANISMS as AllowedMechanismsType,\n\n CKA_VENDOR_DEFINED as VendorDefinedType\n } deriving (Show, Eq) #}\n\ndata Attribute = Class ClassType\n | KeyType KeyTypeValue\n | Label String\n | ModulusBits Int\n | Token Bool\n | Decrypt Bool\n | Sign Bool\n | Modulus Integer\n | PublicExponent Integer\n deriving (Show)\n\ndata LlAttribute = LlAttribute {\n attributeType :: AttributeType,\n attributeValuePtr :: Ptr (),\n attributeSize :: {#type CK_ULONG#}\n}\n\ninstance Storable LlAttribute where\n sizeOf _ = {#sizeof CK_ATTRIBUTE_TYPE#} + {#sizeof CK_VOID_PTR#} + {#sizeof CK_ULONG#}\n alignment _ = 1\n poke p x = do\n poke (p `plusPtr` 0) (fromEnum $ attributeType x)\n poke (p `plusPtr` {#sizeof CK_ATTRIBUTE_TYPE#}) (attributeValuePtr x :: {#type CK_VOID_PTR#})\n poke (p `plusPtr` ({#sizeof CK_ATTRIBUTE_TYPE#} + {#sizeof CK_VOID_PTR#})) (attributeSize x)\n peek p = do\n attrType <- peek (p `plusPtr` 0) :: IO {#type CK_ATTRIBUTE_TYPE#}\n valPtr <- peek (p `plusPtr` {#sizeof CK_ATTRIBUTE_TYPE#})\n valSize <- peek (p `plusPtr` ({#sizeof CK_ATTRIBUTE_TYPE#} + {#sizeof CK_VOID_PTR#}))\n return $ LlAttribute (toEnum $ fromIntegral attrType) valPtr valSize\n\n\n_attrType :: Attribute -> AttributeType\n_attrType (Class _) = ClassType\n_attrType (KeyType _) = KeyTypeType\n_attrType (Label _) = LabelType\n_attrType (ModulusBits _) = ModulusBitsType\n_attrType (Token _) = TokenType\n\n\n_valueSize :: Attribute -> Int\n_valueSize (Class _) = {#sizeof CK_OBJECT_CLASS#}\n_valueSize (KeyType _) = {#sizeof CK_KEY_TYPE#}\n_valueSize (Label l) = BU8.length $ BU8.fromString l\n_valueSize (ModulusBits _) = {#sizeof CK_ULONG#}\n_valueSize (Token _) = {#sizeof CK_BBOOL#}\n\n\n_pokeValue :: Attribute -> Ptr () -> IO ()\n_pokeValue (Class c) ptr = poke (castPtr ptr :: Ptr {#type CK_OBJECT_CLASS#}) (fromIntegral $ fromEnum c)\n_pokeValue (KeyType k) ptr = poke (castPtr ptr :: Ptr {#type CK_KEY_TYPE#}) (fromIntegral $ fromEnum k)\n_pokeValue (Label l) ptr = unsafeUseAsCStringLen (BU8.fromString l) $ \\(src, len) -> copyBytes ptr (castPtr src :: Ptr ()) len\n_pokeValue (ModulusBits l) ptr = poke (castPtr ptr :: Ptr {#type CK_ULONG#}) (fromIntegral l :: {#type CK_KEY_TYPE#})\n_pokeValue (Token b) ptr = poke (castPtr ptr :: Ptr {#type CK_BBOOL#}) (fromBool b :: {#type CK_BBOOL#})\n\n\n_pokeValues :: [Attribute] -> Ptr () -> IO ()\n_pokeValues [] p = return ()\n_pokeValues (a:rem) p = do\n _pokeValue a p\n _pokeValues rem (p `plusPtr` (_valueSize a))\n\n\n_valuesSize :: [Attribute] -> Int\n_valuesSize attribs = foldr (+) 0 (map (_valueSize) attribs)\n\n\n_makeLowLevelAttrs :: [Attribute] -> Ptr () -> [LlAttribute]\n_makeLowLevelAttrs [] valuePtr = []\n_makeLowLevelAttrs (a:rem) valuePtr =\n let valuePtr' = valuePtr `plusPtr` (_valueSize a)\n llAttr = LlAttribute {attributeType=_attrType a, attributeValuePtr=valuePtr, attributeSize=(fromIntegral $ _valueSize a)}\n in\n llAttr:(_makeLowLevelAttrs rem valuePtr')\n\n\n_withAttribs :: [Attribute] -> (Ptr LlAttribute -> IO a) -> IO a\n_withAttribs attribs f = do\n allocaBytes (_valuesSize attribs) $ \\valuesPtr -> do\n _pokeValues attribs valuesPtr\n allocaArray (length attribs) $ \\attrsPtr -> do\n pokeArray attrsPtr (_makeLowLevelAttrs attribs valuesPtr)\n f attrsPtr\n\n\n_peekBigInt :: Ptr () -> CULong -> IO Integer\n_peekBigInt ptr len = do\n arr <- peekArray (fromIntegral len) (castPtr ptr :: Ptr Word8)\n return $ foldl (\\acc v -> (fromIntegral v) + (acc * 256)) 0 arr\n\n\n_llAttrToAttr :: LlAttribute -> IO Attribute\n_llAttrToAttr (LlAttribute ClassType ptr len) = do\n val <- peek (castPtr ptr :: Ptr {#type CK_OBJECT_CLASS#})\n return (Class $ toEnum $ fromIntegral val)\n_llAttrToAttr (LlAttribute ModulusType ptr len) = do\n val <- _peekBigInt ptr len\n return (Modulus val)\n_llAttrToAttr (LlAttribute PublicExponentType ptr len) = do\n val <- _peekBigInt ptr len\n return (PublicExponent val)\n_llAttrToAttr (LlAttribute DecryptType ptr len) = do\n val <- peek (castPtr ptr :: Ptr {#type CK_BBOOL#})\n return $ Decrypt(val \/= 0)\n_llAttrToAttr (LlAttribute SignType ptr len) = do\n val <- peek (castPtr ptr :: Ptr {#type CK_BBOOL#})\n return $ Sign(val \/= 0)\n\n\n-- High level API starts here\n\n\ndata Library = Library {\n libraryHandle :: DL,\n functionListPtr :: FunctionListPtr\n}\n\n\ndata Session = Session SessionHandle FunctionListPtr\n\n\n-- | Load PKCS#11 dynamically linked library\n--\n-- > lib <- loadLibrary \"\/path\/to\/dll.so\"\nloadLibrary :: String -> IO Library\nloadLibrary libraryPath = do\n lib <- dlopen libraryPath []\n getFunctionListFunPtr <- dlsym lib \"C_GetFunctionList\"\n (rv, functionListPtr) <- getFunctionList getFunctionListFunPtr\n if rv \/= 0\n then fail $ \"failed to get list of functions \" ++ (rvToStr rv)\n else do\n rv <- initialize functionListPtr\n if rv \/= 0\n then fail $ \"failed to initialize library \" ++ (rvToStr rv)\n else return Library { libraryHandle = lib, functionListPtr = functionListPtr }\n\n\nreleaseLibrary lib = do\n rv <- finalize $ functionListPtr lib\n dlclose $ libraryHandle lib\n\n\n-- | Returns general information about Cryptoki\ngetInfo :: Library -> IO Info\ngetInfo (Library _ functionListPtr) = do\n (rv, info) <- getInfo' functionListPtr\n if rv \/= 0\n then fail $ \"failed to get library information \" ++ (rvToStr rv)\n else return info\n\n\n-- | Allows to obtain a list of slots in the system\n--\n-- > slotsIds <- getSlotList lib True 10\n--\n-- In this example retrieves list of, at most 10 (third parameter) slot identifiers with tokens present (second parameter is set to True)\ngetSlotList :: Library -> Bool -> Int -> IO [SlotId]\ngetSlotList (Library _ functionListPtr) active num = do\n (rv, slots) <- getSlotList' functionListPtr active num\n if rv \/= 0\n then fail $ \"failed to get list of slots \" ++ (rvToStr rv)\n else return $ map (fromIntegral) slots\n\n\n-- | Obtains information about a particular slot in the system\n--\n-- > slotInfo <- getSlotInfo lib slotId\ngetSlotInfo :: Library -> SlotId -> IO SlotInfo\ngetSlotInfo (Library _ functionListPtr) slotId = do\n (rv, slotInfo) <- getSlotInfo' functionListPtr slotId\n if rv \/= 0\n then fail $ \"failed to get slot information \" ++ (rvToStr rv)\n else return slotInfo\n\n\n-- | Obtains information about a particular token in the system\n--\n-- > tokenInfo <- getTokenInfo lib slotId\ngetTokenInfo :: Library -> SlotId -> IO TokenInfo\ngetTokenInfo (Library _ functionListPtr) slotId = do\n (rv, slotInfo) <- getTokenInfo' functionListPtr slotId\n if rv \/= 0\n then fail $ \"failed to get token information \" ++ (rvToStr rv)\n else return slotInfo\n\n\n_openSessionEx :: Library -> SlotId -> Int -> IO Session\n_openSessionEx (Library _ functionListPtr) slotId flags = do\n (rv, sessionHandle) <- openSession' functionListPtr slotId flags\n if rv \/= 0\n then fail $ \"failed to open slot: \" ++ (rvToStr rv)\n else return $ Session sessionHandle functionListPtr\n\n\n_closeSessionEx :: Session -> IO ()\n_closeSessionEx (Session sessionHandle functionListPtr) = do\n rv <- closeSession' functionListPtr sessionHandle\n if rv \/= 0\n then fail $ \"failed to close slot: \" ++ (rvToStr rv)\n else return ()\n\n\nwithSession :: Library -> SlotId -> Bool -> (Session -> IO a) -> IO a\nwithSession lib slotId writable f = do\n let flags = if writable then _rwSession else 0\n bracket\n (_openSessionEx lib slotId (flags .|. _serialSession))\n (_closeSessionEx)\n (f)\n\n\n\n_findObjectsInitEx :: Session -> [Attribute] -> IO ()\n_findObjectsInitEx (Session sessionHandle functionListPtr) attribs = do\n rv <- findObjectsInit' functionListPtr sessionHandle attribs\n if rv \/= 0\n then fail $ \"failed to initialize search: \" ++ (rvToStr rv)\n else return ()\n\n\n_findObjectsEx :: Session -> IO [ObjectHandle]\n_findObjectsEx (Session sessionHandle functionListPtr) = do\n (rv, objectsHandles) <- findObjects' functionListPtr sessionHandle 10\n if rv \/= 0\n then fail $ \"failed to execute search: \" ++ (rvToStr rv)\n else return objectsHandles\n\n\n_findObjectsFinalEx :: Session -> IO ()\n_findObjectsFinalEx (Session sessionHandle functionListPtr) = do\n rv <- findObjectsFinal' functionListPtr sessionHandle\n if rv \/= 0\n then fail $ \"failed to finalize search: \" ++ (rvToStr rv)\n else return ()\n\n\nfindObjects :: Session -> [Attribute] -> IO [ObjectHandle]\nfindObjects session attribs = do\n _findObjectsInitEx session attribs\n finally (_findObjectsEx session) (_findObjectsFinalEx session)\n\n\ngenerateKeyPair :: Session -> MechType -> [Attribute] -> [Attribute] -> IO (ObjectHandle, ObjectHandle)\ngenerateKeyPair (Session sessionHandle functionListPtr) mechType pubKeyAttrs privKeyAttrs = do\n (rv, pubKeyHandle, privKeyHandle) <- _generateKeyPair functionListPtr sessionHandle mechType pubKeyAttrs privKeyAttrs\n if rv \/= 0\n then fail $ \"failed to generate key pair: \" ++ (rvToStr rv)\n else return (pubKeyHandle, privKeyHandle)\n\n\n_getAttr :: Session -> ObjectHandle -> AttributeType -> Ptr x -> IO ()\n_getAttr (Session sessionHandle functionListPtr) objHandle attrType valPtr = do\n alloca $ \\attrPtr -> do\n poke attrPtr (LlAttribute attrType (castPtr valPtr) (fromIntegral $ sizeOf valPtr))\n rv <- {#call unsafe CK_FUNCTION_LIST.C_GetAttributeValue#} functionListPtr sessionHandle objHandle attrPtr 1\n if rv \/= 0\n then fail $ \"failed to get attribute: \" ++ (rvToStr rv)\n else return ()\n\n\ngetBoolAttr :: Session -> ObjectHandle -> AttributeType -> IO Bool\ngetBoolAttr sess objHandle attrType = do\n alloca $ \\valuePtr -> do\n _getAttr sess objHandle attrType (valuePtr :: Ptr CK_BBOOL)\n val <- peek valuePtr\n return $ toBool val\n\n\ngetObjectAttr :: Session -> ObjectHandle -> AttributeType -> IO Attribute\ngetObjectAttr (Session sessionHandle functionListPtr) objHandle attrType = do\n alloca $ \\attrPtr -> do\n poke attrPtr (LlAttribute attrType nullPtr 0)\n rv <- {#call unsafe CK_FUNCTION_LIST.C_GetAttributeValue#} functionListPtr sessionHandle objHandle attrPtr 1\n attrWithLen <- peek attrPtr\n allocaBytes (fromIntegral $ attributeSize attrWithLen) $ \\attrVal -> do\n poke attrPtr (LlAttribute attrType attrVal (attributeSize attrWithLen))\n rv <- {#call unsafe CK_FUNCTION_LIST.C_GetAttributeValue#} functionListPtr sessionHandle objHandle attrPtr 1\n if rv \/= 0\n then fail $ \"failed to get attribute: \" ++ (rvToStr rv)\n else do\n llAttr <- peek attrPtr\n _llAttrToAttr llAttr\n\n\ngetTokenFlag sess objHandle = getBoolAttr sess objHandle TokenType\ngetPrivateFlag sess objHandle = getBoolAttr sess objHandle PrivateType\ngetSensitiveFlag sess objHandle = getBoolAttr sess objHandle SensitiveType\ngetEncryptFlag sess objHandle = getBoolAttr sess objHandle EncryptType\ngetDecryptFlag sess objHandle = getBoolAttr sess objHandle DecryptType\ngetWrapFlag sess objHandle = getBoolAttr sess objHandle WrapType\ngetUnwrapFlag sess objHandle = getBoolAttr sess objHandle UnwrapType\ngetSignFlag sess objHandle = getBoolAttr sess objHandle SignType\n\ngetModulus :: Session -> ObjectHandle -> IO Integer\ngetModulus sess objHandle = do\n (Modulus m) <- getObjectAttr sess objHandle ModulusType\n return m\n\ngetPublicExponent :: Session -> ObjectHandle -> IO Integer\ngetPublicExponent sess objHandle = do\n (PublicExponent v) <- getObjectAttr sess objHandle PublicExponentType\n return v\n\n\nlogin :: Session -> UserType -> BU8.ByteString -> IO ()\nlogin (Session sessionHandle functionListPtr) userType pin = do\n rv <- _login functionListPtr sessionHandle userType pin\n if rv \/= 0\n then fail $ \"login failed: \" ++ (rvToStr rv)\n else return ()\n\n\nlogout :: Session -> IO ()\nlogout (Session sessionHandle functionListPtr) = do\n rv <- {#call unsafe CK_FUNCTION_LIST.C_Logout#} functionListPtr sessionHandle\n if rv \/= 0\n then fail $ \"logout failed: \" ++ (rvToStr rv)\n else return ()\n\n\n{#enum define MechType {\n CKM_RSA_PKCS_KEY_PAIR_GEN as RsaPkcsKeyPairGen,\n CKM_RSA_PKCS as RsaPkcs,\n CKM_RSA_9796 as Rsa9796,\n CKM_RSA_X_509 as RsaX509,\n CKM_MD2_RSA_PKCS as Md2RsaPkcs,-- 0x00000004\n CKM_MD5_RSA_PKCS as Md5RsaPkcs,-- 0x00000005\n CKM_SHA1_RSA_PKCS as Sha1RsaPkcs,-- 0x00000006\n CKM_RIPEMD128_RSA_PKCS as RipeMd128RsaPkcs,-- 0x00000007\n CKM_RIPEMD160_RSA_PKCS as RipeMd160RsaPkcs,-- 0x00000008\n CKM_RSA_PKCS_OAEP as RsaPkcsOaep,-- 0x00000009\n CKM_RSA_X9_31_KEY_PAIR_GEN as RsaX931KeyPairGen,-- 0x0000000A\n CKM_RSA_X9_31 as RsaX931,-- 0x0000000B\n CKM_SHA1_RSA_X9_31 as Sha1RsaX931,-- 0x0000000C\n CKM_RSA_PKCS_PSS as RsaPkcsPss,-- 0x0000000D\n CKM_SHA1_RSA_PKCS_PSS as Sha1RsaPkcsPss,-- 0x0000000E\n CKM_DSA_KEY_PAIR_GEN as DsaKeyPairGen,-- 0x00000010\n CKM_DSA as Dsa,-- 0x00000011\n CKM_DSA_SHA1 as DsaSha1,-- 0x00000012\n CKM_DH_PKCS_KEY_PAIR_GEN as DhPkcsKeyPairGen,-- 0x00000020\n CKM_DH_PKCS_DERIVE as DhPkcsDerive,-- 0x00000021\n CKM_X9_42_DH_KEY_PAIR_GEN as X942DhKeyPairGen,-- 0x00000030\n CKM_X9_42_DH_DERIVE as X942DhDerive,-- 0x00000031\n CKM_X9_42_DH_HYBRID_DERIVE as X942DhHybridDerive,-- 0x00000032\n CKM_X9_42_MQV_DERIVE as X942MqvDerive,-- 0x00000033\n CKM_SHA256_RSA_PKCS as Sha256RsaPkcs,-- 0x00000040\n CKM_SHA384_RSA_PKCS as Sha384RsaPkcs,-- 0x00000041\n CKM_SHA512_RSA_PKCS as Sha512RsaPkcs,-- 0x00000042\n CKM_SHA256_RSA_PKCS_PSS as Sha256RsaPkcsPss,-- 0x00000043\n CKM_SHA384_RSA_PKCS_PSS as Sha384RsaPkcsPss,-- 0x00000044\n CKM_SHA512_RSA_PKCS_PSS as Sha512RsaPkcsPss,-- 0x00000045\n\n -- SHA-224 RSA mechanisms are new for PKCS #11 v2.20 amendment 3\n CKM_SHA224_RSA_PKCS as Sha224RsaPkcs,-- 0x00000046\n CKM_SHA224_RSA_PKCS_PSS as Sha224RsaPkcsPss,-- 0x00000047\n\n CKM_RC2_KEY_GEN as Rc2KeyGen,-- 0x00000100\n CKM_RC2_ECB as Rc2Ecb,-- 0x00000101\n CKM_RC2_CBC as Rc2Cbc,-- 0x00000102\n CKM_RC2_MAC as Rc2Mac,-- 0x00000103\n\n -- CKM_RC2_MAC_GENERAL and CKM_RC2_CBC_PAD are new for v2.0\n CKM_RC2_MAC_GENERAL as Rc2MacGeneral,-- 0x00000104\n CKM_RC2_CBC_PAD as Rc2CbcPad,--0x00000105\n\n CKM_RC4_KEY_GEN as Rc4KeyGen,--0x00000110\n CKM_RC4 as Rc4,--0x00000111\n CKM_DES_KEY_GEN as DesKeyGen,--0x00000120\n CKM_DES_ECB as DesEcb,--0x00000121\n CKM_DES_CBC as DesCbc,--0x00000122\n CKM_DES_MAC as DesMac,--0x00000123\n\n -- CKM_DES_MAC_GENERAL and CKM_DES_CBC_PAD are new for v2.0\n CKM_DES_MAC_GENERAL as DesMacGeneral,--0x00000124\n CKM_DES_CBC_PAD as DesCbcPad,--0x00000125\n\n CKM_DES2_KEY_GEN as Des2KeyGen,--0x00000130\n CKM_DES3_KEY_GEN as Des3KeyGen,--0x00000131\n CKM_DES3_ECB as Des3Ecb,--0x00000132\n CKM_DES3_CBC as Des3Cbc,--0x00000133\n CKM_DES3_MAC as Des3Mac,--0x00000134\n\n -- CKM_DES3_MAC_GENERAL, CKM_DES3_CBC_PAD, CKM_CDMF_KEY_GEN,\n -- CKM_CDMF_ECB, CKM_CDMF_CBC, CKM_CDMF_MAC,\n -- CKM_CDMF_MAC_GENERAL, and CKM_CDMF_CBC_PAD are new for v2.0\n CKM_DES3_MAC_GENERAL as Des3MacGeneral,--0x00000135\n CKM_DES3_CBC_PAD as Des3CbcPad,--0x00000136\n CKM_CDMF_KEY_GEN as CdmfKeyGen,--0x00000140\n CKM_CDMF_ECB as CdmfEcb,--0x00000141\n CKM_CDMF_CBC as CdmfCbc,--0x00000142\n CKM_CDMF_MAC as CdmfMac,--0x00000143\n CKM_CDMF_MAC_GENERAL as CdmfMacGeneral,--0x00000144\n CKM_CDMF_CBC_PAD as CdmfCbcPad,--0x00000145\n\n -- the following four DES mechanisms are new for v2.20\n CKM_DES_OFB64 as DesOfb64,--0x00000150\n CKM_DES_OFB8 as DesOfb8,--0x00000151\n CKM_DES_CFB64 as DesCfb64,--0x00000152\n CKM_DES_CFB8 as DesCfb8,--0x00000153\n\n CKM_MD2 as Md2,--0x00000200\n\n -- CKM_MD2_HMAC and CKM_MD2_HMAC_GENERAL are new for v2.0\n CKM_MD2_HMAC as Md2Hmac,--0x00000201\n CKM_MD2_HMAC_GENERAL as Md2HmacGeneral,--0x00000202\n\n CKM_MD5 as Md5,--0x00000210\n\n -- CKM_MD5_HMAC and CKM_MD5_HMAC_GENERAL are new for v2.0\n CKM_MD5_HMAC as Md5Hmac,--0x00000211\n CKM_MD5_HMAC_GENERAL as Md5HmacGeneral,--0x00000212\n\n CKM_SHA_1 as Sha1,--0x00000220\n\n -- CKM_SHA_1_HMAC and CKM_SHA_1_HMAC_GENERAL are new for v2.0\n CKM_SHA_1_HMAC as Sha1Hmac,--0x00000221\n CKM_SHA_1_HMAC_GENERAL as Sha1HmacGeneral,--0x00000222\n\n -- CKM_RIPEMD128, CKM_RIPEMD128_HMAC,\n -- CKM_RIPEMD128_HMAC_GENERAL, CKM_RIPEMD160, CKM_RIPEMD160_HMAC,\n -- and CKM_RIPEMD160_HMAC_GENERAL are new for v2.10\n CKM_RIPEMD128 as RipeMd128,--0x00000230\n CKM_RIPEMD128_HMAC as RipeMd128Hmac,--0x00000231\n CKM_RIPEMD128_HMAC_GENERAL as RipeMd128HmacGeneral,--0x00000232\n CKM_RIPEMD160 as Ripe160,--0x00000240\n CKM_RIPEMD160_HMAC as Ripe160Hmac,--0x00000241\n CKM_RIPEMD160_HMAC_GENERAL as Ripe160HmacGeneral,--0x00000242\n\n -- CKM_SHA256\/384\/512 are new for v2.20\n CKM_SHA256 as Sha256,--0x00000250\n CKM_SHA256_HMAC as Sha256Hmac,--0x00000251\n CKM_SHA256_HMAC_GENERAL as Sha256HmacGeneral,--0x00000252\n\n -- SHA-224 is new for PKCS #11 v2.20 amendment 3\n CKM_SHA224 as Sha224,--0x00000255\n CKM_SHA224_HMAC as Sha224Hmac,--0x00000256\n CKM_SHA224_HMAC_GENERAL as Sha224HmacGeneral,--0x00000257\n\n CKM_SHA384 as Sha384,--0x00000260\n CKM_SHA384_HMAC as Sha384Hmac,--0x00000261\n CKM_SHA384_HMAC_GENERAL as Sha384HmacGeneral,--0x00000262\n CKM_SHA512 as Sha512,--0x00000270\n CKM_SHA512_HMAC as Sha512Hmac,--0x00000271\n CKM_SHA512_HMAC_GENERAL as Sha512HmacGeneral,--0x00000272\n\n -- SecurID is new for PKCS #11 v2.20 amendment 1\n --CKM_SECURID_KEY_GEN 0x00000280\n --CKM_SECURID 0x00000282\n\n -- HOTP is new for PKCS #11 v2.20 amendment 1\n --CKM_HOTP_KEY_GEN 0x00000290\n --CKM_HOTP 0x00000291\n\n -- ACTI is new for PKCS #11 v2.20 amendment 1\n --CKM_ACTI 0x000002A0\n --CKM_ACTI_KEY_GEN 0x000002A1\n\n -- All of the following mechanisms are new for v2.0\n -- Note that CAST128 and CAST5 are the same algorithm\n CKM_CAST_KEY_GEN as CastKeyGen,--0x00000300\n CKM_CAST_ECB as CastEcb,--0x00000301\n CKM_CAST_CBC as CastCbc,--0x00000302\n CKM_CAST_MAC as CastMac,--0x00000303\n CKM_CAST_MAC_GENERAL as CastMacGeneral,--0x00000304\n CKM_CAST_CBC_PAD as CastCbcPad,--0x00000305\n CKM_CAST3_KEY_GEN as Cast3KeyGen,--0x00000310\n CKM_CAST3_ECB as Cast3Ecb,--0x00000311\n CKM_CAST3_CBC as Cast3Cbc,--0x00000312\n CKM_CAST3_MAC as Cast3Mac,--0x00000313\n CKM_CAST3_MAC_GENERAL as Cast3MacGeneral,--0x00000314\n CKM_CAST3_CBC_PAD as Cast3CbcPad,--0x00000315\n CKM_CAST5_KEY_GEN as Cast5KeyGen,--0x00000320\n CKM_CAST128_KEY_GEN as Cast128KeyGen,--0x00000320\n CKM_CAST5_ECB as Cast5Ecb,--0x00000321\n CKM_CAST128_ECB as Cast128Ecb,--0x00000321\n CKM_CAST5_CBC as Cast5Cbc,--0x00000322\n CKM_CAST128_CBC as Cast128Cbc,--0x00000322\n CKM_CAST5_MAC as Cast5Mac,--0x00000323\n CKM_CAST128_MAC as Cast128Mac,--0x00000323\n CKM_CAST5_MAC_GENERAL as Cast5MacGeneral,--0x00000324\n CKM_CAST128_MAC_GENERAL as Cast128MacGeneral,--0x00000324\n CKM_CAST5_CBC_PAD as Cast5CbcPad,--0x00000325\n CKM_CAST128_CBC_PAD as Cast128CbcPad,--0x00000325\n CKM_RC5_KEY_GEN as Rc5KeyGen,--0x00000330\n CKM_RC5_ECB as Rc5Ecb,--0x00000331\n CKM_RC5_CBC as Rc5Cbc,--0x00000332\n CKM_RC5_MAC as Rc5Mac,--0x00000333\n CKM_RC5_MAC_GENERAL as Rc5MacGeneral,--0x00000334\n CKM_RC5_CBC_PAD as Rc5CbcPad,--0x00000335\n CKM_IDEA_KEY_GEN as IdeaKeyGen,--0x00000340\n CKM_IDEA_ECB as IdeaEcb,--0x00000341\n CKM_IDEA_CBC as IdeaCbc,--0x00000342\n CKM_IDEA_MAC as IdeaMac,--0x00000343\n CKM_IDEA_MAC_GENERAL as IdeaMacGeneral,--0x00000344\n CKM_IDEA_CBC_PAD as IdeaCbcPad,--0x00000345\n CKM_GENERIC_SECRET_KEY_GEN as GeneralSecretKeyGen,--0x00000350\n CKM_CONCATENATE_BASE_AND_KEY as ConcatenateBaseAndKey,--0x00000360\n CKM_CONCATENATE_BASE_AND_DATA as ConcatenateBaseAndData,--0x00000362\n CKM_CONCATENATE_DATA_AND_BASE as ConcatenateDataAndBase,--0x00000363\n CKM_XOR_BASE_AND_DATA as XorBaseAndData,--0x00000364\n CKM_EXTRACT_KEY_FROM_KEY as ExtractKeyFromKey,--0x00000365\n CKM_SSL3_PRE_MASTER_KEY_GEN as Ssl3PreMasterKeyGen,--0x00000370\n CKM_SSL3_MASTER_KEY_DERIVE as Ssl3MasterKeyDerive,--0x00000371\n CKM_SSL3_KEY_AND_MAC_DERIVE as Ssl3KeyAndMacDerive,--0x00000372\n\n -- CKM_SSL3_MASTER_KEY_DERIVE_DH, CKM_TLS_PRE_MASTER_KEY_GEN,\n -- CKM_TLS_MASTER_KEY_DERIVE, CKM_TLS_KEY_AND_MAC_DERIVE, and\n -- CKM_TLS_MASTER_KEY_DERIVE_DH are new for v2.11\n --CKM_SSL3_MASTER_KEY_DERIVE_DH 0x00000373\n --CKM_TLS_PRE_MASTER_KEY_GEN 0x00000374\n --CKM_TLS_MASTER_KEY_DERIVE 0x00000375\n --CKM_TLS_KEY_AND_MAC_DERIVE 0x00000376\n --CKM_TLS_MASTER_KEY_DERIVE_DH 0x00000377\n\n -- CKM_TLS_PRF is new for v2.20\n --CKM_TLS_PRF 0x00000378\n\n --CKM_SSL3_MD5_MAC 0x00000380\n --CKM_SSL3_SHA1_MAC 0x00000381\n --CKM_MD5_KEY_DERIVATION 0x00000390\n --CKM_MD2_KEY_DERIVATION 0x00000391\n --CKM_SHA1_KEY_DERIVATION 0x00000392\n\n -- CKM_SHA256\/384\/512 are new for v2.20\n --CKM_SHA256_KEY_DERIVATION 0x00000393\n --CKM_SHA384_KEY_DERIVATION 0x00000394\n --CKM_SHA512_KEY_DERIVATION 0x00000395\n\n -- SHA-224 key derivation is new for PKCS #11 v2.20 amendment 3\n CKM_SHA224_KEY_DERIVATION as Sha224KeyDerivation,--0x00000396\n\n CKM_PBE_MD2_DES_CBC as PbeMd2DesCbc,--0x000003A0\n CKM_PBE_MD5_DES_CBC as PbeMd5DesCbc,--0x000003A1\n CKM_PBE_MD5_CAST_CBC as PbeMd5CastCbc,--0x000003A2\n CKM_PBE_MD5_CAST3_CBC as PbeMd5Cast3Cbc,--0x000003A3\n CKM_PBE_MD5_CAST5_CBC as PbeMd5Cast5Cbc,--0x000003A4\n CKM_PBE_MD5_CAST128_CBC as PbeMd5Cast128Cbc,--0x000003A4\n CKM_PBE_SHA1_CAST5_CBC as PbeSha1Cast5Cbc,--0x000003A5\n CKM_PBE_SHA1_CAST128_CBC as PbeSha1Cast128Cbc,--0x000003A5\n CKM_PBE_SHA1_RC4_128 as PbeSha1Rc4128,--0x000003A6\n CKM_PBE_SHA1_RC4_40 as PbeSha1Rc440,--0x000003A7\n CKM_PBE_SHA1_DES3_EDE_CBC as PbeSha1Des3EdeCbc,--0x000003A8\n CKM_PBE_SHA1_DES2_EDE_CBC as PbeSha1Des2EdeCbc,--0x000003A9\n CKM_PBE_SHA1_RC2_128_CBC as PbeSha1Rc2128Cbc,--0x000003AA\n CKM_PBE_SHA1_RC2_40_CBC as PbeSha1Rc240Cbc,--0x000003AB\n\n -- CKM_PKCS5_PBKD2 is new for v2.10\n CKM_PKCS5_PBKD2 as Pkcs5Pbkd2,--0x000003B0\n\n CKM_PBA_SHA1_WITH_SHA1_HMAC as PbaSha1WithSha1Hmac,--0x000003C0\n\n -- WTLS mechanisms are new for v2.20\n --CKM_WTLS_PRE_MASTER_KEY_GEN 0x000003D0\n --CKM_WTLS_MASTER_KEY_DERIVE 0x000003D1\n --CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC 0x000003D2\n --CKM_WTLS_PRF 0x000003D3\n --CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE 0x000003D4\n --CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE 0x000003D5\n\n --CKM_KEY_WRAP_LYNKS 0x00000400\n --CKM_KEY_WRAP_SET_OAEP 0x00000401\n\n -- CKM_CMS_SIG is new for v2.20\n --CKM_CMS_SIG 0x00000500\n\n -- CKM_KIP mechanisms are new for PKCS #11 v2.20 amendment 2\n --CKM_KIP_DERIVE\t 0x00000510\n --CKM_KIP_WRAP\t 0x00000511\n --CKM_KIP_MAC\t 0x00000512\n\n -- Camellia is new for PKCS #11 v2.20 amendment 3\n --CKM_CAMELLIA_KEY_GEN 0x00000550\n --CKM_CAMELLIA_ECB 0x00000551\n --CKM_CAMELLIA_CBC 0x00000552\n --CKM_CAMELLIA_MAC 0x00000553\n --CKM_CAMELLIA_MAC_GENERAL 0x00000554\n --CKM_CAMELLIA_CBC_PAD 0x00000555\n --CKM_CAMELLIA_ECB_ENCRYPT_DATA 0x00000556\n --CKM_CAMELLIA_CBC_ENCRYPT_DATA 0x00000557\n --CKM_CAMELLIA_CTR 0x00000558\n\n -- ARIA is new for PKCS #11 v2.20 amendment 3\n --CKM_ARIA_KEY_GEN 0x00000560\n --CKM_ARIA_ECB 0x00000561\n --CKM_ARIA_CBC 0x00000562\n --CKM_ARIA_MAC 0x00000563\n --CKM_ARIA_MAC_GENERAL 0x00000564\n --CKM_ARIA_CBC_PAD 0x00000565\n --CKM_ARIA_ECB_ENCRYPT_DATA 0x00000566\n --CKM_ARIA_CBC_ENCRYPT_DATA 0x00000567\n\n -- Fortezza mechanisms\n --CKM_SKIPJACK_KEY_GEN 0x00001000\n --CKM_SKIPJACK_ECB64 0x00001001\n --CKM_SKIPJACK_CBC64 0x00001002\n --CKM_SKIPJACK_OFB64 0x00001003\n --CKM_SKIPJACK_CFB64 0x00001004\n --CKM_SKIPJACK_CFB32 0x00001005\n --CKM_SKIPJACK_CFB16 0x00001006\n --CKM_SKIPJACK_CFB8 0x00001007\n --CKM_SKIPJACK_WRAP 0x00001008\n --CKM_SKIPJACK_PRIVATE_WRAP 0x00001009\n --CKM_SKIPJACK_RELAYX 0x0000100a\n --CKM_KEA_KEY_PAIR_GEN 0x00001010\n --CKM_KEA_KEY_DERIVE 0x00001011\n --CKM_FORTEZZA_TIMESTAMP 0x00001020\n --CKM_BATON_KEY_GEN 0x00001030\n --CKM_BATON_ECB128 0x00001031\n --CKM_BATON_ECB96 0x00001032\n --CKM_BATON_CBC128 0x00001033\n --CKM_BATON_COUNTER 0x00001034\n --CKM_BATON_SHUFFLE 0x00001035\n --CKM_BATON_WRAP 0x00001036\n\n -- CKM_ECDSA_KEY_PAIR_GEN is deprecated in v2.11,\n -- CKM_EC_KEY_PAIR_GEN is preferred\n CKM_ECDSA_KEY_PAIR_GEN as EcdsaKeyPairGen,--0x00001040\n CKM_EC_KEY_PAIR_GEN as EcKeyPairGen,--0x00001040\n\n CKM_ECDSA as Ecdsa,--0x00001041\n CKM_ECDSA_SHA1 as EcdsaSha1,--0x00001042\n\n -- CKM_ECDH1_DERIVE, CKM_ECDH1_COFACTOR_DERIVE, and CKM_ECMQV_DERIVE\n -- are new for v2.11\n CKM_ECDH1_DERIVE as Ecdh1Derive,--0x00001050\n CKM_ECDH1_COFACTOR_DERIVE as Ecdh1CofactorDerive,--0x00001051\n CKM_ECMQV_DERIVE as DcmqvDerive,--0x00001052\n\n CKM_JUNIPER_KEY_GEN as JuniperKeyGen,--0x00001060\n CKM_JUNIPER_ECB128 as JuniperEcb128,--0x00001061\n CKM_JUNIPER_CBC128 as JuniperCbc128,--0x00001062\n CKM_JUNIPER_COUNTER as JuniperCounter,--0x00001063\n CKM_JUNIPER_SHUFFLE as JuniperShuffle,--0x00001064\n CKM_JUNIPER_WRAP as JuniperWrap,--0x00001065\n CKM_FASTHASH as FastHash,--0x00001070\n\n -- CKM_AES_KEY_GEN, CKM_AES_ECB, CKM_AES_CBC, CKM_AES_MAC,\n -- CKM_AES_MAC_GENERAL, CKM_AES_CBC_PAD, CKM_DSA_PARAMETER_GEN,\n -- CKM_DH_PKCS_PARAMETER_GEN, and CKM_X9_42_DH_PARAMETER_GEN are\n -- new for v2.11\n CKM_AES_KEY_GEN as AesKeyGen,--0x00001080\n CKM_AES_ECB as AesEcb,\n CKM_AES_CBC as AesCbc,\n CKM_AES_MAC as AesMac,\n CKM_AES_MAC_GENERAL as AesMacGeneral,\n CKM_AES_CBC_PAD as AesCbcPad,\n\n -- AES counter mode is new for PKCS #11 v2.20 amendment 3\n CKM_AES_CTR as AesCtr,\n\n CKM_AES_GCM as AesGcm,--0x00001087\n CKM_AES_CCM as AesCcm,--0x00001088\n CKM_AES_KEY_WRAP as AesKeyWrap,--0x00001090\n CKM_AES_KEY_WRAP_PAD as AesKeyWrapPad,--0x00001091\n\n -- BlowFish and TwoFish are new for v2.20\n CKM_BLOWFISH_KEY_GEN as BlowfishKeyGen,\n CKM_BLOWFISH_CBC as BlowfishCbc,\n CKM_TWOFISH_KEY_GEN as TwoFishKeyGen,\n CKM_TWOFISH_CBC as TwoFishCbc,\n\n -- CKM_xxx_ENCRYPT_DATA mechanisms are new for v2.20\n CKM_DES_ECB_ENCRYPT_DATA as DesEcbEncryptData,\n CKM_DES_CBC_ENCRYPT_DATA as DesCbcEncryptData,\n CKM_DES3_ECB_ENCRYPT_DATA as Des3EcbEncryptData,\n CKM_DES3_CBC_ENCRYPT_DATA as Des3CbcEncryptData,\n CKM_AES_ECB_ENCRYPT_DATA as AesEcbEncryptData,\n CKM_AES_CBC_ENCRYPT_DATA as AesCbcEncryptData,\n\n CKM_DSA_PARAMETER_GEN as DsaParameterGen,\n CKM_DH_PKCS_PARAMETER_GEN as DhPkcsParameterGen,\n CKM_X9_42_DH_PARAMETER_GEN as X9_42DhParameterGen,\n\n CKM_VENDOR_DEFINED as VendorDefined\n } deriving (Eq,Show) #}\n\n\n_decryptInit :: MechType -> Session -> ObjectHandle -> IO ()\n_decryptInit mechType (Session sessionHandle functionListPtr) obj = do\n alloca $ \\mechPtr -> do\n poke mechPtr (Mech {mechType = mechType, mechParamPtr = nullPtr, mechParamSize = 0})\n rv <- {#call unsafe CK_FUNCTION_LIST.C_DecryptInit#} functionListPtr sessionHandle mechPtr obj\n if rv \/= 0\n then fail $ \"failed to initiate decryption: \" ++ (rvToStr rv)\n else return ()\n\n\ndecrypt :: MechType -> Session -> ObjectHandle -> BS.ByteString -> IO BS.ByteString\ndecrypt mechType (Session sessionHandle functionListPtr) obj encData = do\n _decryptInit mechType (Session sessionHandle functionListPtr) obj\n unsafeUseAsCStringLen encData $ \\(encDataPtr, encDataLen) -> do\n putStrLn $ \"in data len \" ++ (show encDataLen)\n putStrLn $ show encData\n allocaBytes encDataLen $ \\outDataPtr -> do\n alloca $ \\outDataLenPtr -> do\n poke outDataLenPtr (fromIntegral encDataLen)\n rv <- {#call unsafe CK_FUNCTION_LIST.C_Decrypt#} functionListPtr sessionHandle (castPtr encDataPtr) (fromIntegral encDataLen) outDataPtr outDataLenPtr\n if rv \/= 0\n then fail $ \"failed to decrypt: \" ++ (rvToStr rv)\n else do\n outDataLen <- peek outDataLenPtr\n res <- BS.packCStringLen (castPtr outDataPtr, fromIntegral outDataLen)\n return res\n\n\n_encryptInit :: MechType -> Session -> ObjectHandle -> IO ()\n_encryptInit mechType (Session sessionHandle functionListPtr) obj = do\n alloca $ \\mechPtr -> do\n poke mechPtr (Mech {mechType = mechType, mechParamPtr = nullPtr, mechParamSize = 0})\n rv <- {#call unsafe CK_FUNCTION_LIST.C_EncryptInit#} functionListPtr sessionHandle mechPtr obj\n if rv \/= 0\n then fail $ \"failed to initiate decryption: \" ++ (rvToStr rv)\n else return ()\n\n\nencrypt :: MechType -> Session -> ObjectHandle -> BS.ByteString -> IO BS.ByteString\nencrypt mechType (Session sessionHandle functionListPtr) obj encData = do\n _encryptInit mechType (Session sessionHandle functionListPtr) obj\n let outLen = 1000\n unsafeUseAsCStringLen encData $ \\(encDataPtr, encDataLen) -> do\n allocaBytes outLen $ \\outDataPtr -> do\n alloca $ \\outDataLenPtr -> do\n poke outDataLenPtr (fromIntegral outLen)\n rv <- {#call unsafe CK_FUNCTION_LIST.C_Encrypt#} functionListPtr sessionHandle (castPtr encDataPtr) (fromIntegral encDataLen) outDataPtr outDataLenPtr\n if rv \/= 0\n then fail $ \"failed to decrypt: \" ++ (rvToStr rv)\n else do\n outDataLen <- peek outDataLenPtr\n res <- BS.packCStringLen (castPtr outDataPtr, fromIntegral outDataLen)\n return res\n\n\nunwrapKey :: MechType -> Session -> ObjectHandle -> BS.ByteString -> [Attribute] -> IO ObjectHandle\nunwrapKey mechType (Session sessionHandle functionListPtr) key wrappedKey template = do\n _withAttribs template $ \\attribsPtr -> do\n alloca $ \\mechPtr -> do\n poke mechPtr (Mech {mechType = mechType, mechParamPtr = nullPtr, mechParamSize = 0})\n unsafeUseAsCStringLen wrappedKey $ \\(wrappedKeyPtr, wrappedKeyLen) -> do\n alloca $ \\unwrappedKeyPtr -> do\n rv <- {#call unsafe CK_FUNCTION_LIST.C_UnwrapKey#} functionListPtr sessionHandle mechPtr key (castPtr wrappedKeyPtr) (fromIntegral wrappedKeyLen) attribsPtr (fromIntegral $ length template) unwrappedKeyPtr\n if rv \/= 0\n then fail $ \"failed to unwrap key: \" ++ (rvToStr rv)\n else do\n unwrappedKey <- peek unwrappedKeyPtr\n return unwrappedKey\n\n\n-- | Obtains a list of mechanism types supported by a token\ngetMechanismList :: Library -> SlotId -> Int -> IO [Int]\ngetMechanismList (Library _ functionListPtr) slotId maxMechanisms = do\n (rv, types) <- _getMechanismList functionListPtr slotId maxMechanisms\n if rv \/= 0\n then fail $ \"failed to get list of mechanisms: \" ++ (rvToStr rv)\n else return $ map (fromIntegral) types\n\n\n-- | Obtains information about a particular mechanism possibly supported by a token\ngetMechanismInfo :: Library -> SlotId -> MechType -> IO MechInfo\ngetMechanismInfo (Library _ functionListPtr) slotId mechId = do\n (rv, types) <- _getMechanismInfo functionListPtr slotId (fromEnum mechId)\n if rv \/= 0\n then fail $ \"failed to get mechanism information: \" ++ (rvToStr rv)\n else return types\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"}
{"commit":"8049ddc355dd693ac279f3561e04cbbab4a6df7e","subject":"Add some little example code fragments to the haddock documentation","message":"Add some little example code fragments to the haddock documentation\n","repos":"markwright\/antlrc","old_file":"src\/Text\/Antlrc\/Lexer.chs","new_file":"src\/Text\/Antlrc\/Lexer.chs","new_contents":"-- Copyright (c)2010-2011, Mark Wright. All rights reserved.\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TypeSynonymInstances #-}\nmodule Text.Antlrc.Lexer where\n\n#include \"antlr3lexer.h\"\n\nimport C2HS\nimport Foreign.C.Types\nimport Foreign.Storable\nimport Ptr\nimport Foreign.Ptr\nimport System.IO.Unsafe\nimport Foreign.C\nimport Control.Monad\nimport Control.Applicative ((<$>))\n\n{#context lib=\"antlr3c\"#}\n\n-- | Lexer token struct.\n{#pointer *ANTLR3_COMMON_TOKEN as CommonToken newtype#}\n\n-- | Lexer input stream struct.\n{#pointer *ANTLR3_INPUT_STREAM as InputStream newtype#}\n\n-- | Lexer struct.\n{#pointer *ANTLR3_LEXER as Lexer newtype#}\n\n-- | Cast from a pointer to an input stream to an input stream.\ntoInputStream :: Ptr InputStream -> InputStream\ntoInputStream = InputStream . castPtr\n\n-- | Cast from a pointer to a token to a token.\ntoCommonToken :: Ptr CommonToken -> CommonToken\ntoCommonToken = CommonToken . castPtr\n\n-- | Cast from a token to a pointer to a token.\nfromCommonToken :: CommonToken -> Ptr b\nfromCommonToken (CommonToken x) = castPtr x\n\n-- The C function definitions are in lexerc.c\n#c\nANTLR3_COMMON_TOKEN *LT(ANTLR3_INPUT_STREAM *input, int lti);\n#endc\n\n-- | Lookahead in the input stream at the token at the specified\n-- | positive offset, where:\n-- > LT input 1 \n-- | is the current token. Or a negative offset may be specified, where: \n-- > LT input (-1) \n-- | is the previous token.\n-- @\n-- foreign export ccall isUnsignedInt :: Ptr InputStream -> IO Bool\n-- isUnsignedInt input =\n-- do token1 <- lT input 1 >>= tokenGetType\n-- if token1 \/= UNSIGNED\n-- then return False\n-- else \n-- do \n-- token2 <- lT input 2 >>= tokenGetType\n-- return ((token2 \/= CHAR) && (token2 \/= SHORT) && (token2 \/= LONG))\n-- @\n{#fun LT as lT\n { toInputStream `Ptr (InputStream)',\n `Int' } -> `Ptr (CommonToken)' fromCommonToken#}\n\n-- | Pointer to an ANTLR string.\n{#pointer *ANTLR3_STRING as AntlrString newtype#}\n\n-- | Cast from an ANTLR string to a pointer to an ANTLR string.\nfromAntlrString :: AntlrString -> Ptr b\nfromAntlrString (AntlrString x) = castPtr x\n\n#c\nANTLR3_STRING *tokenGetAntlrString(ANTLR3_COMMON_TOKEN *token);\n#endc\n\n-- | Obtain the token name ANTLR string for the specified token.\n-- > tokenGetAntlrString token\n-- | For identifier tokens, the token string is interesting. For\n-- | other tokens such as operator tokens, the token string is\n-- | uninteresting, and may not be present, the token identifier enum \n-- | should be used instead.\n{#fun tokenGetAntlrString\n { toCommonToken `Ptr (CommonToken)' } -> `Ptr (AntlrString)' fromAntlrString#}\n\n-- | Convert an ANTLR string to a Maybe String. \nfromAntlrStringToMaybeString :: AntlrString -> IO (Maybe String)\nfromAntlrStringToMaybeString (AntlrString x) = \n if x == Ptr.nullPtr\n then return Nothing\n else \n {#get ANTLR3_STRING->chars#} x >>= \\c ->\n {#get ANTLR3_STRING->len#} x >>= \\l ->\n peekCStringLen ((castPtr c), (fromIntegral l)) >>= \\s ->\n return (Just s)\n\n-- | Obtain the token Maybe String for the specified token.\n-- | For identifier tokens, the token string is interesting. For\n-- | other tokens such as operator tokens, the token string is\n-- | uninteresting, and may not be present, the token identifier enum \n-- | should be used instead.\ntokenGetTextMaybe :: Ptr (CommonToken) -> IO (Maybe String)\ntokenGetTextMaybe c =\n tokenGetAntlrString c >>= \\s ->\n fromAntlrStringToMaybeString (AntlrString s)\n\n-- | Convert from an ANTLR string to a String.\n-- | Note: the peekCStringLen function does not say what will happen if the\n-- | c pointer is 0.\nfromAntlrStringToString :: AntlrString -> IO String\nfromAntlrStringToString (AntlrString x) = \n {#get ANTLR3_STRING->chars#} x >>= \\c ->\n {#get ANTLR3_STRING->len#} x >>= \\l ->\n peekCStringLen ((castPtr c), (fromIntegral l)) >>= \\s ->\n return s\n\n-- | Obtain the token String for the specified token.\n-- | Note: the peekCStringLen function does not say what will happen if the\n-- | c pointer is 0.\n-- @\n-- foreign export ccall saIntV :: Ptr CommonToken -> IO (StablePtr TermInfo)\n-- saIntV token =\n-- do\n-- -- read the IntV integer value from the token text into n\n-- t <- tokenGetText token\n-- n <- readIO t\n-- -- obtain the source code line and charPosition from the token\n-- l <- tokenGetLine token\n-- c <- tokenGetCharPositionInLine token\n-- -- return the term, which is TmZero, or TmSucc TmZero, or TmSucc (TmSucc (...TmSucc TmZero))\n-- newStablePtr (intV (Info l c) n)\n-- @\ntokenGetText :: Ptr (CommonToken) -> IO String\ntokenGetText c =\n tokenGetAntlrString c >>= \\s ->\n fromAntlrStringToString (AntlrString s)\n\n-- | Obtain the token identifier for the specified token.\n-- @\n-- foreign export ccall isInt :: Ptr InputStream -> IO Bool\n-- isInt input =\n-- do \n-- token1 <- lT input 1 >>= tokenGetType\n-- return (token1 == INT)\n-- @\ntokenGetType :: (Enum e) => Ptr (CommonToken) -> IO e\ntokenGetType token = {#get ANTLR3_COMMON_TOKEN->type#} token >>= return . cToEnum\n\n-- | Obtain the character position in the source code line of where the token\n-- | was read, for non-imaginary tokens.\n-- @\n-- foreign export ccall saTrue :: Ptr CommonToken -> IO (StablePtr TermInfo)\n-- saTrue token =\n-- do\n-- -- obtain the source code line and charPosition from the token\n-- l <- tokenGetLine token\n-- c <- tokenGetCharPositionInLine token\n-- -- return the TmTrue term\n-- newStablePtr (TmTrue (Info l c))\n-- @\ntokenGetCharPositionInLine :: Ptr (CommonToken) -> IO Int\ntokenGetCharPositionInLine token = {#get ANTLR3_COMMON_TOKEN->charPosition#} token >>= return . cIntConv\n\n-- | Obtain the the source code line of where the token was read, for non-imaginary tokens.\n-- @\n-- foreign export ccall saFalse :: Ptr CommonToken -> IO (StablePtr TermInfo)\n-- saFalse token =\n-- do\n-- -- obtain the source code line and charPosition from the token\n-- l <- tokenGetLine token\n-- c <- tokenGetCharPositionInLine token\n-- -- return the TmFalse term\n-- newStablePtr (TmFalse (Info l c))\n-- @\ntokenGetLine :: Ptr (CommonToken) -> IO Int\ntokenGetLine token = {#get ANTLR3_COMMON_TOKEN->line#} token >>= return . cIntConv\n","old_contents":"-- Copyright (c)2010-2011, Mark Wright. All rights reserved.\n\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TypeSynonymInstances #-}\nmodule Text.Antlrc.Lexer where\n\n#include \"antlr3lexer.h\"\n\nimport C2HS\nimport Foreign.C.Types\nimport Foreign.Storable\nimport Ptr\nimport Foreign.Ptr\nimport System.IO.Unsafe\nimport Foreign.C\nimport Control.Monad\nimport Control.Applicative ((<$>))\n\n{#context lib=\"antlr3c\"#}\n\n-- | Lexer token struct.\n{#pointer *ANTLR3_COMMON_TOKEN as CommonToken newtype#}\n\n-- | Lexer input stream struct.\n{#pointer *ANTLR3_INPUT_STREAM as InputStream newtype#}\n\n-- | Lexer struct.\n{#pointer *ANTLR3_LEXER as Lexer newtype#}\n\n-- | Cast from a pointer to an input stream to an input stream.\ntoInputStream :: Ptr InputStream -> InputStream\ntoInputStream = InputStream . castPtr\n\n-- | Cast from a pointer to a token to a token.\ntoCommonToken :: Ptr CommonToken -> CommonToken\ntoCommonToken = CommonToken . castPtr\n\n-- | Cast from a token to a pointer to a token.\nfromCommonToken :: CommonToken -> Ptr b\nfromCommonToken (CommonToken x) = castPtr x\n\n-- The C function definitions are in lexerc.c\n#c\nANTLR3_COMMON_TOKEN *LT(ANTLR3_INPUT_STREAM *input, int lti);\n#endc\n\n-- | Lookahead in the input stream at the token at the specified\n-- | positive offset, where:L \n-- >>> LT inputStream 1 \n-- | is the current token, or negative offset, where: \n-- >>> LT inputstream -1 \n-- | is the previous token.\n{#fun LT as lT\n { toInputStream `Ptr (InputStream)',\n `Int' } -> `Ptr (CommonToken)' fromCommonToken#}\n\n-- | Pointer to an ANTLR string.\n{#pointer *ANTLR3_STRING as AntlrString newtype#}\n\n-- | Cast from an ANTLR string to a pointer to an ANTLR string.\nfromAntlrString :: AntlrString -> Ptr b\nfromAntlrString (AntlrString x) = castPtr x\n\n#c\nANTLR3_STRING *tokenGetAntlrString(ANTLR3_COMMON_TOKEN *token);\n#endc\n\n-- | Obtain the token name ANTLR string for the specified token.\n-- >>> tokenGetAntlrString token\n-- | For identifier tokens, the token string is interesting. For\n-- | other tokens such as operator tokens, the token string is\n-- | uninteresting, and may not be present, the token identifier enum \n-- | should be used instead.\n{#fun tokenGetAntlrString\n { toCommonToken `Ptr (CommonToken)' } -> `Ptr (AntlrString)' fromAntlrString#}\n\n-- | Convert an ANTLR string to a Maybe String. \nfromAntlrStringToMaybeString :: AntlrString -> IO (Maybe String)\nfromAntlrStringToMaybeString (AntlrString x) = \n if x == Ptr.nullPtr\n then return Nothing\n else \n {#get ANTLR3_STRING->chars#} x >>= \\c ->\n {#get ANTLR3_STRING->len#} x >>= \\l ->\n peekCStringLen ((castPtr c), (fromIntegral l)) >>= \\s ->\n return (Just s)\n\n-- | Obtain the token Maybe String for the specified token.\n-- >>> tokenGetTextMaybe token\n-- | For identifier tokens, the token string is interesting. For\n-- | other tokens such as operator tokens, the token string is\n-- | uninteresting, and may not be present, the token identifier enum \n-- | should be used instead.\ntokenGetTextMaybe :: Ptr (CommonToken) -> IO (Maybe String)\ntokenGetTextMaybe c =\n tokenGetAntlrString c >>= \\s ->\n fromAntlrStringToMaybeString (AntlrString s)\n\n-- | Convert from an ANTLR string to a String.\n-- | Note: the peekCStringLen function does not say what will happen if the\n-- | c pointer is 0.\nfromAntlrStringToString :: AntlrString -> IO String\nfromAntlrStringToString (AntlrString x) = \n {#get ANTLR3_STRING->chars#} x >>= \\c ->\n {#get ANTLR3_STRING->len#} x >>= \\l ->\n peekCStringLen ((castPtr c), (fromIntegral l)) >>= \\s ->\n return s\n\n-- | Obtain the token String for the specified token.\n-- >>> tokenGetText token\n-- | Note: the peekCStringLen function does not say what will happen if the\n-- | c pointer is 0.\ntokenGetText :: Ptr (CommonToken) -> IO String\ntokenGetText c =\n tokenGetAntlrString c >>= \\s ->\n fromAntlrStringToString (AntlrString s)\n\n-- | Obtain the token identifier for the specified token.\n-- >>> tokenGetType token\ntokenGetType :: (Enum e) => Ptr (CommonToken) -> IO e\ntokenGetType token = {#get ANTLR3_COMMON_TOKEN->type#} token >>= return . cToEnum\n\n-- | Obtain the character position in the source code line of where the token\n-- | was read, for non-imaginary tokens.\n-- >>> tokenGetCharPositionInLine token\ntokenGetCharPositionInLine :: Ptr (CommonToken) -> IO Int\ntokenGetCharPositionInLine token = {#get ANTLR3_COMMON_TOKEN->charPosition#} token >>= return . cIntConv\n\n-- | Obtain the the source code line of where the token was read, for non-imaginary tokens.\n-- >>> tokenGetLine token\ntokenGetLine :: Ptr (CommonToken) -> IO Int\ntokenGetLine token = {#get ANTLR3_COMMON_TOKEN->line#} token >>= return . cIntConv\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"50d8336e6ad708f8b2a3623b1ddc9f028a809caa","subject":"Improve documentation for marshalling functions","message":"Improve documentation for marshalling functions\n","repos":"mwu-tow\/cuda","old_file":"Foreign\/CUDA\/Driver\/Marshal.chs","new_file":"Foreign\/CUDA\/Driver\/Marshal.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# OPTIONS_HADDOCK prune #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Marshal\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Memory management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Marshal (\n\n -- * Host Allocation\n AllocFlag(..),\n mallocHostArray, freeHost, registerArray, unregisterArray,\n\n -- * Device Allocation\n mallocArray, allocaArray, free,\n\n -- * Unified Memory Allocation\n AttachFlag(..),\n mallocManagedArray,\n\n -- * Marshalling\n peekArray, peekArrayAsync, peekArray2D, peekArray2DAsync, peekListArray,\n pokeArray, pokeArrayAsync, pokeArray2D, pokeArray2DAsync, pokeListArray,\n copyArray, copyArrayAsync, copyArray2D, copyArray2DAsync,\n copyArrayPeer, copyArrayPeerAsync,\n\n -- * Combined Allocation and Marshalling\n newListArray, newListArrayLen,\n withListArray, withListArrayLen,\n\n -- * Utility\n memset, memsetAsync,\n getDevicePtr, getBasePtr, getMemInfo,\n\n -- Internal\n useDeviceHandle, peekDeviceHandle\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Ptr\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Stream ( Stream(..), defaultStream )\nimport Foreign.CUDA.Driver.Context.Base ( Context(..) )\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Data.Int\nimport Data.Maybe\nimport Unsafe.Coerce\nimport Control.Applicative\nimport Control.Exception\nimport Prelude\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.Storable\nimport qualified Foreign.Marshal as F\n\n#c\ntypedef enum CUmemhostalloc_option_enum {\n CU_MEMHOSTALLOC_OPTION_PORTABLE = CU_MEMHOSTALLOC_PORTABLE,\n CU_MEMHOSTALLOC_OPTION_DEVICE_MAPPED = CU_MEMHOSTALLOC_DEVICEMAP,\n CU_MEMHOSTALLOC_OPTION_WRITE_COMBINED = CU_MEMHOSTALLOC_WRITECOMBINED\n} CUmemhostalloc_option;\n#endc\n\n\n--------------------------------------------------------------------------------\n-- Host Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Options for host allocation\n--\n{# enum CUmemhostalloc_option as AllocFlag\n { underscoreToCase }\n with prefix=\"CU_MEMHOSTALLOC_OPTION\" deriving (Eq, Show, Bounded) #}\n\n-- |\n-- Allocate a section of linear memory on the host which is page-locked and\n-- directly accessible from the device. The storage is sufficient to hold the\n-- given number of elements of a storable type.\n--\n-- Note that since the amount of pageable memory is thusly reduced, overall\n-- system performance may suffer. This is best used sparingly to allocate\n-- staging areas for data exchange.\n--\n-- Host memory allocated in this way is automatically and immediately\n-- accessible to all contexts on all devices which support unified\n-- addressing.\n--\n-- \n--\n{-# INLINEABLE mallocHostArray #-}\nmallocHostArray :: Storable a => [AllocFlag] -> Int -> IO (HostPtr a)\nmallocHostArray !flags = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (HostPtr a')\n doMalloc x !n = resultIfOk =<< cuMemHostAlloc (n * sizeOf x) flags\n\n{-# INLINE cuMemHostAlloc #-}\n{# fun unsafe cuMemHostAlloc\n { alloca'- `HostPtr a' peekHP*\n , `Int'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n peekHP !p = HostPtr . castPtr <$> peek p\n\n\n-- |\n-- Free a section of page-locked host memory.\n--\n-- \n--\n{-# INLINEABLE freeHost #-}\nfreeHost :: HostPtr a -> IO ()\nfreeHost !p = nothingIfOk =<< cuMemFreeHost p\n\n{-# INLINE cuMemFreeHost #-}\n{# fun unsafe cuMemFreeHost\n { useHP `HostPtr a' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Page-locks the specified array (on the host) and maps it for the device(s) as\n-- specified by the given allocation flags. Subsequently, the memory is accessed\n-- directly by the device so can be read and written with much higher bandwidth\n-- than pageable memory that has not been registered. The memory range is added\n-- to the same tracking mechanism as 'mallocHostArray' to automatically\n-- accelerate calls to functions such as 'pokeArray'.\n--\n-- Note that page-locking excessive amounts of memory may degrade system\n-- performance, since it reduces the amount of pageable memory available. This\n-- is best used sparingly to allocate staging areas for data exchange.\n--\n-- This function has limited support on Mac OS X. OS 10.7 or later is\n-- required.\n--\n-- Requires CUDA-4.0.\n--\n-- \n--\n{-# INLINEABLE registerArray #-}\nregisterArray :: Storable a => [AllocFlag] -> Int -> Ptr a -> IO (HostPtr a)\n#if CUDA_VERSION < 4000\nregisterArray _ _ _ = requireSDK 'registerArray 4.0\n#else\nregisterArray !flags !n = go undefined\n where\n go :: Storable b => b -> Ptr b -> IO (HostPtr b)\n go x !p = do\n status <- cuMemHostRegister p (n * sizeOf x) flags\n resultIfOk (status,HostPtr p)\n\n{-# INLINE cuMemHostRegister #-}\n{# fun unsafe cuMemHostRegister\n { castPtr `Ptr a'\n , `Int'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Unmaps the memory from the given pointer, and makes it pageable again.\n--\n-- Requires CUDA-4.0.\n--\n-- \n--\n{-# INLINEABLE unregisterArray #-}\nunregisterArray :: HostPtr a -> IO (Ptr a)\n#if CUDA_VERSION < 4000\nunregisterArray _ = requireSDK 'unregisterArray 4.0\n#else\nunregisterArray (HostPtr !p) = do\n status <- cuMemHostUnregister p\n resultIfOk (status,p)\n\n{-# INLINE cuMemHostUnregister #-}\n{# fun unsafe cuMemHostUnregister\n { castPtr `Ptr a' } -> `Status' cToEnum #}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Device Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a section of linear memory on the device, and return a reference to\n-- it. The memory is sufficient to hold the given number of elements of storable\n-- type. It is suitably aligned for any type, and is not cleared.\n--\n-- \n--\n{-# INLINEABLE mallocArray #-}\nmallocArray :: Storable a => Int -> IO (DevicePtr a)\nmallocArray = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')\n doMalloc x !n = resultIfOk =<< cuMemAlloc (n * sizeOf x)\n\n{-# INLINE cuMemAlloc #-}\n{# fun unsafe cuMemAlloc\n { alloca'- `DevicePtr a' peekDeviceHandle*\n , `Int' } -> `Status' cToEnum #}\n where\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n\n\n-- |\n-- Execute a computation on the device, passing a pointer to a temporarily\n-- allocated block of memory sufficient to hold the given number of elements of\n-- storable type. The memory is freed when the computation terminates (normally\n-- or via an exception), so the pointer must not be used after this.\n--\n-- Note that kernel launches can be asynchronous, so you may want to add a\n-- synchronisation point using 'Foreign.CUDA.Driver.Context.sync' as part\n-- of the continuation.\n--\n{-# INLINEABLE allocaArray #-}\nallocaArray :: Storable a => Int -> (DevicePtr a -> IO b) -> IO b\nallocaArray !n = bracket (mallocArray n) free\n\n\n-- |\n-- Release a section of device memory.\n--\n-- \n--\n{-# INLINEABLE free #-}\nfree :: DevicePtr a -> IO ()\nfree !dp = nothingIfOk =<< cuMemFree dp\n\n{-# INLINE cuMemFree #-}\n{# fun unsafe cuMemFree\n { useDeviceHandle `DevicePtr a' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Unified memory allocations\n--------------------------------------------------------------------------------\n\n-- |\n-- Options for unified memory allocations\n--\n#if CUDA_VERSION < 6000\ndata AttachFlag\n#else\n{# enum CUmemAttach_flags as AttachFlag\n { underscoreToCase }\n with prefix=\"CU_MEM_ATTACH_OPTION\" deriving (Eq, Show, Bounded) #}\n#endif\n\n-- |\n-- Allocates memory that will be automatically managed by the Unified Memory\n-- system. The returned pointer is valid on the CPU and on all GPUs which\n-- supported managed memory. All accesses to this pointer must obey the\n-- Unified Memory programming model.\n--\n-- On a multi-GPU system with peer-to-peer support, where multiple GPUs\n-- support managed memory, the physical storage is created on the GPU which\n-- is active at the time 'mallocManagedArray' is called. All other GPUs\n-- will access the array at reduced bandwidth via peer mapping over the\n-- PCIe bus. The Unified Memory system does not migrate memory between\n-- GPUs.\n--\n-- On a multi-GPU system where multiple GPUs support managed memory, but\n-- not all pairs of such GPUs have peer-to-peer support between them, the\n-- physical storage is allocated in system memory (zero-copy memory) and\n-- all GPUs will access the data at reduced bandwidth over the PCIe bus.\n--\n-- Requires CUDA-6.0\n--\n-- \n--\n{-# INLINEABLE mallocManagedArray #-}\nmallocManagedArray :: Storable a => [AttachFlag] -> Int -> IO (DevicePtr a)\n#if CUDA_VERSION < 6000\nmallocManagedArray _ _ = requireSDK 'mallocManagedArray 6.0\n#else\nmallocManagedArray !flags = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')\n doMalloc x !n = resultIfOk =<< cuMemAllocManaged (n * sizeOf x) flags\n\n{-# INLINE cuMemAllocManaged #-}\n{# fun unsafe cuMemAllocManaged\n { alloca'- `DevicePtr a' peekDeviceHandle*\n , `Int'\n , combineBitMasks `[AttachFlag]' } -> `Status' cToEnum #}\n where\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- Device -> Host\n-- --------------\n\n-- |\n-- Copy a number of elements from the device to host memory. This is a\n-- synchronous operation.\n--\n-- \n--\n{-# INLINEABLE peekArray #-}\npeekArray :: Storable a => Int -> DevicePtr a -> Ptr a -> IO ()\npeekArray !n !dptr !hptr = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ = nothingIfOk =<< cuMemcpyDtoH hptr dptr (n * sizeOf x)\n\n{-# INLINE cuMemcpyDtoH #-}\n{# fun cuMemcpyDtoH\n { castPtr `Ptr a'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy memory from the device asynchronously, possibly associated with a\n-- particular stream. The destination host memory must be page-locked.\n--\n-- \n--\n{-# INLINEABLE peekArrayAsync #-}\npeekArrayAsync :: Storable a => Int -> DevicePtr a -> HostPtr a -> Maybe Stream -> IO ()\npeekArrayAsync !n !dptr !hptr !mst = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ = nothingIfOk =<< cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) (fromMaybe defaultStream mst)\n\n{-# INLINE cuMemcpyDtoHAsync #-}\n{# fun cuMemcpyDtoHAsync\n { useHP `HostPtr a'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Copy a 2D array from the device to the host.\n--\n-- \n--\n{-# INLINEABLE peekArray2D #-}\npeekArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> Ptr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> IO ()\npeekArray2D !w !h !dptr !dw !dx !dy !hptr !hw !hx !hy = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n in\n nothingIfOk =<< cuMemcpy2DDtoH hptr hw' hx' hy dptr dw' dx' dy w' h\n\n{-# INLINE cuMemcpy2DDtoH #-}\n{# fun cuMemcpy2DDtoH\n { castPtr `Ptr a'\n , `Int'\n , `Int'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n }\n -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D array from the device to the host asynchronously, possibly\n-- associated with a particular execution stream. The destination host memory\n-- must be page-locked.\n--\n-- \n--\n{-# INLINEABLE peekArray2DAsync #-}\npeekArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> HostPtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> Maybe Stream -- ^ stream to associate to\n -> IO ()\npeekArray2DAsync !w !h !dptr !dw !dx !dy !hptr !hw !hx !hy !mst = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n st = fromMaybe defaultStream mst\n in\n nothingIfOk =<< cuMemcpy2DDtoHAsync hptr hw' hx' hy dptr dw' dx' dy w' h st\n\n{-# INLINE cuMemcpy2DDtoHAsync #-}\n{# fun cuMemcpy2DDtoHAsync\n { useHP `HostPtr a'\n , `Int'\n , `Int'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , useStream `Stream'\n }\n -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Copy a number of elements from the device into a new Haskell list. Note that\n-- this requires two memory copies: firstly from the device into a heap\n-- allocated array, and from there marshalled into a list.\n--\n{-# INLINEABLE peekListArray #-}\npeekListArray :: Storable a => Int -> DevicePtr a -> IO [a]\npeekListArray !n !dptr =\n F.allocaArray n $ \\p -> do\n peekArray n dptr p\n F.peekArray n p\n\n\n-- Host -> Device\n-- --------------\n\n-- |\n-- Copy a number of elements onto the device. This is a synchronous operation.\n--\n-- \n--\n{-# INLINEABLE pokeArray #-}\npokeArray :: Storable a => Int -> Ptr a -> DevicePtr a -> IO ()\npokeArray !n !hptr !dptr = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPoke x _ = nothingIfOk =<< cuMemcpyHtoD dptr hptr (n * sizeOf x)\n\n{-# INLINE cuMemcpyHtoD #-}\n{# fun cuMemcpyHtoD\n { useDeviceHandle `DevicePtr a'\n , castPtr `Ptr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy memory onto the device asynchronously, possibly associated with a\n-- particular stream. The source host memory must be page-locked.\n--\n-- \n--\n{-# INLINEABLE pokeArrayAsync #-}\npokeArrayAsync :: Storable a => Int -> HostPtr a -> DevicePtr a -> Maybe Stream -> IO ()\npokeArrayAsync !n !hptr !dptr !mst = dopoke undefined dptr\n where\n dopoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n dopoke x _ = nothingIfOk =<< cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) (fromMaybe defaultStream mst)\n\n{-# INLINE cuMemcpyHtoDAsync #-}\n{# fun cuMemcpyHtoDAsync\n { useDeviceHandle `DevicePtr a'\n , useHP `HostPtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Copy a 2D array from the host to the device.\n--\n-- \n--\n{-# INLINEABLE pokeArray2D #-}\npokeArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> Ptr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> IO ()\npokeArray2D !w !h !hptr !hw !hx !hy !dptr !dw !dx !dy = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPoke x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n in\n nothingIfOk =<< cuMemcpy2DHtoD dptr dw' dx' dy hptr hw' hx' hy w' h\n\n{-# INLINE cuMemcpy2DHtoD #-}\n{# fun cuMemcpy2DHtoD\n { useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , castPtr `Ptr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n }\n -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D array from the host to the device asynchronously, possibly\n-- associated with a particular execution stream. The source host memory must be\n-- page-locked.\n--\n-- \n--\n{-# INLINEABLE pokeArray2DAsync #-}\npokeArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> HostPtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> Maybe Stream -- ^ stream to associate to\n -> IO ()\npokeArray2DAsync !w !h !hptr !hw !hx !hy !dptr !dw !dx !dy !mst = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPoke x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n st = fromMaybe defaultStream mst\n in\n nothingIfOk =<< cuMemcpy2DHtoDAsync dptr dw' dx' dy hptr hw' hx' hy w' h st\n\n{-# INLINE cuMemcpy2DHtoDAsync #-}\n{# fun cuMemcpy2DHtoDAsync\n { useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , useHP `HostPtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , useStream `Stream'\n }\n -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Write a list of storable elements into a device array. The device array must\n-- be sufficiently large to hold the entire list. This requires two marshalling\n-- operations.\n--\n{-# INLINEABLE pokeListArray #-}\npokeListArray :: Storable a => [a] -> DevicePtr a -> IO ()\npokeListArray !xs !dptr = F.withArrayLen xs $ \\ !len !p -> pokeArray len p dptr\n\n\n-- Device -> Device\n-- ----------------\n\n-- |\n-- Copy the given number of elements from the first device array (source) to the\n-- second device (destination). The copied areas may not overlap. This operation\n-- is asynchronous with respect to the host, but will never overlap with kernel\n-- execution.\n--\n-- \n--\n{-# INLINEABLE copyArray #-}\ncopyArray :: Storable a => Int -> DevicePtr a -> DevicePtr a -> IO ()\ncopyArray !n = docopy undefined\n where\n docopy :: Storable a' => a' -> DevicePtr a' -> DevicePtr a' -> IO ()\n docopy x src dst = nothingIfOk =<< cuMemcpyDtoD dst src (n * sizeOf x)\n\n{-# INLINE cuMemcpyDtoD #-}\n{# fun unsafe cuMemcpyDtoD\n { useDeviceHandle `DevicePtr a'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy the given number of elements from the first device array (source) to the\n-- second device array (destination). The copied areas may not overlap. The\n-- operation is asynchronous with respect to the host, and can be asynchronous\n-- to other device operations by associating it with a particular stream.\n--\n-- \n--\n{-# INLINEABLE copyArrayAsync #-}\ncopyArrayAsync :: Storable a => Int -> DevicePtr a -> DevicePtr a -> Maybe Stream -> IO ()\ncopyArrayAsync !n !src !dst !mst = docopy undefined src\n where\n docopy :: Storable a' => a' -> DevicePtr a' -> IO ()\n docopy x _ = nothingIfOk =<< cuMemcpyDtoDAsync dst src (n * sizeOf x) (fromMaybe defaultStream mst)\n\n{-# INLINE cuMemcpyDtoDAsync #-}\n{# fun unsafe cuMemcpyDtoDAsync\n { useDeviceHandle `DevicePtr a'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D array from the first device array (source) to the second device\n-- array (destination). The copied areas must not overlap. This operation is\n-- asynchronous with respect to the host, but will never overlap with kernel\n-- execution.\n--\n-- \n--\n{-# INLINEABLE copyArray2D #-}\ncopyArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> IO ()\ncopyArray2D !w !h !src !hw !hx !hy !dst !dw !dx !dy = doCopy undefined dst\n where\n doCopy :: Storable a' => a' -> DevicePtr a' -> IO ()\n doCopy x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n in\n nothingIfOk =<< cuMemcpy2DDtoD dst dw' dx' dy src hw' hx' hy w' h\n\n{-# INLINE cuMemcpy2DDtoD #-}\n{# fun unsafe cuMemcpy2DDtoD\n { useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n }\n -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D array from the first device array (source) to the second device\n-- array (destination). The copied areas may not overlap. The operation is\n-- asynchronous with respect to the host, and can be asynchronous to other\n-- device operations by associating it with a particular execution stream.\n--\n-- \n--\n{-# INLINEABLE copyArray2DAsync #-}\ncopyArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> Maybe Stream -- ^ stream to associate to\n -> IO ()\ncopyArray2DAsync !w !h !src !hw !hx !hy !dst !dw !dx !dy !mst = doCopy undefined dst\n where\n doCopy :: Storable a' => a' -> DevicePtr a' -> IO ()\n doCopy x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n st = fromMaybe defaultStream mst\n in\n nothingIfOk =<< cuMemcpy2DDtoDAsync dst dw' dx' dy src hw' hx' hy w' h st\n\n{-# INLINE cuMemcpy2DDtoDAsync #-}\n{# fun unsafe cuMemcpy2DDtoDAsync\n { useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , useStream `Stream'\n }\n -> `Status' cToEnum #}\n\n\n\n-- Context -> Context\n-- ------------------\n\n-- |\n-- Copies an array from device memory in one context to device memory in another\n-- context. Note that this function is asynchronous with respect to the host,\n-- but serialised with respect to all pending and future asynchronous work in\n-- the source and destination contexts. To avoid this synchronisation, use\n-- 'copyArrayPeerAsync' instead.\n--\n-- Requires CUDA-4.0.\n--\n-- \n--\n{-# INLINEABLE copyArrayPeer #-}\ncopyArrayPeer :: Storable a\n => Int -- ^ number of array elements\n -> DevicePtr a -> Context -- ^ source array and context\n -> DevicePtr a -> Context -- ^ destination array and context\n -> IO ()\n#if CUDA_VERSION < 4000\ncopyArrayPeer _ _ _ _ _ = requireSDK 'copyArrayPeer 4.0\n#else\ncopyArrayPeer !n !src !srcCtx !dst !dstCtx = go undefined src dst\n where\n go :: Storable b => b -> DevicePtr b -> DevicePtr b -> IO ()\n go x _ _ = nothingIfOk =<< cuMemcpyPeer dst dstCtx src srcCtx (n * sizeOf x)\n\n{-# INLINE cuMemcpyPeer #-}\n{# fun unsafe cuMemcpyPeer\n { useDeviceHandle `DevicePtr a'\n , useContext `Context'\n , useDeviceHandle `DevicePtr a'\n , useContext `Context'\n , `Int' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Copies from device memory in one context to device memory in another context.\n-- Note that this function is asynchronous with respect to the host and all work\n-- in other streams and devices.\n--\n-- Requires CUDA-4.0.\n--\n-- \n--\n{-# INLINEABLE copyArrayPeerAsync #-}\ncopyArrayPeerAsync :: Storable a\n => Int -- ^ number of array elements\n -> DevicePtr a -> Context -- ^ source array and context\n -> DevicePtr a -> Context -- ^ destination array and device context\n -> Maybe Stream -- ^ stream to associate with\n -> IO ()\n#if CUDA_VERSION < 4000\ncopyArrayPeerAsync _ _ _ _ _ _ = requireSDK 'copyArrayPeerAsync 4.0\n#else\ncopyArrayPeerAsync !n !src !srcCtx !dst !dstCtx !st = go undefined src dst\n where\n go :: Storable b => b -> DevicePtr b -> DevicePtr b -> IO ()\n go x _ _ = nothingIfOk =<< cuMemcpyPeerAsync dst dstCtx src srcCtx (n * sizeOf x) stream\n stream = fromMaybe defaultStream st\n\n{-# INLINE cuMemcpyPeerAsync #-}\n{# fun unsafe cuMemcpyPeerAsync\n { useDeviceHandle `DevicePtr a'\n , useContext `Context'\n , useDeviceHandle `DevicePtr a'\n , useContext `Context'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Combined Allocation and Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Write a list of storable elements into a newly allocated device array,\n-- returning the device pointer together with the number of elements that were\n-- written. Note that this requires two memory copies: firstly from a Haskell\n-- list to a heap allocated array, and from there onto the graphics device. The\n-- memory should be 'free'd when no longer required.\n--\n{-# INLINEABLE newListArrayLen #-}\nnewListArrayLen :: Storable a => [a] -> IO (DevicePtr a, Int)\nnewListArrayLen xs =\n F.withArrayLen xs $ \\len p ->\n bracketOnError (mallocArray len) free $ \\d_xs -> do\n pokeArray len p d_xs\n return (d_xs, len)\n\n\n-- |\n-- Write a list of storable elements into a newly allocated device array. This\n-- is 'newListArrayLen' composed with 'fst'.\n--\n{-# INLINEABLE newListArray #-}\nnewListArray :: Storable a => [a] -> IO (DevicePtr a)\nnewListArray xs = fst `fmap` newListArrayLen xs\n\n\n-- |\n-- Temporarily store a list of elements into a newly allocated device array. An\n-- IO action is applied to to the array, the result of which is returned.\n-- Similar to 'newListArray', this requires copying the data twice.\n--\n-- As with 'allocaArray', the memory is freed once the action completes, so you\n-- should not return the pointer from the action, and be wary of asynchronous\n-- kernel execution.\n--\n{-# INLINEABLE withListArray #-}\nwithListArray :: Storable a => [a] -> (DevicePtr a -> IO b) -> IO b\nwithListArray xs = withListArrayLen xs . const\n\n\n-- |\n-- A variant of 'withListArray' which also supplies the number of elements in\n-- the array to the applied function\n--\n{-# INLINEABLE withListArrayLen #-}\nwithListArrayLen :: Storable a => [a] -> (Int -> DevicePtr a -> IO b) -> IO b\nwithListArrayLen xs f =\n bracket (newListArrayLen xs) (free . fst) (uncurry . flip $ f)\n--\n-- XXX: Will this attempt to double-free the device array on error (together\n-- with newListArrayLen)?\n--\n\n\n--------------------------------------------------------------------------------\n-- Utility\n--------------------------------------------------------------------------------\n\n-- |\n-- Set a number of data elements to the specified value, which may be either 8-,\n-- 16-, or 32-bits wide.\n--\n-- \n--\n-- \n--\n-- \n--\n{-# INLINEABLE memset #-}\nmemset :: Storable a => DevicePtr a -> Int -> a -> IO ()\nmemset !dptr !n !val = case sizeOf val of\n 1 -> nothingIfOk =<< cuMemsetD8 dptr val n\n 2 -> nothingIfOk =<< cuMemsetD16 dptr val n\n 4 -> nothingIfOk =<< cuMemsetD32 dptr val n\n _ -> cudaError \"can only memset 8-, 16-, and 32-bit values\"\n\n--\n-- We use unsafe coerce below to reinterpret the bits of the value to memset as,\n-- into the integer type required by the setting functions.\n--\n{-# INLINE cuMemsetD8 #-}\n{# fun unsafe cuMemsetD8\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{-# INLINE cuMemsetD16 #-}\n{# fun unsafe cuMemsetD16\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{-# INLINE cuMemsetD32 #-}\n{# fun unsafe cuMemsetD32\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set the number of data elements to the specified value, which may be either\n-- 8-, 16-, or 32-bits wide. The operation is asynchronous and may optionally be\n-- associated with a stream.\n--\n-- Requires CUDA-3.2.\n--\n-- \n--\n-- \n--\n-- \n--\n{-# INLINEABLE memsetAsync #-}\nmemsetAsync :: Storable a => DevicePtr a -> Int -> a -> Maybe Stream -> IO ()\n#if CUDA_VERSION < 3020\nmemsetAsync _ _ _ _ = requireSDK 'memsetAsync 3.2\n#else\nmemsetAsync !dptr !n !val !mst = case sizeOf val of\n 1 -> nothingIfOk =<< cuMemsetD8Async dptr val n stream\n 2 -> nothingIfOk =<< cuMemsetD16Async dptr val n stream\n 4 -> nothingIfOk =<< cuMemsetD32Async dptr val n stream\n _ -> cudaError \"can only memset 8-, 16-, and 32-bit values\"\n where\n stream = fromMaybe defaultStream mst\n\n{-# INLINE cuMemsetD8Async #-}\n{# fun unsafe cuMemsetD8Async\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n{-# INLINE cuMemsetD16Async #-}\n{# fun unsafe cuMemsetD16Async\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n{-# INLINE cuMemsetD32Async #-}\n{# fun unsafe cuMemsetD32Async\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Return the device pointer associated with a mapped, pinned host buffer, which\n-- was allocated with the 'DeviceMapped' option by 'mallocHostArray'.\n--\n-- Currently, no options are supported and this must be empty.\n--\n-- \n--\n{-# INLINEABLE getDevicePtr #-}\ngetDevicePtr :: [AllocFlag] -> HostPtr a -> IO (DevicePtr a)\ngetDevicePtr !flags !hp = resultIfOk =<< cuMemHostGetDevicePointer hp flags\n\n{-# INLINE cuMemHostGetDevicePointer #-}\n{# fun unsafe cuMemHostGetDevicePointer\n { alloca'- `DevicePtr a' peekDeviceHandle*\n , useHP `HostPtr a'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Return the base address and allocation size of the given device pointer.\n--\n-- \n--\n{-# INLINEABLE getBasePtr #-}\ngetBasePtr :: DevicePtr a -> IO (DevicePtr a, Int64)\ngetBasePtr !dptr = do\n (status,base,size) <- cuMemGetAddressRange dptr\n resultIfOk (status, (base,size))\n\n{-# INLINE cuMemGetAddressRange #-}\n{# fun unsafe cuMemGetAddressRange\n { alloca'- `DevicePtr a' peekDeviceHandle*\n , alloca'- `Int64' peekIntConv*\n , useDeviceHandle `DevicePtr a' } -> `Status' cToEnum #}\n where\n alloca' :: Storable a => (Ptr a -> IO b) -> IO b\n alloca' = F.alloca\n\n-- |\n-- Return the amount of free and total memory respectively available to the\n-- current context (bytes).\n--\n-- \n--\n{-# INLINEABLE getMemInfo #-}\ngetMemInfo :: IO (Int64, Int64)\ngetMemInfo = do\n (!status,!f,!t) <- cuMemGetInfo\n resultIfOk (status,(f,t))\n\n{-# INLINE cuMemGetInfo #-}\n{# fun unsafe cuMemGetInfo\n { alloca'- `Int64' peekIntConv*\n , alloca'- `Int64' peekIntConv* } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\ntype DeviceHandle = {# type CUdeviceptr #}\n\n-- Lift an opaque handle to a typed DevicePtr representation. This occasions\n-- arcane distinctions for the different driver versions and Tesla (compute 1.x)\n-- and Fermi (compute 2.x) class architectures on 32- and 64-bit hosts.\n--\n{-# INLINE peekDeviceHandle #-}\npeekDeviceHandle :: Ptr DeviceHandle -> IO (DevicePtr a)\npeekDeviceHandle !p = DevicePtr . intPtrToPtr . fromIntegral <$> peek p\n\n-- Use a device pointer as an opaque handle type\n--\n{-# INLINE useDeviceHandle #-}\nuseDeviceHandle :: DevicePtr a -> DeviceHandle\nuseDeviceHandle = fromIntegral . ptrToIntPtr . useDevicePtr\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# OPTIONS_HADDOCK prune #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Marshal\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Memory management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Marshal (\n\n -- * Host Allocation\n AllocFlag(..),\n mallocHostArray, freeHost, registerArray, unregisterArray,\n\n -- * Device Allocation\n mallocArray, allocaArray, free,\n\n -- * Unified Memory Allocation\n AttachFlag(..),\n mallocManagedArray,\n\n -- * Marshalling\n peekArray, peekArrayAsync, peekArray2D, peekArray2DAsync, peekListArray,\n pokeArray, pokeArrayAsync, pokeArray2D, pokeArray2DAsync, pokeListArray,\n copyArray, copyArrayAsync, copyArray2D, copyArray2DAsync,\n copyArrayPeer, copyArrayPeerAsync,\n\n -- * Combined Allocation and Marshalling\n newListArray, newListArrayLen,\n withListArray, withListArrayLen,\n\n -- * Utility\n memset, memsetAsync,\n getDevicePtr, getBasePtr, getMemInfo,\n\n -- Internal\n useDeviceHandle, peekDeviceHandle\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Ptr\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Stream ( Stream(..), defaultStream )\nimport Foreign.CUDA.Driver.Context.Base ( Context(..) )\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Data.Int\nimport Data.Maybe\nimport Unsafe.Coerce\nimport Control.Applicative\nimport Control.Exception\nimport Prelude\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.Storable\nimport qualified Foreign.Marshal as F\n\n#c\ntypedef enum CUmemhostalloc_option_enum {\n CU_MEMHOSTALLOC_OPTION_PORTABLE = CU_MEMHOSTALLOC_PORTABLE,\n CU_MEMHOSTALLOC_OPTION_DEVICE_MAPPED = CU_MEMHOSTALLOC_DEVICEMAP,\n CU_MEMHOSTALLOC_OPTION_WRITE_COMBINED = CU_MEMHOSTALLOC_WRITECOMBINED\n} CUmemhostalloc_option;\n#endc\n\n\n--------------------------------------------------------------------------------\n-- Host Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Options for host allocation\n--\n{# enum CUmemhostalloc_option as AllocFlag\n { underscoreToCase }\n with prefix=\"CU_MEMHOSTALLOC_OPTION\" deriving (Eq, Show, Bounded) #}\n\n-- |\n-- Allocate a section of linear memory on the host which is page-locked and\n-- directly accessible from the device. The storage is sufficient to hold the\n-- given number of elements of a storable type.\n--\n-- Note that since the amount of pageable memory is thusly reduced, overall\n-- system performance may suffer. This is best used sparingly to allocate\n-- staging areas for data exchange.\n--\n{-# INLINEABLE mallocHostArray #-}\nmallocHostArray :: Storable a => [AllocFlag] -> Int -> IO (HostPtr a)\nmallocHostArray !flags = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (HostPtr a')\n doMalloc x !n = resultIfOk =<< cuMemHostAlloc (n * sizeOf x) flags\n\n{-# INLINE cuMemHostAlloc #-}\n{# fun unsafe cuMemHostAlloc\n { alloca'- `HostPtr a' peekHP*\n , `Int'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n peekHP !p = HostPtr . castPtr <$> peek p\n\n\n-- |\n-- Free a section of page-locked host memory\n--\n{-# INLINEABLE freeHost #-}\nfreeHost :: HostPtr a -> IO ()\nfreeHost !p = nothingIfOk =<< cuMemFreeHost p\n\n{-# INLINE cuMemFreeHost #-}\n{# fun unsafe cuMemFreeHost\n { useHP `HostPtr a' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Page-locks the specified array (on the host) and maps it for the device(s) as\n-- specified by the given allocation flags. Subsequently, the memory is accessed\n-- directly by the device so can be read and written with much higher bandwidth\n-- than pageable memory that has not been registered. The memory range is added\n-- to the same tracking mechanism as 'mallocHostArray' to automatically\n-- accelerate calls to functions such as 'pokeArray'.\n--\n-- Note that page-locking excessive amounts of memory may degrade system\n-- performance, since it reduces the amount of pageable memory available. This\n-- is best used sparingly to allocate staging areas for data exchange.\n--\n-- This function is not yet implemented on Mac OS X. Requires cuda-4.0.\n--\n{-# INLINEABLE registerArray #-}\nregisterArray :: Storable a => [AllocFlag] -> Int -> Ptr a -> IO (HostPtr a)\n#if CUDA_VERSION < 4000\nregisterArray _ _ _ = requireSDK 'registerArray 4.0\n#else\nregisterArray !flags !n = go undefined\n where\n go :: Storable b => b -> Ptr b -> IO (HostPtr b)\n go x !p = do\n status <- cuMemHostRegister p (n * sizeOf x) flags\n resultIfOk (status,HostPtr p)\n\n{-# INLINE cuMemHostRegister #-}\n{# fun unsafe cuMemHostRegister\n { castPtr `Ptr a'\n , `Int'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Unmaps the memory from the given pointer, and makes it pageable again.\n--\n-- This function is not yet implemented on Mac OS X. Requires cuda-4.0.\n--\n{-# INLINEABLE unregisterArray #-}\nunregisterArray :: HostPtr a -> IO (Ptr a)\n#if CUDA_VERSION < 4000\nunregisterArray _ = requireSDK 'unregisterArray 4.0\n#else\nunregisterArray (HostPtr !p) = do\n status <- cuMemHostUnregister p\n resultIfOk (status,p)\n\n{-# INLINE cuMemHostUnregister #-}\n{# fun unsafe cuMemHostUnregister\n { castPtr `Ptr a' } -> `Status' cToEnum #}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Device Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a section of linear memory on the device, and return a reference to\n-- it. The memory is sufficient to hold the given number of elements of storable\n-- type. It is suitably aligned for any type, and is not cleared.\n--\n{-# INLINEABLE mallocArray #-}\nmallocArray :: Storable a => Int -> IO (DevicePtr a)\nmallocArray = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')\n doMalloc x !n = resultIfOk =<< cuMemAlloc (n * sizeOf x)\n\n{-# INLINE cuMemAlloc #-}\n{# fun unsafe cuMemAlloc\n { alloca'- `DevicePtr a' peekDeviceHandle*\n , `Int' } -> `Status' cToEnum #}\n where\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n\n\n-- |\n-- Execute a computation on the device, passing a pointer to a temporarily\n-- allocated block of memory sufficient to hold the given number of elements of\n-- storable type. The memory is freed when the computation terminates (normally\n-- or via an exception), so the pointer must not be used after this.\n--\n-- Note that kernel launches can be asynchronous, so you may want to add a\n-- synchronisation point using 'sync' as part of the computation.\n--\n{-# INLINEABLE allocaArray #-}\nallocaArray :: Storable a => Int -> (DevicePtr a -> IO b) -> IO b\nallocaArray !n = bracket (mallocArray n) free\n\n\n-- |\n-- Release a section of device memory\n--\n{-# INLINEABLE free #-}\nfree :: DevicePtr a -> IO ()\nfree !dp = nothingIfOk =<< cuMemFree dp\n\n{-# INLINE cuMemFree #-}\n{# fun unsafe cuMemFree\n { useDeviceHandle `DevicePtr a' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Unified memory allocations\n--------------------------------------------------------------------------------\n\n-- |\n-- Options for unified memory allocations\n--\n#if CUDA_VERSION < 6000\ndata AttachFlag\n#else\n{# enum CUmemAttach_flags as AttachFlag\n { underscoreToCase }\n with prefix=\"CU_MEM_ATTACH_OPTION\" deriving (Eq, Show, Bounded) #}\n#endif\n\n-- |\n-- Allocates memory that will be automatically managed by the Unified Memory\n-- system\n--\n{-# INLINEABLE mallocManagedArray #-}\nmallocManagedArray :: Storable a => [AttachFlag] -> Int -> IO (DevicePtr a)\n#if CUDA_VERSION < 6000\nmallocManagedArray _ _ = requireSDK 'mallocManagedArray 6.0\n#else\nmallocManagedArray !flags = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')\n doMalloc x !n = resultIfOk =<< cuMemAllocManaged (n * sizeOf x) flags\n\n{-# INLINE cuMemAllocManaged #-}\n{# fun unsafe cuMemAllocManaged\n { alloca'- `DevicePtr a' peekDeviceHandle*\n , `Int'\n , combineBitMasks `[AttachFlag]' } -> `Status' cToEnum #}\n where\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- Device -> Host\n-- --------------\n\n-- |\n-- Copy a number of elements from the device to host memory. This is a\n-- synchronous operation\n--\n{-# INLINEABLE peekArray #-}\npeekArray :: Storable a => Int -> DevicePtr a -> Ptr a -> IO ()\npeekArray !n !dptr !hptr = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ = nothingIfOk =<< cuMemcpyDtoH hptr dptr (n * sizeOf x)\n\n{-# INLINE cuMemcpyDtoH #-}\n{# fun cuMemcpyDtoH\n { castPtr `Ptr a'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy memory from the device asynchronously, possibly associated with a\n-- particular stream. The destination host memory must be page-locked.\n--\n{-# INLINEABLE peekArrayAsync #-}\npeekArrayAsync :: Storable a => Int -> DevicePtr a -> HostPtr a -> Maybe Stream -> IO ()\npeekArrayAsync !n !dptr !hptr !mst = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ = nothingIfOk =<< cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) (fromMaybe defaultStream mst)\n\n{-# INLINE cuMemcpyDtoHAsync #-}\n{# fun cuMemcpyDtoHAsync\n { useHP `HostPtr a'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Copy a 2D array from the device to the host.\n--\n{-# INLINEABLE peekArray2D #-}\npeekArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> Ptr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> IO ()\npeekArray2D !w !h !dptr !dw !dx !dy !hptr !hw !hx !hy = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n in\n nothingIfOk =<< cuMemcpy2DDtoH hptr hw' hx' hy dptr dw' dx' dy w' h\n\n{-# INLINE cuMemcpy2DDtoH #-}\n{# fun cuMemcpy2DDtoH\n { castPtr `Ptr a'\n , `Int'\n , `Int'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n }\n -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D array from the device to the host asynchronously, possibly\n-- associated with a particular execution stream. The destination host memory\n-- must be page-locked.\n--\n{-# INLINEABLE peekArray2DAsync #-}\npeekArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> HostPtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> Maybe Stream -- ^ stream to associate to\n -> IO ()\npeekArray2DAsync !w !h !dptr !dw !dx !dy !hptr !hw !hx !hy !mst = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n st = fromMaybe defaultStream mst\n in\n nothingIfOk =<< cuMemcpy2DDtoHAsync hptr hw' hx' hy dptr dw' dx' dy w' h st\n\n{-# INLINE cuMemcpy2DDtoHAsync #-}\n{# fun cuMemcpy2DDtoHAsync\n { useHP `HostPtr a'\n , `Int'\n , `Int'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , useStream `Stream'\n }\n -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Copy a number of elements from the device into a new Haskell list. Note that\n-- this requires two memory copies: firstly from the device into a heap\n-- allocated array, and from there marshalled into a list.\n--\n{-# INLINEABLE peekListArray #-}\npeekListArray :: Storable a => Int -> DevicePtr a -> IO [a]\npeekListArray !n !dptr =\n F.allocaArray n $ \\p -> do\n peekArray n dptr p\n F.peekArray n p\n\n\n-- Host -> Device\n-- --------------\n\n-- |\n-- Copy a number of elements onto the device. This is a synchronous operation\n--\n{-# INLINEABLE pokeArray #-}\npokeArray :: Storable a => Int -> Ptr a -> DevicePtr a -> IO ()\npokeArray !n !hptr !dptr = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPoke x _ = nothingIfOk =<< cuMemcpyHtoD dptr hptr (n * sizeOf x)\n\n{-# INLINE cuMemcpyHtoD #-}\n{# fun cuMemcpyHtoD\n { useDeviceHandle `DevicePtr a'\n , castPtr `Ptr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy memory onto the device asynchronously, possibly associated with a\n-- particular stream. The source host memory must be page-locked.\n--\n{-# INLINEABLE pokeArrayAsync #-}\npokeArrayAsync :: Storable a => Int -> HostPtr a -> DevicePtr a -> Maybe Stream -> IO ()\npokeArrayAsync !n !hptr !dptr !mst = dopoke undefined dptr\n where\n dopoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n dopoke x _ = nothingIfOk =<< cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) (fromMaybe defaultStream mst)\n\n{-# INLINE cuMemcpyHtoDAsync #-}\n{# fun cuMemcpyHtoDAsync\n { useDeviceHandle `DevicePtr a'\n , useHP `HostPtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Copy a 2D array from the host to the device.\n--\n{-# INLINEABLE pokeArray2D #-}\npokeArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> Ptr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> IO ()\npokeArray2D !w !h !hptr !hw !hx !hy !dptr !dw !dx !dy = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPoke x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n in\n nothingIfOk =<< cuMemcpy2DHtoD dptr dw' dx' dy hptr hw' hx' hy w' h\n\n{-# INLINE cuMemcpy2DHtoD #-}\n{# fun cuMemcpy2DHtoD\n { useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , castPtr `Ptr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n }\n -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D array from the host to the device asynchronously, possibly\n-- associated with a particular execution stream. The source host memory must be\n-- page-locked.\n--\n{-# INLINEABLE pokeArray2DAsync #-}\npokeArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> HostPtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> Maybe Stream -- ^ stream to associate to\n -> IO ()\npokeArray2DAsync !w !h !hptr !hw !hx !hy !dptr !dw !dx !dy !mst = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPoke x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n st = fromMaybe defaultStream mst\n in\n nothingIfOk =<< cuMemcpy2DHtoDAsync dptr dw' dx' dy hptr hw' hx' hy w' h st\n\n{-# INLINE cuMemcpy2DHtoDAsync #-}\n{# fun cuMemcpy2DHtoDAsync\n { useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , useHP `HostPtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , useStream `Stream'\n }\n -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Write a list of storable elements into a device array. The device array must\n-- be sufficiently large to hold the entire list. This requires two marshalling\n-- operations.\n--\n{-# INLINEABLE pokeListArray #-}\npokeListArray :: Storable a => [a] -> DevicePtr a -> IO ()\npokeListArray !xs !dptr = F.withArrayLen xs $ \\ !len !p -> pokeArray len p dptr\n\n\n-- Device -> Device\n-- ----------------\n\n-- |\n-- Copy the given number of elements from the first device array (source) to the\n-- second device (destination). The copied areas may not overlap. This operation\n-- is asynchronous with respect to the host, but will never overlap with kernel\n-- execution.\n--\n{-# INLINEABLE copyArray #-}\ncopyArray :: Storable a => Int -> DevicePtr a -> DevicePtr a -> IO ()\ncopyArray !n = docopy undefined\n where\n docopy :: Storable a' => a' -> DevicePtr a' -> DevicePtr a' -> IO ()\n docopy x src dst = nothingIfOk =<< cuMemcpyDtoD dst src (n * sizeOf x)\n\n{-# INLINE cuMemcpyDtoD #-}\n{# fun unsafe cuMemcpyDtoD\n { useDeviceHandle `DevicePtr a'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy the given number of elements from the first device array (source) to the\n-- second device array (destination). The copied areas may not overlap. The\n-- operation is asynchronous with respect to the host, and can be asynchronous\n-- to other device operations by associating it with a particular stream.\n--\n{-# INLINEABLE copyArrayAsync #-}\ncopyArrayAsync :: Storable a => Int -> DevicePtr a -> DevicePtr a -> Maybe Stream -> IO ()\ncopyArrayAsync !n !src !dst !mst = docopy undefined src\n where\n docopy :: Storable a' => a' -> DevicePtr a' -> IO ()\n docopy x _ = nothingIfOk =<< cuMemcpyDtoDAsync dst src (n * sizeOf x) (fromMaybe defaultStream mst)\n\n{-# INLINE cuMemcpyDtoDAsync #-}\n{# fun unsafe cuMemcpyDtoDAsync\n { useDeviceHandle `DevicePtr a'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D array from the first device array (source) to the second device\n-- array (destination). The copied areas must not overlap. This operation is\n-- asynchronous with respect to the host, but will never overlap with kernel\n-- execution.\n--\n{-# INLINEABLE copyArray2D #-}\ncopyArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> IO ()\ncopyArray2D !w !h !src !hw !hx !hy !dst !dw !dx !dy = doCopy undefined dst\n where\n doCopy :: Storable a' => a' -> DevicePtr a' -> IO ()\n doCopy x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n in\n nothingIfOk =<< cuMemcpy2DDtoD dst dw' dx' dy src hw' hx' hy w' h\n\n{-# INLINE cuMemcpy2DDtoD #-}\n{# fun unsafe cuMemcpy2DDtoD\n { useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n }\n -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D array from the first device array (source) to the second device\n-- array (destination). The copied areas may not overlap. The operation is\n-- asynchronous with respect to the host, and can be asynchronous to other\n-- device operations by associating it with a particular execution stream.\n--\n{-# INLINEABLE copyArray2DAsync #-}\ncopyArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> Maybe Stream -- ^ stream to associate to\n -> IO ()\ncopyArray2DAsync !w !h !src !hw !hx !hy !dst !dw !dx !dy !mst = doCopy undefined dst\n where\n doCopy :: Storable a' => a' -> DevicePtr a' -> IO ()\n doCopy x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n st = fromMaybe defaultStream mst\n in\n nothingIfOk =<< cuMemcpy2DDtoDAsync dst dw' dx' dy src hw' hx' hy w' h st\n\n{-# INLINE cuMemcpy2DDtoDAsync #-}\n{# fun unsafe cuMemcpy2DDtoDAsync\n { useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , useStream `Stream'\n }\n -> `Status' cToEnum #}\n\n\n\n-- Context -> Context\n-- ------------------\n\n-- |\n-- Copies an array from device memory in one context to device memory in another\n-- context. Note that this function is asynchronous with respect to the host,\n-- but serialised with respect to all pending and future asynchronous work in\n-- the source and destination contexts. To avoid this synchronisation, use\n-- 'copyArrayPeerAsync' instead.\n--\n{-# INLINEABLE copyArrayPeer #-}\ncopyArrayPeer :: Storable a\n => Int -- ^ number of array elements\n -> DevicePtr a -> Context -- ^ source array and context\n -> DevicePtr a -> Context -- ^ destination array and context\n -> IO ()\n#if CUDA_VERSION < 4000\ncopyArrayPeer _ _ _ _ _ = requireSDK 'copyArrayPeer 4.0\n#else\ncopyArrayPeer !n !src !srcCtx !dst !dstCtx = go undefined src dst\n where\n go :: Storable b => b -> DevicePtr b -> DevicePtr b -> IO ()\n go x _ _ = nothingIfOk =<< cuMemcpyPeer dst dstCtx src srcCtx (n * sizeOf x)\n\n{-# INLINE cuMemcpyPeer #-}\n{# fun unsafe cuMemcpyPeer\n { useDeviceHandle `DevicePtr a'\n , useContext `Context'\n , useDeviceHandle `DevicePtr a'\n , useContext `Context'\n , `Int' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Copies from device memory in one context to device memory in another context.\n-- Note that this function is asynchronous with respect to the host and all work\n-- in other streams and devices.\n--\n{-# INLINEABLE copyArrayPeerAsync #-}\ncopyArrayPeerAsync :: Storable a\n => Int -- ^ number of array elements\n -> DevicePtr a -> Context -- ^ source array and context\n -> DevicePtr a -> Context -- ^ destination array and device context\n -> Maybe Stream -- ^ stream to associate with\n -> IO ()\n#if CUDA_VERSION < 4000\ncopyArrayPeerAsync _ _ _ _ _ _ = requireSDK 'copyArrayPeerAsync 4.0\n#else\ncopyArrayPeerAsync !n !src !srcCtx !dst !dstCtx !st = go undefined src dst\n where\n go :: Storable b => b -> DevicePtr b -> DevicePtr b -> IO ()\n go x _ _ = nothingIfOk =<< cuMemcpyPeerAsync dst dstCtx src srcCtx (n * sizeOf x) stream\n stream = fromMaybe defaultStream st\n\n{-# INLINE cuMemcpyPeerAsync #-}\n{# fun unsafe cuMemcpyPeerAsync\n { useDeviceHandle `DevicePtr a'\n , useContext `Context'\n , useDeviceHandle `DevicePtr a'\n , useContext `Context'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Combined Allocation and Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Write a list of storable elements into a newly allocated device array,\n-- returning the device pointer together with the number of elements that were\n-- written. Note that this requires two memory copies: firstly from a Haskell\n-- list to a heap allocated array, and from there onto the graphics device. The\n-- memory should be 'free'd when no longer required.\n--\n{-# INLINEABLE newListArrayLen #-}\nnewListArrayLen :: Storable a => [a] -> IO (DevicePtr a, Int)\nnewListArrayLen xs =\n F.withArrayLen xs $ \\len p ->\n bracketOnError (mallocArray len) free $ \\d_xs -> do\n pokeArray len p d_xs\n return (d_xs, len)\n\n\n-- |\n-- Write a list of storable elements into a newly allocated device array. This\n-- is 'newListArrayLen' composed with 'fst'.\n--\n{-# INLINEABLE newListArray #-}\nnewListArray :: Storable a => [a] -> IO (DevicePtr a)\nnewListArray xs = fst `fmap` newListArrayLen xs\n\n\n-- |\n-- Temporarily store a list of elements into a newly allocated device array. An\n-- IO action is applied to to the array, the result of which is returned.\n-- Similar to 'newListArray', this requires copying the data twice.\n--\n-- As with 'allocaArray', the memory is freed once the action completes, so you\n-- should not return the pointer from the action, and be wary of asynchronous\n-- kernel execution.\n--\n{-# INLINEABLE withListArray #-}\nwithListArray :: Storable a => [a] -> (DevicePtr a -> IO b) -> IO b\nwithListArray xs = withListArrayLen xs . const\n\n\n-- |\n-- A variant of 'withListArray' which also supplies the number of elements in\n-- the array to the applied function\n--\n{-# INLINEABLE withListArrayLen #-}\nwithListArrayLen :: Storable a => [a] -> (Int -> DevicePtr a -> IO b) -> IO b\nwithListArrayLen xs f =\n bracket (newListArrayLen xs) (free . fst) (uncurry . flip $ f)\n--\n-- XXX: Will this attempt to double-free the device array on error (together\n-- with newListArrayLen)?\n--\n\n\n--------------------------------------------------------------------------------\n-- Utility\n--------------------------------------------------------------------------------\n\n-- |\n-- Set a number of data elements to the specified value, which may be either 8-,\n-- 16-, or 32-bits wide.\n--\n{-# INLINEABLE memset #-}\nmemset :: Storable a => DevicePtr a -> Int -> a -> IO ()\nmemset !dptr !n !val = case sizeOf val of\n 1 -> nothingIfOk =<< cuMemsetD8 dptr val n\n 2 -> nothingIfOk =<< cuMemsetD16 dptr val n\n 4 -> nothingIfOk =<< cuMemsetD32 dptr val n\n _ -> cudaError \"can only memset 8-, 16-, and 32-bit values\"\n\n--\n-- We use unsafe coerce below to reinterpret the bits of the value to memset as,\n-- into the integer type required by the setting functions.\n--\n{-# INLINE cuMemsetD8 #-}\n{# fun unsafe cuMemsetD8\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{-# INLINE cuMemsetD16 #-}\n{# fun unsafe cuMemsetD16\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{-# INLINE cuMemsetD32 #-}\n{# fun unsafe cuMemsetD32\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set the number of data elements to the specified value, which may be either\n-- 8-, 16-, or 32-bits wide. The operation is asynchronous and may optionally be\n-- associated with a stream. Requires cuda-3.2.\n--\n{-# INLINEABLE memsetAsync #-}\nmemsetAsync :: Storable a => DevicePtr a -> Int -> a -> Maybe Stream -> IO ()\n#if CUDA_VERSION < 3020\nmemsetAsync _ _ _ _ = requireSDK 'memsetAsync 3.2\n#else\nmemsetAsync !dptr !n !val !mst = case sizeOf val of\n 1 -> nothingIfOk =<< cuMemsetD8Async dptr val n stream\n 2 -> nothingIfOk =<< cuMemsetD16Async dptr val n stream\n 4 -> nothingIfOk =<< cuMemsetD32Async dptr val n stream\n _ -> cudaError \"can only memset 8-, 16-, and 32-bit values\"\n where\n stream = fromMaybe defaultStream mst\n\n{-# INLINE cuMemsetD8Async #-}\n{# fun unsafe cuMemsetD8Async\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n{-# INLINE cuMemsetD16Async #-}\n{# fun unsafe cuMemsetD16Async\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n{-# INLINE cuMemsetD32Async #-}\n{# fun unsafe cuMemsetD32Async\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Return the device pointer associated with a mapped, pinned host buffer, which\n-- was allocated with the 'DeviceMapped' option by 'mallocHostArray'.\n--\n-- Currently, no options are supported and this must be empty.\n--\n{-# INLINEABLE getDevicePtr #-}\ngetDevicePtr :: [AllocFlag] -> HostPtr a -> IO (DevicePtr a)\ngetDevicePtr !flags !hp = resultIfOk =<< cuMemHostGetDevicePointer hp flags\n\n{-# INLINE cuMemHostGetDevicePointer #-}\n{# fun unsafe cuMemHostGetDevicePointer\n { alloca'- `DevicePtr a' peekDeviceHandle*\n , useHP `HostPtr a'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n useHP = castPtr . useHostPtr\n\n-- |\n-- Return the base address and allocation size of the given device pointer\n--\n{-# INLINEABLE getBasePtr #-}\ngetBasePtr :: DevicePtr a -> IO (DevicePtr a, Int64)\ngetBasePtr !dptr = do\n (status,base,size) <- cuMemGetAddressRange dptr\n resultIfOk (status, (base,size))\n\n{-# INLINE cuMemGetAddressRange #-}\n{# fun unsafe cuMemGetAddressRange\n { alloca'- `DevicePtr a' peekDeviceHandle*\n , alloca'- `Int64' peekIntConv*\n , useDeviceHandle `DevicePtr a' } -> `Status' cToEnum #}\n where\n alloca' :: Storable a => (Ptr a -> IO b) -> IO b\n alloca' = F.alloca\n\n-- |\n-- Return the amount of free and total memory respectively available to the\n-- current context (bytes)\n--\n{-# INLINEABLE getMemInfo #-}\ngetMemInfo :: IO (Int64, Int64)\ngetMemInfo = do\n (!status,!f,!t) <- cuMemGetInfo\n resultIfOk (status,(f,t))\n\n{-# INLINE cuMemGetInfo #-}\n{# fun unsafe cuMemGetInfo\n { alloca'- `Int64' peekIntConv*\n , alloca'- `Int64' peekIntConv* } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\ntype DeviceHandle = {# type CUdeviceptr #}\n\n-- Lift an opaque handle to a typed DevicePtr representation. This occasions\n-- arcane distinctions for the different driver versions and Tesla (compute 1.x)\n-- and Fermi (compute 2.x) class architectures on 32- and 64-bit hosts.\n--\n{-# INLINE peekDeviceHandle #-}\npeekDeviceHandle :: Ptr DeviceHandle -> IO (DevicePtr a)\npeekDeviceHandle !p = DevicePtr . intPtrToPtr . fromIntegral <$> peek p\n\n-- Use a device pointer as an opaque handle type\n--\n{-# INLINE useDeviceHandle #-}\nuseDeviceHandle :: DevicePtr a -> DeviceHandle\nuseDeviceHandle = fromIntegral . ptrToIntPtr . useDevicePtr\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"99117121ee892224b11a629ade8b3fd52347cf74","subject":"gstreamer: more docs in M.S.G.Core.Caps","message":"gstreamer: more docs in M.S.G.Core.Caps\n\ndarcs-hash:20080519005233-21862-3482d0bfae90095b3eec2d958ddc367fb347b13c.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Caps.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Caps.chs","new_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gstreamer -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GStreamer, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GStreamer documentation.\n-- \n-- |\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\n-- \n-- A structure describing sets of media formats.\nmodule Media.Streaming.GStreamer.Core.Caps (\n \n-- * Detail\n -- | 'Caps' (short for \/capabilities\/) are lightweight objects\n -- describing media types. They are composed of arrays of\n -- 'Structure's.\n -- \n -- 'Caps' are exposed on 'PadTemplate's to describe all the\n -- possible types a given 'Pad' can handle. They are also stored\n -- in the 'Registry' along with the description of an 'Element'.\n -- \n -- 'Caps' can be retrieved from an 'Element'\\'s 'Pad's using the\n -- 'padGetCaps' function. The returned 'Caps' describes the possible\n -- types that the pad can handle or produce at runtime.\n -- \n -- 'Caps' are also attached to 'Buffers' to describe the type of\n -- the contained data using the function 'bufferSetCaps'. 'Caps'\n -- attached to a buffer allow for format negotiation upstream and\n -- downstream.\n -- \n -- 'Caps' are \/fixed\/ when they have no properties with ranges or\n -- lists. Use 'capsIsFixed' to test for fixed caps. Only fixed\n -- caps may be set on a 'Pad' or 'Buffer'.\n\n-- * Types\n Caps,\n capsNone,\n capsAny,\n\n-- * Caps Operations\n capsSize,\n capsGetStructure,\n capsIsEmpty,\n capsIsFixed,\n capsIsEqual,\n capsIsEqualFixed,\n capsIsAlwaysCompatible, \n capsIsSubset,\n capsIntersect,\n capsUnion,\n capsSubtract,\n capsNormalize,\n capsFromString,\n capsToString,\n\n-- * Caps Mutation\n CapsM,\n capsCreate,\n capsModify,\n capsAppendStructure,\n capsMergeStructure,\n capsRemoveStructure,\n capsTruncate\n \n ) where\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nimport Control.Monad (liftM)\nimport Control.Monad.Reader\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import Media.Streaming.GStreamer.Core.Types#}\n\n-- | A 'Caps' that represents an undefined media type.\ncapsNone :: Caps\ncapsNone =\n unsafePerformIO $ {# call caps_new_empty #} >>= takeCaps\n\n-- | A 'Caps' that represents all possible media types.\ncapsAny :: Caps\ncapsAny =\n unsafePerformIO $ {# call caps_new_any #} >>= takeCaps\n\n-- | Get the number of structures contained in the 'Caps'.\ncapsSize :: Caps -- ^ @caps@ - a 'Caps'\n -> Word -- ^ the number of structures contained in the 'Caps'\ncapsSize caps =\n fromIntegral $ unsafePerformIO $ {# call caps_get_size #} caps\n\n-- | Get the 'Structure' at the given index.\ncapsGetStructure :: Caps -- ^ @caps@ - a 'Caps'\n -> Word -- ^ @index@ - the index of the 'Structure'\n -> Maybe Structure -- ^ the 'Structure' at the given index, or 'Nothing'\n -- if @index@ is invalid\ncapsGetStructure caps index =\n unsafePerformIO $\n {# call caps_get_structure #} caps (fromIntegral index) >>=\n maybePeek peekStructure\n\n-- | Create a new 'Caps' containing only the 'Structure' at the given\n-- index of the caps.\ncapsCopyNth :: Caps -- ^ @caps@ - a 'Caps'\n -> Word -- ^ @index@ - the index of the 'Structure'\n -> Maybe Caps -- ^ the new 'Caps', or 'Nothing'\n -- if @index@ is invalid\ncapsCopyNth caps index =\n unsafePerformIO $\n {# call caps_copy_nth #} caps (fromIntegral index) >>=\n maybePeek takeCaps\n\n-- | Determine whether @caps@ represents no media formats.\ncapsIsEmpty :: Caps -- ^ @caps@ - a 'Caps'\n -> Bool -- ^ 'True' if @caps@ is empty, otherwise 'False'\ncapsIsEmpty caps =\n toBool $ unsafePerformIO $\n {# call caps_is_empty #} caps\n\n-- | Determine whether the @caps@ is fixed; that is, if it has exactly\n-- one structure, and each field in the structure describes a fixed type.\ncapsIsFixed :: Caps -- ^ @caps@ - a 'Caps'\n -> Bool -- ^ 'True' if @caps@ is fixed, otherwise 'False'\ncapsIsFixed caps =\n toBool $ unsafePerformIO $\n {# call caps_is_fixed #} caps\n\n-- | Returns 'True' if the caps represent the same set of capabilities.\n-- \n-- This function does not work reliably if optional properties for\n-- 'Caps' are included on one 'Caps' but omitted on the other.\ncapsIsEqual :: Caps -- ^ @caps1@ - the first 'Caps'\n -> Caps -- ^ @caps2@ - the second 'Caps'\n -> Bool -- ^ 'True' if both 'Caps' represent the same set\n -- of capabilities.\ncapsIsEqual caps1 caps2 =\n toBool $ unsafePerformIO $\n {# call caps_is_equal #} caps1 caps2\n\ninstance Eq Caps where\n (==) = capsIsEqual\n\n-- | Returns 'True' if the caps are equal. The caps must both be\n-- fixed.\ncapsIsEqualFixed :: Caps -- ^ @caps1@ - the first 'Caps'\n -> Caps -- ^ @caps2@ - the second 'Caps'\n -> Bool -- ^ 'True' if both 'Caps' represent the same set\n -- of capabilities\ncapsIsEqualFixed caps1 caps2 =\n toBool $ unsafePerformIO $\n {# call caps_is_equal_fixed #} caps1 caps2\n\n-- | Returns 'True' if every media format in the first caps is also\n-- contained by the second. That is, the first is a subset of the\n-- second.\ncapsIsAlwaysCompatible :: Caps -- ^ @caps1@ - the first 'Caps'\n -> Caps -- ^ @caps2@ - the second 'Caps'\n -> Bool -- ^ 'True' if @caps1@ is a subset of @caps2@, otherwise 'False'\ncapsIsAlwaysCompatible caps1 caps2 =\n toBool $ unsafePerformIO $\n {# call caps_is_always_compatible #} caps1 caps2\n\n-- | Returns 'True' if all caps represented by the first argument are\n-- also represented by the second.\n-- \n-- This function does not work reliably if optional properties for\n-- caps are included on one caps and omitted on the other.\ncapsIsSubset :: Caps -- ^ @caps1@ - the first 'Caps'\n -> Caps -- ^ @caps2@ - the second 'Caps'\n -> Bool -- ^ 'True' if @caps1@ is a subset of @caps2@, otherwise 'False'\ncapsIsSubset caps1 caps2 =\n toBool $ unsafePerformIO $\n {# call caps_is_subset #} caps1 caps2\n\n-- | Creates a new caps containing all the formats that are common to\n-- both of the caps.\ncapsIntersect :: Caps -- ^ @caps1@ - the first 'Caps'\n -> Caps -- ^ @caps2@ - the second 'Caps'\n -> Caps -- ^ a new 'Caps' containing all capabilities present\n -- in both @caps1@ and @caps2@\ncapsIntersect caps1 caps2 =\n unsafePerformIO $\n {# call caps_intersect #} caps1 caps2 >>=\n takeCaps\n\n-- | Creates a new caps containing all the formats that are common to\n-- either of the caps. If either of the structures are equivalient\n-- to 'capsAny', the result will be 'capsAny'.\ncapsUnion :: Caps -- ^ @caps1@ - the first 'Caps'\n -> Caps -- ^ @caps2@ - the second 'Caps'\n -> Caps -- ^ a new 'Caps' containing all capabilities present\n -- in either @caps1@ and @caps2@\ncapsUnion caps1 caps2 =\n unsafePerformIO $\n {# call caps_union #} caps1 caps2 >>=\n takeCaps\n\n-- | Creates a new caps containing all the formats that are in the\n-- first but not the second.\ncapsSubtract :: Caps -- ^ @caps1@ - the first 'Caps'\n -> Caps -- ^ @caps2@ - the second 'Caps'\n -> Caps -- ^ a new 'Caps' containing all capabilities present\n -- in @caps1@ but not @caps2@\ncapsSubtract caps1 caps2 =\n unsafePerformIO $\n {# call caps_subtract #} caps1 caps2 >>=\n takeCaps\n\n-- | Creates a new caps that represents the same set of formats as the\n-- argument, but that contains no lists.\ncapsNormalize :: Caps -- ^ @caps@ - a 'Caps'\n -> Caps -- ^ the new, normalized 'Caps'\ncapsNormalize caps =\n unsafePerformIO $\n {# call caps_normalize #} caps >>= takeCaps\n\n-- | Converts the argument to a string representation. The string can\n-- be converted back to a caps using 'capsFromString'.\ncapsToString :: Caps -- ^ @caps@ - a 'Caps'\n -> String -- ^ the string representation of 'Caps'\ncapsToString caps =\n unsafePerformIO $\n {# call caps_to_string #} caps >>= readUTFString\n\n-- | Read a caps from a string.\ncapsFromString :: String -- ^ @string@ - the string representation of a 'Caps'\n -> Maybe Caps -- ^ the new 'Caps', or 'Nothing' if @string@ is invalid\ncapsFromString string =\n unsafePerformIO $\n withUTFString string {# call caps_from_string #} >>=\n maybePeek takeCaps\n\n-- | A 'Monad' for sequencing modifications to a 'Caps'.\nnewtype CapsM a =\n CapsM (ReaderT (Ptr Caps) IO a)\n deriving (Functor, Monad)\n\naskCapsPtr :: CapsM (Ptr Caps)\naskCapsPtr = CapsM $ ask\n\nmarshalCapsModify :: IO (Ptr Caps)\n -> CapsM a\n -> (Caps, a)\nmarshalCapsModify mkCaps (CapsM action) =\n unsafePerformIO $\n do ptr <- mkCaps\n result <- runReaderT action ptr\n caps <- takeCaps ptr\n return (caps, result)\n\n-- | Create a caps and mutate it according to the given action.\ncapsCreate :: CapsM a -- ^ @mutate@ - the mutating action\n -> (Caps, a) -- ^ the new 'Caps' and the action's result\ncapsCreate mutate =\n marshalCapsModify\n {# call caps_new_empty #}\n mutate\n\n-- | Copy a caps and mutate it according to the given action.\ncapsModify :: Caps -- ^ @caps@ - the 'Caps' to modify\n -> CapsM a -- ^ @mutate@ - the mutating action\n -> (Caps, a) -- ^ the new 'Caps' and the action's result\ncapsModify caps mutate =\n marshalCapsModify ({# call caps_copy #} caps) mutate\n\n-- | Append the given structure to the current caps.\ncapsAppendStructure :: Structure -- ^ @structure@ - the 'Structure' to append to the current 'Caps'\n -> CapsM ()\ncapsAppendStructure structure = do\n capsPtr <- askCapsPtr\n CapsM $ liftIO $ withStructure structure $ \\structurePtr ->\n do structurePtr' <- gst_structure_copy structurePtr\n gst_caps_append_structure capsPtr structurePtr\n where _ = {# call caps_append_structure #}\n _ = {# call structure_copy #}\n\n-- | Append the structure to the current caps, if it is not already\n-- expressed by the caps.\ncapsMergeStructure :: Structure -- ^ @structure@ - the 'Structure' to merge with the current 'Caps'\n -> CapsM ()\ncapsMergeStructure structure = do\n capsPtr <- askCapsPtr\n CapsM $ liftIO $ withStructure structure $ \\structurePtr ->\n do structurePtr' <- gst_structure_copy structurePtr\n gst_caps_merge_structure capsPtr structurePtr\n where _ = {# call caps_merge_structure #}\n _ = {# call structure_copy #}\n\n-- | Removes the structure at the given index from the current caps.\ncapsRemoveStructure :: Word -- ^ @idx@ - the index of the 'Structure' to remove\n -> CapsM ()\ncapsRemoveStructure idx = do\n capsPtr <- askCapsPtr\n CapsM $ liftIO $ gst_caps_remove_structure capsPtr $ fromIntegral idx\n where _ = {# call caps_remove_structure #}\n\n-- | Discard all but the first structure from the current caps.\ncapsTruncate :: CapsM ()\ncapsTruncate = do\n capsPtr <- askCapsPtr\n CapsM $ liftIO $ gst_caps_truncate capsPtr\n where _ = {# call caps_truncate #}\n","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gstreamer -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GStreamer, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GStreamer documentation.\n-- \n-- |\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\n-- \n-- A structure describing sets of media formats.\nmodule Media.Streaming.GStreamer.Core.Caps (\n \n-- * Detail\n -- | 'Caps' (short for \/capabilities\/) are lightweight objects\n -- describing media types. They are composed of arrays of\n -- 'Structure's.\n -- \n -- 'Caps' are exposed on 'PadTemplate's to describe all the\n -- possible types a given 'Pad' can handle. They are also stored\n -- in the 'Registry' along with the description of an 'Element'.\n -- \n -- 'Caps' can be retrieved from an 'Element'\\'s 'Pad's using the\n -- 'padGetCaps' function. The returned 'Caps' describes the possible\n -- types that the pad can handle or produce at runtime.\n -- \n -- 'Caps' are also attached to 'Buffers' to describe the type of\n -- the contained data using the function 'bufferSetCaps'. 'Caps'\n -- attached to a buffer allow for format negotiation upstream and\n -- downstream.\n -- \n -- 'Caps' are \/fixed\/ when they have no properties with ranges or\n -- lists. Use 'capsIsFixed' to test for fixed caps. Only fixed\n -- caps may be set on a 'Pad' or 'Buffer'.\n\n-- * Types\n Caps,\n capsNone,\n capsAny,\n\n-- * Caps Operations\n capsSize,\n capsGetStructure,\n capsIsEmpty,\n capsIsFixed,\n capsIsEqual,\n capsIsEqualFixed,\n capsIsAlwaysCompatible, \n capsIsSubset,\n capsIntersect,\n capsUnion,\n capsSubtract,\n capsNormalize,\n capsFromString,\n capsToString,\n\n-- * Caps Mutation\n CapsM,\n capsCreate,\n capsModify,\n capsAppendStructure,\n capsMergeStructure,\n capsRemoveStructure,\n capsTruncate\n \n ) where\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\nimport Control.Monad (liftM)\nimport Control.Monad.Reader\nimport System.Glib.FFI\nimport System.Glib.UTFString\n{#import Media.Streaming.GStreamer.Core.Types#}\n\n-- | A 'Caps' that represents an undefined media type.\ncapsNone :: Caps\ncapsNone =\n unsafePerformIO $ {# call caps_new_empty #} >>= takeCaps\n\n-- | A 'Caps' that represents all possible media types.\ncapsAny :: Caps\ncapsAny =\n unsafePerformIO $ {# call caps_new_any #} >>= takeCaps\n\n-- | Returns the number of structures contained in the 'Caps'.\ncapsSize :: Caps\n -> Word\ncapsSize caps =\n fromIntegral $ unsafePerformIO $ {# call caps_get_size #} caps\n\n-- | Returns the 'Structure' at the given index.\ncapsGetStructure :: Caps\n -> Word\n -> Maybe Structure\ncapsGetStructure caps index =\n unsafePerformIO $\n {# call caps_get_structure #} caps (fromIntegral index) >>=\n maybePeek peekStructure\n\n-- | Returns a new 'Caps' containing only the 'Structure' at the given\n-- index of the caps.\ncapsCopyNth :: Caps\n -> Word\n -> Maybe Caps\ncapsCopyNth caps index =\n unsafePerformIO $\n {# call caps_copy_nth #} caps (fromIntegral index) >>=\n maybePeek takeCaps\n\n-- | Returns 'True' if the caps represents no media formats.\ncapsIsEmpty :: Caps\n -> Bool\ncapsIsEmpty caps =\n toBool $ unsafePerformIO $\n {# call caps_is_empty #} caps\n\n-- | Returns 'True' if the caps is fixed.\ncapsIsFixed :: Caps\n -> Bool\ncapsIsFixed caps =\n toBool $ unsafePerformIO $\n {# call caps_is_fixed #} caps\n\n-- | Returns 'True' if the caps represent the same set of capabilities.\ncapsIsEqual :: Caps\n -> Caps\n -> Bool\ncapsIsEqual caps1 caps2 =\n toBool $ unsafePerformIO $\n {# call caps_is_equal #} caps1 caps2\n\ninstance Eq Caps where\n (==) = capsIsEqual\n\n-- | Returns 'True' if the caps are equal. The caps must both be\n-- fixed.\ncapsIsEqualFixed :: Caps\n -> Caps\n -> Bool\ncapsIsEqualFixed caps1 caps2 =\n toBool $ unsafePerformIO $\n {# call caps_is_equal_fixed #} caps1 caps2\n\n-- | Returns 'True' if every media format in the first caps is also\n-- contained by the second. That is, the first is a subset of the\n-- second.\ncapsIsAlwaysCompatible :: Caps\n -> Caps\n -> Bool\ncapsIsAlwaysCompatible caps1 caps2 =\n toBool $ unsafePerformIO $\n {# call caps_is_always_compatible #} caps1 caps2\n\n-- | Returns 'True' if all caps represented by the first argument are\n-- also represented by the second.\n-- \n-- This function does not work reliably if optional properties for\n-- caps are included on one caps and omitted on the other.\ncapsIsSubset :: Caps\n -> Caps\n -> Bool\ncapsIsSubset caps1 caps2 =\n toBool $ unsafePerformIO $\n {# call caps_is_subset #} caps1 caps2\n\n-- | Creates a new caps containing all the formats that are common to\n-- both of the caps.\ncapsIntersect :: Caps\n -> Caps\n -> Caps\ncapsIntersect caps1 caps2 =\n unsafePerformIO $\n {# call caps_intersect #} caps1 caps2 >>=\n takeCaps\n\n-- | Creates a new caps containing all the formats that are common to\n-- either of the caps. If either of the structures are equivalient\n-- to 'capsAny', the result will be 'capsAny'.\ncapsUnion :: Caps\n -> Caps\n -> Caps\ncapsUnion caps1 caps2 =\n unsafePerformIO $\n {# call caps_union #} caps1 caps2 >>=\n takeCaps\n\n-- | Creates a new caps containing all the formats that are in the\n-- first but not the second.\ncapsSubtract :: Caps\n -> Caps\n -> Caps\ncapsSubtract caps1 caps2 =\n unsafePerformIO $\n {# call caps_subtract #} caps1 caps2 >>=\n takeCaps\n\n-- | Creates a new caps that represents the same set of formats as the\n-- argument, but that contains no lists.\ncapsNormalize :: Caps\n -> Caps\ncapsNormalize caps =\n unsafePerformIO $\n {# call caps_normalize #} caps >>= takeCaps\n\n-- | Converts the argument to a string representation. The string can\n-- be converted back to a caps using 'capsFromString'.\ncapsToString :: Caps\n -> String\ncapsToString caps =\n unsafePerformIO $\n {# call caps_to_string #} caps >>= readUTFString\n\n-- | Read a caps from a string.\ncapsFromString :: String\n -> Maybe Caps\ncapsFromString string =\n unsafePerformIO $\n withUTFString string {# call caps_from_string #} >>=\n maybePeek takeCaps\n\n-- | A 'Monad' for sequencing modifications to a 'Caps'.\nnewtype CapsM a =\n CapsM (ReaderT (Ptr Caps) IO a)\n deriving (Functor, Monad)\n\naskCapsPtr :: CapsM (Ptr Caps)\naskCapsPtr = CapsM $ ask\n\nmarshalCapsModify :: IO (Ptr Caps)\n -> CapsM a\n -> (Caps, a)\nmarshalCapsModify mkCaps (CapsM action) =\n unsafePerformIO $\n do ptr <- mkCaps\n result <- runReaderT action ptr\n caps <- takeCaps ptr\n return (caps, result)\n\n-- | Create a caps and mutate it according to the given action.\ncapsCreate :: CapsM a\n -> (Caps, a)\ncapsCreate action =\n marshalCapsModify\n {# call caps_new_empty #}\n action\n\n-- | Copy a caps and mutate it according to the given action.\ncapsModify :: Caps\n -> CapsM a\n -> (Caps, a)\ncapsModify caps action =\n marshalCapsModify ({# call caps_copy #} caps) action\n\n-- | Append the given structure to the current caps.\ncapsAppendStructure :: Structure\n -> CapsM ()\ncapsAppendStructure structure = do\n capsPtr <- askCapsPtr\n CapsM $ liftIO $ withStructure structure $ \\structurePtr ->\n do structurePtr' <- gst_structure_copy structurePtr\n gst_caps_append_structure capsPtr structurePtr\n where _ = {# call caps_append_structure #}\n _ = {# call structure_copy #}\n\n-- | Append the structure to the current caps, if it is not already\n-- expressed by the caps.\ncapsMergeStructure :: Structure\n -> CapsM ()\ncapsMergeStructure structure = do\n capsPtr <- askCapsPtr\n CapsM $ liftIO $ withStructure structure $ \\structurePtr ->\n do structurePtr' <- gst_structure_copy structurePtr\n gst_caps_merge_structure capsPtr structurePtr\n where _ = {# call caps_merge_structure #}\n _ = {# call structure_copy #}\n\n-- | Removes the structure at the given index from the current caps.\ncapsRemoveStructure :: Word\n -> CapsM ()\ncapsRemoveStructure idx = do\n capsPtr <- askCapsPtr\n CapsM $ liftIO $ gst_caps_remove_structure capsPtr $ fromIntegral idx\n where _ = {# call caps_remove_structure #}\n\n-- | Discard all but the first structure from the current caps.\ncapsTruncate :: CapsM ()\ncapsTruncate = do\n capsPtr <- askCapsPtr\n CapsM $ liftIO $ gst_caps_truncate capsPtr\n where _ = {# call caps_truncate #}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"d137f67cbd66f6f938b35cdd4817cb699a7476f9","subject":"Bindings for MPI_WTIME_IS_GLOBAL","message":"Bindings for MPI_WTIME_IS_GLOBAL\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Control\/Parallel\/MPI\/Internal.chs","new_file":"src\/Control\/Parallel\/MPI\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n#include \n#include \"init_wrapper.h\"\n#include \"comparison_result.h\"\n#include \"error_classes.h\"\n#include \"thread_support.h\"\n-----------------------------------------------------------------------------\n{- |\nModule : Control.Parallel.MPI.Internal\nCopyright : (c) 2010 Bernie Pope, Dmitry Astapov\nLicense : BSD-style\nMaintainer : florbitous@gmail.com\nStability : experimental\nPortability : ghc\n\nThis module contains low-level Haskell bindings to core MPI functions.\nAll Haskell functions correspond to MPI functions or values with the similar\nname (i.e. @commRank@ is the binding for @MPI_Comm_rank@ etc)\n\nNote that most of this module is re-exported by\n\"Control.Parallel.MPI\", so if you are not interested in writing\nlow-level code, you should probably import \"Control.Parallel.MPI\" and\neither \"Control.Parallel.MPI.Storable\" or \"Control.Parallel.MPI.Serializable\".\n-}\n-----------------------------------------------------------------------------\nmodule Control.Parallel.MPI.Internal\n (\n\n -- * MPI runtime management\n -- ** Initialization, finalization, termination.\n init, finalize, initialized, finalized, abort,\n -- ** Multi-threaded environment support\n ThreadSupport (..), initThread, queryThread, isThreadMain,\n -- ** Predefined constants\n maxProcessorName, maxErrorString,\n -- ** Runtime attributes.\n getProcessorName, Version (..), getVersion,\n\n -- * Requests and statuses.\n Request, Status (..), probe, test, cancel, wait, waitall,\n\n -- * Process management.\n -- ** Communicators.\n Comm, commWorld, commSelf, commSize, commRank, commTestInter,\n commRemoteSize, commCompare, commGroup, commGetAttr,\n\n -- ** Process groups.\n Group, groupEmpty, groupRank, groupSize, groupUnion,\n groupIntersection, groupDifference, groupCompare, groupExcl,\n groupIncl, groupTranslateRanks,\n -- ** Comparisons.\n ComparisonResult (..),\n\n -- * Error handling.\n Errhandler, errorsAreFatal, errorsReturn, commSetErrhandler, commGetErrhandler,\n ErrorClass (..), MPIError(..),\n\n -- Ranks.\n Rank, rankId, toRank, fromRank, anySource, theRoot, procNull,\n\n -- * Data types.\n Datatype, char, wchar, short, int, long, longLong, unsignedChar, unsignedShort, unsigned, unsignedLong, unsignedLongLong, float, double, longDouble, byte, packed, typeSize,\n\n -- * Point-to-point operations\n -- ** Tags.\n Tag, toTag, fromTag, anyTag, unitTag, tagUpperBound,\n -- ** Blocking operations\n BufferPtr, Count, -- XXX: what will break if we don't export those?\n send, bsend, ssend, rsend, recv,\n -- ** Non-blocking operations\n isend, ibsend, issend, irecv,\n isendPtr, ibsendPtr, issendPtr, irecvPtr,\n\n\n -- * Collective operations\n -- ** One-to-all\n bcast, scatter, scatterv,\n -- ** All-to-one\n gather, gatherv, reduce,\n -- ** All-to-all\n allgather, allgatherv,\n alltoall, alltoallv,\n allreduce, reduceScatter,\n barrier,\n\n -- ** Reduction operations.\n Operation, maxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp,\n opCreate, opFree,\n\n -- * Timing.\n wtime, wtick,\n\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Data.Maybe (fromMaybe)\nimport Control.Monad (liftM, unless)\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception\n\n{# context prefix = \"MPI\" #}\n\n-- | Pointer to memory buffer that either holds data to be sent or is\n-- used to receive some data. You would\n-- probably have to use 'castPtr' to pass some actual pointers to\n-- API functions.\ntype BufferPtr = Ptr ()\n\n-- | Count of elements in the send\/receive buffer\ntype Count = CInt\n\n{-\nThis module provides Haskell enum that comprises of MPI constants\n@MPI_IDENT@, @MPI_CONGRUENT@, @MPI_SIMILAR@ and @MPI_UNEQUAL@.\n\nThose are used to compare communicators (f.e. 'commCompare') and\nprocess groups (f.e. 'groupCompare').\n-}\n{# enum ComparisonResult {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- | Which Haskell type will be used as @Comm@ depends on the MPI\n-- implementation that was selected during compilation. It could be\n-- @CInt@, @Ptr ()@, @Ptr CInt@ or something else.\ntype MPIComm = {# type MPI_Comm #}\nnewtype Comm = MkComm { fromComm :: MPIComm }\nforeign import ccall \"&mpi_comm_world\" commWorld_ :: Ptr MPIComm\nforeign import ccall \"&mpi_comm_self\" commSelf_ :: Ptr MPIComm\n\n-- | Predefined handle for communicator that includes all running\n-- processes. Similar to @MPI_Comm_world@\ncommWorld :: Comm\ncommWorld = MkComm <$> unsafePerformIO $ peek commWorld_\n\n-- | Predefined handle for communicator that includes only current\n-- process. Similar to @MPI_Comm_self@\ncommSelf :: Comm\ncommSelf = MkComm <$> unsafePerformIO $ peek commSelf_\n\nforeign import ccall \"&mpi_max_processor_name\" max_processor_name_ :: Ptr CInt\nforeign import ccall \"&mpi_max_error_string\" max_error_string_ :: Ptr CInt\nmaxProcessorName :: CInt\nmaxProcessorName = unsafePerformIO $ peek max_processor_name_\nmaxErrorString :: CInt\nmaxErrorString = unsafePerformIO $ peek max_error_string_\n\n-- | Initialize the MPI environment. The MPI environment must be intialized by each\n-- MPI process before any other MPI function is called. Note that\n-- the environment may also be initialized by the functions 'initThread', 'mpi',\n-- and 'mpiWorld'. It is an error to attempt to initialize the environment more\n-- than once for a given MPI program execution. The only MPI functions that may\n-- be called before the MPI environment is initialized are 'getVersion',\n-- 'initialized' and 'finalized'. This function corresponds to @MPI_Init@.\n{# fun unsafe init_wrapper as init {} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been initialized. Returns @True@ if the\n-- environment has been initialized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Initialized@.\n{# fun unsafe Initialized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been finalized. Returns @True@ if the\n-- environment has been finalized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Finalized@.\n{# fun unsafe Finalized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Initialize the MPI environment with a \/required\/ level of thread support.\n-- See the documentation for 'init' for more information about MPI initialization.\n-- The \/provided\/ level of thread support is returned in the result.\n-- There is no guarantee that provided will be greater than or equal to required.\n-- The level of provided thread support depends on the underlying MPI implementation,\n-- and may also depend on information provided when the program is executed\n-- (for example, by supplying appropriate arguments to @mpiexec@).\n-- If the required level of support cannot be provided then it will try to\n-- return the least supported level greater than what was required.\n-- If that cannot be satisfied then it will return the highest supported level\n-- provided by the MPI implementation. See the documentation for 'ThreadSupport'\n-- for information about what levels are available and their relative ordering.\n-- This function corresponds to @MPI_Init_thread@.\n{# fun unsafe init_wrapper_thread as initThread\n {cFromEnum `ThreadSupport', alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\n{# fun unsafe Query_thread as ^ {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n{# fun unsafe Is_thread_main as ^\n {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Terminate the MPI execution environment.\n-- Once 'finalize' is called no other MPI functions may be called except\n-- 'getVersion', 'initialized' and 'finalized'. Each process must complete\n-- any pending communication that it initiated before calling 'finalize'.\n-- If 'finalize' returns then regular (non-MPI) computations may continue,\n-- but no further MPI computation is possible. Note: the error code returned\n-- by 'finalize' is not checked. This function corresponds to @MPI_Finalize@.\n{# fun unsafe Finalize as ^ {} -> `()' discard*- #}\ndiscard _ = return ()\n-- XXX can't call checkError on finalize, because\n-- checkError calls Internal.errorClass and Internal.errorString.\n-- These cannot be called after finalize (at least on OpenMPI).\n\ngetProcessorName :: IO String\ngetProcessorName = do\n allocaBytes (fromIntegral maxProcessorName) $ \\ptr -> do\n len <- getProcessorName' ptr\n peekCStringLen (ptr, cIntConv len)\n where\n getProcessorName' = {# fun unsafe Get_processor_name as getProcessorName_\n {id `Ptr CChar', alloca- `CInt' peekIntConv*} -> `()' checkError*- #}\n\ndata Version =\n Version { version :: Int, subversion :: Int }\n deriving (Eq, Ord)\n\ninstance Show Version where\n show v = show (version v) ++ \".\" ++ show (subversion v)\n\ngetVersion :: IO Version\ngetVersion = do\n (version, subversion) <- getVersion'\n return $ Version version subversion\n where\n getVersion' = {# fun unsafe Get_version as getVersion_\n {alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Return the number of processes involved in a communicator. For 'commWorld'\n-- it returns the total number of processes available. If the communicator is\n-- and intra-communicator it returns the number of processes in the local group.\n-- This function corresponds to @MPI_Comm_size@.\n{# fun unsafe Comm_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n{# fun unsafe Comm_remote_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n{# fun unsafe Comm_test_inter as ^\n {fromComm `Comm', alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\ncommGetAttr :: Storable e => Comm -> Int -> IO (Maybe e)\ncommGetAttr comm key = do\n isInitialized <- initialized\n if isInitialized then do\n alloca $ \\ptr -> do\n found <- commGetAttr' comm key (castPtr ptr)\n if found then do ptr2 <- peek ptr\n Just <$> peek ptr2\n else return Nothing\n else return Nothing\n where\n commGetAttr' = {# fun unsafe Comm_get_attr as commGetAttr_\n {fromComm `Comm', cIntConv `Int', id `Ptr ()', alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\nforeign import ccall unsafe \"&mpi_tag_ub\" tagUB_ :: Ptr Int\n\n-- | Maximum tag value supported by the current MPI implementation. Corresponds to the value of standard MPI\n-- attribute @MPI_TAG_UB@.\n--\n-- When called before 'init' or 'initThread' would return 0.\ntagUpperBound :: Int\ntagUpperBound =\n let key = unsafePerformIO (peek tagUB_)\n in fromMaybe 0 $ unsafePerformIO (commGetAttr commWorld key)\n\nforeign import ccall unsafe \"&mpi_tag_ub\" tagUB_ :: Ptr Int\n\n{- | True if clocks at all processes in\n'commWorld' are synchronized, False otherwise. The expectation is that\nthe variation in time, as measured by calls to 'wtime', will be less then one half the\nround-trip time for an MPI message of length zero. \n\nCommunicators other than 'commWorld' could have different clocks.\nYou could find it out by querying attribute 'wtimeIsGlobalKey' with 'commGetAttr'.\n\nWhen wtimeIsGlobal is called before 'init' or 'initThread' it would return False.\n-}\nwtimeIsGlobal :: Bool\nwtimeIsGlobal =\n fromMaybe False $ unsafePerformIO (commGetAttr commWorld wtimeIsGlobalKey)\n\nforeign import ccall unsafe \"&mpi_wtime_is_global\" wtimeIsGlobal_ :: Ptr Int\n\n-- | Numeric key for standard MPI communicator attribute @MPI_WTIME_IS_GLOBAL@.\n-- To be used with 'commGetAttr'.\nwtimeIsGlobalKey :: Int\nwtimeIsGlobalKey = unsafePerformIO (peek wtimeIsGlobal_)\n\n-- | Return the rank of the calling process for the given\n-- communicator. If it is an intercommunicator, returns rank of the\n-- process in the local group.\n{# fun unsafe Comm_rank as ^\n {fromComm `Comm', alloca- `Rank' peekIntConv* } -> `()' checkError*- #}\n\n{- | Compares two communicators.\n\n* If they are handles for the same MPI communicator object, result is 'Identical';\n\n* If both communicators are identical in constituents and rank\n order, result is `Congruent';\n\n* If they have the same members, nbut with different ranks, then\n result is 'Similar';\n\n* Otherwise, result is 'Unequal'.\n\n-}\n{# fun unsafe Comm_compare as ^\n {fromComm `Comm', fromComm `Comm', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- | Test for an incomming message, without actually receiving it.\n-- If a message has been sent from @Rank@ to the current process with @Tag@ on the\n-- communicator @Comm@ then 'probe' will return the 'Status' of the message. Otherwise\n-- it will block the current process until such a matching message is sent.\n-- This allows the current process to check for an incoming message and decide\n-- how to receive it, based on the information in the 'Status'.\n-- This function corresponds to @MPI_Probe@.\n{# fun Probe as ^\n {fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n{- probe :: Rank -- ^ Rank of the sender.\n -> Tag -- ^ Tag of the sent message.\n -> Comm -- ^ Communicator.\n -> IO Status -- ^ Information about the incoming message (but not the content of the message). -}\n\n{# fun unsafe Send as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Bsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Ssend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Rsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Recv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast* } -> `()' checkError*- #}\n{# fun unsafe Isend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n{# fun unsafe Ibsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n{# fun unsafe Issend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n{# fun Irecv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n\n-- | Like 'isend', but stores Request at the supplied pointer. Useful\n-- for making arrays of Requests that could be passed to 'waitall'\n{# fun unsafe Isend as isendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'ibsend', but stores Request at the supplied pointer. Useful\n-- for making arrays of Requests that could be passed to 'waitall'\n{# fun unsafe Ibsend as ibsendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'issend', but stores Request at the supplied pointer. Useful\n-- for making arrays of Requests that could be passed to 'waitall'\n{# fun unsafe Issend as issendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'irecv', but stores Request at the supplied pointer. Useful\n-- for making arrays of Requests that could be passed to 'waitall'\n{# fun Irecv as irecvPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n{# fun unsafe Bcast as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocks until all processes on the communicator call this function.\n-- This function corresponds to @MPI_Barrier@.\n{# fun unsafe Barrier as ^ {fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocking test for the completion of a send of receive.\n-- See 'test' for a non-blocking variant.\n-- This function corresponds to @MPI_Wait@.\n{# fun unsafe Wait as ^\n {withRequest* `Request', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Takes pointer to the array of Requests of given size, 'wait's on all of them,\n-- populates array of Statuses of the same size. This function corresponds to @MPI_Waitall@\n{# fun unsafe Waitall as ^\n { id `Count', castPtr `Ptr Request', castPtr `Ptr Status'} -> `()' checkError*- #}\n-- TODO: Make this Storable Array instead of Ptr ?\n\n-- | Non-blocking test for the completion of a send or receive.\n-- Returns @Nothing@ if the request is not complete, otherwise\n-- it returns @Just status@. See 'wait' for a blocking variant.\n-- This function corresponds to @MPI_Test@.\ntest :: Request -> IO (Maybe Status)\ntest request = do\n (flag, status) <- test' request\n if flag\n then return $ Just status\n else return Nothing\n where\n test' = {# fun unsafe Test as test_\n {withRequest* `Request', alloca- `Bool' peekBool*, allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Cancel a pending communication request.\n-- This function corresponds to @MPI_Cancel@.\n{# fun unsafe Cancel as ^\n {withRequest* `Request'} -> `()' checkError*- #}\nwithRequest req f = do alloca $ \\ptr -> do poke ptr req\n f (castPtr ptr)\n{# fun unsafe Scatter as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n{# fun unsafe Gather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- We pass counts\/displs as Ptr CInt so that caller could supply nullPtr here\n-- which would be impossible if we marshal arrays ourselves here.\n{# fun unsafe Scatterv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Gatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Allgather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Allgatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Alltoall as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Alltoallv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\n{# fun Reduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n{# fun Allreduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n{# fun Reduce_scatter as ^\n { id `BufferPtr', id `BufferPtr', id `Ptr CInt', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Op_create as ^\n {castFunPtr `FunPtr (Ptr t -> Ptr t -> Ptr CInt -> Ptr Datatype -> IO ())', cFromEnum `Bool', alloca- `Operation' peekOperation*} -> `()' checkError*- #}\n{# fun Op_free as ^ {withOperation* `Operation'} -> `()' checkError*- #}\n{# fun unsafe Wtime as ^ {} -> `Double' realToFrac #}\n{# fun unsafe Wtick as ^ {} -> `Double' realToFrac #}\n\n-- | Return the process group from a communicator.\n{# fun unsafe Comm_group as ^\n {fromComm `Comm', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupRank = unsafePerformIO <$> groupRank'\n where groupRank' = {# fun unsafe Group_rank as groupRank_\n {fromGroup `Group', alloca- `Rank' peekIntConv*} -> `()' checkError*- #}\n\ngroupSize = unsafePerformIO <$> groupSize'\n where groupSize' = {# fun unsafe Group_size as groupSize_\n {fromGroup `Group', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\ngroupUnion g1 g2 = unsafePerformIO $ groupUnion' g1 g2\n where groupUnion' = {# fun unsafe Group_union as groupUnion_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupIntersection g1 g2 = unsafePerformIO $ groupIntersection' g1 g2\n where groupIntersection' = {# fun unsafe Group_intersection as groupIntersection_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupDifference g1 g2 = unsafePerformIO $ groupDifference' g1 g2\n where groupDifference' = {# fun unsafe Group_difference as groupDifference_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupCompare g1 g2 = unsafePerformIO $ groupCompare' g1 g2\n where\n groupCompare' = {# fun unsafe Group_compare as groupCompare_\n {fromGroup `Group', fromGroup `Group', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- Technically it might make better sense to make the second argument a Set rather than a list\n-- but the order is significant in the groupIncl function (the other function, not this one).\n-- For the sake of keeping their types in sync, a list is used instead.\n{# fun unsafe Group_excl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n{# fun unsafe Group_incl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupTranslateRanks :: Group -> [Rank] -> Group -> [Rank]\ngroupTranslateRanks group1 ranks group2 =\n unsafePerformIO $ do\n let (rankIntList :: [Int]) = map fromEnum ranks\n withArrayLen rankIntList $ \\size ranksPtr ->\n allocaArray size $ \\resultPtr -> do\n groupTranslateRanks' group1 (cFromEnum size) (castPtr ranksPtr) group2 resultPtr\n map toRank <$> peekArray size resultPtr\n where\n groupTranslateRanks' = {# fun unsafe Group_translate_ranks as groupTranslateRanks_\n {fromGroup `Group', id `CInt', id `Ptr CInt', fromGroup `Group', id `Ptr CInt'} -> `()' checkError*- #}\n\nwithRanksAsInts ranks f = withArrayLen (map fromEnum ranks) $ \\size ptr -> f (cIntConv size, castPtr ptr)\n\n-- | Return the number of bytes used to store an MPI 'Datatype'.\ntypeSize = unsafePerformIO . typeSize'\n where\n typeSize' =\n {# fun unsafe Type_size as typeSize_\n {fromDatatype `Datatype', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n{# fun unsafe Error_class as ^\n { id `CInt', alloca- `CInt' peek*} -> `CInt' id #}\n\n-- | Set the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_set_errhandler@.\n{# fun unsafe Comm_set_errhandler as ^\n {fromComm `Comm', fromErrhandler `Errhandler'} -> `()' checkError*- #}\n\n-- | Get the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_get_errhandler@.\n{# fun unsafe Comm_get_errhandler as ^\n {fromComm `Comm', alloca- `Errhandler' peekErrhandler*} -> `()' checkError*- #}\n\n-- | Tries to terminate all MPI processes in its communicator argument.\n-- The second argument is an error code which \/may\/ be used as the return status\n-- of the MPI process, but this is not guaranteed. On systems where 'Int' has a larger\n-- range than 'CInt', the error code will be clipped to fit into the range of 'CInt'.\n-- This function corresponds to @MPI_Abort@.\nabort :: Comm -> Int -> IO ()\nabort comm code =\n abort' comm (toErrorCode code)\n where\n toErrorCode :: Int -> CInt\n toErrorCode i\n -- Assumes Int always has range at least as big as CInt.\n | i < (fromIntegral (minBound :: CInt)) = minBound\n | i > (fromIntegral (maxBound :: CInt)) = maxBound\n | otherwise = cIntConv i\n\n abort' = {# fun unsafe Abort as abort_ {fromComm `Comm', id `CInt'} -> `()' checkError*- #}\n\n\ntype MPIDatatype = {# type MPI_Datatype #}\n\nnewtype Datatype = MkDatatype { fromDatatype :: MPIDatatype }\n\nforeign import ccall unsafe \"&mpi_char\" char_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_wchar\" wchar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_short\" short_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_int\" int_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long\" long_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_long\" longLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_char\" unsignedChar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_short\" unsignedShort_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned\" unsigned_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long\" unsignedLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long_long\" unsignedLongLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_float\" float_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_double\" double_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_double\" longDouble_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_byte\" byte_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_packed\" packed_ :: Ptr MPIDatatype\n\nchar, wchar, short, int, long, longLong, unsignedChar, unsignedShort :: Datatype\nunsigned, unsignedLong, unsignedLongLong, float, double, longDouble :: Datatype\nbyte, packed :: Datatype\n\nchar = MkDatatype <$> unsafePerformIO $ peek char_\nwchar = MkDatatype <$> unsafePerformIO $ peek wchar_\nshort = MkDatatype <$> unsafePerformIO $ peek short_\nint = MkDatatype <$> unsafePerformIO $ peek int_\nlong = MkDatatype <$> unsafePerformIO $ peek long_\nlongLong = MkDatatype <$> unsafePerformIO $ peek longLong_\nunsignedChar = MkDatatype <$> unsafePerformIO $ peek unsignedChar_\nunsignedShort = MkDatatype <$> unsafePerformIO $ peek unsignedShort_\nunsigned = MkDatatype <$> unsafePerformIO $ peek unsigned_\nunsignedLong = MkDatatype <$> unsafePerformIO $ peek unsignedLong_\nunsignedLongLong = MkDatatype <$> unsafePerformIO $ peek unsignedLongLong_\nfloat = MkDatatype <$> unsafePerformIO $ peek float_\ndouble = MkDatatype <$> unsafePerformIO $ peek double_\nlongDouble = MkDatatype <$> unsafePerformIO $ peek longDouble_\nbyte = MkDatatype <$> unsafePerformIO $ peek byte_\npacked = MkDatatype <$> unsafePerformIO $ peek packed_\n\n\ntype MPIErrhandler = {# type MPI_Errhandler #}\nnewtype Errhandler = MkErrhandler { fromErrhandler :: MPIErrhandler } deriving Storable\npeekErrhandler ptr = MkErrhandler <$> peek ptr\n\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr MPIErrhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr MPIErrhandler\nerrorsAreFatal, errorsReturn :: Errhandler\nerrorsAreFatal = MkErrhandler <$> unsafePerformIO $ peek errorsAreFatal_\nerrorsReturn = MkErrhandler <$> unsafePerformIO $ peek errorsReturn_\n\n{# enum ErrorClass {underscoreToCase} deriving (Eq,Ord,Show,Typeable) #}\n\n-- XXX Should this be a ForeinPtr?\n-- there is a MPI_Group_free function, which we should probably\n-- call when the group is no longer referenced.\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIGroup = {# type MPI_Group #}\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\npeekGroup ptr = MkGroup <$> peek ptr\n\nforeign import ccall \"&mpi_group_empty\" groupEmpty_ :: Ptr MPIGroup\n-- | Predefined handle for group without any members. Corresponds to @MPI_GROUP_EMPTY@\ngroupEmpty :: Group\ngroupEmpty = MkGroup <$> unsafePerformIO $ peek groupEmpty_\n\n\n{-\nThis module provides Haskell type that represents values of @MPI_Op@\ntype (reduction operations), and predefined reduction operations\ndefined in the MPI Report.\n-}\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIOperation = {# type MPI_Op #}\nnewtype Operation = MkOperation { fromOperation :: MPIOperation } deriving Storable\npeekOperation ptr = MkOperation <$> peek ptr\nwithOperation op f = alloca $ \\ptr -> do poke ptr (fromOperation op)\n f (castPtr ptr)\n\nforeign import ccall unsafe \"&mpi_max\" maxOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_min\" minOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_sum\" sumOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_prod\" prodOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_land\" landOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_band\" bandOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lor\" lorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bor\" borOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lxor\" lxorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bxor\" bxorOp_ :: Ptr MPIOperation\n-- foreign import ccall \"mpi_maxloc\" maxlocOp :: MPIOperation\n-- foreign import ccall \"mpi_minloc\" minlocOp :: MPIOperation\n-- foreign import ccall \"mpi_replace\" replaceOp :: MPIOperation\n-- TODO: support for those requires better support for pair datatypes\n\nmaxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp :: Operation\nmaxOp = MkOperation <$> unsafePerformIO $ peek maxOp_\nminOp = MkOperation <$> unsafePerformIO $ peek minOp_\nsumOp = MkOperation <$> unsafePerformIO $ peek sumOp_\nprodOp = MkOperation <$> unsafePerformIO $ peek prodOp_\nlandOp = MkOperation <$> unsafePerformIO $ peek landOp_\nbandOp = MkOperation <$> unsafePerformIO $ peek bandOp_\nlorOp = MkOperation <$> unsafePerformIO $ peek lorOp_\nborOp = MkOperation <$> unsafePerformIO $ peek borOp_\nlxorOp = MkOperation <$> unsafePerformIO $ peek lxorOp_\nbxorOp = MkOperation <$> unsafePerformIO $ peek bxorOp_\n\n\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI rank designations.\n-}\n\nnewtype Rank = MkRank { rankId :: Int }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Rank where\n (MkRank x) + (MkRank y) = MkRank (x+y)\n (MkRank x) * (MkRank y) = MkRank (x*y)\n abs (MkRank x) = MkRank (abs x)\n signum (MkRank x) = MkRank (signum x)\n fromInteger x\n | x > ( fromIntegral (maxBound :: CInt)) = error \"Rank value does not fit into 32 bits\"\n | x < 0 = error \"Negative Rank value\"\n | otherwise = MkRank (fromIntegral x)\n\nforeign import ccall \"mpi_any_source\" anySource_ :: Ptr Int\nforeign import ccall \"mpi_root\" theRoot_ :: Ptr Int\nforeign import ccall \"mpi_proc_null\" procNull_ :: Ptr Int\n\n-- | Predefined rank number that allows reception of point-to-point messages\n-- regardless of their source. Corresponds to @MPI_ANY_SOURCE@\nanySource :: Rank\nanySource = toRank $ unsafePerformIO $ peek anySource_\n\n-- | Predefined rank number that specifies root process during\n-- operations involving intercommunicators. Corresponds to @MPI_ROOT@\ntheRoot :: Rank\ntheRoot = toRank $ unsafePerformIO $ peek theRoot_\n\n-- | Predefined rank number that specifies non-root processes during\n-- operations involving intercommunicators. Corresponds to @MPI_PROC_NULL@\nprocNull :: Rank\nprocNull = toRank $ unsafePerformIO $ peek procNull_\n\ninstance Show Rank where\n show = show . rankId\n\ntoRank :: Enum a => a -> Rank\ntoRank x = MkRank { rankId = fromEnum x }\n\nfromRank :: Enum a => Rank -> a\nfromRank = toEnum . rankId\n\n{- This module provides Haskell representation of the @MPI_Request@ type. -}\ntype MPIRequest = {# type MPI_Request #}\nnewtype Request = MkRequest MPIRequest deriving Storable\npeekRequest ptr = MkRequest <$> peek ptr\n\n{-\nThis module provides Haskell representation of the @MPI_Status@ type\n(request status).\n\nField `status_error' should be used with care:\n\\\"The error field in status is not needed for calls that return only\none status, such as @MPI_WAIT@, since that would only duplicate the\ninformation returned by the function itself. The current design avoids\nthe additional overhead of setting it, in such cases. The field is\nneeded for calls that return multiple statuses, since each request may\nhave had a different failure.\\\"\n(this is a quote from )\n\nThis means that, for example, during the call to @MPI_Wait@\nimplementation is free to leave this field filled with whatever\ngarbage got there during memory allocation. Haskell FFI is not\nblanking out freshly allocated memory, so beware!\n-}\n\n-- | Haskell structure that holds fields of @MPI_Status@.\n--\n-- Please note that MPI report lists only three fields as mandatory:\n-- @status_source@, @status_tag@ and @status_error@. However, all\n-- MPI implementations that were used to test those bindings supported\n-- extended set of fields represented here.\ndata Status =\n Status\n { status_source :: CInt -- ^ rank of the source process\n , status_tag :: CInt -- ^ tag assigned at source\n , status_error :: CInt -- ^ error code, if any\n , status_count :: CInt -- ^ number of received elements, if applicable\n , status_cancelled :: CInt -- ^ whether the request was cancelled\n }\n deriving (Eq, Ord, Show)\n\ninstance Storable Status where\n sizeOf _ = {#sizeof MPI_Status #}\n alignment _ = 4\n peek p = Status\n <$> liftM cIntConv ({#get MPI_Status->MPI_SOURCE #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_TAG #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_ERROR #} p)\n#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields-\n <*> liftM cIntConv ({#get MPI_Status->count #} p)\n <*> liftM cIntConv ({#get MPI_Status->cancelled #} p)\n#else\n <*> liftM cIntConv ({#get MPI_Status->_count #} p)\n <*> liftM cIntConv ({#get MPI_Status->_cancelled #} p)\n#endif\n poke p x = do\n {#set MPI_Status.MPI_SOURCE #} p (cIntConv $ status_source x)\n {#set MPI_Status.MPI_TAG #} p (cIntConv $ status_tag x)\n {#set MPI_Status.MPI_ERROR #} p (cIntConv $ status_error x)\n#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields AND different order of fields\n {#set MPI_Status.count #} p (cIntConv $ status_count x)\n {#set MPI_Status.cancelled #} p (cIntConv $ status_cancelled x)\n#else\n {#set MPI_Status._count #} p (cIntConv $ status_count x)\n {#set MPI_Status._cancelled #} p (cIntConv $ status_cancelled x)\n#endif\n\n-- NOTE: Int here is picked arbitrary\nallocaCast f =\n alloca $ \\(ptr :: Ptr Int) -> f (castPtr ptr :: Ptr ())\npeekCast = peek . castPtr\n\n\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI tags.\n-}\n\nnewtype Tag = MkTag { tagVal :: Int }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Tag where\n (MkTag x) + (MkTag y) = MkTag (x+y)\n (MkTag x) * (MkTag y) = MkTag (x*y)\n abs (MkTag x) = MkTag (abs x)\n signum (MkTag x) = MkTag (signum x)\n fromInteger x\n | fromIntegral x > tagUpperBound = error \"Tag value is over the MPI_TAG_UB\"\n | x < 0 = error \"Negative Tag value\"\n | otherwise = MkTag (fromIntegral x)\n\ninstance Show Tag where\n show = show . tagVal\n\ntoTag :: Enum a => a -> Tag\ntoTag x = MkTag { tagVal = fromEnum x }\n\nfromTag :: Enum a => Tag -> a\nfromTag = toEnum . tagVal\n\nforeign import ccall unsafe \"&mpi_any_tag\" anyTag_ :: Ptr Int\n\n-- | Predefined tag value that allows reception of the messages with\n-- arbitrary tag values. Corresponds to @MPI_ANY_TAG@.\nanyTag :: Tag\nanyTag = toTag $ unsafePerformIO $ peek anyTag_\n\n-- | A tag with unit value. Intended to be used as a convenient default.\nunitTag :: Tag\nunitTag = toTag ()\n\n\n{-\nThis module provides Haskell datatypes that comprises of values of\npredefined MPI constants @MPI_THREAD_SINGLE@, @MPI_THREAD_FUNNELED@,\n@MPI_THREAD_SERIALIZED@, @MPI_THREAD_MULTIPLE@.\n-}\n\n{# enum ThreadSupport {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- | Value thrown as exception when MPI runtime is instructed to pass\n-- errors to user code (via 'commSetErrhandler' and 'errorsReturn').\n-- Since raw MPI errors codes are not standartized and not portable,\n-- they are not exposed.\ndata MPIError\n = MPIError\n { mpiErrorClass :: ErrorClass -- ^ Broad class of errors this one belongs to\n , mpiErrorString :: String -- ^ Human-readable error description\n }\n deriving (Eq, Show, Typeable)\n\ninstance Exception MPIError\n\ncheckError :: CInt -> IO ()\ncheckError code = do\n -- We ignore the error code from the call to Internal.errorClass\n -- because we call errorClass from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n (_, errClassRaw) <- errorClass code\n let errClass = cToEnum errClassRaw\n unless (errClass == Success) $ do\n errStr <- errorString code\n throwIO $ MPIError errClass errStr\n\n-- | Convert MPI error code human-readable error description. Corresponds to @MPI_Error_string@.\nerrorString :: CInt -> IO String\nerrorString code =\n allocaBytes (fromIntegral maxErrorString) $ \\ptr ->\n alloca $ \\lenPtr -> do\n -- We ignore the error code from the call to Internal.errorString\n -- because we call errorString from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n _ <- errorString' code ptr lenPtr\n len <- peek lenPtr\n peekCStringLen (ptr, cIntConv len)\n where\n errorString' = {# call unsafe Error_string as errorString_ #}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n#include \n#include \"init_wrapper.h\"\n#include \"comparison_result.h\"\n#include \"error_classes.h\"\n#include \"thread_support.h\"\n-----------------------------------------------------------------------------\n{- |\nModule : Control.Parallel.MPI.Internal\nCopyright : (c) 2010 Bernie Pope, Dmitry Astapov\nLicense : BSD-style\nMaintainer : florbitous@gmail.com\nStability : experimental\nPortability : ghc\n\nThis module contains low-level Haskell bindings to core MPI functions.\nAll Haskell functions correspond to MPI functions or values with the similar\nname (i.e. @commRank@ is the binding for @MPI_Comm_rank@ etc)\n\nNote that most of this module is re-exported by\n\"Control.Parallel.MPI\", so if you are not interested in writing\nlow-level code, you should probably import \"Control.Parallel.MPI\" and\neither \"Control.Parallel.MPI.Storable\" or \"Control.Parallel.MPI.Serializable\".\n-}\n-----------------------------------------------------------------------------\nmodule Control.Parallel.MPI.Internal\n (\n\n -- * MPI runtime management\n -- ** Initialization, finalization, termination.\n init, finalize, initialized, finalized, abort,\n -- ** Multi-threaded environment support\n ThreadSupport (..), initThread, queryThread, isThreadMain,\n -- ** Predefined constants\n maxProcessorName, maxErrorString,\n -- ** Runtime attributes.\n getProcessorName, Version (..), getVersion,\n\n -- * Requests and statuses.\n Request, Status (..), probe, test, cancel, wait, waitall,\n\n -- * Process management.\n -- ** Communicators.\n Comm, commWorld, commSelf, commSize, commRank, commTestInter,\n commRemoteSize, commCompare, commGroup, commGetAttr,\n\n -- ** Process groups.\n Group, groupEmpty, groupRank, groupSize, groupUnion,\n groupIntersection, groupDifference, groupCompare, groupExcl,\n groupIncl, groupTranslateRanks,\n -- ** Comparisons.\n ComparisonResult (..),\n\n -- * Error handling.\n Errhandler, errorsAreFatal, errorsReturn, commSetErrhandler, commGetErrhandler,\n ErrorClass (..), MPIError(..),\n\n -- Ranks.\n Rank, rankId, toRank, fromRank, anySource, theRoot, procNull,\n\n -- * Data types.\n Datatype, char, wchar, short, int, long, longLong, unsignedChar, unsignedShort, unsigned, unsignedLong, unsignedLongLong, float, double, longDouble, byte, packed, typeSize,\n\n -- * Point-to-point operations\n -- ** Tags.\n Tag, toTag, fromTag, anyTag, unitTag, tagUpperBound,\n -- ** Blocking operations\n BufferPtr, Count, -- XXX: what will break if we don't export those?\n send, bsend, ssend, rsend, recv,\n -- ** Non-blocking operations\n isend, ibsend, issend, irecv,\n isendPtr, ibsendPtr, issendPtr, irecvPtr,\n\n\n -- * Collective operations\n -- ** One-to-all\n bcast, scatter, scatterv,\n -- ** All-to-one\n gather, gatherv, reduce,\n -- ** All-to-all\n allgather, allgatherv,\n alltoall, alltoallv,\n allreduce, reduceScatter,\n barrier,\n\n -- ** Reduction operations.\n Operation, maxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp,\n opCreate, opFree,\n\n -- * Timing.\n wtime, wtick,\n\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Data.Maybe (fromMaybe)\nimport Control.Monad (liftM, unless)\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception\n\n{# context prefix = \"MPI\" #}\n\n-- | Pointer to memory buffer that either holds data to be sent or is\n-- used to receive some data. You would\n-- probably have to use 'castPtr' to pass some actual pointers to\n-- API functions.\ntype BufferPtr = Ptr ()\n\n-- | Count of elements in the send\/receive buffer\ntype Count = CInt\n\n{-\nThis module provides Haskell enum that comprises of MPI constants\n@MPI_IDENT@, @MPI_CONGRUENT@, @MPI_SIMILAR@ and @MPI_UNEQUAL@.\n\nThose are used to compare communicators (f.e. 'commCompare') and\nprocess groups (f.e. 'groupCompare').\n-}\n{# enum ComparisonResult {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- | Which Haskell type will be used as @Comm@ depends on the MPI\n-- implementation that was selected during compilation. It could be\n-- @CInt@, @Ptr ()@, @Ptr CInt@ or something else.\ntype MPIComm = {# type MPI_Comm #}\nnewtype Comm = MkComm { fromComm :: MPIComm }\nforeign import ccall \"&mpi_comm_world\" commWorld_ :: Ptr MPIComm\nforeign import ccall \"&mpi_comm_self\" commSelf_ :: Ptr MPIComm\n\n-- | Predefined handle for communicator that includes all running\n-- processes. Similar to @MPI_Comm_world@\ncommWorld :: Comm\ncommWorld = MkComm <$> unsafePerformIO $ peek commWorld_\n\n-- | Predefined handle for communicator that includes only current\n-- process. Similar to @MPI_Comm_self@\ncommSelf :: Comm\ncommSelf = MkComm <$> unsafePerformIO $ peek commSelf_\n\nforeign import ccall \"&mpi_max_processor_name\" max_processor_name_ :: Ptr CInt\nforeign import ccall \"&mpi_max_error_string\" max_error_string_ :: Ptr CInt\nmaxProcessorName :: CInt\nmaxProcessorName = unsafePerformIO $ peek max_processor_name_\nmaxErrorString :: CInt\nmaxErrorString = unsafePerformIO $ peek max_error_string_\n\n-- | Initialize the MPI environment. The MPI environment must be intialized by each\n-- MPI process before any other MPI function is called. Note that\n-- the environment may also be initialized by the functions 'initThread', 'mpi',\n-- and 'mpiWorld'. It is an error to attempt to initialize the environment more\n-- than once for a given MPI program execution. The only MPI functions that may\n-- be called before the MPI environment is initialized are 'getVersion',\n-- 'initialized' and 'finalized'. This function corresponds to @MPI_Init@.\n{# fun unsafe init_wrapper as init {} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been initialized. Returns @True@ if the\n-- environment has been initialized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Initialized@.\n{# fun unsafe Initialized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been finalized. Returns @True@ if the\n-- environment has been finalized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Finalized@.\n{# fun unsafe Finalized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Initialize the MPI environment with a \/required\/ level of thread support.\n-- See the documentation for 'init' for more information about MPI initialization.\n-- The \/provided\/ level of thread support is returned in the result.\n-- There is no guarantee that provided will be greater than or equal to required.\n-- The level of provided thread support depends on the underlying MPI implementation,\n-- and may also depend on information provided when the program is executed\n-- (for example, by supplying appropriate arguments to @mpiexec@).\n-- If the required level of support cannot be provided then it will try to\n-- return the least supported level greater than what was required.\n-- If that cannot be satisfied then it will return the highest supported level\n-- provided by the MPI implementation. See the documentation for 'ThreadSupport'\n-- for information about what levels are available and their relative ordering.\n-- This function corresponds to @MPI_Init_thread@.\n{# fun unsafe init_wrapper_thread as initThread\n {cFromEnum `ThreadSupport', alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\n{# fun unsafe Query_thread as ^ {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n{# fun unsafe Is_thread_main as ^\n {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Terminate the MPI execution environment.\n-- Once 'finalize' is called no other MPI functions may be called except\n-- 'getVersion', 'initialized' and 'finalized'. Each process must complete\n-- any pending communication that it initiated before calling 'finalize'.\n-- If 'finalize' returns then regular (non-MPI) computations may continue,\n-- but no further MPI computation is possible. Note: the error code returned\n-- by 'finalize' is not checked. This function corresponds to @MPI_Finalize@.\n{# fun unsafe Finalize as ^ {} -> `()' discard*- #}\ndiscard _ = return ()\n-- XXX can't call checkError on finalize, because\n-- checkError calls Internal.errorClass and Internal.errorString.\n-- These cannot be called after finalize (at least on OpenMPI).\n\ngetProcessorName :: IO String\ngetProcessorName = do\n allocaBytes (fromIntegral maxProcessorName) $ \\ptr -> do\n len <- getProcessorName' ptr\n peekCStringLen (ptr, cIntConv len)\n where\n getProcessorName' = {# fun unsafe Get_processor_name as getProcessorName_\n {id `Ptr CChar', alloca- `CInt' peekIntConv*} -> `()' checkError*- #}\n\ndata Version =\n Version { version :: Int, subversion :: Int }\n deriving (Eq, Ord)\n\ninstance Show Version where\n show v = show (version v) ++ \".\" ++ show (subversion v)\n\ngetVersion :: IO Version\ngetVersion = do\n (version, subversion) <- getVersion'\n return $ Version version subversion\n where\n getVersion' = {# fun unsafe Get_version as getVersion_\n {alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Return the number of processes involved in a communicator. For 'commWorld'\n-- it returns the total number of processes available. If the communicator is\n-- and intra-communicator it returns the number of processes in the local group.\n-- This function corresponds to @MPI_Comm_size@.\n{# fun unsafe Comm_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n{# fun unsafe Comm_remote_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n{# fun unsafe Comm_test_inter as ^\n {fromComm `Comm', alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\ncommGetAttr :: Storable e => Comm -> Int -> IO (Maybe e)\ncommGetAttr comm key = do\n isInitialized <- initialized\n if isInitialized then do\n alloca $ \\ptr -> do\n found <- commGetAttr' comm key (castPtr ptr)\n if found then do ptr2 <- peek ptr\n Just <$> peek ptr2\n else return Nothing\n else return Nothing\n where\n commGetAttr' = {# fun unsafe Comm_get_attr as commGetAttr_\n {fromComm `Comm', cIntConv `Int', id `Ptr ()', alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\nforeign import ccall unsafe \"&mpi_tag_ub\" tagUB_ :: Ptr Int\n\n-- | Maximum tag value supported by the current MPI implementation. Corresponds to the value of standard MPI\n-- attribute @MPI_TAG_UB@.\n--\n-- When called before 'init' or 'initThread' would return 0.\ntagUpperBound :: Int\ntagUpperBound =\n let key = unsafePerformIO (peek tagUB_)\n in fromMaybe 0 $ unsafePerformIO (commGetAttr commWorld key)\n\n-- | Return the rank of the calling process for the given communicator.\n-- This function corresponds to @MPI_Comm_rank@.\n{# fun unsafe Comm_rank as ^\n {fromComm `Comm', alloca- `Rank' peekIntConv* } -> `()' checkError*- #}\n\n{# fun unsafe Comm_compare as ^\n {fromComm `Comm', fromComm `Comm', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- | Test for an incomming message, without actually receiving it.\n-- If a message has been sent from @Rank@ to the current process with @Tag@ on the\n-- communicator @Comm@ then 'probe' will return the 'Status' of the message. Otherwise\n-- it will block the current process until such a matching message is sent.\n-- This allows the current process to check for an incoming message and decide\n-- how to receive it, based on the information in the 'Status'.\n-- This function corresponds to @MPI_Probe@.\n{# fun Probe as ^\n {fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n{- probe :: Rank -- ^ Rank of the sender.\n -> Tag -- ^ Tag of the sent message.\n -> Comm -- ^ Communicator.\n -> IO Status -- ^ Information about the incoming message (but not the content of the message). -}\n\n{# fun unsafe Send as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Bsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Ssend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Rsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Recv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast* } -> `()' checkError*- #}\n{# fun unsafe Isend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n{# fun unsafe Ibsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n{# fun unsafe Issend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n{# fun Irecv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n\n-- | Like 'isend', but stores Request at the supplied pointer. Useful\n-- for making arrays of Requests that could be passed to 'waitall'\n{# fun unsafe Isend as isendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'ibsend', but stores Request at the supplied pointer. Useful\n-- for making arrays of Requests that could be passed to 'waitall'\n{# fun unsafe Ibsend as ibsendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'issend', but stores Request at the supplied pointer. Useful\n-- for making arrays of Requests that could be passed to 'waitall'\n{# fun unsafe Issend as issendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'irecv', but stores Request at the supplied pointer. Useful\n-- for making arrays of Requests that could be passed to 'waitall'\n{# fun Irecv as irecvPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n{# fun unsafe Bcast as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocks until all processes on the communicator call this function.\n-- This function corresponds to @MPI_Barrier@.\n{# fun unsafe Barrier as ^ {fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocking test for the completion of a send of receive.\n-- See 'test' for a non-blocking variant.\n-- This function corresponds to @MPI_Wait@.\n{# fun unsafe Wait as ^\n {withRequest* `Request', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Takes pointer to the array of Requests of given size, 'wait's on all of them,\n-- populates array of Statuses of the same size. This function corresponds to @MPI_Waitall@\n{# fun unsafe Waitall as ^\n { id `Count', castPtr `Ptr Request', castPtr `Ptr Status'} -> `()' checkError*- #}\n-- TODO: Make this Storable Array instead of Ptr ?\n\n-- | Non-blocking test for the completion of a send or receive.\n-- Returns @Nothing@ if the request is not complete, otherwise\n-- it returns @Just status@. See 'wait' for a blocking variant.\n-- This function corresponds to @MPI_Test@.\ntest :: Request -> IO (Maybe Status)\ntest request = do\n (flag, status) <- test' request\n if flag\n then return $ Just status\n else return Nothing\n where\n test' = {# fun unsafe Test as test_\n {withRequest* `Request', alloca- `Bool' peekBool*, allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Cancel a pending communication request.\n-- This function corresponds to @MPI_Cancel@.\n{# fun unsafe Cancel as ^\n {withRequest* `Request'} -> `()' checkError*- #}\nwithRequest req f = do alloca $ \\ptr -> do poke ptr req\n f (castPtr ptr)\n{# fun unsafe Scatter as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n{# fun unsafe Gather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- We pass counts\/displs as Ptr CInt so that caller could supply nullPtr here\n-- which would be impossible if we marshal arrays ourselves here.\n{# fun unsafe Scatterv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Gatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Allgather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Allgatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Alltoall as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Alltoallv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\n{# fun Reduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n{# fun Allreduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n{# fun Reduce_scatter as ^\n { id `BufferPtr', id `BufferPtr', id `Ptr CInt', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Op_create as ^\n {castFunPtr `FunPtr (Ptr t -> Ptr t -> Ptr CInt -> Ptr Datatype -> IO ())', cFromEnum `Bool', alloca- `Operation' peekOperation*} -> `()' checkError*- #}\n{# fun Op_free as ^ {withOperation* `Operation'} -> `()' checkError*- #}\n{# fun unsafe Wtime as ^ {} -> `Double' realToFrac #}\n{# fun unsafe Wtick as ^ {} -> `Double' realToFrac #}\n\n-- | Return the process group from a communicator.\n{# fun unsafe Comm_group as ^\n {fromComm `Comm', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupRank = unsafePerformIO <$> groupRank'\n where groupRank' = {# fun unsafe Group_rank as groupRank_\n {fromGroup `Group', alloca- `Rank' peekIntConv*} -> `()' checkError*- #}\n\ngroupSize = unsafePerformIO <$> groupSize'\n where groupSize' = {# fun unsafe Group_size as groupSize_\n {fromGroup `Group', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\ngroupUnion g1 g2 = unsafePerformIO $ groupUnion' g1 g2\n where groupUnion' = {# fun unsafe Group_union as groupUnion_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupIntersection g1 g2 = unsafePerformIO $ groupIntersection' g1 g2\n where groupIntersection' = {# fun unsafe Group_intersection as groupIntersection_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupDifference g1 g2 = unsafePerformIO $ groupDifference' g1 g2\n where groupDifference' = {# fun unsafe Group_difference as groupDifference_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupCompare g1 g2 = unsafePerformIO $ groupCompare' g1 g2\n where\n groupCompare' = {# fun unsafe Group_compare as groupCompare_\n {fromGroup `Group', fromGroup `Group', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- Technically it might make better sense to make the second argument a Set rather than a list\n-- but the order is significant in the groupIncl function (the other function, not this one).\n-- For the sake of keeping their types in sync, a list is used instead.\n{# fun unsafe Group_excl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n{# fun unsafe Group_incl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupTranslateRanks :: Group -> [Rank] -> Group -> [Rank]\ngroupTranslateRanks group1 ranks group2 =\n unsafePerformIO $ do\n let (rankIntList :: [Int]) = map fromEnum ranks\n withArrayLen rankIntList $ \\size ranksPtr ->\n allocaArray size $ \\resultPtr -> do\n groupTranslateRanks' group1 (cFromEnum size) (castPtr ranksPtr) group2 resultPtr\n map toRank <$> peekArray size resultPtr\n where\n groupTranslateRanks' = {# fun unsafe Group_translate_ranks as groupTranslateRanks_\n {fromGroup `Group', id `CInt', id `Ptr CInt', fromGroup `Group', id `Ptr CInt'} -> `()' checkError*- #}\n\nwithRanksAsInts ranks f = withArrayLen (map fromEnum ranks) $ \\size ptr -> f (cIntConv size, castPtr ptr)\n\n-- | Return the number of bytes used to store an MPI 'Datatype'.\ntypeSize = unsafePerformIO . typeSize'\n where\n typeSize' =\n {# fun unsafe Type_size as typeSize_\n {fromDatatype `Datatype', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n{# fun unsafe Error_class as ^\n { id `CInt', alloca- `CInt' peek*} -> `CInt' id #}\n\n-- | Set the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_set_errhandler@.\n{# fun unsafe Comm_set_errhandler as ^\n {fromComm `Comm', fromErrhandler `Errhandler'} -> `()' checkError*- #}\n\n-- | Get the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_get_errhandler@.\n{# fun unsafe Comm_get_errhandler as ^\n {fromComm `Comm', alloca- `Errhandler' peekErrhandler*} -> `()' checkError*- #}\n\n-- | Tries to terminate all MPI processes in its communicator argument.\n-- The second argument is an error code which \/may\/ be used as the return status\n-- of the MPI process, but this is not guaranteed. On systems where 'Int' has a larger\n-- range than 'CInt', the error code will be clipped to fit into the range of 'CInt'.\n-- This function corresponds to @MPI_Abort@.\nabort :: Comm -> Int -> IO ()\nabort comm code =\n abort' comm (toErrorCode code)\n where\n toErrorCode :: Int -> CInt\n toErrorCode i\n -- Assumes Int always has range at least as big as CInt.\n | i < (fromIntegral (minBound :: CInt)) = minBound\n | i > (fromIntegral (maxBound :: CInt)) = maxBound\n | otherwise = cIntConv i\n\n abort' = {# fun unsafe Abort as abort_ {fromComm `Comm', id `CInt'} -> `()' checkError*- #}\n\n\ntype MPIDatatype = {# type MPI_Datatype #}\n\nnewtype Datatype = MkDatatype { fromDatatype :: MPIDatatype }\n\nforeign import ccall unsafe \"&mpi_char\" char_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_wchar\" wchar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_short\" short_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_int\" int_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long\" long_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_long\" longLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_char\" unsignedChar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_short\" unsignedShort_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned\" unsigned_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long\" unsignedLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long_long\" unsignedLongLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_float\" float_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_double\" double_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_double\" longDouble_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_byte\" byte_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_packed\" packed_ :: Ptr MPIDatatype\n\nchar, wchar, short, int, long, longLong, unsignedChar, unsignedShort :: Datatype\nunsigned, unsignedLong, unsignedLongLong, float, double, longDouble :: Datatype\nbyte, packed :: Datatype\n\nchar = MkDatatype <$> unsafePerformIO $ peek char_\nwchar = MkDatatype <$> unsafePerformIO $ peek wchar_\nshort = MkDatatype <$> unsafePerformIO $ peek short_\nint = MkDatatype <$> unsafePerformIO $ peek int_\nlong = MkDatatype <$> unsafePerformIO $ peek long_\nlongLong = MkDatatype <$> unsafePerformIO $ peek longLong_\nunsignedChar = MkDatatype <$> unsafePerformIO $ peek unsignedChar_\nunsignedShort = MkDatatype <$> unsafePerformIO $ peek unsignedShort_\nunsigned = MkDatatype <$> unsafePerformIO $ peek unsigned_\nunsignedLong = MkDatatype <$> unsafePerformIO $ peek unsignedLong_\nunsignedLongLong = MkDatatype <$> unsafePerformIO $ peek unsignedLongLong_\nfloat = MkDatatype <$> unsafePerformIO $ peek float_\ndouble = MkDatatype <$> unsafePerformIO $ peek double_\nlongDouble = MkDatatype <$> unsafePerformIO $ peek longDouble_\nbyte = MkDatatype <$> unsafePerformIO $ peek byte_\npacked = MkDatatype <$> unsafePerformIO $ peek packed_\n\n\ntype MPIErrhandler = {# type MPI_Errhandler #}\nnewtype Errhandler = MkErrhandler { fromErrhandler :: MPIErrhandler } deriving Storable\npeekErrhandler ptr = MkErrhandler <$> peek ptr\n\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr MPIErrhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr MPIErrhandler\nerrorsAreFatal, errorsReturn :: Errhandler\nerrorsAreFatal = MkErrhandler <$> unsafePerformIO $ peek errorsAreFatal_\nerrorsReturn = MkErrhandler <$> unsafePerformIO $ peek errorsReturn_\n\n{# enum ErrorClass {underscoreToCase} deriving (Eq,Ord,Show,Typeable) #}\n\n-- XXX Should this be a ForeinPtr?\n-- there is a MPI_Group_free function, which we should probably\n-- call when the group is no longer referenced.\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIGroup = {# type MPI_Group #}\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\npeekGroup ptr = MkGroup <$> peek ptr\n\nforeign import ccall \"&mpi_group_empty\" groupEmpty_ :: Ptr MPIGroup\n-- | Predefined handle for group without any members. Corresponds to @MPI_GROUP_EMPTY@\ngroupEmpty :: Group\ngroupEmpty = MkGroup <$> unsafePerformIO $ peek groupEmpty_\n\n\n{-\nThis module provides Haskell type that represents values of @MPI_Op@\ntype (reduction operations), and predefined reduction operations\ndefined in the MPI Report.\n-}\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIOperation = {# type MPI_Op #}\nnewtype Operation = MkOperation { fromOperation :: MPIOperation } deriving Storable\npeekOperation ptr = MkOperation <$> peek ptr\nwithOperation op f = alloca $ \\ptr -> do poke ptr (fromOperation op)\n f (castPtr ptr)\n\nforeign import ccall unsafe \"&mpi_max\" maxOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_min\" minOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_sum\" sumOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_prod\" prodOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_land\" landOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_band\" bandOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lor\" lorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bor\" borOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lxor\" lxorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bxor\" bxorOp_ :: Ptr MPIOperation\n-- foreign import ccall \"mpi_maxloc\" maxlocOp :: MPIOperation\n-- foreign import ccall \"mpi_minloc\" minlocOp :: MPIOperation\n-- foreign import ccall \"mpi_replace\" replaceOp :: MPIOperation\n-- TODO: support for those requires better support for pair datatypes\n\nmaxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp :: Operation\nmaxOp = MkOperation <$> unsafePerformIO $ peek maxOp_\nminOp = MkOperation <$> unsafePerformIO $ peek minOp_\nsumOp = MkOperation <$> unsafePerformIO $ peek sumOp_\nprodOp = MkOperation <$> unsafePerformIO $ peek prodOp_\nlandOp = MkOperation <$> unsafePerformIO $ peek landOp_\nbandOp = MkOperation <$> unsafePerformIO $ peek bandOp_\nlorOp = MkOperation <$> unsafePerformIO $ peek lorOp_\nborOp = MkOperation <$> unsafePerformIO $ peek borOp_\nlxorOp = MkOperation <$> unsafePerformIO $ peek lxorOp_\nbxorOp = MkOperation <$> unsafePerformIO $ peek bxorOp_\n\n\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI rank designations.\n-}\n\nnewtype Rank = MkRank { rankId :: Int }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Rank where\n (MkRank x) + (MkRank y) = MkRank (x+y)\n (MkRank x) * (MkRank y) = MkRank (x*y)\n abs (MkRank x) = MkRank (abs x)\n signum (MkRank x) = MkRank (signum x)\n fromInteger x\n | x > ( fromIntegral (maxBound :: CInt)) = error \"Rank value does not fit into 32 bits\"\n | x < 0 = error \"Negative Rank value\"\n | otherwise = MkRank (fromIntegral x)\n\nforeign import ccall \"mpi_any_source\" anySource_ :: Ptr Int\nforeign import ccall \"mpi_root\" theRoot_ :: Ptr Int\nforeign import ccall \"mpi_proc_null\" procNull_ :: Ptr Int\n\n-- | Predefined rank number that allows reception of point-to-point messages\n-- regardless of their source. Corresponds to @MPI_ANY_SOURCE@\nanySource :: Rank\nanySource = toRank $ unsafePerformIO $ peek anySource_\n\n-- | Predefined rank number that specifies root process during\n-- operations involving intercommunicators. Corresponds to @MPI_ROOT@\ntheRoot :: Rank\ntheRoot = toRank $ unsafePerformIO $ peek theRoot_\n\n-- | Predefined rank number that specifies non-root processes during\n-- operations involving intercommunicators. Corresponds to @MPI_PROC_NULL@\nprocNull :: Rank\nprocNull = toRank $ unsafePerformIO $ peek procNull_\n\ninstance Show Rank where\n show = show . rankId\n\ntoRank :: Enum a => a -> Rank\ntoRank x = MkRank { rankId = fromEnum x }\n\nfromRank :: Enum a => Rank -> a\nfromRank = toEnum . rankId\n\n{- This module provides Haskell representation of the @MPI_Request@ type. -}\ntype MPIRequest = {# type MPI_Request #}\nnewtype Request = MkRequest MPIRequest deriving Storable\npeekRequest ptr = MkRequest <$> peek ptr\n\n{-\nThis module provides Haskell representation of the @MPI_Status@ type\n(request status).\n\nField `status_error' should be used with care:\n\\\"The error field in status is not needed for calls that return only\none status, such as @MPI_WAIT@, since that would only duplicate the\ninformation returned by the function itself. The current design avoids\nthe additional overhead of setting it, in such cases. The field is\nneeded for calls that return multiple statuses, since each request may\nhave had a different failure.\\\"\n(this is a quote from )\n\nThis means that, for example, during the call to @MPI_Wait@\nimplementation is free to leave this field filled with whatever\ngarbage got there during memory allocation. Haskell FFI is not\nblanking out freshly allocated memory, so beware!\n-}\n\n-- | Haskell structure that holds fields of @MPI_Status@.\n--\n-- Please note that MPI report lists only three fields as mandatory:\n-- @status_source@, @status_tag@ and @status_error@. However, all\n-- MPI implementations that were used to test those bindings supported\n-- extended set of fields represented here.\ndata Status =\n Status\n { status_source :: CInt -- ^ rank of the source process\n , status_tag :: CInt -- ^ tag assigned at source\n , status_error :: CInt -- ^ error code, if any\n , status_count :: CInt -- ^ number of received elements, if applicable\n , status_cancelled :: CInt -- ^ whether the request was cancelled\n }\n deriving (Eq, Ord, Show)\n\ninstance Storable Status where\n sizeOf _ = {#sizeof MPI_Status #}\n alignment _ = 4\n peek p = Status\n <$> liftM cIntConv ({#get MPI_Status->MPI_SOURCE #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_TAG #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_ERROR #} p)\n#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields-\n <*> liftM cIntConv ({#get MPI_Status->count #} p)\n <*> liftM cIntConv ({#get MPI_Status->cancelled #} p)\n#else\n <*> liftM cIntConv ({#get MPI_Status->_count #} p)\n <*> liftM cIntConv ({#get MPI_Status->_cancelled #} p)\n#endif\n poke p x = do\n {#set MPI_Status.MPI_SOURCE #} p (cIntConv $ status_source x)\n {#set MPI_Status.MPI_TAG #} p (cIntConv $ status_tag x)\n {#set MPI_Status.MPI_ERROR #} p (cIntConv $ status_error x)\n#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields AND different order of fields\n {#set MPI_Status.count #} p (cIntConv $ status_count x)\n {#set MPI_Status.cancelled #} p (cIntConv $ status_cancelled x)\n#else\n {#set MPI_Status._count #} p (cIntConv $ status_count x)\n {#set MPI_Status._cancelled #} p (cIntConv $ status_cancelled x)\n#endif\n\n-- NOTE: Int here is picked arbitrary\nallocaCast f =\n alloca $ \\(ptr :: Ptr Int) -> f (castPtr ptr :: Ptr ())\npeekCast = peek . castPtr\n\n\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI tags.\n-}\n\nnewtype Tag = MkTag { tagVal :: Int }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Tag where\n (MkTag x) + (MkTag y) = MkTag (x+y)\n (MkTag x) * (MkTag y) = MkTag (x*y)\n abs (MkTag x) = MkTag (abs x)\n signum (MkTag x) = MkTag (signum x)\n fromInteger x\n | fromIntegral x > tagUpperBound = error \"Tag value is over the MPI_TAG_UB\"\n | x < 0 = error \"Negative Tag value\"\n | otherwise = MkTag (fromIntegral x)\n\ninstance Show Tag where\n show = show . tagVal\n\ntoTag :: Enum a => a -> Tag\ntoTag x = MkTag { tagVal = fromEnum x }\n\nfromTag :: Enum a => Tag -> a\nfromTag = toEnum . tagVal\n\nforeign import ccall unsafe \"&mpi_any_tag\" anyTag_ :: Ptr Int\n\n-- | Predefined tag value that allows reception of the messages with\n-- arbitrary tag values. Corresponds to @MPI_ANY_TAG@.\nanyTag :: Tag\nanyTag = toTag $ unsafePerformIO $ peek anyTag_\n\n-- | A tag with unit value. Intended to be used as a convenient default.\nunitTag :: Tag\nunitTag = toTag ()\n\n\n{-\nThis module provides Haskell datatypes that comprises of values of\npredefined MPI constants @MPI_THREAD_SINGLE@, @MPI_THREAD_FUNNELED@,\n@MPI_THREAD_SERIALIZED@, @MPI_THREAD_MULTIPLE@.\n-}\n\n{# enum ThreadSupport {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- | Value thrown as exception when MPI runtime is instructed to pass\n-- errors to user code (via 'commSetErrhandler' and 'errorsReturn').\n-- Since raw MPI errors codes are not standartized and not portable,\n-- they are not exposed.\ndata MPIError\n = MPIError\n { mpiErrorClass :: ErrorClass -- ^ Broad class of errors this one belongs to\n , mpiErrorString :: String -- ^ Human-readable error description\n }\n deriving (Eq, Show, Typeable)\n\ninstance Exception MPIError\n\ncheckError :: CInt -> IO ()\ncheckError code = do\n -- We ignore the error code from the call to Internal.errorClass\n -- because we call errorClass from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n (_, errClassRaw) <- errorClass code\n let errClass = cToEnum errClassRaw\n unless (errClass == Success) $ do\n errStr <- errorString code\n throwIO $ MPIError errClass errStr\n\n-- | Convert MPI error code human-readable error description. Corresponds to @MPI_Error_string@.\nerrorString :: CInt -> IO String\nerrorString code =\n allocaBytes (fromIntegral maxErrorString) $ \\ptr ->\n alloca $ \\lenPtr -> do\n -- We ignore the error code from the call to Internal.errorString\n -- because we call errorString from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n _ <- errorString' code ptr lenPtr\n len <- peek lenPtr\n peekCStringLen (ptr, cIntConv len)\n where\n errorString' = {# call unsafe Error_string as errorString_ #}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"cdc89c3a2b21a862807f9b4734cae9c74448e984","subject":"Clean up","message":"Clean up","repos":"TomMD\/CV,BeautifulDestinations\/CV,aleator\/CV,aleator\/CV","old_file":"CV\/TemplateMatching.chs","new_file":"CV\/TemplateMatching.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ScopedTypeVariables#-}\n#include \"cvWrapLEO.h\"\nmodule CV.TemplateMatching where\n\nimport Foreign.C.Types\nimport Foreign.Ptr\n\nimport CV.Image\nimport CV.Transforms\n\nimport Utils.Function\nimport Utils.Point\nimport Utils.Rectangle hiding (scale)\n\n{#import CV.Image#}\nimport C2HSTools\n\ngetTemplateMap image template = unsafePerformIO $\n\t withImage image $ \\cvimg ->\n\t withImage template $ \\cvtemp ->\n creatingImage $ {#call templateImage#} cvimg cvtemp\n \n\n#c\nenum MatchType {\n CV_TM_SQDIFF\n ,CV_TM_SQDIFF_NORMED \n ,CV_TM_CCORR\n ,CV_TM_CCORR_NORMED\n ,CV_TM_CCOEFF\n ,CV_TM_CCOEFF_NORMED \n};\n#endc\n{#enum MatchType {}#}\n\n\nsimpleTemplateMatch :: MatchType -> Image GrayScale D32 -> Image GrayScale D32 -> ((Int,Int),Double)\nsimpleTemplateMatch mt image template \n\t= unsafePerformIO $ do\n\t withImage image $ \\cvimg ->\n\t withImage template $ \\cvtemp ->\n\t alloca $ \\(ptrintx :: Ptr CInt) ->\n\t alloca $ \\(ptrinty :: Ptr CInt)->\n\t alloca $ \\(ptrdblval :: Ptr CDouble) -> do {\n\t {#call simpleMatchTemplate#} cvimg cvtemp ptrintx ptrinty ptrdblval (fromIntegral $ fromEnum mt);\n\t\t x <- peek ptrintx;\n\t\t\ty <- peek ptrinty;\n\t\t\tv <- peek ptrdblval;\n\t\t return ((fromIntegral x,fromIntegral y),realToFrac v); }\n\nmatchTemplate :: MatchType-> Image GrayScale D32 -> Image GrayScale D32 -> Image GrayScale D32 \nmatchTemplate mt image template = unsafePerformIO $ do\n let isize = getSize image\n tsize = getSize template\n size = isize - tsize + (1,1) \n res <- create size \n withGenImage image $ \\cimg -> \n withGenImage template $ \\ctempl ->\n withGenImage res $ \\cresult -> \n {#call cvMatchTemplate#} cimg ctempl cresult (fromIntegral . fromEnum $ mt)\n return res\n\n\n-- | Perform subpixel template matching using intensity interpolation\nsubPixelTemplateMatch :: MatchType -> Image GrayScale D32 -> Image GrayScale D32 -> Double -> (Double,Double)\nsubPixelTemplateMatch mt image template n -- TODO: Make iterative #SpeedUp\n = (fromIntegral (tx)+fromIntegral sbx\/n \n ,fromIntegral (ty)+fromIntegral sby\/n)\n where\n (otw,oth) = getSize template\n ((orX,orY),_) = simpleTemplateMatch CV_TM_CCORR_NORMED image template\n (tx,ty) = (orX-otw`div`2, orY-oth`div`2)\n\n bigTempl = scaleSingleRatio Linear n template\n (tw,th) = getSize bigTempl\n region = scaleSingleRatio Linear n . getRegion (tx,ty) (otw*2,oth*2) $ image\n ((sbx,sby),_) = simpleTemplateMatch CV_TM_CCORR_NORMED region bigTempl\n \nregionToInt rc = mkRectangle (floor x,floor y) (ceiling w,ceiling h)\n where\n (x,y) = topLeft rc\n (w,h) = rSize rc\n\n#c\nenum ShapeMatchMethod {\n Method1 = CV_CONTOURS_MATCH_I1,\n Method2 = CV_CONTOURS_MATCH_I2,\n Method3 = CV_CONTOURS_MATCH_I3\n};\n#endc\n{#enum ShapeMatchMethod {}#}\n\n\n--\u00a0| Match shapes\nmatchShapes :: ShapeMatchMethod -> Image GrayScale D8 -> Image GrayScale D8 -> Double\nmatchShapes m a b = unsafePerformIO $ do\n withGenImage a $ \\c_a ->\n withGenImage b $ \\c_b ->\n {#call cvMatchShapes#} c_a c_b (fromIntegral . fromEnum $ m) 0 \n >>= return.realToFrac\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ScopedTypeVariables#-}\n#include \"cvWrapLEO.h\"\nmodule CV.TemplateMatching where\n\nimport Foreign.C.Types\nimport Foreign.Ptr\n\nimport CV.Image\nimport CV.Transforms\n\nimport Utils.Function\nimport Utils.Point\nimport Utils.Rectangle hiding (scale)\n\n{#import CV.Image#}\nimport C2HSTools\n\ngetTemplateMap image template = unsafePerformIO $\n\t withImage image $ \\cvimg ->\n\t withImage template $ \\cvtemp ->\n creatingImage $ {#call templateImage#} cvimg cvtemp\n \n\n#c\nenum MatchType {\n CV_TM_SQDIFF\n ,CV_TM_SQDIFF_NORMED \n ,CV_TM_CCORR\n ,CV_TM_CCORR_NORMED\n ,CV_TM_CCOEFF\n ,CV_TM_CCOEFF_NORMED \n};\n#endc\n{#enum MatchType {}#}\n\n-- TODO: Make this somehow smarter #PotentialDanger\n--data MatchType = CV_TM_SQDIFF | CV_TM_SQDIFF_NORMED | CV_TM_CCORR\n-- | CV_TM_CCORR_NORMED | CV_TM_CCOEFF | CV_TM_CCOEFF_NORMED \n-- deriving (Eq,Show,Enum)\n\n\nsimpleTemplateMatch :: MatchType -> Image GrayScale D32 -> Image GrayScale D32 -> ((Int,Int),Double)\nsimpleTemplateMatch mt image template \n\t= unsafePerformIO $ do\n\t withImage image $ \\cvimg ->\n\t withImage template $ \\cvtemp ->\n\t alloca $ \\(ptrintx :: Ptr CInt) ->\n\t alloca $ \\(ptrinty :: Ptr CInt)->\n\t alloca $ \\(ptrdblval :: Ptr CDouble) -> do {\n\t {#call simpleMatchTemplate#} cvimg cvtemp ptrintx ptrinty ptrdblval (fromIntegral $ fromEnum mt);\n\t\t x <- peek ptrintx;\n\t\t\ty <- peek ptrinty;\n\t\t\tv <- peek ptrdblval;\n\t\t return ((fromIntegral x,fromIntegral y),realToFrac v); }\n\nmatchTemplate :: MatchType-> Image GrayScale D32 -> Image GrayScale D32 -> Image GrayScale D32 \nmatchTemplate mt image template = unsafePerformIO $ do\n let isize = getSize image\n tsize = getSize template\n size = isize - tsize + (1,1) \n res <- create size \n withGenImage image $ \\cimg -> \n withGenImage template $ \\ctempl ->\n withGenImage res $ \\cresult -> \n {#call cvMatchTemplate#} cimg ctempl cresult (fromIntegral . fromEnum $ mt)\n return res\n\n\n-- | Perform subpixel template matching using intensity interpolation\nsubPixelTemplateMatch :: MatchType -> Image GrayScale D32 -> Image GrayScale D32 -> Double -> (Double,Double)\nsubPixelTemplateMatch mt image template n -- TODO: Make iterative #SpeedUp\n = (fromIntegral (tx)+fromIntegral sbx\/n \n ,fromIntegral (ty)+fromIntegral sby\/n)\n where\n (otw,oth) = getSize template\n ((orX,orY),_) = simpleTemplateMatch CV_TM_CCORR_NORMED image template\n (tx,ty) = (orX-otw`div`2, orY-oth`div`2)\n\n bigTempl = scaleSingleRatio Linear n template\n (tw,th) = getSize bigTempl\n region = scaleSingleRatio Linear n . getRegion (tx,ty) (otw*2,oth*2) $ image\n ((sbx,sby),_) = simpleTemplateMatch CV_TM_CCORR_NORMED region bigTempl\n \nregionToInt rc = mkRectangle (floor x,floor y) (ceiling w,ceiling h)\n where\n (x,y) = topLeft rc\n (w,h) = rSize rc\n\n#c\nenum ShapeMatchMethod {\n Method1 = CV_CONTOURS_MATCH_I1,\n Method2 = CV_CONTOURS_MATCH_I2,\n Method3 = CV_CONTOURS_MATCH_I3\n};\n#endc\n{#enum ShapeMatchMethod {}#}\n\n\n--\u00a0| Match shapes\nmatchShapes :: ShapeMatchMethod -> Image GrayScale D8 -> Image GrayScale D8 -> Double\nmatchShapes m a b = unsafePerformIO $ do\n withGenImage a $ \\c_a ->\n withGenImage b $ \\c_b ->\n {#call cvMatchShapes#} c_a c_b (fromIntegral . fromEnum $ m) 0 \n >>= return.realToFrac\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"e62f89508e169f33c1f1c0f762e15067aebde5c6","subject":"trying to avoid a possible leak","message":"trying to avoid a possible leak\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/GDAL.chs","new_file":"src\/GDAL\/Internal\/GDAL.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ExistentialQuantification #-}\n\nmodule GDAL.Internal.GDAL (\n GDALType (..)\n , GDALRasterException (..)\n , DataType (..)\n , Geotransform (..)\n , Driver (..)\n , Dataset\n , DatasetH (..)\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , RasterBandH (..)\n , nullDatasetH\n , allRegister\n , destroyDriverManager\n , create\n , createMem\n , flushCache\n , openReadOnly\n , openReadWrite\n , unsafeToReadOnly\n , createCopy\n , driverCreationOptionList\n\n , dataTypeSize\n , dataTypeByName\n , dataTypeUnion\n , dataTypeIsComplex\n\n , datasetSize\n , reifyDataType\n , datasetProjection\n , setDatasetProjection\n , datasetGeotransform\n , setDatasetGeotransform\n , datasetBandCount\n\n , bandDataType\n , reifyBandDataType\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , allBand\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , readBand\n , readBandPure\n , readBandBlock\n , writeBand\n , writeBandBlock\n\n , foldl'\n , foldlM'\n , ifoldl'\n , ifoldlM'\n\n , unDataset\n , unBand\n , withLockedDatasetPtr\n , withLockedBandPtr\n , newDerivedDatasetHandle\n , version\n) where\n\n{#context lib = \"gdal\" prefix = \"GDAL\" #}\n\nimport Control.Applicative ((<$>), (<*>), liftA2, pure)\nimport Control.DeepSeq (NFData(rnf))\nimport Control.Exception (Exception(..), throw)\nimport Control.Monad (liftM, liftM2, when, void)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Data.Int (Int16, Int32)\nimport Data.Bits ((.&.))\nimport Data.Complex (Complex(..), realPart)\nimport Data.Coerce (coerce)\nimport Data.Proxy (Proxy(..))\nimport Data.Text (Text)\nimport Data.Typeable (Typeable)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Unboxed (Vector)\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (toBool, fromBool, with)\n\nimport System.IO.Unsafe (unsafePerformIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.Util\n{#import GDAL.Internal.CPLError#}\n{#import GDAL.Internal.CPLString#}\n{#import GDAL.Internal.CPLProgress#}\nimport GDAL.Internal.OGRError\nimport GDAL.Internal.OSR\n\n\n#include \"gdal.h\"\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n{#enum define Version { GDAL_VERSION_MAJOR as VersionMajor\n , GDAL_VERSION_MINOR as VersionMinor } #}\n\nversion :: (Int, Int)\nversion = (fromEnum VersionMajor, fromEnum VersionMinor)\n\ndata GDALRasterException\n = InvalidRasterSize !Size\n | InvalidBlockSize !Int\n | InvalidDataType !DataType\n | InvalidProjection !OGRException\n | InvalidDriverOptions ![Text]\n | NullDataset\n | CopyStopped\n | UnknownRasterDataType\n | UnsupportedRasterDataType !DataType\n deriving (Typeable, Show, Eq)\n\ninstance NFData GDALRasterException where\n rnf a = a `seq` () -- All fields are already strict so no need to rnf them\n\ninstance Exception GDALRasterException where\n toException = bindingExceptionToException\n fromException = bindingExceptionFromException\n\n\nclass (Storable a, Show a, Typeable a) => GDALType a where\n dataType :: Proxy a -> DataType\n -- | default nodata value when writing to bands with no datavalue set\n nodata :: a\n -- | how to convert to double for use in setBandNodataValue\n toCDouble :: a -> CDouble\n -- | how to convert from double for use with bandNodataValue\n fromCDouble :: CDouble -> a\n\n fillBand :: a -> RWBand s -> GDAL s ()\n fillBand v = fillRaster (toCDouble v) (toCDouble v)\n {-# INLINE fillBand #-}\n\n{#enum DataType {} omit (GDT_TypeCount) deriving (Eq, Show, Bounded) #}\n\ninstance NFData DataType where\n rnf a = a `seq`()\n\n{#fun pure unsafe GetDataTypeSize as dataTypeSize\n { fromEnumC `DataType' } -> `Int' #}\n\n{#fun pure unsafe DataTypeIsComplex as ^\n { fromEnumC `DataType' } -> `Bool' #}\n\n{#fun pure unsafe GetDataTypeByName as dataTypeByName\n { `String' } -> `DataType' toEnumC #}\n\n{#fun pure unsafe DataTypeUnion as ^\n { fromEnumC `DataType', fromEnumC `DataType' } -> `DataType' toEnumC #}\n\n\n{#enum Access {} deriving (Eq, Show) #}\n\n{#enum RWFlag {} deriving (Eq, Show) #}\n\n{#pointer DatasetH newtype #}\n\nnullDatasetH :: DatasetH\nnullDatasetH = DatasetH nullPtr\n\nderiving instance Eq DatasetH\n\nnewtype Dataset s (t::AccessMode)\n = Dataset (Mutex, DatasetH)\n\nunDataset :: Dataset s t -> DatasetH\nunDataset (Dataset (_,p)) = p\n\nwithLockedDatasetPtr\n :: Dataset s t -> (DatasetH -> IO b) -> IO b\nwithLockedDatasetPtr (Dataset (m,p)) f = withMutex m (f p)\n\ntype RODataset s = Dataset s ReadOnly\ntype RWDataset s = Dataset s ReadWrite\n\n{#pointer RasterBandH newtype #}\n\nnewtype Band s (t::AccessMode) = Band (Mutex, RasterBandH)\n\nunBand :: Band s t -> RasterBandH\nunBand (Band (_,p)) = p\n\nreifyBandDataType\n :: Band s t -> (forall a. GDALType a => Proxy a -> b) -> b\nreifyBandDataType b = reifyDataType (bandDataType b)\n\nwithLockedBandPtr\n :: Band s t -> (RasterBandH -> IO b) -> IO b\nwithLockedBandPtr (Band (m,p)) f = withMutex m (f p)\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s ReadWrite\n\n\n{#pointer DriverH newtype#}\n\n{#fun AllRegister as ^ {} -> `()' #}\n\n{#fun DestroyDriverManager as ^ {} -> `()'#}\n\ndriverByName :: Driver -> IO DriverH\ndriverByName s = withCString (show s) {#call unsafe GetDriverByName as ^#}\n\ndriverCreationOptionList :: Driver -> String\ndriverCreationOptionList driver = unsafePerformIO $ do\n d <- driverByName driver\n {#call GetDriverCreationOptionList\tas ^#} d >>= peekCString\n\nvalidateCreationOptions :: DriverH -> Ptr CString -> IO ()\nvalidateCreationOptions d o = do\n (valid,errs) <- collectMessages $\n liftM toBool ({#call GDALValidateCreationOptions as ^ #} d o)\n let msgs = map (\\(_,_,m)->m) errs\n when (not valid) (throwBindingException (InvalidDriverOptions msgs))\n\ncreate\n :: Driver -> String -> Size -> Int -> DataType -> OptionList\n -> GDAL s (Dataset s ReadWrite)\ncreate _ _ _ _ GDT_Unknown _ =\n throwBindingException UnknownRasterDataType\ncreate drv path (XY nx ny) bands dtype options = do\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC dtype\n d <- driverByName drv\n throwIfError \"create\" $ withOptionList options $ \\opts -> do\n validateCreationOptions d opts\n {#call GDALCreate as ^#} d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\n\nopenReadOnly :: String -> GDAL s (RODataset s)\nopenReadOnly p = openWithMode GA_ReadOnly p\n\nopenReadWrite :: String -> GDAL s (RWDataset s)\nopenReadWrite p = openWithMode GA_Update p\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t)\nopenWithMode m path = do\n dsH <- liftIO $ withCString path $ \\p ->\n throwIfError \"GDALOpen\" ({#call GDALOpen as ^#} p (fromEnumC m))\n newDatasetHandle dsH\n\nunsafeToReadOnly :: RWDataset s -> GDAL s (RODataset s)\nunsafeToReadOnly ds = flushCache ds >> return (coerce ds)\n\ncreateCopy\n :: Driver -> String -> Dataset s t -> Bool -> OptionList\n -> Maybe ProgressFun -> GDAL s (RWDataset s)\ncreateCopy driver path ds strict options progressFun = do\n mPtr <- liftIO $ do\n d <- driverByName driver\n throwIfError \"createCopy\" $\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc ->\n withOptionList options $ \\o -> do\n validateCreationOptions d o\n withLockedDatasetPtr ds $ \\dsPtr ->\n {#call GDALCreateCopy as ^#}\n d p dsPtr (fromBool strict) o pFunc (castPtr nullPtr)\n maybe (throwBindingException CopyStopped) newDatasetHandle mPtr\n\n\nnewDatasetHandle :: DatasetH -> GDAL s (Dataset s t)\nnewDatasetHandle dh\n | dh==nullDatasetH = throwBindingException NullDataset\n | otherwise = do\n registerFinalizer (safeCloseDataset dh)\n m <- liftIO newMutex\n return $ Dataset (m,dh)\n\nnewDerivedDatasetHandle\n :: Dataset s t' -> DatasetH -> GDAL s (Dataset s t)\nnewDerivedDatasetHandle (Dataset (m,_)) dh\n | dh==nullDatasetH = throwBindingException NullDataset\n | otherwise = do\n registerFinalizer (safeCloseDataset dh)\n return $ Dataset (m,dh)\n\nsafeCloseDataset :: DatasetH -> IO ()\nsafeCloseDataset = {#call GDALClose as ^#}\n\ncreateMem\n :: Size -> Int -> DataType -> OptionList -> GDAL s (Dataset s ReadWrite)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s. RWDataset s -> GDAL s ()\nflushCache = liftIO . flip withLockedDatasetPtr {#call GDALFlushCache as ^#}\n\ndatasetSize :: Dataset s t -> Size\ndatasetSize ds =\n fmap fromIntegral $\n XY ({#call pure unsafe GetRasterXSize as ^#} (unDataset ds))\n ({#call pure unsafe GetRasterYSize as ^#} (unDataset ds))\n\ndatasetProjection :: Dataset s t -> GDAL s (Maybe SpatialReference)\ndatasetProjection ds = do\n let d = unDataset ds\n srs <- liftIO ({#call unsafe GetProjectionRef as ^#} d >>= peekCString)\n if null srs\n then return Nothing\n else either (throwBindingException . InvalidProjection)\n (return . Just)\n (fromWkt srs)\n\n\nsetDatasetProjection :: RWDataset s -> SpatialReference -> GDAL s ()\nsetDatasetProjection ds srs =\n liftIO $\n throwIfError_ \"setDatasetProjection\" $\n withLockedDatasetPtr ds $\n withCString (toWkt srs) . {#call SetProjection as ^#}\n\n\ndata Geotransform\n = Geotransform {\n gtXOff :: !Double\n , gtXDelta :: !Double\n , gtXRot :: !Double\n , gtYOff :: !Double\n , gtYRot :: !Double\n , gtYDelta :: !Double\n } deriving (Eq, Show)\n\ninstance Storable Geotransform where\n sizeOf _ = sizeOf (undefined :: CDouble) * 6\n alignment _ = alignment (undefined :: CDouble)\n poke pGt (Geotransform g0 g1 g2 g3 g4 g5) = do\n let p = castPtr pGt :: Ptr CDouble\n pokeElemOff p 0 (realToFrac g0)\n pokeElemOff p 1 (realToFrac g1)\n pokeElemOff p 2 (realToFrac g2)\n pokeElemOff p 3 (realToFrac g3)\n pokeElemOff p 4 (realToFrac g4)\n pokeElemOff p 5 (realToFrac g5)\n peek pGt = do\n let p = castPtr pGt :: Ptr CDouble\n Geotransform <$> liftM realToFrac (peekElemOff p 0)\n <*> liftM realToFrac (peekElemOff p 1)\n <*> liftM realToFrac (peekElemOff p 2)\n <*> liftM realToFrac (peekElemOff p 3)\n <*> liftM realToFrac (peekElemOff p 4)\n <*> liftM realToFrac (peekElemOff p 5)\n\n\ndatasetGeotransform :: Dataset s t -> GDAL s (Maybe Geotransform)\ndatasetGeotransform ds = liftIO $ alloca $ \\p -> do\n ret <- {#call unsafe GetGeoTransform as ^#} (unDataset ds) (castPtr p)\n if toEnumC ret == GDAL.Internal.CPLError.None\n then liftM Just (peek p)\n else return Nothing\n\n\nsetDatasetGeotransform :: RWDataset s -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = liftIO $\n throwIfError_ \"setDatasetGeotransform\" $\n withLockedDatasetPtr ds $ \\d ->\n with gt ({#call SetGeoTransform as ^#} d . castPtr)\n\n\ndatasetBandCount :: Dataset s t -> GDAL s Int\ndatasetBandCount =\n liftM fromIntegral . liftIO . {#call unsafe GetRasterCount as ^#} . unDataset\n\ngetBand :: Int -> Dataset s t -> GDAL s (Band s t)\ngetBand b (Dataset (m,dp)) = liftIO $ do\n p <- throwIfError \"getBand\" $ {#call GetRasterBand as ^#} dp (fromIntegral b)\n return (Band (m, p))\n\n\nreifyDataType :: DataType -> (forall a. GDALType a => Proxy a -> b) -> b\nreifyDataType dt f =\n case dt of\n GDT_Unknown -> throw (bindingExceptionToException UnknownRasterDataType)\n GDT_Byte -> f (Proxy :: Proxy Word8)\n GDT_UInt16 -> f (Proxy :: Proxy Word16)\n GDT_UInt32 -> f (Proxy :: Proxy Word32)\n GDT_Int16 -> f (Proxy :: Proxy Int16)\n GDT_Int32 -> f (Proxy :: Proxy Int32)\n GDT_Float32 -> f (Proxy :: Proxy Float)\n GDT_Float64 -> f (Proxy :: Proxy Double)\n#ifdef STORABLE_COMPLEX\n GDT_CInt16 -> f (Proxy :: Proxy (Complex Int16))\n GDT_CInt32 -> f (Proxy :: Proxy (Complex Int32))\n GDT_CFloat32 -> f (Proxy :: Proxy (Complex Float))\n GDT_CFloat64 -> f (Proxy :: Proxy (Complex Double))\n#else\n d -> throw\n (bindingExceptionToException (UnsupportedRasterDataType d))\n#endif\n\n\n\n\nbandDataType :: Band s t -> DataType\nbandDataType = toEnumC . {#call pure unsafe GetRasterDataType as ^#} . unBand\n\nbandBlockSize :: (Band s t) -> Size\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n {#call unsafe GetBlockSize as ^#} (unBand band) xPtr yPtr\n liftM (fmap fromIntegral) (liftM2 XY (peek xPtr) (peek yPtr))\n\nbandBlockLen :: Band s t -> Int\nbandBlockLen = (\\(XY x y) -> x*y) . bandBlockSize\n\nbandSize :: Band s a -> Size\nbandSize band =\n fmap fromIntegral $\n XY ({#call pure unsafe GetRasterBandXSize as ^#} (unBand band))\n ({#call pure unsafe GetRasterBandYSize as ^#} (unBand band))\n\nallBand :: Band s a -> Window Int\nallBand = Window (pure 0) . bandSize\n\nbandBlockCount :: Band s t -> XY Int\nbandBlockCount b = fmap ceiling $ liftA2 ((\/) :: Double -> Double -> Double)\n (fmap fromIntegral (bandSize b))\n (fmap fromIntegral (bandBlockSize b))\n\ncheckType\n :: GDALType a => Band s t -> Proxy a -> GDAL s ()\ncheckType b p\n | rt == bt = return ()\n | otherwise = throwBindingException (InvalidDataType bt)\n where rt = dataType p\n bt = bandDataType b\n\nbandNodataValue :: GDALType a => Band s t -> GDAL s (Maybe a)\nbandNodataValue b =\n liftM (fmap fromCDouble) (liftIO (bandNodataValueIO (unBand b)))\n\nbandNodataValueIO :: RasterBandH -> IO (Maybe CDouble)\nbandNodataValueIO b = alloca $ \\p -> do\n value <- {#call unsafe GetRasterNoDataValue as ^#} b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n{-# INLINE bandNodataValueIO #-}\n\n\nsetBandNodataValue :: GDALType a => RWBand s -> a -> GDAL s ()\nsetBandNodataValue b v =\n liftIO $\n throwIfError_ \"setBandNodataValue\" $\n {#call SetRasterNoDataValue as ^#} (unBand b) (toCDouble v)\n\nfillRaster :: CDouble -> CDouble -> RWBand s -> GDAL s ()\nfillRaster r i b =\n liftIO $\n throwIfError_ \"fillRaster\" $\n {#call GDALFillRaster as ^#} (unBand b) r i\n\n\nreadBand :: forall s t a. GDALType a\n => (Band s t)\n -> Window Int\n -> Size\n -> GDAL s (Vector (Value a))\nreadBand band win size = liftIO $ readBandIO band win size\n{-# INLINE readBand #-}\n\nreadBandPure :: forall s a. GDALType a\n => (ROBand s)\n -> Window Int\n -> Size\n -> Vector (Value a)\nreadBandPure band win size = unsafePerformIO $ readBandIO band win size\n{-# INLINE readBandPure #-}\n\nreadBandIO :: forall s t a. GDALType a\n => (Band s t)\n -> Window Int\n -> Size\n -> IO (Vector (Value a))\nreadBandIO band win (XY bx by) = readMasked band read_\n where\n XY sx sy = winSize win\n XY xoff yoff = winMin win\n read_ :: forall a'. GDALType a' => RasterBandH -> IO (St.Vector a')\n read_ b = do\n vec <- Stm.new (bx*by)\n let dtype = fromEnumC (dataType (Proxy :: Proxy a'))\n Stm.unsafeWith vec $ \\ptr -> do\n throwIfError_ \"readBandIO\" $ do\n e <- {#call RasterAdviseRead as ^#}\n b\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (fromIntegral bx)\n (fromIntegral by)\n dtype\n (castPtr nullPtr)\n if toEnumC e == CE_None\n then {#call RasterIO as ^#}\n b\n (fromEnumC GF_Read)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n dtype\n 0\n 0\n else return e\n St.unsafeFreeze vec\n{-# INLINE readBandIO #-}\n\nreadMasked\n :: GDALType a\n => Band s t\n -> (forall a'. GDALType a' => RasterBandH -> IO (St.Vector a'))\n -> IO (Vector (Value a))\nreadMasked band reader = withLockedBandPtr band $ \\bPtr -> do\n flags <- {#call unsafe GetMaskFlags as ^#} bPtr\n reader bPtr >>= fmap stToUValue . mask flags bPtr\n where\n mask fs\n | hasFlag fs MaskPerDataset = useMaskBand\n | hasFlag fs MaskNoData = useNoData\n | hasFlag fs MaskAllValid = useAsIs\n | otherwise = useMaskBand\n hasFlag fs f = fromEnumC f .&. fs == fromEnumC f\n useAsIs _ = return . St.map Value\n useNoData bPtr vs = do\n mNodata <- bandNodataValueIO bPtr\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toCDouble v == nd then NoData else Value v\n return (St.map toValue vs)\n useMaskBand bPtr vs = do\n ms <- {#call GetMaskBand as ^#} bPtr >>= reader :: IO (St.Vector Word8)\n return $ St.zipWith (\\v m -> if m\/=0 then Value v else NoData) vs ms\n{-# INLINE readMasked #-}\n\n{#enum define MaskFlag { GMF_ALL_VALID as MaskAllValid\n , GMF_PER_DATASET as MaskPerDataset\n , GMF_ALPHA as MaskAlpha\n , GMF_NODATA as MaskNoData\n } deriving (Eq,Bounded,Show) #}\n\n\nwriteBand :: forall s a. GDALType a\n => RWBand s\n -> Window Int\n -> Size\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band win sz@(XY bx by) uvec = liftIO $\n withLockedBandPtr band $ \\bPtr -> do\n bNodata <- fmap (maybe nodata fromCDouble) (bandNodataValueIO bPtr)\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) (uToStValue uvec)\n XY sx sy = winSize win\n XY xoff yoff = winMin win\n if nElems \/= len\n then throwBindingException (InvalidRasterSize sz)\n else withForeignPtr fp $ \\ptr -> do\n throwIfError_ \"writeBand\" $\n {#call RasterIO as ^#}\n bPtr\n (fromEnumC GF_Write)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (dataType (Proxy :: Proxy a)))\n 0\n 0\n{-# INLINE writeBand #-}\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t -> BlockIx -> GDAL s (Vector (Value a))\nreadBandBlock band blockIx = do\n checkType band (Proxy :: Proxy a)\n liftIO $ readMasked band $ \\b -> do\n vec <- Stm.new (bandBlockLen band)\n Stm.unsafeWith vec $ \\ptr ->\n throwIfError_ \"readBandBlock\" $\n {#call ReadBlock as ^#} b x y (castPtr ptr)\n St.unsafeFreeze vec\n where XY x y = fmap fromIntegral blockIx\n{-# INLINE readBandBlock #-}\n\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s t -> GDAL s b\nfoldl' f = foldlM' (\\acc -> return . f acc)\n{-# INLINE foldl' #-}\n\nifoldl'\n :: forall s t a b. GDALType a\n => (b -> BlockIx -> Value a -> b) -> b -> Band s t -> GDAL s b\nifoldl' f = ifoldlM' (\\acc ix -> return . f acc ix)\n{-# INLINE ifoldl' #-}\n\nfoldlM'\n :: forall s t a b. GDALType a\n => (b -> Value a -> IO b) -> b -> Band s t -> GDAL s b\nfoldlM' f = ifoldlM' (\\acc _ -> f acc)\n{-# INLINE foldlM' #-}\n\nifoldlM'\n :: forall s t a b. GDALType a\n => (b -> BlockIx -> Value a -> IO b) -> b -> Band s t -> GDAL s b\nifoldlM' f initialAcc band = do\n checkType band (Proxy :: Proxy a)\n liftIO $ do\n mNodata <- bandNodataValueIO (unBand band)\n fp <- mallocForeignPtrArray (sx*sy)\n withForeignPtr fp $ \\ptr -> throwIfError \"ifoldM'\" $ do\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toCDouble v == nd then NoData else Value v\n goB !iB !jB !acc\n | iB < nx = do\n void $ withLockedBandPtr band $ \\b ->\n {#call ReadBlock as ^#}\n b (fromIntegral iB) (fromIntegral jB) (castPtr ptr)\n go 0 0 acc >>= goB (iB+1) jB\n | jB+1 < ny = goB 0 (jB+1) acc\n | otherwise = return acc\n where\n applyTo i j a = f a ix . toValue =<< peekElemOff ptr (j*sx+i)\n where ix = XY (iB*sx+i) (jB*sy+j)\n stopx\n | mx \/= 0 && iB==nx-1 = mx\n | otherwise = sx\n stopy\n | my \/= 0 && jB==ny-1 = my\n | otherwise = sy\n go !i !j !acc'\n | i < stopx = applyTo i j acc' >>= go (i+1) j\n | j+1 < stopy = go 0 (j+1) acc'\n | otherwise = return acc'\n goB 0 0 initialAcc\n where\n !(XY mx my) = liftA2 mod (bandSize band) (bandBlockSize band)\n !(XY nx ny) = bandBlockCount band\n !(XY sx sy) = bandBlockSize band\n{-# INLINE ifoldlM' #-}\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s -> BlockIx -> Vector (Value a) -> GDAL s ()\nwriteBandBlock band blockIx uvec = do\n checkType band (Proxy :: Proxy a)\n liftIO $ withLockedBandPtr band $ \\b -> do\n bNodata <- fmap (maybe nodata fromCDouble) (bandNodataValueIO b)\n let (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) (uToStValue uvec)\n nElems = bandBlockLen band\n if nElems \/= len\n then throwBindingException (InvalidBlockSize len)\n else withForeignPtr fp $ \\ptr ->\n throwIfError_ \"writeBandBlock\" $\n {#call WriteBlock as ^#} b x y (castPtr ptr)\n where XY x y = fmap fromIntegral blockIx\n{-# INLINE writeBandBlock #-}\n\n\n\ninstance GDALType Word8 where\n dataType _ = GDT_Byte\n nodata = maxBound\n toCDouble = fromIntegral\n fromCDouble = truncate\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Word16 where\n dataType _ = GDT_UInt16\n nodata = maxBound\n toCDouble = fromIntegral\n fromCDouble = truncate\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Word32 where\n dataType _ = GDT_UInt32\n nodata = maxBound\n toCDouble = fromIntegral\n fromCDouble = truncate\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int16 where\n dataType _ = GDT_Int16\n nodata = minBound\n toCDouble = fromIntegral\n fromCDouble = truncate\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int32 where\n dataType _ = GDT_Int32\n nodata = minBound\n toCDouble = fromIntegral\n fromCDouble = truncate\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Float where\n dataType _ = GDT_Float32\n nodata = 0\/0\n toCDouble = realToFrac\n fromCDouble = realToFrac\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Double where\n dataType _ = GDT_Float64\n nodata = 0\/0\n toCDouble = realToFrac\n fromCDouble = realToFrac\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\n#ifdef STORABLE_COMPLEX\ninstance GDALType (Complex Int16) where\n dataType _ = GDT_CInt16\n nodata = nodata :+ nodata\n toCDouble = fromIntegral . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n fillBand (r :+ i) = fillRaster (toCDouble r) (toCDouble i)\n {-# INLINE fillBand #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Int32) where\n dataType _ = GDT_CInt32\n nodata = nodata :+ nodata\n toCDouble = fromIntegral . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n fillBand (r :+ i) = fillRaster (toCDouble r) (toCDouble i)\n {-# INLINE fillBand #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Float) where\n dataType _ = GDT_CFloat32\n nodata = nodata :+ nodata\n toCDouble = realToFrac . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n fillBand (r :+ i) = fillRaster (toCDouble r) (toCDouble i)\n {-# INLINE fillBand #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Double) where\n dataType _ = GDT_CFloat64\n nodata = nodata :+ nodata\n toCDouble = realToFrac . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n fillBand (r :+ i) = fillRaster (toCDouble r) (toCDouble i)\n {-# INLINE fillBand #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE TemplateHaskell #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE ExistentialQuantification #-}\n\nmodule GDAL.Internal.GDAL (\n GDALType (..)\n , GDALRasterException (..)\n , DataType (..)\n , Geotransform (..)\n , Driver (..)\n , Dataset\n , DatasetH (..)\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , RasterBandH (..)\n , nullDatasetH\n , allRegister\n , destroyDriverManager\n , create\n , createMem\n , flushCache\n , openReadOnly\n , openReadWrite\n , unsafeToReadOnly\n , createCopy\n , driverCreationOptionList\n\n , dataTypeSize\n , dataTypeByName\n , dataTypeUnion\n , dataTypeIsComplex\n\n , datasetSize\n , reifyDataType\n , datasetProjection\n , setDatasetProjection\n , datasetGeotransform\n , setDatasetGeotransform\n , datasetBandCount\n\n , bandDataType\n , reifyBandDataType\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , allBand\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , readBand\n , readBandPure\n , readBandBlock\n , writeBand\n , writeBandBlock\n\n , foldl'\n , foldlM'\n , ifoldl'\n , ifoldlM'\n\n , unDataset\n , unBand\n , withLockedDatasetPtr\n , withLockedBandPtr\n , newDerivedDatasetHandle\n , version\n) where\n\n{#context lib = \"gdal\" prefix = \"GDAL\" #}\n\nimport Control.Applicative ((<$>), (<*>), liftA2, pure)\nimport Control.DeepSeq (NFData(rnf))\nimport Control.Exception (Exception(..), throw)\nimport Control.Monad (liftM, liftM2, when, void)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Data.Int (Int16, Int32)\nimport Data.Bits ((.&.))\nimport Data.Complex (Complex(..), realPart)\nimport Data.Coerce (coerce)\nimport Data.Proxy (Proxy(..))\nimport Data.Text (Text)\nimport Data.Typeable (Typeable)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Unboxed (Vector)\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (toBool, fromBool, with)\n\nimport System.IO.Unsafe (unsafePerformIO)\nimport System.Process (readProcess)\nimport Data.Char (toUpper)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.Util\n{#import GDAL.Internal.CPLError#}\n{#import GDAL.Internal.CPLString#}\n{#import GDAL.Internal.CPLProgress#}\nimport GDAL.Internal.OGRError\nimport GDAL.Internal.OSR\n\n\n#include \"gdal.h\"\n\n$(let names = fmap (words . map toUpper) $\n readProcess \"gdal-config\" [\"--formats\"] \"\"\n in createEnum \"Driver\" names)\n\n{#enum define Version { GDAL_VERSION_MAJOR as VersionMajor\n , GDAL_VERSION_MINOR as VersionMinor } #}\n\nversion :: (Int, Int)\nversion = (fromEnum VersionMajor, fromEnum VersionMinor)\n\ndata GDALRasterException\n = InvalidRasterSize !Size\n | InvalidBlockSize !Int\n | InvalidDataType !DataType\n | InvalidProjection !OGRException\n | InvalidDriverOptions ![Text]\n | NullDataset\n | CopyStopped\n | UnknownRasterDataType\n | UnsupportedRasterDataType !DataType\n deriving (Typeable, Show, Eq)\n\ninstance NFData GDALRasterException where\n rnf a = a `seq` () -- All fields are already strict so no need to rnf them\n\ninstance Exception GDALRasterException where\n toException = bindingExceptionToException\n fromException = bindingExceptionFromException\n\n\nclass (Storable a, Show a, Typeable a) => GDALType a where\n dataType :: Proxy a -> DataType\n -- | default nodata value when writing to bands with no datavalue set\n nodata :: a\n -- | how to convert to double for use in setBandNodataValue\n toCDouble :: a -> CDouble\n -- | how to convert from double for use with bandNodataValue\n fromCDouble :: CDouble -> a\n\n fillBand :: a -> RWBand s -> GDAL s ()\n fillBand v = fillRaster (toCDouble v) (toCDouble v)\n {-# INLINE fillBand #-}\n\n{#enum DataType {} omit (GDT_TypeCount) deriving (Eq, Show, Bounded) #}\n\ninstance NFData DataType where\n rnf a = a `seq`()\n\n{#fun pure unsafe GetDataTypeSize as dataTypeSize\n { fromEnumC `DataType' } -> `Int' #}\n\n{#fun pure unsafe DataTypeIsComplex as ^\n { fromEnumC `DataType' } -> `Bool' #}\n\n{#fun pure unsafe GetDataTypeByName as dataTypeByName\n { `String' } -> `DataType' toEnumC #}\n\n{#fun pure unsafe DataTypeUnion as ^\n { fromEnumC `DataType', fromEnumC `DataType' } -> `DataType' toEnumC #}\n\n\n{#enum Access {} deriving (Eq, Show) #}\n\n{#enum RWFlag {} deriving (Eq, Show) #}\n\n{#pointer DatasetH newtype #}\n\nnullDatasetH :: DatasetH\nnullDatasetH = DatasetH nullPtr\n\nderiving instance Eq DatasetH\n\nnewtype Dataset s (t::AccessMode)\n = Dataset (Mutex, DatasetH)\n\nunDataset :: Dataset s t -> DatasetH\nunDataset (Dataset (_,p)) = p\n\nwithLockedDatasetPtr\n :: Dataset s t -> (DatasetH -> IO b) -> IO b\nwithLockedDatasetPtr (Dataset (m,p)) f = withMutex m (f p)\n\ntype RODataset s = Dataset s ReadOnly\ntype RWDataset s = Dataset s ReadWrite\n\n{#pointer RasterBandH newtype #}\n\nnewtype Band s (t::AccessMode) = Band (Mutex, RasterBandH)\n\nunBand :: Band s t -> RasterBandH\nunBand (Band (_,p)) = p\n\nreifyBandDataType\n :: Band s t -> (forall a. GDALType a => Proxy a -> b) -> b\nreifyBandDataType b = reifyDataType (bandDataType b)\n\nwithLockedBandPtr\n :: Band s t -> (RasterBandH -> IO b) -> IO b\nwithLockedBandPtr (Band (m,p)) f = withMutex m (f p)\n\ntype ROBand s = Band s ReadOnly\ntype RWBand s = Band s ReadWrite\n\n\n{#pointer DriverH newtype#}\n\n{#fun AllRegister as ^ {} -> `()' #}\n\n{#fun DestroyDriverManager as ^ {} -> `()'#}\n\ndriverByName :: Driver -> IO DriverH\ndriverByName s = withCString (show s) {#call unsafe GetDriverByName as ^#}\n\ndriverCreationOptionList :: Driver -> String\ndriverCreationOptionList driver = unsafePerformIO $ do\n d <- driverByName driver\n {#call GetDriverCreationOptionList\tas ^#} d >>= peekCString\n\nvalidateCreationOptions :: DriverH -> Ptr CString -> IO ()\nvalidateCreationOptions d o = do\n (valid,errs) <- collectMessages $\n liftM toBool ({#call GDALValidateCreationOptions as ^ #} d o)\n let msgs = map (\\(_,_,m)->m) errs\n when (not valid) (throwBindingException (InvalidDriverOptions msgs))\n\ncreate\n :: Driver -> String -> Size -> Int -> DataType -> OptionList\n -> GDAL s (Dataset s ReadWrite)\ncreate _ _ _ _ GDT_Unknown _ =\n throwBindingException UnknownRasterDataType\ncreate drv path (XY nx ny) bands dtype options = do\n ptr <- liftIO $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC dtype\n d <- driverByName drv\n throwIfError \"create\" $ withOptionList options $ \\opts -> do\n validateCreationOptions d opts\n {#call GDALCreate as ^#} d path' nx' ny' bands' dtype' opts\n newDatasetHandle ptr\n\nopenReadOnly :: String -> GDAL s (RODataset s)\nopenReadOnly p = openWithMode GA_ReadOnly p\n\nopenReadWrite :: String -> GDAL s (RWDataset s)\nopenReadWrite p = openWithMode GA_Update p\n\nopenWithMode :: Access -> String -> GDAL s (Dataset s t)\nopenWithMode m path = do\n dsH <- liftIO $ withCString path $ \\p ->\n throwIfError \"GDALOpen\" ({#call GDALOpen as ^#} p (fromEnumC m))\n newDatasetHandle dsH\n\nunsafeToReadOnly :: RWDataset s -> GDAL s (RODataset s)\nunsafeToReadOnly ds = flushCache ds >> return (coerce ds)\n\ncreateCopy\n :: Driver -> String -> Dataset s t -> Bool -> OptionList\n -> Maybe ProgressFun -> GDAL s (RWDataset s)\ncreateCopy driver path ds strict options progressFun = do\n mPtr <- liftIO $ do\n d <- driverByName driver\n throwIfError \"createCopy\" $\n withCString path $ \\p ->\n withProgressFun progressFun $ \\pFunc ->\n withOptionList options $ \\o -> do\n validateCreationOptions d o\n withLockedDatasetPtr ds $ \\dsPtr ->\n {#call GDALCreateCopy as ^#}\n d p dsPtr (fromBool strict) o pFunc (castPtr nullPtr)\n maybe (throwBindingException CopyStopped) newDatasetHandle mPtr\n\n\nnewDatasetHandle :: DatasetH -> GDAL s (Dataset s t)\nnewDatasetHandle dh\n | dh==nullDatasetH = throwBindingException NullDataset\n | otherwise = do\n registerFinalizer (safeCloseDataset dh)\n m <- liftIO newMutex\n return $ Dataset (m,dh)\n\nnewDerivedDatasetHandle\n :: Dataset s t' -> DatasetH -> GDAL s (Dataset s t)\nnewDerivedDatasetHandle (Dataset (m,_)) dh\n | dh==nullDatasetH = throwBindingException NullDataset\n | otherwise = do\n registerFinalizer (safeCloseDataset dh)\n return $ Dataset (m,dh)\n\nsafeCloseDataset :: DatasetH -> IO ()\nsafeCloseDataset p = do\n count <- {#call unsafe DereferenceDataset as ^#} p\n when (count < 1) $ do\n void ({#call unsafe ReferenceDataset as ^#} p)\n {#call GDALClose as ^#} p\n\ncreateMem\n :: Size -> Int -> DataType -> OptionList -> GDAL s (Dataset s ReadWrite)\ncreateMem = create MEM \"\"\n\nflushCache :: forall s. RWDataset s -> GDAL s ()\nflushCache = liftIO . flip withLockedDatasetPtr {#call GDALFlushCache as ^#}\n\ndatasetSize :: Dataset s t -> Size\ndatasetSize ds =\n fmap fromIntegral $\n XY ({#call pure unsafe GetRasterXSize as ^#} (unDataset ds))\n ({#call pure unsafe GetRasterYSize as ^#} (unDataset ds))\n\ndatasetProjection :: Dataset s t -> GDAL s (Maybe SpatialReference)\ndatasetProjection ds = do\n let d = unDataset ds\n srs <- liftIO ({#call unsafe GetProjectionRef as ^#} d >>= peekCString)\n if null srs\n then return Nothing\n else either (throwBindingException . InvalidProjection)\n (return . Just)\n (fromWkt srs)\n\n\nsetDatasetProjection :: RWDataset s -> SpatialReference -> GDAL s ()\nsetDatasetProjection ds srs =\n liftIO $\n throwIfError_ \"setDatasetProjection\" $\n withLockedDatasetPtr ds $\n withCString (toWkt srs) . {#call SetProjection as ^#}\n\n\ndata Geotransform\n = Geotransform {\n gtXOff :: !Double\n , gtXDelta :: !Double\n , gtXRot :: !Double\n , gtYOff :: !Double\n , gtYRot :: !Double\n , gtYDelta :: !Double\n } deriving (Eq, Show)\n\ninstance Storable Geotransform where\n sizeOf _ = sizeOf (undefined :: CDouble) * 6\n alignment _ = alignment (undefined :: CDouble)\n poke pGt (Geotransform g0 g1 g2 g3 g4 g5) = do\n let p = castPtr pGt :: Ptr CDouble\n pokeElemOff p 0 (realToFrac g0)\n pokeElemOff p 1 (realToFrac g1)\n pokeElemOff p 2 (realToFrac g2)\n pokeElemOff p 3 (realToFrac g3)\n pokeElemOff p 4 (realToFrac g4)\n pokeElemOff p 5 (realToFrac g5)\n peek pGt = do\n let p = castPtr pGt :: Ptr CDouble\n Geotransform <$> liftM realToFrac (peekElemOff p 0)\n <*> liftM realToFrac (peekElemOff p 1)\n <*> liftM realToFrac (peekElemOff p 2)\n <*> liftM realToFrac (peekElemOff p 3)\n <*> liftM realToFrac (peekElemOff p 4)\n <*> liftM realToFrac (peekElemOff p 5)\n\n\ndatasetGeotransform :: Dataset s t -> GDAL s (Maybe Geotransform)\ndatasetGeotransform ds = liftIO $ alloca $ \\p -> do\n ret <- {#call unsafe GetGeoTransform as ^#} (unDataset ds) (castPtr p)\n if toEnumC ret == GDAL.Internal.CPLError.None\n then liftM Just (peek p)\n else return Nothing\n\n\nsetDatasetGeotransform :: RWDataset s -> Geotransform -> GDAL s ()\nsetDatasetGeotransform ds gt = liftIO $\n throwIfError_ \"setDatasetGeotransform\" $\n withLockedDatasetPtr ds $ \\d ->\n with gt ({#call SetGeoTransform as ^#} d . castPtr)\n\n\ndatasetBandCount :: Dataset s t -> GDAL s Int\ndatasetBandCount =\n liftM fromIntegral . liftIO . {#call unsafe GetRasterCount as ^#} . unDataset\n\ngetBand :: Int -> Dataset s t -> GDAL s (Band s t)\ngetBand b (Dataset (m,dp)) = liftIO $ do\n p <- throwIfError \"getBand\" $ {#call GetRasterBand as ^#} dp (fromIntegral b)\n return (Band (m, p))\n\n\nreifyDataType :: DataType -> (forall a. GDALType a => Proxy a -> b) -> b\nreifyDataType dt f =\n case dt of\n GDT_Unknown -> throw (bindingExceptionToException UnknownRasterDataType)\n GDT_Byte -> f (Proxy :: Proxy Word8)\n GDT_UInt16 -> f (Proxy :: Proxy Word16)\n GDT_UInt32 -> f (Proxy :: Proxy Word32)\n GDT_Int16 -> f (Proxy :: Proxy Int16)\n GDT_Int32 -> f (Proxy :: Proxy Int32)\n GDT_Float32 -> f (Proxy :: Proxy Float)\n GDT_Float64 -> f (Proxy :: Proxy Double)\n#ifdef STORABLE_COMPLEX\n GDT_CInt16 -> f (Proxy :: Proxy (Complex Int16))\n GDT_CInt32 -> f (Proxy :: Proxy (Complex Int32))\n GDT_CFloat32 -> f (Proxy :: Proxy (Complex Float))\n GDT_CFloat64 -> f (Proxy :: Proxy (Complex Double))\n#else\n d -> throw\n (bindingExceptionToException (UnsupportedRasterDataType d))\n#endif\n\n\n\n\nbandDataType :: Band s t -> DataType\nbandDataType = toEnumC . {#call pure unsafe GetRasterDataType as ^#} . unBand\n\nbandBlockSize :: (Band s t) -> Size\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n {#call unsafe GetBlockSize as ^#} (unBand band) xPtr yPtr\n liftM (fmap fromIntegral) (liftM2 XY (peek xPtr) (peek yPtr))\n\nbandBlockLen :: Band s t -> Int\nbandBlockLen = (\\(XY x y) -> x*y) . bandBlockSize\n\nbandSize :: Band s a -> Size\nbandSize band =\n fmap fromIntegral $\n XY ({#call pure unsafe GetRasterBandXSize as ^#} (unBand band))\n ({#call pure unsafe GetRasterBandYSize as ^#} (unBand band))\n\nallBand :: Band s a -> Window Int\nallBand = Window (pure 0) . bandSize\n\nbandBlockCount :: Band s t -> XY Int\nbandBlockCount b = fmap ceiling $ liftA2 ((\/) :: Double -> Double -> Double)\n (fmap fromIntegral (bandSize b))\n (fmap fromIntegral (bandBlockSize b))\n\ncheckType\n :: GDALType a => Band s t -> Proxy a -> GDAL s ()\ncheckType b p\n | rt == bt = return ()\n | otherwise = throwBindingException (InvalidDataType bt)\n where rt = dataType p\n bt = bandDataType b\n\nbandNodataValue :: GDALType a => Band s t -> GDAL s (Maybe a)\nbandNodataValue b =\n liftM (fmap fromCDouble) (liftIO (bandNodataValueIO (unBand b)))\n\nbandNodataValueIO :: RasterBandH -> IO (Maybe CDouble)\nbandNodataValueIO b = alloca $ \\p -> do\n value <- {#call unsafe GetRasterNoDataValue as ^#} b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n{-# INLINE bandNodataValueIO #-}\n\n\nsetBandNodataValue :: GDALType a => RWBand s -> a -> GDAL s ()\nsetBandNodataValue b v =\n liftIO $\n throwIfError_ \"setBandNodataValue\" $\n {#call SetRasterNoDataValue as ^#} (unBand b) (toCDouble v)\n\nfillRaster :: CDouble -> CDouble -> RWBand s -> GDAL s ()\nfillRaster r i b =\n liftIO $\n throwIfError_ \"fillRaster\" $\n {#call GDALFillRaster as ^#} (unBand b) r i\n\n\nreadBand :: forall s t a. GDALType a\n => (Band s t)\n -> Window Int\n -> Size\n -> GDAL s (Vector (Value a))\nreadBand band win size = liftIO $ readBandIO band win size\n{-# INLINE readBand #-}\n\nreadBandPure :: forall s a. GDALType a\n => (ROBand s)\n -> Window Int\n -> Size\n -> Vector (Value a)\nreadBandPure band win size = unsafePerformIO $ readBandIO band win size\n{-# INLINE readBandPure #-}\n\nreadBandIO :: forall s t a. GDALType a\n => (Band s t)\n -> Window Int\n -> Size\n -> IO (Vector (Value a))\nreadBandIO band win (XY bx by) = readMasked band read_\n where\n XY sx sy = winSize win\n XY xoff yoff = winMin win\n read_ :: forall a'. GDALType a' => RasterBandH -> IO (St.Vector a')\n read_ b = do\n vec <- Stm.new (bx*by)\n let dtype = fromEnumC (dataType (Proxy :: Proxy a'))\n Stm.unsafeWith vec $ \\ptr -> do\n throwIfError_ \"readBandIO\" $ do\n e <- {#call RasterAdviseRead as ^#}\n b\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (fromIntegral bx)\n (fromIntegral by)\n dtype\n (castPtr nullPtr)\n if toEnumC e == CE_None\n then {#call RasterIO as ^#}\n b\n (fromEnumC GF_Read)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n dtype\n 0\n 0\n else return e\n St.unsafeFreeze vec\n{-# INLINE readBandIO #-}\n\nreadMasked\n :: GDALType a\n => Band s t\n -> (forall a'. GDALType a' => RasterBandH -> IO (St.Vector a'))\n -> IO (Vector (Value a))\nreadMasked band reader = withLockedBandPtr band $ \\bPtr -> do\n flags <- {#call unsafe GetMaskFlags as ^#} bPtr\n reader bPtr >>= fmap stToUValue . mask flags bPtr\n where\n mask fs\n | hasFlag fs MaskPerDataset = useMaskBand\n | hasFlag fs MaskNoData = useNoData\n | hasFlag fs MaskAllValid = useAsIs\n | otherwise = useMaskBand\n hasFlag fs f = fromEnumC f .&. fs == fromEnumC f\n useAsIs _ = return . St.map Value\n useNoData bPtr vs = do\n mNodata <- bandNodataValueIO bPtr\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toCDouble v == nd then NoData else Value v\n return (St.map toValue vs)\n useMaskBand bPtr vs = do\n ms <- {#call GetMaskBand as ^#} bPtr >>= reader :: IO (St.Vector Word8)\n return $ St.zipWith (\\v m -> if m\/=0 then Value v else NoData) vs ms\n{-# INLINE readMasked #-}\n\n{#enum define MaskFlag { GMF_ALL_VALID as MaskAllValid\n , GMF_PER_DATASET as MaskPerDataset\n , GMF_ALPHA as MaskAlpha\n , GMF_NODATA as MaskNoData\n } deriving (Eq,Bounded,Show) #}\n\n\nwriteBand :: forall s a. GDALType a\n => RWBand s\n -> Window Int\n -> Size\n -> Vector (Value a)\n -> GDAL s ()\nwriteBand band win sz@(XY bx by) uvec = liftIO $\n withLockedBandPtr band $ \\bPtr -> do\n bNodata <- fmap (maybe nodata fromCDouble) (bandNodataValueIO bPtr)\n let nElems = bx * by\n (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) (uToStValue uvec)\n XY sx sy = winSize win\n XY xoff yoff = winMin win\n if nElems \/= len\n then throwBindingException (InvalidRasterSize sz)\n else withForeignPtr fp $ \\ptr -> do\n throwIfError_ \"writeBand\" $\n {#call RasterIO as ^#}\n bPtr\n (fromEnumC GF_Write)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (dataType (Proxy :: Proxy a)))\n 0\n 0\n{-# INLINE writeBand #-}\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s t -> BlockIx -> GDAL s (Vector (Value a))\nreadBandBlock band blockIx = do\n checkType band (Proxy :: Proxy a)\n liftIO $ readMasked band $ \\b -> do\n vec <- Stm.new (bandBlockLen band)\n Stm.unsafeWith vec $ \\ptr ->\n throwIfError_ \"readBandBlock\" $\n {#call ReadBlock as ^#} b x y (castPtr ptr)\n St.unsafeFreeze vec\n where XY x y = fmap fromIntegral blockIx\n{-# INLINE readBandBlock #-}\n\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s t -> GDAL s b\nfoldl' f = foldlM' (\\acc -> return . f acc)\n{-# INLINE foldl' #-}\n\nifoldl'\n :: forall s t a b. GDALType a\n => (b -> BlockIx -> Value a -> b) -> b -> Band s t -> GDAL s b\nifoldl' f = ifoldlM' (\\acc ix -> return . f acc ix)\n{-# INLINE ifoldl' #-}\n\nfoldlM'\n :: forall s t a b. GDALType a\n => (b -> Value a -> IO b) -> b -> Band s t -> GDAL s b\nfoldlM' f = ifoldlM' (\\acc _ -> f acc)\n{-# INLINE foldlM' #-}\n\nifoldlM'\n :: forall s t a b. GDALType a\n => (b -> BlockIx -> Value a -> IO b) -> b -> Band s t -> GDAL s b\nifoldlM' f initialAcc band = do\n checkType band (Proxy :: Proxy a)\n liftIO $ do\n mNodata <- bandNodataValueIO (unBand band)\n fp <- mallocForeignPtrArray (sx*sy)\n withForeignPtr fp $ \\ptr -> throwIfError \"ifoldM'\" $ do\n let toValue = case mNodata of\n Nothing -> Value\n Just nd ->\n \\v -> if toCDouble v == nd then NoData else Value v\n goB !iB !jB !acc\n | iB < nx = do\n void $ withLockedBandPtr band $ \\b ->\n {#call ReadBlock as ^#}\n b (fromIntegral iB) (fromIntegral jB) (castPtr ptr)\n go 0 0 acc >>= goB (iB+1) jB\n | jB+1 < ny = goB 0 (jB+1) acc\n | otherwise = return acc\n where\n applyTo i j a = f a ix . toValue =<< peekElemOff ptr (j*sx+i)\n where ix = XY (iB*sx+i) (jB*sy+j)\n stopx\n | mx \/= 0 && iB==nx-1 = mx\n | otherwise = sx\n stopy\n | my \/= 0 && jB==ny-1 = my\n | otherwise = sy\n go !i !j !acc'\n | i < stopx = applyTo i j acc' >>= go (i+1) j\n | j+1 < stopy = go 0 (j+1) acc'\n | otherwise = return acc'\n goB 0 0 initialAcc\n where\n !(XY mx my) = liftA2 mod (bandSize band) (bandBlockSize band)\n !(XY nx ny) = bandBlockCount band\n !(XY sx sy) = bandBlockSize band\n{-# INLINE ifoldlM' #-}\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s -> BlockIx -> Vector (Value a) -> GDAL s ()\nwriteBandBlock band blockIx uvec = do\n checkType band (Proxy :: Proxy a)\n liftIO $ withLockedBandPtr band $ \\b -> do\n bNodata <- fmap (maybe nodata fromCDouble) (bandNodataValueIO b)\n let (fp, len) = St.unsafeToForeignPtr0 vec\n vec = St.map (fromValue bNodata) (uToStValue uvec)\n nElems = bandBlockLen band\n if nElems \/= len\n then throwBindingException (InvalidBlockSize len)\n else withForeignPtr fp $ \\ptr ->\n throwIfError_ \"writeBandBlock\" $\n {#call WriteBlock as ^#} b x y (castPtr ptr)\n where XY x y = fmap fromIntegral blockIx\n{-# INLINE writeBandBlock #-}\n\n\n\ninstance GDALType Word8 where\n dataType _ = GDT_Byte\n nodata = maxBound\n toCDouble = fromIntegral\n fromCDouble = truncate\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Word16 where\n dataType _ = GDT_UInt16\n nodata = maxBound\n toCDouble = fromIntegral\n fromCDouble = truncate\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Word32 where\n dataType _ = GDT_UInt32\n nodata = maxBound\n toCDouble = fromIntegral\n fromCDouble = truncate\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int16 where\n dataType _ = GDT_Int16\n nodata = minBound\n toCDouble = fromIntegral\n fromCDouble = truncate\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Int32 where\n dataType _ = GDT_Int32\n nodata = minBound\n toCDouble = fromIntegral\n fromCDouble = truncate\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Float where\n dataType _ = GDT_Float32\n nodata = 0\/0\n toCDouble = realToFrac\n fromCDouble = realToFrac\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType Double where\n dataType _ = GDT_Float64\n nodata = 0\/0\n toCDouble = realToFrac\n fromCDouble = realToFrac\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\n#ifdef STORABLE_COMPLEX\ninstance GDALType (Complex Int16) where\n dataType _ = GDT_CInt16\n nodata = nodata :+ nodata\n toCDouble = fromIntegral . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n fillBand (r :+ i) = fillRaster (toCDouble r) (toCDouble i)\n {-# INLINE fillBand #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Int32) where\n dataType _ = GDT_CInt32\n nodata = nodata :+ nodata\n toCDouble = fromIntegral . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n fillBand (r :+ i) = fillRaster (toCDouble r) (toCDouble i)\n {-# INLINE fillBand #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Float) where\n dataType _ = GDT_CFloat32\n nodata = nodata :+ nodata\n toCDouble = realToFrac . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n fillBand (r :+ i) = fillRaster (toCDouble r) (toCDouble i)\n {-# INLINE fillBand #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n\ninstance GDALType (Complex Double) where\n dataType _ = GDT_CFloat64\n nodata = nodata :+ nodata\n toCDouble = realToFrac . realPart\n fromCDouble d = fromCDouble d :+ fromCDouble d\n fillBand (r :+ i) = fillRaster (toCDouble r) (toCDouble i)\n {-# INLINE fillBand #-}\n {-# INLINE toCDouble #-}\n {-# INLINE fromCDouble #-}\n#endif\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"289190cf8005382bb4f552ff213219b880cb4e6c","subject":"display timing in fold example","message":"display timing in fold example\n\nIgnore-this: 6ac7695be202842e29ca1e8b3b907e5e\n\ndarcs-hash:20091228070050-dcabc-4012893c79aa59a92538086723a0a28290b7a47c.gz\n","repos":"mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"examples\/src\/fold\/Fold.chs","new_file":"examples\/src\/fold\/Fold.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n--\n-- Module : Fold\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Reduce a vector to a single value\n--\n--------------------------------------------------------------------------------\n\nmodule Main where\n\n#include \"fold.h\"\n\n-- Friends\nimport C2HS\nimport Time\nimport RandomVector\n\n-- System\nimport Control.Exception\nimport qualified Foreign.CUDA.Runtime as CUDA\n\n\n--------------------------------------------------------------------------------\n-- Reference\n--------------------------------------------------------------------------------\n\nfoldRef :: Num e => [e] -> IO e\nfoldRef xs = do\n (t,r) <- benchmark 100 (evaluate (foldl (+) 0 xs)) (return ())\n putStrLn $ \"== Reference: \" ++ show (timeIn millisecond t) ++ \"ms\"\n return r\n\n--------------------------------------------------------------------------------\n-- CUDA\n--------------------------------------------------------------------------------\n\n--\n-- Note that this requires two memory copies: once from a Haskell list to the C\n-- heap, and from there into the graphics card memory. See the `bandwidthTest'\n-- example for the atrocious performance of this operation.\n--\n-- For this test, cheat a little and just time the pure computation.\n--\nfoldCUDA :: [Float] -> IO Float\nfoldCUDA xs = do\n let len = length xs\n CUDA.withListArray xs $ \\d_xs -> do\n (t,r) <- benchmark 100 (fold_plusf d_xs len) CUDA.sync\n putStrLn $ \"== CUDA: \" ++ show (timeIn millisecond t) ++ \"ms\"\n return r\n\n{# fun unsafe fold_plusf\n { withDP* `CUDA.DevicePtr Float'\n , `Int'\n }\n -> `Float' cFloatConv #}\n where\n withDP p a = CUDA.withDevicePtr p $ \\p' -> a (castPtr p')\n\n\n--------------------------------------------------------------------------------\n-- Main\n--------------------------------------------------------------------------------\n\nmain :: IO ()\nmain = do\n dev <- CUDA.get\n props <- CUDA.props dev\n putStrLn $ \"Using device \" ++ show dev ++ \": \" ++ CUDA.deviceName props\n\n xs <- randomList 30000\n ref <- foldRef xs\n cuda <- foldCUDA xs\n\n putStrLn $ \"== Validating: \" ++ if ((ref-cuda)\/ref) < 0.0001 then \"Ok!\" else \"INVALID!\"\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n--\n-- Module : Fold\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Reduce a vector to a single value\n--\n--------------------------------------------------------------------------------\n\nmodule Main where\n\n#include \"fold.h\"\n\n-- Friends\nimport C2HS\nimport RandomVector\n\n-- System\nimport Control.Exception\nimport qualified Foreign.CUDA.Runtime as CUDA\n\n\n--------------------------------------------------------------------------------\n-- Reference\n--------------------------------------------------------------------------------\n\nfoldRef :: (Num e, Storable e) => [e] -> IO e\nfoldRef xs = evaluate (foldl (+) 0 xs)\n\n--------------------------------------------------------------------------------\n-- CUDA\n--------------------------------------------------------------------------------\n\n--\n-- Note that this requires two memory copies: once from a Haskell list to the C\n-- heap, and from there into the graphics card memory.\n--\nfoldCUDA :: [Float] -> IO Float\nfoldCUDA xs =\n let len = length xs in\n CUDA.withListArray xs $ \\d_xs -> fold_plusf d_xs len\n\n{# fun unsafe fold_plusf\n { withDP* `CUDA.DevicePtr Float'\n , `Int'\n }\n -> `Float' cFloatConv #}\n where\n withDP p a = CUDA.withDevicePtr p $ \\p' -> a (castPtr p')\n\n\n--------------------------------------------------------------------------------\n-- Main\n--------------------------------------------------------------------------------\n\nmain :: IO ()\nmain = do\n putStrLn \"== Generating random numbers\"\n xs <- randomList 30000\n\n putStrLn \"== Generating reference solution\"\n ref <- foldRef xs\n\n putStrLn \"== Testing CUDA\"\n cuda <- foldCUDA xs\n\n putStr \"== Validating: \"\n putStrLn $ if ((ref-cuda)\/ref) < 0.0001 then \"Ok!\" else \"INVALID!\"\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"c4fb947e4c3bb1bf985e8751abe69a47fcf22d5e","subject":"Tie the knot on metadata","message":"Tie the knot on metadata\n","repos":"travitch\/llvm-analysis,wangxiayang\/llvm-analysis,wangxiayang\/llvm-analysis,travitch\/llvm-analysis","old_file":"src\/Data\/LLVM\/Private\/Parser\/Unmarshal.chs","new_file":"src\/Data\/LLVM\/Private\/Parser\/Unmarshal.chs","new_contents":"-- | This module converts the C form of the LLVM IR into a fully\n-- referential Haskell version of the IR. The translation is slightly\n-- lossy around integral types in some cases, as Haskell Ints do not\n-- have the same range as C ints. In the vast majority of cases this\n-- should not really be an issue, but it is possible to lose\n-- information. If it is an issue it can be changed.\n{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, RankNTypes #-}\nmodule Data.LLVM.Private.Parser.Unmarshal ( parseLLVMBitcodeFile ) where\n\n#include \"c++\/marshal.h\"\n\nimport Prelude hiding ( catch )\n\nimport Control.Applicative\nimport Control.DeepSeq\nimport Control.Exception\nimport Control.Monad.State\nimport Data.Array.Storable\nimport Data.ByteString.Char8 ( ByteString )\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport Data.IORef\nimport Data.Map ( Map )\nimport Data.Set ( Set )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.Maybe ( catMaybes, isJust )\nimport Data.Typeable\nimport Foreign.C\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Data.LLVM.Private.Parser.Options\nimport Data.LLVM.Types\nimport Data.LLVM.Private.Types.Dwarf\n\ndata TranslationException = TooManyReturnValues\n | InvalidBranchInst\n | InvalidSwitchLayout\n | InvalidIndirectBranchOperands\n | KnotTyingFailure ValueTag\n | TypeKnotTyingFailure TypeTag\n | MetaKnotFailure\n | InvalidSelectArgs !Int\n | InvalidExtractElementInst !Int\n | InvalidInsertElementInst !Int\n | InvalidShuffleVectorInst !Int\n | InvalidFunctionInTranslateValue\n | InvalidAliasInTranslateValue\n | InvalidGlobalVarInTranslateValue\n | InvalidBinaryOp !Int\n | InvalidUnaryOp !Int\n | InvalidGEPInst !Int\n | InvalidExtractValueInst !Int\n | InvalidInsertValueInst !Int\n deriving (Show, Typeable)\ninstance Exception TranslationException\n\n\n{#enum TypeTag {} deriving (Show, Eq) #}\n{#enum ValueTag {underscoreToCase} deriving (Show, Eq) #}\n{#enum MetaTag {underscoreToCase} deriving (Show, Eq) #}\n\ndata CModule\n{#pointer *CModule as ModulePtr -> CModule #}\n\ncModuleIdentifier :: ModulePtr -> IO ByteString\ncModuleIdentifier m = ({#get CModule->moduleIdentifier#} m) >>= BS.packCString\n\ncModuleDataLayout :: ModulePtr -> IO ByteString\ncModuleDataLayout m = ({#get CModule->moduleDataLayout#} m) >>= BS.packCString\n\ncModuleTargetTriple :: ModulePtr -> IO ByteString\ncModuleTargetTriple m = ({#get CModule->targetTriple#} m) >>= BS.packCString\n\ncModuleInlineAsm :: ModulePtr -> IO ByteString\ncModuleInlineAsm m = ({#get CModule->moduleInlineAsm#} m) >>= BS.packCString\n\ncModuleHasError :: ModulePtr -> IO Bool\ncModuleHasError m = toBool <$> ({#get CModule->hasError#} m)\n\ncModuleErrorMessage :: ModulePtr -> IO (Maybe String)\ncModuleErrorMessage m = do\n hasError <- cModuleHasError m\n case hasError of\n True -> do\n msgPtr <- ({#get CModule->errMsg#} m)\n s <- peekCString msgPtr\n return (Just s)\n False -> return Nothing\n\ncModuleLittleEndian :: ModulePtr -> IO Bool\ncModuleLittleEndian m = toBool <$> ({#get CModule->littleEndian#} m)\n\ncModulePointerSize :: ModulePtr -> IO Int\ncModulePointerSize m = fromIntegral <$> ({#get CModule->pointerSize#} m)\n\ncModuleGlobalVariables :: ModulePtr -> IO [ValuePtr]\ncModuleGlobalVariables m =\n peekArray m {#get CModule->globalVariables#} {#get CModule->numGlobalVariables#}\n\ncModuleGlobalAliases :: ModulePtr -> IO [ValuePtr]\ncModuleGlobalAliases m =\n peekArray m ({#get CModule->globalAliases#}) ({#get CModule->numGlobalAliases#})\n\ncModuleFunctions :: ModulePtr -> IO [ValuePtr]\ncModuleFunctions m =\n peekArray m ({#get CModule->functions#}) ({#get CModule->numFunctions#})\n\npeekArray :: forall a b c e . (Integral c, Storable e) =>\n a -> (a -> IO (Ptr b)) -> (a -> IO c) -> IO [e]\npeekArray obj arrAccessor sizeAccessor = do\n nElts <- sizeAccessor obj\n arrPtr <- arrAccessor obj\n case nElts == 0 || arrPtr == nullPtr of\n True -> return []\n False -> do\n fArrPtr <- newForeignPtr_ (castPtr arrPtr)\n arr <- unsafeForeignPtrToStorableArray fArrPtr (1, fromIntegral nElts)\n getElems arr\n\ndata CType\n{#pointer *CType as TypePtr -> CType #}\ncTypeTag :: TypePtr -> IO TypeTag\ncTypeTag t = toEnum . fromIntegral <$> {#get CType->typeTag#} t\ncTypeSize :: TypePtr -> IO Int\ncTypeSize t = fromIntegral <$> {#get CType->size#} t\ncTypeIsVarArg :: TypePtr -> IO Bool\ncTypeIsVarArg t = toBool <$> {#get CType->isVarArg#} t\ncTypeIsPacked :: TypePtr -> IO Bool\ncTypeIsPacked t = toBool <$> {#get CType->isPacked#} t\ncTypeList :: TypePtr -> IO [TypePtr]\ncTypeList t =\n peekArray t {#get CType->typeList#} {#get CType->typeListLen#}\ncTypeInner :: TypePtr -> IO TypePtr\ncTypeInner = {#get CType->innerType#}\ncTypeName :: TypePtr -> IO String\ncTypeName t = {#get CType->name#} t >>= peekCString\ncTypeAddrSpace :: TypePtr -> IO Int\ncTypeAddrSpace t = fromIntegral <$> {#get CType->addrSpace#} t\n\ndata CValue\n{#pointer *CValue as ValuePtr -> CValue #}\n\ncValueTag :: ValuePtr -> IO ValueTag\ncValueTag v = toEnum . fromIntegral <$> ({#get CValue->valueTag#} v)\ncValueType :: ValuePtr -> IO TypePtr\ncValueType = {#get CValue->valueType#}\ncValueName :: ValuePtr -> IO (Maybe Identifier)\ncValueName v = do\n tag <- cValueTag v\n namePtr <- ({#get CValue->name#}) v\n case namePtr == nullPtr of\n True -> return Nothing\n False -> do\n name <- BS.packCString namePtr\n case tag of\n ValFunction -> return $! (Just . makeGlobalIdentifier) name\n ValGlobalvariable -> return $! (Just . makeGlobalIdentifier) name\n ValAlias -> return $! (Just . makeGlobalIdentifier) name\n _ -> return $! (Just . makeLocalIdentifier) name\ncValueMetadata :: ValuePtr -> IO [MetaPtr]\ncValueMetadata v = peekArray v {#get CValue->md#} {#get CValue->numMetadata#}\ncValueData :: ValuePtr -> IO (Ptr ())\ncValueData = {#get CValue->data#}\n\ndata CMeta\n{#pointer *CMeta as MetaPtr -> CMeta #}\n\ncMetaTypeTag :: MetaPtr -> IO MetaTag\ncMetaTypeTag v = toEnum . fromIntegral <$> {#get CMeta->metaTag #} v\n\ncMetaTag :: MetaPtr -> IO DW_TAG\ncMetaTag p = dw_tag <$> {#get CMeta->tag#} p\n\ncMetaArrayElts :: MetaPtr -> IO [MetaPtr]\ncMetaArrayElts p =\n peekArray p {#get CMeta->u.metaArrayInfo.arrayElts#} {#get CMeta->u.metaArrayInfo.arrayLen#}\ncMetaEnumeratorName :: MetaPtr -> KnotMonad ByteString\ncMetaEnumeratorName = shareString {#get CMeta->u.metaEnumeratorInfo.enumName#}\ncMetaEnumeratorValue :: MetaPtr -> IO Int64\ncMetaEnumeratorValue p = fromIntegral <$> {#get CMeta->u.metaEnumeratorInfo.enumValue#} p\ncMetaGlobalContext :: MetaPtr -> IO MetaPtr\ncMetaGlobalContext = {#get CMeta->u.metaGlobalInfo.context #}\ncMetaGlobalName :: MetaPtr -> KnotMonad ByteString\ncMetaGlobalName = shareString {#get CMeta->u.metaGlobalInfo.name#}\ncMetaGlobalDisplayName :: MetaPtr -> KnotMonad ByteString\ncMetaGlobalDisplayName = shareString {#get CMeta->u.metaGlobalInfo.displayName#}\ncMetaGlobalLinkageName :: MetaPtr -> KnotMonad ByteString\ncMetaGlobalLinkageName = shareString {#get CMeta->u.metaGlobalInfo.linkageName#}\ncMetaGlobalCompileUnit :: MetaPtr -> IO MetaPtr\ncMetaGlobalCompileUnit = {#get CMeta->u.metaGlobalInfo.compileUnit#}\ncMetaGlobalLine :: MetaPtr -> IO Int32\ncMetaGlobalLine p = fromIntegral <$> {#get CMeta->u.metaGlobalInfo.lineNumber#} p\ncMetaGlobalType :: MetaPtr -> IO MetaPtr\ncMetaGlobalType = {#get CMeta->u.metaGlobalInfo.globalType#}\ncMetaGlobalIsLocal :: MetaPtr -> IO Bool\ncMetaGlobalIsLocal p = toBool <$> {#get CMeta->u.metaGlobalInfo.isLocalToUnit#} p\ncMetaGlobalIsDefinition :: MetaPtr -> IO Bool\ncMetaGlobalIsDefinition p = toBool <$> {#get CMeta->u.metaGlobalInfo.isDefinition#} p\ncMetaLocationLine :: MetaPtr -> IO Int32\ncMetaLocationLine p = fromIntegral <$> {#get CMeta->u.metaLocationInfo.lineNumber#} p\ncMetaLocationColumn :: MetaPtr -> IO Int32\ncMetaLocationColumn p = fromIntegral <$> {#get CMeta->u.metaLocationInfo.columnNumber#} p\ncMetaLocationScope :: MetaPtr -> IO MetaPtr\ncMetaLocationScope = {#get CMeta->u.metaLocationInfo.scope#}\ncMetaSubrangeLo :: MetaPtr -> IO Int64\ncMetaSubrangeLo p = fromIntegral <$> {#get CMeta->u.metaSubrangeInfo.lo#} p\ncMetaSubrangeHi :: MetaPtr -> IO Int64\ncMetaSubrangeHi p = fromIntegral <$> {#get CMeta->u.metaSubrangeInfo.hi#} p\ncMetaTemplateTypeContext :: MetaPtr -> IO MetaPtr\ncMetaTemplateTypeContext = {#get CMeta->u.metaTemplateTypeInfo.context#}\ncMetaTemplateTypeName :: MetaPtr -> KnotMonad ByteString\ncMetaTemplateTypeName = shareString {#get CMeta->u.metaTemplateTypeInfo.name#}\ncMetaTemplateTypeType :: MetaPtr -> IO MetaPtr\ncMetaTemplateTypeType = {#get CMeta->u.metaTemplateTypeInfo.type#}\ncMetaTemplateTypeLine :: MetaPtr -> IO Int32\ncMetaTemplateTypeLine p = fromIntegral <$> {#get CMeta->u.metaTemplateTypeInfo.lineNumber#} p\ncMetaTemplateTypeColumn :: MetaPtr -> IO Int32\ncMetaTemplateTypeColumn p = fromIntegral <$> {#get CMeta->u.metaTemplateTypeInfo.columnNumber#} p\ncMetaTemplateValueContext :: MetaPtr -> IO MetaPtr\ncMetaTemplateValueContext = {#get CMeta->u.metaTemplateValueInfo.context#}\ncMetaTemplateValueName :: MetaPtr -> KnotMonad ByteString\ncMetaTemplateValueName = shareString {#get CMeta->u.metaTemplateValueInfo.name#}\ncMetaTemplateValueType :: MetaPtr -> IO MetaPtr\ncMetaTemplateValueType = {#get CMeta->u.metaTemplateValueInfo.type#}\ncMetaTemplateValueValue :: MetaPtr -> IO Int64\ncMetaTemplateValueValue p = fromIntegral <$> {#get CMeta->u.metaTemplateValueInfo.value#} p\ncMetaTemplateValueLine :: MetaPtr -> IO Int32\ncMetaTemplateValueLine p = fromIntegral <$> {#get CMeta->u.metaTemplateValueInfo.lineNumber#} p\ncMetaTemplateValueColumn :: MetaPtr -> IO Int32\ncMetaTemplateValueColumn p = fromIntegral <$> {#get CMeta->u.metaTemplateValueInfo.columnNumber#} p\ncMetaVariableContext :: MetaPtr -> IO MetaPtr\ncMetaVariableContext = {#get CMeta->u.metaVariableInfo.context#}\ncMetaVariableName :: MetaPtr -> KnotMonad ByteString\ncMetaVariableName = shareString {#get CMeta->u.metaVariableInfo.name#}\ncMetaVariableCompileUnit :: MetaPtr -> IO MetaPtr\ncMetaVariableCompileUnit = {#get CMeta->u.metaVariableInfo.compileUnit#}\ncMetaVariableLine :: MetaPtr -> IO Int32\ncMetaVariableLine p = fromIntegral <$> {#get CMeta->u.metaVariableInfo.lineNumber#} p\ncMetaVariableArgNumber :: MetaPtr -> IO Int32\ncMetaVariableArgNumber p = fromIntegral <$> {#get CMeta->u.metaVariableInfo.argNumber#} p\ncMetaVariableType :: MetaPtr -> IO MetaPtr\ncMetaVariableType = {#get CMeta->u.metaVariableInfo.type#}\ncMetaVariableIsArtificial :: MetaPtr -> IO Bool\ncMetaVariableIsArtificial p = toBool <$> {#get CMeta->u.metaVariableInfo.isArtificial#} p\ncMetaVariableHasComplexAddress :: MetaPtr -> IO Bool\ncMetaVariableHasComplexAddress p = toBool <$> {#get CMeta->u.metaVariableInfo.hasComplexAddress #} p\ncMetaVariableAddrElements :: MetaPtr -> IO [Int64]\ncMetaVariableAddrElements p = do\n ca <- cMetaVariableHasComplexAddress p\n case ca of\n True -> peekArray p {#get CMeta->u.metaVariableInfo.addrElements#} {#get CMeta->u.metaVariableInfo.numAddrElements#}\n False -> return []\ncMetaVariableIsBlockByRefVar :: MetaPtr -> IO Bool\ncMetaVariableIsBlockByRefVar p = toBool <$> {#get CMeta->u.metaVariableInfo.isBlockByRefVar#} p\ncMetaCompileUnitLanguage :: MetaPtr -> IO DW_LANG\ncMetaCompileUnitLanguage p = dw_lang <$> {#get CMeta->u.metaCompileUnitInfo.language#} p\ncMetaCompileUnitFilename :: MetaPtr -> KnotMonad ByteString\ncMetaCompileUnitFilename = shareString {#get CMeta->u.metaCompileUnitInfo.filename#}\ncMetaCompileUnitDirectory :: MetaPtr -> KnotMonad ByteString\ncMetaCompileUnitDirectory = shareString {#get CMeta->u.metaCompileUnitInfo.directory#}\ncMetaCompileUnitProducer :: MetaPtr -> KnotMonad ByteString\ncMetaCompileUnitProducer = shareString {#get CMeta->u.metaCompileUnitInfo.producer#}\ncMetaCompileUnitIsMain :: MetaPtr -> IO Bool\ncMetaCompileUnitIsMain p = toBool <$> {#get CMeta->u.metaCompileUnitInfo.isMain#} p\ncMetaCompileUnitIsOptimized :: MetaPtr -> IO Bool\ncMetaCompileUnitIsOptimized p = toBool <$> {#get CMeta->u.metaCompileUnitInfo.isOptimized#} p\ncMetaCompileUnitFlags :: MetaPtr -> KnotMonad ByteString\ncMetaCompileUnitFlags = shareString {#get CMeta->u.metaCompileUnitInfo.flags#}\ncMetaCompileUnitRuntimeVersion :: MetaPtr -> IO Int32\ncMetaCompileUnitRuntimeVersion p = fromIntegral <$> {#get CMeta->u.metaCompileUnitInfo.runtimeVersion#} p\ncMetaFileFilename :: MetaPtr -> KnotMonad ByteString\ncMetaFileFilename = shareString {#get CMeta->u.metaFileInfo.filename#}\ncMetaFileDirectory :: MetaPtr -> KnotMonad ByteString\ncMetaFileDirectory = shareString {#get CMeta->u.metaFileInfo.directory#}\ncMetaFileCompileUnit :: MetaPtr -> IO MetaPtr\ncMetaFileCompileUnit = {#get CMeta->u.metaFileInfo.compileUnit#}\ncMetaLexicalBlockContext :: MetaPtr -> IO MetaPtr\ncMetaLexicalBlockContext = {#get CMeta->u.metaLexicalBlockInfo.context#}\ncMetaLexicalBlockLine :: MetaPtr -> IO Int32\ncMetaLexicalBlockLine p = fromIntegral <$> {#get CMeta->u.metaLexicalBlockInfo.lineNumber#} p\ncMetaLexicalBlockColumn :: MetaPtr -> IO Int32\ncMetaLexicalBlockColumn p = fromIntegral <$> {#get CMeta->u.metaLexicalBlockInfo.columnNumber#} p\ncMetaNamespaceContext :: MetaPtr -> IO MetaPtr\ncMetaNamespaceContext = {#get CMeta->u.metaNamespaceInfo.context#}\ncMetaNamespaceName :: MetaPtr -> KnotMonad ByteString\ncMetaNamespaceName = shareString {#get CMeta->u.metaNamespaceInfo.name#}\ncMetaNamespaceCompileUnit :: MetaPtr -> IO MetaPtr\ncMetaNamespaceCompileUnit = {#get CMeta->u.metaNamespaceInfo.compileUnit#}\ncMetaNamespaceLine :: MetaPtr -> IO Int32\ncMetaNamespaceLine p = fromIntegral <$> {#get CMeta->u.metaNamespaceInfo.lineNumber#} p\ncMetaSubprogramContext :: MetaPtr -> IO MetaPtr\ncMetaSubprogramContext = {#get CMeta->u.metaSubprogramInfo.context#}\ncMetaSubprogramName :: MetaPtr -> KnotMonad ByteString\ncMetaSubprogramName = shareString {#get CMeta->u.metaSubprogramInfo.name#}\ncMetaSubprogramDisplayName :: MetaPtr -> KnotMonad ByteString\ncMetaSubprogramDisplayName = shareString {#get CMeta->u.metaSubprogramInfo.displayName#}\ncMetaSubprogramLinkageName :: MetaPtr -> KnotMonad ByteString\ncMetaSubprogramLinkageName = shareString {#get CMeta->u.metaSubprogramInfo.linkageName#}\ncMetaSubprogramCompileUnit :: MetaPtr -> IO MetaPtr\ncMetaSubprogramCompileUnit = {#get CMeta->u.metaSubprogramInfo.compileUnit#}\ncMetaSubprogramLine :: MetaPtr -> IO Int32\ncMetaSubprogramLine p = fromIntegral <$> {#get CMeta->u.metaSubprogramInfo.lineNumber#} p\ncMetaSubprogramType :: MetaPtr -> IO MetaPtr\ncMetaSubprogramType = {#get CMeta->u.metaSubprogramInfo.type#}\ncMetaSubprogramIsLocal :: MetaPtr -> IO Bool\ncMetaSubprogramIsLocal p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isLocalToUnit#} p\ncMetaSubprogramIsDefinition :: MetaPtr -> IO Bool\ncMetaSubprogramIsDefinition p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isDefinition#} p\ncMetaSubprogramVirtuality :: MetaPtr -> IO DW_VIRTUALITY\ncMetaSubprogramVirtuality p = dw_virtuality <$> {#get CMeta->u.metaSubprogramInfo.virtuality#} p\ncMetaSubprogramVirtualIndex :: MetaPtr -> IO Int32\ncMetaSubprogramVirtualIndex p = fromIntegral <$> {#get CMeta->u.metaSubprogramInfo.virtualIndex#} p\ncMetaSubprogramContainingType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaSubprogramContainingType = optionalField {#get CMeta->u.metaSubprogramInfo.containingType#}\ncMetaSubprogramIsArtificial :: MetaPtr -> IO Bool\ncMetaSubprogramIsArtificial p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isArtificial#} p\ncMetaSubprogramIsPrivate :: MetaPtr -> IO Bool\ncMetaSubprogramIsPrivate p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isPrivate#} p\ncMetaSubprogramIsProtected :: MetaPtr -> IO Bool\ncMetaSubprogramIsProtected p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isProtected#} p\ncMetaSubprogramIsExplicit :: MetaPtr -> IO Bool\ncMetaSubprogramIsExplicit p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isExplicit#} p\ncMetaSubprogramIsPrototyped :: MetaPtr -> IO Bool\ncMetaSubprogramIsPrototyped p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isPrototyped#} p\ncMetaSubprogramIsOptimized :: MetaPtr -> IO Bool\ncMetaSubprogramIsOptimized p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isOptimized#} p\ncMetaTypeContext :: MetaPtr -> IO MetaPtr\ncMetaTypeContext = {#get CMeta->u.metaTypeInfo.context#}\ncMetaTypeName :: MetaPtr -> KnotMonad ByteString\ncMetaTypeName = shareString {#get CMeta->u.metaTypeInfo.name#}\ncMetaTypeCompileUnit :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeCompileUnit = optionalField {#get CMeta->u.metaTypeInfo.compileUnit#}\ncMetaTypeFile :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeFile = optionalField {#get CMeta->u.metaTypeInfo.file#}\ncMetaTypeLine :: MetaPtr -> IO Int32\ncMetaTypeLine p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.lineNumber#} p\ncMetaTypeSize :: MetaPtr -> IO Int64\ncMetaTypeSize p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.sizeInBits#} p\ncMetaTypeAlign :: MetaPtr -> IO Int64\ncMetaTypeAlign p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.alignInBits#} p\ncMetaTypeOffset :: MetaPtr -> IO Int64\ncMetaTypeOffset p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.offsetInBits#} p\ncMetaTypeFlags :: MetaPtr -> IO Int32\ncMetaTypeFlags p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.flags#} p\ncMetaTypeIsPrivate :: MetaPtr -> IO Bool\ncMetaTypeIsPrivate p = toBool <$> {#get CMeta->u.metaTypeInfo.isPrivate#} p\ncMetaTypeIsProtected :: MetaPtr -> IO Bool\ncMetaTypeIsProtected p = toBool <$> {#get CMeta->u.metaTypeInfo.isProtected#} p\ncMetaTypeIsForward :: MetaPtr -> IO Bool\ncMetaTypeIsForward p = toBool <$> {#get CMeta->u.metaTypeInfo.isForward#} p\ncMetaTypeIsByRefStruct :: MetaPtr -> IO Bool\ncMetaTypeIsByRefStruct p = toBool <$> {#get CMeta->u.metaTypeInfo.isByRefStruct#} p\ncMetaTypeIsVirtual :: MetaPtr -> IO Bool\ncMetaTypeIsVirtual p = toBool <$> {#get CMeta->u.metaTypeInfo.isVirtual#} p\ncMetaTypeIsArtificial :: MetaPtr -> IO Bool\ncMetaTypeIsArtificial p = toBool <$> {#get CMeta->u.metaTypeInfo.isArtificial#} p\ncMetaTypeEncoding :: MetaPtr -> IO DW_ATE\ncMetaTypeEncoding p = dw_ate <$> {#get CMeta->u.metaTypeInfo.encoding#} p\ncMetaTypeDerivedFrom :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeDerivedFrom = optionalField {#get CMeta->u.metaTypeInfo.typeDerivedFrom#}\ncMetaTypeCompositeComponents :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeCompositeComponents = optionalField {#get CMeta->u.metaTypeInfo.typeArray#}\ncMetaTypeRuntimeLanguage :: MetaPtr -> IO Int32\ncMetaTypeRuntimeLanguage p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.runTimeLang#} p\ncMetaTypeContainingType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeContainingType = optionalField {#get CMeta->u.metaTypeInfo.containingType#}\ncMetaTypeTemplateParams :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeTemplateParams = optionalField {#get CMeta->u.metaTypeInfo.templateParams#}\n\noptionalField :: (a -> IO (Ptr b)) -> a -> IO (Maybe (Ptr b))\noptionalField accessor p = do\n v <- accessor p\n case v == nullPtr of\n True -> return Nothing\n False -> return (Just v)\n\n-- | This helper converts C char* strings into ByteStrings, sharing\n-- identical bytestrings on the Haskell side. This is a simple\n-- space-saving optimization (assuming the entire cache is garbage\n-- collected)\nshareString :: (a -> IO CString) -> a -> KnotMonad ByteString\nshareString accessor ptr = do\n str <- liftIO $ accessor ptr >>= BS.packCString\n s <- get\n let cache = stringCache s\n case M.lookup str cache of\n Just cval -> return cval\n Nothing -> do\n put s { stringCache = M.insert str str cache }\n return str\n\ndata CGlobalInfo\n{#pointer *CGlobalInfo as GlobalInfoPtr -> CGlobalInfo #}\ncGlobalIsExternal :: GlobalInfoPtr -> IO Bool\ncGlobalIsExternal g = toBool <$> ({#get CGlobalInfo->isExternal#} g)\ncGlobalAlignment :: GlobalInfoPtr -> IO Int64\ncGlobalAlignment g = fromIntegral <$> ({#get CGlobalInfo->alignment#} g)\ncGlobalVisibility :: GlobalInfoPtr -> IO VisibilityStyle\ncGlobalVisibility g = toEnum . fromIntegral <$> ({#get CGlobalInfo->visibility#} g)\ncGlobalLinkage :: GlobalInfoPtr -> IO LinkageType\ncGlobalLinkage g = toEnum . fromIntegral <$> ({#get CGlobalInfo->linkage#} g)\ncGlobalSection :: GlobalInfoPtr -> IO (Maybe ByteString)\ncGlobalSection g = do\n s <- {#get CGlobalInfo->section#} g\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just bs\ncGlobalInitializer :: GlobalInfoPtr -> IO ValuePtr\ncGlobalInitializer = {#get CGlobalInfo->initializer#}\ncGlobalIsThreadLocal :: GlobalInfoPtr -> IO Bool\ncGlobalIsThreadLocal g = toBool <$> ({#get CGlobalInfo->isThreadLocal#} g)\ncGlobalAliasee :: GlobalInfoPtr -> IO ValuePtr\ncGlobalAliasee = {#get CGlobalInfo->aliasee#}\ncGlobalIsConstant :: GlobalInfoPtr -> IO Bool\ncGlobalIsConstant g = toBool <$> {#get CGlobalInfo->isConstant#} g\n\ndata CFunctionInfo\n{#pointer *CFunctionInfo as FunctionInfoPtr -> CFunctionInfo #}\ncFunctionIsExternal :: FunctionInfoPtr -> IO Bool\ncFunctionIsExternal f = toBool <$> {#get CFunctionInfo->isExternal#} f\ncFunctionAlignment :: FunctionInfoPtr -> IO Int64\ncFunctionAlignment f = fromIntegral <$> {#get CFunctionInfo->alignment#} f\ncFunctionVisibility :: FunctionInfoPtr -> IO VisibilityStyle\ncFunctionVisibility f = toEnum . fromIntegral <$> {#get CFunctionInfo->visibility#} f\ncFunctionLinkage :: FunctionInfoPtr -> IO LinkageType\ncFunctionLinkage f = toEnum . fromIntegral <$> {#get CFunctionInfo->linkage#} f\ncFunctionSection :: FunctionInfoPtr -> IO (Maybe ByteString)\ncFunctionSection f = do\n s <- {#get CFunctionInfo->section#} f\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just bs\ncFunctionIsVarArg :: FunctionInfoPtr -> IO Bool\ncFunctionIsVarArg f = toBool <$> {#get CFunctionInfo->isVarArg#} f\ncFunctionCallingConvention :: FunctionInfoPtr -> IO CallingConvention\ncFunctionCallingConvention f = toEnum . fromIntegral <$> {#get CFunctionInfo->callingConvention#} f\ncFunctionGCName :: FunctionInfoPtr -> IO (Maybe ByteString)\ncFunctionGCName f = do\n s <- {#get CFunctionInfo->gcName#} f\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just bs\ncFunctionArguments :: FunctionInfoPtr -> IO [ValuePtr]\ncFunctionArguments f =\n peekArray f {#get CFunctionInfo->arguments#} {#get CFunctionInfo->argListLen#}\ncFunctionBlocks :: FunctionInfoPtr -> IO [ValuePtr]\ncFunctionBlocks f =\n peekArray f {#get CFunctionInfo->body#} {#get CFunctionInfo->blockListLen#}\n\ndata CArgInfo\n{#pointer *CArgumentInfo as ArgInfoPtr -> CArgInfo #}\ncArgInfoHasSRet :: ArgInfoPtr -> IO Bool\ncArgInfoHasSRet a = toBool <$> ({#get CArgumentInfo->hasSRet#} a)\ncArgInfoHasByVal :: ArgInfoPtr -> IO Bool\ncArgInfoHasByVal a = toBool <$> ({#get CArgumentInfo->hasByVal#} a)\ncArgInfoHasNest :: ArgInfoPtr -> IO Bool\ncArgInfoHasNest a = toBool <$> ({#get CArgumentInfo->hasNest#} a)\ncArgInfoHasNoAlias :: ArgInfoPtr -> IO Bool\ncArgInfoHasNoAlias a = toBool <$> ({#get CArgumentInfo->hasNoAlias#} a)\ncArgInfoHasNoCapture :: ArgInfoPtr -> IO Bool\ncArgInfoHasNoCapture a = toBool <$> ({#get CArgumentInfo->hasNoCapture#} a)\n\ndata CBasicBlockInfo\n{#pointer *CBasicBlockInfo as BasicBlockPtr -> CBasicBlockInfo #}\n\ncBasicBlockInstructions :: BasicBlockPtr -> IO [ValuePtr]\ncBasicBlockInstructions b =\n peekArray b {#get CBasicBlockInfo->instructions#} {#get CBasicBlockInfo->blockLen#}\n\ndata CInlineAsmInfo\n{#pointer *CInlineAsmInfo as InlineAsmInfoPtr -> CInlineAsmInfo #}\n\ncInlineAsmString :: InlineAsmInfoPtr -> IO ByteString\ncInlineAsmString a =\n ({#get CInlineAsmInfo->asmString#} a) >>= BS.packCString\ncInlineAsmConstraints :: InlineAsmInfoPtr -> IO ByteString\ncInlineAsmConstraints a =\n ({#get CInlineAsmInfo->constraintString#} a) >>= BS.packCString\n\ndata CBlockAddrInfo\n{#pointer *CBlockAddrInfo as BlockAddrInfoPtr -> CBlockAddrInfo #}\n\ncBlockAddrFunc :: BlockAddrInfoPtr -> IO ValuePtr\ncBlockAddrFunc = {#get CBlockAddrInfo->func #}\ncBlockAddrBlock :: BlockAddrInfoPtr -> IO ValuePtr\ncBlockAddrBlock = {#get CBlockAddrInfo->block #}\n\ndata CAggregateInfo\n{#pointer *CConstAggregate as AggregateInfoPtr -> CAggregateInfo #}\n\ncAggregateValues :: AggregateInfoPtr -> IO [ValuePtr]\ncAggregateValues a =\n peekArray a {#get CConstAggregate->constants#} {#get CConstAggregate->numElements#}\n\ndata CConstFP\n{#pointer *CConstFP as FPInfoPtr -> CConstFP #}\ncFPVal :: FPInfoPtr -> IO Double\ncFPVal f = realToFrac <$> ({#get CConstFP->val#} f)\n\ndata CConstInt\n{#pointer *CConstInt as IntInfoPtr -> CConstInt #}\ncIntVal :: IntInfoPtr -> IO Integer\ncIntVal i = fromIntegral <$> ({#get CConstInt->val#} i)\n\ndata CInstructionInfo\n{#pointer *CInstructionInfo as InstInfoPtr -> CInstructionInfo #}\ncInstructionOperands :: InstInfoPtr -> IO [ValuePtr]\ncInstructionOperands i =\n peekArray i {#get CInstructionInfo->operands#} {#get CInstructionInfo->numOperands#}\ncInstructionArithFlags :: InstInfoPtr -> IO ArithFlags\ncInstructionArithFlags o = toEnum . fromIntegral <$> {#get CInstructionInfo->flags#} o\ncInstructionAlign :: InstInfoPtr -> IO Int64\ncInstructionAlign u = fromIntegral <$> {#get CInstructionInfo->align#} u\ncInstructionIsVolatile :: InstInfoPtr -> IO Bool\ncInstructionIsVolatile u = toBool <$> {#get CInstructionInfo->isVolatile#} u\ncInstructionAddrSpace :: InstInfoPtr -> IO Int\ncInstructionAddrSpace u = fromIntegral <$> {#get CInstructionInfo->addrSpace#} u\ncInstructionCmpPred :: InstInfoPtr -> IO CmpPredicate\ncInstructionCmpPred c = toEnum . fromIntegral <$> {#get CInstructionInfo->cmpPred#} c\ncInstructionInBounds :: InstInfoPtr -> IO Bool\ncInstructionInBounds g = toBool <$> {#get CInstructionInfo->inBounds#} g\ncInstructionIndices :: InstInfoPtr -> IO [Int]\ncInstructionIndices i =\n peekArray i {#get CInstructionInfo->indices#} {#get CInstructionInfo->numIndices#}\n\ndata CConstExprInfo\n{#pointer *CConstExprInfo as ConstExprPtr -> CConstExprInfo #}\ncConstExprTag :: ConstExprPtr -> IO ValueTag\ncConstExprTag e = toEnum . fromIntegral <$> {#get CConstExprInfo->instrType#} e\ncConstExprInstInfo :: ConstExprPtr -> IO InstInfoPtr\ncConstExprInstInfo = {#get CConstExprInfo->ii#}\n\ndata CPHIInfo\n{#pointer *CPHIInfo as PHIInfoPtr -> CPHIInfo #}\ncPHIValues :: PHIInfoPtr -> IO [ValuePtr]\ncPHIValues p =\n peekArray p {#get CPHIInfo->incomingValues#} {#get CPHIInfo->numIncomingValues#}\ncPHIBlocks :: PHIInfoPtr -> IO [ValuePtr]\ncPHIBlocks p =\n peekArray p {#get CPHIInfo->valueBlocks#} {#get CPHIInfo->numIncomingValues#}\n\ndata CCallInfo\n{#pointer *CCallInfo as CallInfoPtr -> CCallInfo #}\ncCallValue :: CallInfoPtr -> IO ValuePtr\ncCallValue = {#get CCallInfo->calledValue #}\ncCallArguments :: CallInfoPtr -> IO [ValuePtr]\ncCallArguments c =\n peekArray c {#get CCallInfo->arguments#} {#get CCallInfo->argListLen#}\ncCallConvention :: CallInfoPtr -> IO CallingConvention\ncCallConvention c = toEnum . fromIntegral <$> {#get CCallInfo->callingConvention#} c\ncCallHasSRet :: CallInfoPtr -> IO Bool\ncCallHasSRet c = toBool <$> {#get CCallInfo->hasSRet#} c\ncCallIsTail :: CallInfoPtr -> IO Bool\ncCallIsTail c = toBool <$> {#get CCallInfo->isTail#} c\ncCallUnwindDest :: CallInfoPtr -> IO ValuePtr\ncCallUnwindDest = {#get CCallInfo->unwindDest#}\ncCallNormalDest :: CallInfoPtr -> IO ValuePtr\ncCallNormalDest = {#get CCallInfo->normalDest#}\n\n-- | Parse the named file into an FFI-friendly representation of an\n-- LLVM module.\n{#fun marshalLLVM { `String', fromBool `Bool' } -> `ModulePtr' id #}\n\n-- | Free all of the resources allocated by 'marshalLLVM'\n{#fun disposeCModule { id `ModulePtr' } -> `()' #}\n\ntype KnotMonad = StateT KnotState IO\ndata KnotState = KnotState { valueMap :: Map IntPtr Value\n , typeMap :: Map IntPtr Type\n , metaMap :: Map IntPtr Metadata\n , idSrc :: IORef Int\n , typeIdSrc :: IORef Int\n , metaIdSrc :: IORef Int\n , result :: Maybe Module\n , visitedTypes :: Set IntPtr\n , visitedMetadata :: Set IntPtr\n , localId :: Int\n , constantTranslationDepth :: Int\n , stringCache :: Map ByteString ByteString\n }\nemptyState :: IORef Int -> IORef Int -> IORef Int -> KnotState\nemptyState r1 r2 r3 =\n KnotState { valueMap = M.empty\n , typeMap = M.empty\n , metaMap = M.empty\n , idSrc = r1\n , typeIdSrc = r2\n , metaIdSrc = r3\n , result = Nothing\n , visitedTypes = S.empty\n , visitedMetadata = S.empty\n , localId = 0\n , constantTranslationDepth = 0\n , stringCache = M.empty\n }\n\nnextId :: KnotMonad Int\nnextId = do\n s <- get\n let r = idSrc s\n thisId <- liftIO $ readIORef r\n liftIO $ modifyIORef r (+1)\n\n return thisId\n\nnextTypeId :: KnotMonad Int\nnextTypeId = do\n s <- get\n let r = typeIdSrc s\n thisId <- liftIO $ readIORef r\n liftIO $ modifyIORef r (+1)\n\n return thisId\n\nnextMetaId :: KnotMonad Int\nnextMetaId = do\n s <- get\n let r = metaIdSrc s\n thisId <- liftIO $ readIORef r\n liftIO $ modifyIORef r (+1)\n\n return thisId\n\n-- | Parse the named LLVM bitcode file into the LLVM form of the IR (a\n-- 'Module'). In the case of an error, a descriptive string will be\n-- returned.\nparseLLVMBitcodeFile :: ParserOptions -> FilePath -> IO (Either String Module)\nparseLLVMBitcodeFile opts bitcodefile = do\n let includeLineNumbers = metaPositionPrecision opts == PositionPrecise\n m <- marshalLLVM bitcodefile includeLineNumbers\n\n hasError <- cModuleHasError m\n case hasError of\n True -> do\n Just err <- cModuleErrorMessage m\n disposeCModule m\n return $ Left err\n False -> catch (doParse m) exHandler\n where\n exHandler :: TranslationException -> IO (Either String Module)\n exHandler ex = return $ Left (show ex)\n doParse m = do\n idref <- newIORef 0\n tref <- newIORef 0\n mref <- newIORef 0\n res <- evalStateT (mfix (tieKnot m)) (emptyState idref tref mref)\n\n disposeCModule m\n case result res of\n Just r -> return $ Right (r `deepseq` r)\n Nothing -> return $ Left \"No module in result\"\n\n\ntieKnot :: ModulePtr -> KnotState -> KnotMonad KnotState\ntieKnot m finalState = do\n modIdent <- liftIO $ cModuleIdentifier m\n dataLayout <- liftIO $ cModuleDataLayout m\n triple <- liftIO $ cModuleTargetTriple m\n inlineAsm <- liftIO $ cModuleInlineAsm m\n\n vars <- liftIO $ cModuleGlobalVariables m\n aliases <- liftIO $ cModuleGlobalAliases m\n funcs <- liftIO $ cModuleFunctions m\n\n vars' <- mapM (translateGlobalVariable finalState) vars\n aliases' <- mapM (translateAlias finalState) aliases\n funcs' <- mapM (translateFunction finalState) funcs\n\n let ir = Module { moduleIdentifier = modIdent\n , moduleDataLayout = dataLayout\n , moduleTarget = triple\n , moduleAssembly = Assembly inlineAsm\n , moduleAliases = aliases'\n , moduleGlobalVariables = vars'\n , moduleFunctions = funcs'\n }\n s <- get\n return s { result = Just ir }\n\ntranslateType :: KnotState -> TypePtr -> KnotMonad Type\ntranslateType finalState tp = do\n s <- get\n let ip = ptrToIntPtr tp\n -- This top-level translateType function is never called\n -- recursively, so the set it introduces here will be valid for the\n -- entire duration of the translateType call. It will be\n -- overwritten on the next call.\n put s { visitedTypes = S.singleton ip }\n case M.lookup ip (typeMap s) of\n Just t -> return t\n Nothing -> do\n t <- translateType' finalState tp\n st <- get\n put st { typeMap = M.insert ip t (typeMap st) }\n return t\n\ntranslateTypeRec :: KnotState -> TypePtr -> KnotMonad Type\ntranslateTypeRec finalState tp = do\n s <- get\n let ip = ptrToIntPtr tp\n -- Mark this type as visited in the state - the pattern match below\n -- refers to the version of the map *before* this insertion.\n put s { visitedTypes = S.insert ip (visitedTypes s) }\n case M.lookup ip (typeMap s) of\n -- If we already translated, just do the simple thing.\n Just t -> return t\n Nothing -> do\n tag <- liftIO $ cTypeTag tp\n case (S.member ip (visitedTypes s), tag) of\n -- This is a cyclic reference - look it up in the final result\n (False, TYPE_NAMED) -> do\n -- If we have never seen a reference to this named type\n -- before, we need to create it.\n name <- liftIO $ cTypeName tp\n itp <- liftIO $ cTypeInner tp\n innerType <- translateTypeRec finalState itp\n\n let t = TypeNamed name innerType\n\n st <- get\n let m = typeMap st\n m' = M.insert (ptrToIntPtr itp) innerType m\n m'' = M.insert ip t m'\n put st { typeMap = m'' }\n\n return t\n\n (True, TYPE_NAMED) -> do\n -- Otherwise, if we *have* seen it before, we can just look\n -- it up. This handles the case of seeing the same named\n -- type for the first time within e.g., a TypeStruct\n return $ M.findWithDefault (throw (TypeKnotTyingFailure tag)) ip (typeMap finalState)\n (True, _) -> do\n -- Here we have detected a cycle in a type that isn't broken\n -- up by a NamedType. We introduce an artificial name (a\n -- type upref) to break the cycle. This makes it a lot\n -- easier to print out types later on, as we don't have to\n -- do on-the-fly cycle detection everywhere we want to work\n -- with types.\n let innerType = M.findWithDefault (throw (TypeKnotTyingFailure tag)) ip (typeMap finalState)\n uprefName <- nextTypeId\n let t = TypeNamed (show uprefName) innerType\n st <- get\n put st { typeMap = M.insert ip t (typeMap st) }\n return t\n _ -> translateType' finalState tp\n\ntranslateType' :: KnotState -> TypePtr -> KnotMonad Type\ntranslateType' finalState tp = do\n s <- get\n tag <- liftIO $ cTypeTag tp\n t <- case tag of\n TYPE_VOID -> return TypeVoid\n TYPE_FLOAT -> return TypeFloat\n TYPE_DOUBLE -> return TypeDouble\n TYPE_X86_FP80 -> return TypeX86FP80\n TYPE_FP128 -> return TypeFP128\n TYPE_PPC_FP128 -> return TypePPCFP128\n TYPE_LABEL -> return TypeLabel\n TYPE_METADATA -> return TypeMetadata\n TYPE_X86_MMX -> return TypeX86MMX\n TYPE_OPAQUE -> return TypeOpaque\n TYPE_INTEGER -> do\n sz <- liftIO $ cTypeSize tp\n return $ TypeInteger sz\n TYPE_FUNCTION -> do\n isVa <- liftIO $ cTypeIsVarArg tp\n rtp <- liftIO $ cTypeInner tp\n argTypePtrs <- liftIO $ cTypeList tp\n\n rType <- translateTypeRec finalState rtp\n argTypes <- mapM (translateTypeRec finalState) argTypePtrs\n\n return $ TypeFunction rType argTypes isVa\n TYPE_STRUCT -> do\n isPacked <- liftIO $ cTypeIsPacked tp\n ptrs <- liftIO $ cTypeList tp\n\n types <- mapM (translateTypeRec finalState) ptrs\n\n return $ TypeStruct types isPacked\n TYPE_ARRAY -> do\n sz <- liftIO $ cTypeSize tp\n itp <- liftIO $ cTypeInner tp\n innerType <- translateTypeRec finalState itp\n\n return $ TypeArray sz innerType\n TYPE_POINTER -> do\n itp <- liftIO $ cTypeInner tp\n addrSpc <- liftIO $ cTypeAddrSpace tp\n innerType <- translateTypeRec finalState itp\n\n return $ TypePointer innerType addrSpc\n TYPE_VECTOR -> do\n sz <- liftIO $ cTypeSize tp\n itp <- liftIO $ cTypeInner tp\n innerType <- translateTypeRec finalState itp\n\n return $ TypeVector sz innerType\n TYPE_NAMED -> do\n name <- liftIO $ cTypeName tp\n itp <- liftIO $ cTypeInner tp\n innerType <- translateTypeRec finalState itp\n\n return $ TypeNamed name innerType\n -- Need to get the latest state that exists after processing all\n -- inner types above, otherwise we'll erase their updates from the\n -- map.\n s' <- get\n put s' { typeMap = M.insert (ptrToIntPtr tp) t (typeMap s') }\n return t\n\nrecordValue :: ValuePtr -> Value -> KnotMonad ()\nrecordValue vp v = do\n s <- get\n let key = ptrToIntPtr vp\n oldMap = valueMap s\n put s { valueMap = M.insert key v oldMap }\n\ntranslateAlias :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateAlias finalState vp = do\n name <- liftIO $ cValueName vp\n typePtr <- liftIO $ cValueType vp\n dataPtr <- liftIO $ cValueData vp\n metaPtr <- liftIO $ cValueMetadata vp\n let dataPtr' = castPtr dataPtr\n\n mds <- mapM (translateMetadata finalState) metaPtr\n\n vis <- liftIO $ cGlobalVisibility dataPtr'\n link <- liftIO $ cGlobalLinkage dataPtr'\n aliasee <- liftIO $ cGlobalAliasee dataPtr'\n\n ta <- translateConstOrRef finalState aliasee\n tt <- translateType finalState typePtr\n\n uid <- nextId\n\n let ga = GlobalAlias { globalAliasLinkage = link\n , globalAliasVisibility = vis\n , globalAliasValue = ta\n }\n v = Value { valueType = tt\n , valueName = name\n , valueMetadata = mds\n , valueContent = ga\n , valueUniqueId = uid\n }\n\n recordValue vp v\n\n return v\n\ntranslateGlobalVariable :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateGlobalVariable finalState vp = do\n name <- liftIO $ cValueName vp\n typePtr <- liftIO $ cValueType vp\n dataPtr <- liftIO $ cValueData vp\n metaPtr <- liftIO $ cValueMetadata vp\n tt <- translateType finalState typePtr\n\n mds <- mapM (translateMetadata finalState) metaPtr\n uid <- nextId\n\n let dataPtr' = castPtr dataPtr\n basicVal = Value { valueName = name\n , valueType = tt\n , valueMetadata = mds\n , valueContent = ExternalValue\n , valueUniqueId = uid\n }\n isExtern <- liftIO $ cGlobalIsExternal dataPtr'\n\n case isExtern of\n True -> do\n recordValue vp basicVal\n return basicVal\n False -> do\n align <- liftIO $ cGlobalAlignment dataPtr'\n vis <- liftIO $ cGlobalVisibility dataPtr'\n link <- liftIO $ cGlobalLinkage dataPtr'\n section <- liftIO $ cGlobalSection dataPtr'\n isThreadLocal <- liftIO $ cGlobalIsThreadLocal dataPtr'\n initializer <- liftIO $ cGlobalInitializer dataPtr'\n isConst <- liftIO $ cGlobalIsConstant dataPtr'\n\n ti <- case initializer == nullPtr of\n True -> return Nothing\n False -> do\n tv <- translateConstOrRef finalState initializer\n return $ Just tv\n\n let gv = GlobalDeclaration { globalVariableLinkage = link\n , globalVariableVisibility = vis\n , globalVariableInitializer = ti\n , globalVariableAlignment = align\n , globalVariableSection = section\n , globalVariableIsThreadLocal = isThreadLocal\n , globalVariableIsConstant = isConst\n }\n v = basicVal { valueContent = gv }\n recordValue vp v\n return v\n\nresetLocalIdCounter :: KnotMonad ()\nresetLocalIdCounter = do\n s <- get\n put s { localId = 0 }\n\ntranslateFunction :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateFunction finalState vp = do\n name <- liftIO $ cValueName vp\n typePtr <- liftIO $ cValueType vp\n dataPtr <- liftIO $ cValueData vp\n metaPtr <- liftIO $ cValueMetadata vp\n tt <- translateType finalState typePtr\n\n mds <- mapM (translateMetadata finalState) metaPtr\n\n uid <- nextId\n\n resetLocalIdCounter\n\n let dataPtr' = castPtr dataPtr\n basicVal = Value { valueName = name\n , valueType = tt\n , valueMetadata = mds\n , valueContent = ExternalFunction [] -- FIXME: there are attributes here\n , valueUniqueId = uid\n }\n isExtern <- liftIO $ cFunctionIsExternal dataPtr'\n\n case isExtern of\n True -> do\n recordValue vp basicVal\n return basicVal\n False -> do\n align <- liftIO $ cFunctionAlignment dataPtr'\n vis <- liftIO $ cFunctionVisibility dataPtr'\n link <- liftIO $ cFunctionLinkage dataPtr'\n section <- liftIO $ cFunctionSection dataPtr'\n cc <- liftIO $ cFunctionCallingConvention dataPtr'\n gcname <- liftIO $ cFunctionGCName dataPtr'\n args <- liftIO $ cFunctionArguments dataPtr'\n blocks <- liftIO $ cFunctionBlocks dataPtr'\n isVarArg <- liftIO $ cFunctionIsVarArg dataPtr'\n\n args' <- mapM (translateValue finalState) args\n blocks' <- mapM (translateValue finalState) blocks\n\n let f = Function { functionParameters = args'\n , functionBody = blocks'\n , functionLinkage = link\n , functionVisibility = vis\n , functionCC = cc\n , functionRetAttrs = [] -- FIXME\n , functionAttrs = [] -- FIXME\n , functionSection = section\n , functionAlign = align\n , functionGCName = gcname\n , functionIsVararg = isVarArg\n }\n v = basicVal { valueContent = f }\n recordValue vp v\n return v\n\nconstantBracket :: KnotMonad ValueT -> KnotMonad ValueT\nconstantBracket c = do\n s <- get\n let tdepth = constantTranslationDepth s\n put s { constantTranslationDepth = tdepth + 1 }\n ret <- c\n s' <- get\n let tdepth' = constantTranslationDepth s'\n put s' { constantTranslationDepth = tdepth' - 1 }\n return ret\n\n-- | This wrapper checks to see if we have translated the value yet\n-- (but not against the final state - only the internal running\n-- state). This way we really translate it if it hasn't been seen\n-- yet, but get the translated value if we have touched it before.\ntranslateValue :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateValue finalState vp = do\n s <- get\n case M.lookup (ptrToIntPtr vp) (valueMap s) of\n Nothing -> translateValue' finalState vp\n Just v -> return v\n\n-- | Only the top-level translators should call this: Globals and BasicBlocks\n-- (Or translateConstOrRef when translating constants)\ntranslateValue' :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateValue' finalState vp = do\n tag <- liftIO $ cValueTag vp\n name <- liftIO $ cValueName vp\n typePtr <- liftIO $ cValueType vp\n dataPtr <- liftIO $ cValueData vp\n metaPtr <- liftIO $ cValueMetadata vp\n\n mds <- mapM (translateMetadata finalState) metaPtr\n\n s <- get\n let cdepth = constantTranslationDepth s\n idCtr = localId s\n realName <- case isJust name || isGlobal tag || isConstant tag || cdepth > 0 of\n True -> return name\n False -> do\n put s { localId = idCtr + 1 }\n return $ Just $ makeLocalIdentifier $ BS.pack (show idCtr)\n\n tt <- translateType finalState typePtr\n\n content <- case tag of\n ValArgument -> translateArgument finalState (castPtr dataPtr)\n ValBasicblock -> translateBasicBlock finalState (castPtr dataPtr)\n ValInlineasm -> constantBracket $ translateInlineAsm finalState (castPtr dataPtr)\n ValBlockaddress -> constantBracket $ translateBlockAddress finalState (castPtr dataPtr)\n ValConstantaggregatezero -> return ConstantAggregateZero\n ValConstantpointernull -> return ConstantPointerNull\n ValUndefvalue -> return UndefValue\n ValConstantarray -> constantBracket $ translateConstantAggregate finalState ConstantArray (castPtr dataPtr)\n ValConstantstruct -> constantBracket $ translateConstantAggregate finalState ConstantStruct (castPtr dataPtr)\n ValConstantvector -> constantBracket $ translateConstantAggregate finalState ConstantVector (castPtr dataPtr)\n ValConstantfp -> translateConstantFP finalState (castPtr dataPtr)\n ValConstantint -> translateConstantInt finalState (castPtr dataPtr)\n ValRetinst -> translateRetInst finalState (castPtr dataPtr)\n ValBranchinst -> translateBranchInst finalState (castPtr dataPtr)\n ValSwitchinst -> translateSwitchInst finalState (castPtr dataPtr)\n ValIndirectbrinst -> translateIndirectBrInst finalState (castPtr dataPtr)\n ValInvokeinst -> translateInvokeInst finalState (castPtr dataPtr)\n ValUnwindinst -> return UnwindInst\n ValUnreachableinst -> return UnreachableInst\n ValAddinst -> translateFlaggedBinaryOp finalState AddInst (castPtr dataPtr)\n ValFaddinst -> translateFlaggedBinaryOp finalState AddInst (castPtr dataPtr)\n ValSubinst -> translateFlaggedBinaryOp finalState SubInst (castPtr dataPtr)\n ValFsubinst -> translateFlaggedBinaryOp finalState SubInst (castPtr dataPtr)\n ValMulinst -> translateFlaggedBinaryOp finalState MulInst (castPtr dataPtr)\n ValFmulinst -> translateFlaggedBinaryOp finalState MulInst (castPtr dataPtr)\n ValUdivinst -> translateBinaryOp finalState DivInst (castPtr dataPtr)\n ValSdivinst -> translateBinaryOp finalState DivInst (castPtr dataPtr)\n ValFdivinst -> translateBinaryOp finalState DivInst (castPtr dataPtr)\n ValUreminst -> translateBinaryOp finalState RemInst (castPtr dataPtr)\n ValSreminst -> translateBinaryOp finalState RemInst (castPtr dataPtr)\n ValFreminst -> translateBinaryOp finalState RemInst (castPtr dataPtr)\n ValShlinst -> translateBinaryOp finalState ShlInst (castPtr dataPtr)\n ValLshrinst -> translateBinaryOp finalState LshrInst (castPtr dataPtr)\n ValAshrinst -> translateBinaryOp finalState AshrInst (castPtr dataPtr)\n ValAndinst -> translateBinaryOp finalState AndInst (castPtr dataPtr)\n ValOrinst -> translateBinaryOp finalState OrInst (castPtr dataPtr)\n ValXorinst -> translateBinaryOp finalState XorInst (castPtr dataPtr)\n ValAllocainst -> translateAllocaInst finalState (castPtr dataPtr)\n ValLoadinst -> translateLoadInst finalState (castPtr dataPtr)\n ValStoreinst -> translateStoreInst finalState (castPtr dataPtr)\n ValGetelementptrinst -> translateGEPInst finalState (castPtr dataPtr)\n ValTruncinst -> translateCastInst finalState TruncInst (castPtr dataPtr)\n ValZextinst -> translateCastInst finalState ZExtInst (castPtr dataPtr)\n ValSextinst -> translateCastInst finalState SExtInst (castPtr dataPtr)\n ValFptruncinst -> translateCastInst finalState FPTruncInst (castPtr dataPtr)\n ValFpextinst -> translateCastInst finalState FPExtInst (castPtr dataPtr)\n ValFptouiinst -> translateCastInst finalState FPToUIInst (castPtr dataPtr)\n ValFptosiinst -> translateCastInst finalState FPToSIInst (castPtr dataPtr)\n ValUitofpinst -> translateCastInst finalState UIToFPInst (castPtr dataPtr)\n ValSitofpinst -> translateCastInst finalState SIToFPInst (castPtr dataPtr)\n ValPtrtointinst -> translateCastInst finalState PtrToIntInst (castPtr dataPtr)\n ValInttoptrinst -> translateCastInst finalState IntToPtrInst (castPtr dataPtr)\n ValBitcastinst -> translateCastInst finalState BitcastInst (castPtr dataPtr)\n ValIcmpinst -> translateCmpInst finalState ICmpInst (castPtr dataPtr)\n ValFcmpinst -> translateCmpInst finalState FCmpInst (castPtr dataPtr)\n ValPhinode -> translatePhiNode finalState (castPtr dataPtr)\n ValCallinst -> translateCallInst finalState (castPtr dataPtr)\n ValSelectinst -> translateSelectInst finalState (castPtr dataPtr)\n ValVaarginst -> translateVarArgInst finalState (castPtr dataPtr)\n ValExtractelementinst -> translateExtractElementInst finalState (castPtr dataPtr)\n ValInsertelementinst -> translateInsertElementInst finalState (castPtr dataPtr)\n ValShufflevectorinst -> translateShuffleVectorInst finalState (castPtr dataPtr)\n ValExtractvalueinst -> translateExtractValueInst finalState (castPtr dataPtr)\n ValInsertvalueinst -> translateInsertValueInst finalState (castPtr dataPtr)\n ValFunction -> throw InvalidFunctionInTranslateValue\n ValAlias -> throw InvalidAliasInTranslateValue\n ValGlobalvariable -> throw InvalidGlobalVarInTranslateValue\n ValConstantexpr -> constantBracket $ translateConstantExpr finalState (castPtr dataPtr)\n\n uid <- nextId\n\n let tv = Value { valueType = tt\n , valueName = realName\n , valueMetadata = mds\n , valueContent = content\n , valueUniqueId = uid\n }\n\n recordValue vp tv\n\n return tv\n\nisGlobal :: ValueTag -> Bool\nisGlobal vt = case vt of\n ValFunction -> True\n ValAlias -> True\n ValGlobalvariable -> True\n _ -> False\n\nisConstant :: ValueTag -> Bool\nisConstant vt = case vt of\n ValConstantaggregatezero -> True\n ValConstantarray -> True\n ValConstantfp -> True\n ValConstantint -> True\n ValConstantpointernull -> True\n ValConstantstruct -> True\n ValConstantvector -> True\n ValUndefvalue -> True\n ValConstantexpr -> True\n ValBlockaddress -> True\n ValInlineasm -> True\n _ -> False\n\ntranslateConstOrRef :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateConstOrRef finalState vp = do\n tag <- liftIO $ cValueTag vp\n let ip = ptrToIntPtr vp\n case isConstant tag of\n True -> translateValue finalState vp\n False ->\n return $ M.findWithDefault (throw (KnotTyingFailure tag)) ip (valueMap finalState)\n\n\ntranslateArgument :: KnotState -> ArgInfoPtr -> KnotMonad ValueT\ntranslateArgument _ dataPtr = do\n hasSRet <- liftIO $ cArgInfoHasSRet dataPtr\n hasByVal <- liftIO $ cArgInfoHasByVal dataPtr\n hasNest <- liftIO $ cArgInfoHasNest dataPtr\n hasNoAlias <- liftIO $ cArgInfoHasNoAlias dataPtr\n hasNoCapture <- liftIO $ cArgInfoHasNoCapture dataPtr\n let attrOrNothing b att = if b then Just att else Nothing\n atts = [ attrOrNothing hasSRet PASRet\n , attrOrNothing hasByVal PAByVal\n , attrOrNothing hasNest PANest\n , attrOrNothing hasNoAlias PANoAlias\n , attrOrNothing hasNoCapture PANoCapture\n ]\n return $ Argument (catMaybes atts)\n\ntranslateBasicBlock :: KnotState -> BasicBlockPtr -> KnotMonad ValueT\ntranslateBasicBlock finalState dataPtr = do\n insts <- liftIO $ cBasicBlockInstructions dataPtr\n tinsts <- mapM (translateValue finalState) insts\n return $ BasicBlock tinsts\n\ntranslateInlineAsm :: KnotState -> InlineAsmInfoPtr -> KnotMonad ValueT\ntranslateInlineAsm _ dataPtr = do\n asmString <- liftIO $ cInlineAsmString dataPtr\n constraints <- liftIO $ cInlineAsmConstraints dataPtr\n return $ InlineAsm asmString constraints\n\ntranslateBlockAddress :: KnotState -> BlockAddrInfoPtr -> KnotMonad ValueT\ntranslateBlockAddress finalState dataPtr = do\n fval <- liftIO $ cBlockAddrFunc dataPtr\n bval <- liftIO $ cBlockAddrBlock dataPtr\n f' <- translateConstOrRef finalState fval\n b' <- translateConstOrRef finalState bval\n return $ BlockAddress f' b'\n\ntranslateConstantAggregate :: KnotState -> ([Value] -> ValueT) -> AggregateInfoPtr -> KnotMonad ValueT\ntranslateConstantAggregate finalState constructor dataPtr = do\n vals <- liftIO $ cAggregateValues dataPtr\n vals' <- mapM (translateConstOrRef finalState) vals\n return $ constructor vals'\n\ntranslateConstantFP :: KnotState -> FPInfoPtr -> KnotMonad ValueT\ntranslateConstantFP _ dataPtr = do\n fpval <- liftIO $ cFPVal dataPtr\n return $ ConstantFP fpval\n\ntranslateConstantInt :: KnotState -> IntInfoPtr -> KnotMonad ValueT\ntranslateConstantInt _ dataPtr = do\n intval <- liftIO $ cIntVal dataPtr\n return $ ConstantInt intval\n\ntranslateRetInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateRetInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n case opPtrs of\n [] -> return $ RetInst Nothing\n [val] -> do\n val' <- translateConstOrRef finalState val\n return $ RetInst (Just val')\n _ -> throw TooManyReturnValues\n\n-- | Note, in LLVM the operands of the Branch instruction are ordered as\n--\n-- [Condition, FalseTarget,] TrueTarget\n--\n-- This is not exactly as expected.\ntranslateBranchInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateBranchInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n case opPtrs of\n [dst] -> do\n dst' <- translateConstOrRef finalState dst\n return $ UnconditionalBranchInst dst'\n [val, f, t] -> do\n val' <- translateConstOrRef finalState val\n fbranch <- translateConstOrRef finalState f\n tbranch <- translateConstOrRef finalState t\n return $ BranchInst { branchCondition = val'\n , branchTrueTarget = tbranch\n , branchFalseTarget = fbranch\n }\n _ -> throw InvalidBranchInst\n\ntranslateSwitchInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateSwitchInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n case opPtrs of\n (swVal:defTarget:cases) -> do\n val' <- translateConstOrRef finalState swVal\n def' <- translateConstOrRef finalState defTarget\n -- Process the rest of the list in pairs since that is how LLVM\n -- stores them, but transform it into a nice list of actual\n -- pairs\n let tpairs acc (v1:dest:rest) = do\n v1' <- translateConstOrRef finalState v1\n dest' <- translateConstOrRef finalState dest\n tpairs ((v1', dest'):acc) rest\n tpairs acc [] = return $ reverse acc\n tpairs _ _ = throw InvalidSwitchLayout\n cases' <- tpairs [] cases\n return $ SwitchInst { switchValue = val'\n , switchDefaultTarget = def'\n , switchCases = cases'\n }\n _ -> throw InvalidSwitchLayout\n\ntranslateIndirectBrInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateIndirectBrInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n case opPtrs of\n (addr:targets) -> do\n addr' <- translateConstOrRef finalState addr\n targets' <- mapM (translateConstOrRef finalState) targets\n return $ IndirectBranchInst { indirectBranchAddress = addr'\n , indirectBranchTargets = targets'\n }\n _ -> throw InvalidIndirectBranchOperands\n\ntranslateInvokeInst :: KnotState -> CallInfoPtr -> KnotMonad ValueT\ntranslateInvokeInst finalState dataPtr = do\n func <- liftIO $ cCallValue dataPtr\n args <- liftIO $ cCallArguments dataPtr\n cc <- liftIO $ cCallConvention dataPtr\n hasSRet <- liftIO $ cCallHasSRet dataPtr\n ndest <- liftIO $ cCallNormalDest dataPtr\n udest <- liftIO $ cCallUnwindDest dataPtr\n\n f' <- translateConstOrRef finalState func\n args' <- mapM (translateConstOrRef finalState) args\n n' <- translateConstOrRef finalState ndest\n u' <- translateConstOrRef finalState udest\n\n return $ InvokeInst { invokeConvention = cc\n , invokeParamAttrs = [] -- FIXME\n , invokeFunction = f'\n , invokeArguments = zip args' (repeat []) -- FIXME\n , invokeAttrs = [] -- FIXME\n , invokeNormalLabel = n'\n , invokeUnwindLabel = u'\n , invokeHasSRet = hasSRet\n }\n\ntranslateFlaggedBinaryOp :: KnotState -> (ArithFlags -> Value -> Value -> ValueT) ->\n InstInfoPtr -> KnotMonad ValueT\ntranslateFlaggedBinaryOp finalState constructor dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n flags <- liftIO $ cInstructionArithFlags dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [lhs, rhs] -> return $ constructor flags lhs rhs\n _ -> throw $ InvalidBinaryOp (length ops)\n\ntranslateBinaryOp :: KnotState -> (Value -> Value -> ValueT) ->\n InstInfoPtr -> KnotMonad ValueT\ntranslateBinaryOp finalState constructor dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [lhs, rhs] -> return $ constructor lhs rhs\n _ -> throw $ InvalidBinaryOp (length ops)\n\ntranslateAllocaInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateAllocaInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n align <- liftIO $ cInstructionAlign dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [val] -> return $ AllocaInst val align\n _ -> throw $ InvalidUnaryOp (length ops)\n\n\ntranslateLoadInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateLoadInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n align <- liftIO $ cInstructionAlign dataPtr\n vol <- liftIO $ cInstructionIsVolatile dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [addr] -> return $ LoadInst { loadIsVolatile = vol\n , loadAddress = addr\n , loadAlignment = align\n }\n _ -> throw $ InvalidUnaryOp (length ops)\n\ntranslateStoreInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateStoreInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n addrSpace <- liftIO $ cInstructionAddrSpace dataPtr\n align <- liftIO $ cInstructionAlign dataPtr\n isVol <- liftIO $ cInstructionIsVolatile dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [val, ptr] -> return $ StoreInst { storeIsVolatile = isVol\n , storeValue = val\n , storeAddress = ptr\n , storeAlignment = align\n , storeAddrSpace = addrSpace\n }\n _ -> throw $ InvalidBinaryOp (length ops)\n\ntranslateGEPInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateGEPInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n inBounds <- liftIO $ cInstructionInBounds dataPtr\n addrSpace <- liftIO $ cInstructionAddrSpace dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n (val:indices) -> return $ GetElementPtrInst { getElementPtrInBounds = inBounds\n , getElementPtrValue = val\n , getElementPtrIndices = indices\n , getElementPtrAddrSpace = addrSpace\n }\n _ -> throw $ InvalidGEPInst (length ops)\n\ntranslateCastInst :: KnotState -> (Value -> ValueT) -> InstInfoPtr -> KnotMonad ValueT\ntranslateCastInst finalState constructor dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [v] -> return $ constructor v\n _ -> throw $ InvalidUnaryOp (length ops)\n\ntranslateCmpInst :: KnotState -> (CmpPredicate -> Value -> Value -> ValueT) ->\n InstInfoPtr -> KnotMonad ValueT\ntranslateCmpInst finalState constructor dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n predicate <- liftIO $ cInstructionCmpPred dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [op1, op2] -> return $ constructor predicate op1 op2\n _ -> throw $ InvalidBinaryOp (length ops)\n\ntranslatePhiNode :: KnotState -> PHIInfoPtr -> KnotMonad ValueT\ntranslatePhiNode finalState dataPtr = do\n vptrs <- liftIO $ cPHIValues dataPtr\n bptrs <- liftIO $ cPHIBlocks dataPtr\n\n vals <- mapM (translateConstOrRef finalState) vptrs\n blocks <- mapM (translateConstOrRef finalState) bptrs\n\n return $ PhiNode $ zip vals blocks\n\ntranslateCallInst :: KnotState -> CallInfoPtr -> KnotMonad ValueT\ntranslateCallInst finalState dataPtr = do\n vptr <- liftIO $ cCallValue dataPtr\n aptrs <- liftIO $ cCallArguments dataPtr\n cc <- liftIO $ cCallConvention dataPtr\n hasSRet <- liftIO $ cCallHasSRet dataPtr\n isTail <- liftIO $ cCallIsTail dataPtr\n\n val <- translateConstOrRef finalState vptr\n args <- mapM (translateConstOrRef finalState) aptrs\n\n return $ CallInst { callIsTail = isTail\n , callConvention = cc\n , callParamAttrs = [] -- FIXME\n , callFunction = val\n , callArguments = zip args (repeat []) -- FIXME\n , callAttrs = [] -- FIXME\n , callHasSRet = hasSRet\n }\n\ntranslateSelectInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateSelectInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [cond, trueval, falseval] -> do\n return $ SelectInst cond trueval falseval\n _ -> throw $ InvalidSelectArgs (length ops)\n\ntranslateVarArgInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateVarArgInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [op] -> return $ VaArgInst op\n _ -> throw $ InvalidUnaryOp (length ops)\n\ntranslateExtractElementInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateExtractElementInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [vec, idx] -> do\n return $ ExtractElementInst { extractElementVector = vec\n , extractElementIndex = idx\n }\n _ -> throw $ InvalidExtractElementInst (length ops)\n\ntranslateInsertElementInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateInsertElementInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [vec, val, idx] -> do\n return $ InsertElementInst { insertElementVector = vec\n , insertElementValue = val\n , insertElementIndex = idx\n }\n _ -> throw $ InvalidInsertElementInst (length ops)\n\ntranslateShuffleVectorInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateShuffleVectorInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [v1, v2, vecMask] -> do\n return $ ShuffleVectorInst { shuffleVectorV1 = v1\n , shuffleVectorV2 = v2\n , shuffleVectorMask = vecMask\n }\n _ -> throw $ InvalidShuffleVectorInst (length ops)\n\ntranslateExtractValueInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateExtractValueInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n indices <- liftIO $ cInstructionIndices dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [agg] -> return $ ExtractValueInst { extractValueAggregate = agg\n , extractValueIndices = indices\n }\n _ -> throw $ InvalidExtractValueInst (length ops)\n\ntranslateInsertValueInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateInsertValueInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n indices <- liftIO $ cInstructionIndices dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [agg, val] ->\n return $ InsertValueInst { insertValueAggregate = agg\n , insertValueValue = val\n , insertValueIndices = indices\n }\n _ -> throw $ InvalidInsertValueInst (length ops)\n\ntranslateConstantExpr :: KnotState -> ConstExprPtr -> KnotMonad ValueT\ntranslateConstantExpr finalState dataPtr = do\n ii <- liftIO $ cConstExprInstInfo dataPtr\n tag <- liftIO $ cConstExprTag dataPtr\n vt <- case tag of\n ValAddinst -> translateFlaggedBinaryOp finalState AddInst ii\n ValFaddinst -> translateFlaggedBinaryOp finalState AddInst ii\n ValSubinst -> translateFlaggedBinaryOp finalState SubInst ii\n ValFsubinst -> translateFlaggedBinaryOp finalState SubInst ii\n ValMulinst -> translateFlaggedBinaryOp finalState MulInst ii\n ValFmulinst -> translateFlaggedBinaryOp finalState MulInst ii\n ValUdivinst -> translateBinaryOp finalState DivInst ii\n ValSdivinst -> translateBinaryOp finalState DivInst ii\n ValFdivinst -> translateBinaryOp finalState DivInst ii\n ValUreminst -> translateBinaryOp finalState RemInst ii\n ValSreminst -> translateBinaryOp finalState RemInst ii\n ValFreminst -> translateBinaryOp finalState RemInst ii\n ValShlinst -> translateBinaryOp finalState ShlInst ii\n ValLshrinst -> translateBinaryOp finalState LshrInst ii\n ValAshrinst -> translateBinaryOp finalState AshrInst ii\n ValAndinst -> translateBinaryOp finalState AndInst ii\n ValOrinst -> translateBinaryOp finalState OrInst ii\n ValXorinst -> translateBinaryOp finalState XorInst ii\n ValGetelementptrinst -> translateGEPInst finalState ii\n ValTruncinst -> translateCastInst finalState TruncInst ii\n ValZextinst -> translateCastInst finalState ZExtInst ii\n ValSextinst -> translateCastInst finalState SExtInst ii\n ValFptruncinst -> translateCastInst finalState FPTruncInst ii\n ValFpextinst -> translateCastInst finalState FPExtInst ii\n ValFptouiinst -> translateCastInst finalState FPToUIInst ii\n ValFptosiinst -> translateCastInst finalState FPToSIInst ii\n ValUitofpinst -> translateCastInst finalState UIToFPInst ii\n ValSitofpinst -> translateCastInst finalState SIToFPInst ii\n ValPtrtointinst -> translateCastInst finalState PtrToIntInst ii\n ValInttoptrinst -> translateCastInst finalState IntToPtrInst ii\n ValBitcastinst -> translateCastInst finalState BitcastInst ii\n ValIcmpinst -> translateCmpInst finalState ICmpInst ii\n ValFcmpinst -> translateCmpInst finalState FCmpInst ii\n ValSelectinst -> translateSelectInst finalState ii\n ValVaarginst -> translateVarArgInst finalState ii\n ValExtractelementinst -> translateExtractElementInst finalState ii\n ValInsertelementinst -> translateInsertElementInst finalState ii\n ValShufflevectorinst -> translateShuffleVectorInst finalState ii\n ValExtractvalueinst -> translateExtractValueInst finalState ii\n ValInsertvalueinst -> translateInsertValueInst finalState ii\n return $ ConstantValue vt\n\ntranslateMetadata :: KnotState -> MetaPtr -> KnotMonad Metadata\ntranslateMetadata finalState mp = do\n s <- get\n let ip = ptrToIntPtr mp\n put s { visitedMetadata = S.insert ip (visitedMetadata s) }\n case M.lookup ip (metaMap s) of\n Just m -> return m\n Nothing -> translateMetadata' finalState mp\n\ntranslateMetadataRec :: KnotState -> MetaPtr -> KnotMonad Metadata\ntranslateMetadataRec finalState mp = do\n s <- get\n let ip = ptrToIntPtr mp\n -- If we have already visited this metadata object, look it up in\n -- the final state. We record visits *before* making recursive\n -- calls, allowing us to tie the knot by looking already-visited\n -- nodes up in the final state.\n --\n -- If we haven't seen this node before, we can safely call the\n -- outermost 'translateMetadata', which will make an entry in the\n -- visited set and then do the translation.\n case S.member ip (visitedMetadata s) of\n False -> translateMetadata finalState mp\n True -> return $ M.findWithDefault (throw MetaKnotFailure) ip (metaMap finalState)\n\nmaybeTranslateMetadataRec :: KnotState -> Maybe MetaPtr -> KnotMonad (Maybe Metadata)\nmaybeTranslateMetadataRec _ Nothing = return Nothing\nmaybeTranslateMetadataRec finalState (Just mp) =\n Just <$> translateMetadataRec finalState mp\n\ntranslateMetadata' :: KnotState -> MetaPtr -> KnotMonad Metadata\ntranslateMetadata' finalState mp = do\n let ip = ptrToIntPtr mp\n s <- get\n put s { visitedMetadata = S.insert ip (visitedMetadata s) }\n metaTag <- liftIO $ cMetaTypeTag mp\n tag <- liftIO $ cMetaTag mp\n content <- case metaTag of\n MetaLocation -> do\n line <- liftIO $ cMetaLocationLine mp\n col <- liftIO $ cMetaLocationColumn mp\n scope <- liftIO $ cMetaLocationScope mp\n\n scope' <- translateMetadataRec finalState scope\n return MetaSourceLocation { metaSourceRow = line\n , metaSourceCol = col\n , metaSourceScope = scope'\n }\n MetaDerivedtype -> do\n ctxt <- liftIO $ cMetaTypeContext mp\n name <- cMetaTypeName mp\n f <- liftIO $ cMetaTypeFile mp\n line <- liftIO $ cMetaTypeLine mp\n size <- liftIO $ cMetaTypeSize mp\n align <- liftIO $ cMetaTypeAlign mp\n off <- liftIO $ cMetaTypeOffset mp\n parent <- liftIO $ cMetaTypeDerivedFrom mp\n\n cu <- liftIO $ cMetaTypeCompileUnit mp\n isArtif <- liftIO $ cMetaTypeIsArtificial mp\n isVirt <- liftIO $ cMetaTypeIsVirtual mp\n isForward <- liftIO $ cMetaTypeIsForward mp\n isProt <- liftIO $ cMetaTypeIsProtected mp\n isPriv <- liftIO $ cMetaTypeIsPrivate mp\n\n f' <- maybeTranslateMetadataRec finalState f\n ctxt' <- translateMetadataRec finalState ctxt\n parent' <- maybeTranslateMetadataRec finalState parent\n cu' <- maybeTranslateMetadataRec finalState cu\n\n return MetaDWDerivedType { metaDerivedTypeContext = ctxt'\n , metaDerivedTypeName = name\n , metaDerivedTypeFile = f'\n , metaDerivedTypeLine = line\n , metaDerivedTypeSize = size\n , metaDerivedTypeAlign = align\n , metaDerivedTypeOffset = off\n , metaDerivedTypeParent = parent'\n , metaDerivedTypeTag = tag\n , metaDerivedTypeCompileUnit = cu'\n , metaDerivedTypeIsArtificial = isArtif\n , metaDerivedTypeIsVirtual = isVirt\n , metaDerivedTypeIsForward = isForward\n , metaDerivedTypeIsProtected = isProt\n , metaDerivedTypeIsPrivate = isPriv\n }\n MetaCompositetype -> do\n ctxt <- liftIO $ cMetaTypeContext mp\n name <- cMetaTypeName mp\n f <- liftIO $ cMetaTypeFile mp\n line <- liftIO $ cMetaTypeLine mp\n size <- liftIO $ cMetaTypeSize mp\n align <- liftIO $ cMetaTypeAlign mp\n off <- liftIO $ cMetaTypeOffset mp\n parent <- liftIO $ cMetaTypeDerivedFrom mp\n flags <- liftIO $ cMetaTypeFlags mp\n members <- liftIO $ cMetaTypeCompositeComponents mp\n rlang <- liftIO $ cMetaTypeRuntimeLanguage mp\n ctype <- liftIO $ cMetaTypeContainingType mp\n tparams <- liftIO $ cMetaTypeTemplateParams mp\n cu <- liftIO $ cMetaTypeCompileUnit mp\n isArtif <- liftIO $ cMetaTypeIsArtificial mp\n isVirtual <- liftIO $ cMetaTypeIsVirtual mp\n isForward <- liftIO $ cMetaTypeIsForward mp\n isProt <- liftIO $ cMetaTypeIsProtected mp\n isPriv <- liftIO $ cMetaTypeIsPrivate mp\n isByRef <- liftIO $ cMetaTypeIsByRefStruct mp\n\n ctxt' <- translateMetadataRec finalState ctxt\n f' <- maybeTranslateMetadataRec finalState f\n parent' <- maybeTranslateMetadataRec finalState parent\n members' <- maybeTranslateMetadataRec finalState members\n ctype' <- maybeTranslateMetadataRec finalState ctype\n tparams' <- maybeTranslateMetadataRec finalState tparams\n cu' <- maybeTranslateMetadataRec finalState cu\n\n return MetaDWCompositeType { metaCompositeTypeTag = tag\n , metaCompositeTypeContext = ctxt'\n , metaCompositeTypeName = name\n , metaCompositeTypeFile = f'\n , metaCompositeTypeLine = line\n , metaCompositeTypeSize = size\n , metaCompositeTypeAlign = align\n , metaCompositeTypeOffset = off\n , metaCompositeTypeFlags = flags\n , metaCompositeTypeParent = parent'\n , metaCompositeTypeMembers = members'\n , metaCompositeTypeRuntime = rlang\n , metaCompositeTypeContainer = ctype'\n , metaCompositeTypeTemplateParams = tparams'\n , metaCompositeTypeCompileUnit = cu'\n , metaCompositeTypeIsArtificial = isArtif\n , metaCompositeTypeIsVirtual = isVirtual\n , metaCompositeTypeIsForward = isForward\n , metaCompositeTypeIsProtected = isProt\n , metaCompositeTypeIsPrivate = isPriv\n , metaCompositeTypeIsByRefStruct = isByRef\n }\n MetaBasictype -> do\n ctxt <- liftIO $ cMetaTypeContext mp\n name <- cMetaTypeName mp\n f <- liftIO $ cMetaTypeFile mp\n line <- liftIO $ cMetaTypeLine mp\n size <- liftIO $ cMetaTypeSize mp\n align <- liftIO $ cMetaTypeAlign mp\n off <- liftIO $ cMetaTypeOffset mp\n flags <- liftIO $ cMetaTypeFlags mp\n encoding <- liftIO $ cMetaTypeEncoding mp\n\n ctxt' <- translateMetadataRec finalState ctxt\n f' <- maybeTranslateMetadataRec finalState f\n\n return MetaDWBaseType { metaBaseTypeContext = ctxt'\n , metaBaseTypeName = name\n , metaBaseTypeFile = f'\n , metaBaseTypeLine = line\n , metaBaseTypeSize = size\n , metaBaseTypeAlign = align\n , metaBaseTypeOffset = off\n , metaBaseTypeFlags = flags\n , metaBaseTypeEncoding = encoding\n }\n MetaVariable -> do\n ctxt <- liftIO $ cMetaVariableContext mp\n name <- cMetaVariableName mp\n file <- liftIO $ cMetaVariableCompileUnit mp\n line <- liftIO $ cMetaVariableLine mp\n argNo <- liftIO $ cMetaVariableArgNumber mp\n ty <- liftIO $ cMetaVariableType mp\n isArtif <- liftIO $ cMetaVariableIsArtificial mp\n cplxAddr <- liftIO $ cMetaVariableAddrElements mp\n byRef <- liftIO $ cMetaVariableIsBlockByRefVar mp\n\n ctxt' <- translateMetadataRec finalState ctxt\n file' <- translateMetadataRec finalState file\n ty' <- translateMetadataRec finalState ty\n\n return MetaDWLocal { metaLocalTag = tag\n , metaLocalContext = ctxt'\n , metaLocalName = name\n , metaLocalFile = file'\n , metaLocalLine = line\n , metaLocalArgNo = argNo\n , metaLocalType = ty'\n , metaLocalIsArtificial = isArtif\n , metaLocalIsBlockByRefVar = byRef\n , metaLocalAddrElements = cplxAddr\n }\n MetaSubprogram -> do\n ctxt <- liftIO $ cMetaSubprogramContext mp\n name <- cMetaSubprogramName mp\n displayName <- cMetaSubprogramDisplayName mp\n linkageName <- cMetaSubprogramLinkageName mp\n compUnit <- liftIO $ cMetaSubprogramCompileUnit mp\n line <- liftIO $ cMetaSubprogramLine mp\n ty <- liftIO $ cMetaSubprogramType mp\n isLocal <- liftIO $ cMetaSubprogramIsLocal mp\n isDef <- liftIO $ cMetaSubprogramIsDefinition mp\n virt <- liftIO $ cMetaSubprogramVirtuality mp\n virtIdx <- liftIO $ cMetaSubprogramVirtualIndex mp\n baseType <- liftIO $ cMetaSubprogramContainingType mp\n isArtif <- liftIO $ cMetaSubprogramIsArtificial mp\n isOpt <- liftIO $ cMetaSubprogramIsOptimized mp\n isPrivate <- liftIO $ cMetaSubprogramIsPrivate mp\n isProtected <- liftIO $ cMetaSubprogramIsProtected mp\n isExplicit <- liftIO $ cMetaSubprogramIsExplicit mp\n isPrototyped <- liftIO $ cMetaSubprogramIsPrototyped mp\n\n ctxt' <- translateMetadataRec finalState ctxt\n compUnit' <- translateMetadataRec finalState compUnit\n ty' <- translateMetadataRec finalState ty\n baseType' <- maybeTranslateMetadataRec finalState baseType\n\n return MetaDWSubprogram { metaSubprogramContext = ctxt'\n , metaSubprogramName = name\n , metaSubprogramDisplayName = displayName\n , metaSubprogramLinkageName = linkageName\n , metaSubprogramFile = compUnit'\n , metaSubprogramLine = line\n , metaSubprogramType = ty'\n , metaSubprogramStatic = isLocal\n , metaSubprogramNotExtern = not isPrivate && not isProtected\n , metaSubprogramVirtuality = virt\n , metaSubprogramVirtIndex = virtIdx\n , metaSubprogramBaseType = baseType'\n , metaSubprogramArtificial = isArtif\n , metaSubprogramOptimized = isOpt\n , metaSubprogramIsExplicit = isExplicit\n , metaSubprogramIsPrototyped = isPrototyped\n }\n MetaGlobalvariable -> do\n ctxt <- liftIO $ cMetaGlobalContext mp\n name <- cMetaGlobalName mp\n displayName <- cMetaGlobalDisplayName mp\n linkageName <- cMetaGlobalLinkageName mp\n file <- liftIO $ cMetaGlobalCompileUnit mp\n line <- liftIO $ cMetaGlobalLine mp\n ty <- liftIO $ cMetaGlobalType mp\n isLocal <- liftIO $ cMetaGlobalIsLocal mp\n def <- liftIO $ cMetaGlobalIsDefinition mp\n\n ctxt' <- translateMetadataRec finalState ctxt\n file' <- translateMetadataRec finalState file\n ty' <- translateMetadataRec finalState ty\n\n return MetaDWVariable { metaGlobalVarContext = ctxt'\n , metaGlobalVarName = name\n , metaGlobalVarDisplayName = displayName\n , metaGlobalVarLinkageName = linkageName\n , metaGlobalVarFile = file'\n , metaGlobalVarLine = line\n , metaGlobalVarType = ty'\n , metaGlobalVarStatic = isLocal\n , metaGlobalVarNotExtern = not def\n }\n MetaFile -> do\n file <- cMetaFileFilename mp\n dir <- cMetaFileDirectory mp\n cu <- liftIO $ cMetaFileCompileUnit mp\n\n cu' <- translateMetadataRec finalState cu\n\n return MetaDWFile { metaFileSourceFile = file\n , metaFileSourceDir = dir\n , metaFileCompileUnit = cu'\n }\n MetaCompileunit -> do\n lang <- liftIO $ cMetaCompileUnitLanguage mp\n fname <- cMetaCompileUnitFilename mp\n dir <- cMetaCompileUnitDirectory mp\n producer <- cMetaCompileUnitProducer mp\n isMain <- liftIO $ cMetaCompileUnitIsMain mp\n isOpt <- liftIO $ cMetaCompileUnitIsOptimized mp\n flags <- cMetaCompileUnitFlags mp\n rv <- liftIO $ cMetaCompileUnitRuntimeVersion mp\n\n return MetaDWCompileUnit { metaCompileUnitLanguage = lang\n , metaCompileUnitSourceFile = fname\n , metaCompileUnitCompileDir = dir\n , metaCompileUnitProducer = producer\n , metaCompileUnitIsMain = isMain\n , metaCompileUnitIsOpt = isOpt\n , metaCompileUnitFlags = flags\n , metaCompileUnitVersion = rv\n }\n MetaNamespace -> do\n ctxt <- liftIO $ cMetaNamespaceContext mp\n name <- cMetaNamespaceName mp\n cu <- liftIO $ cMetaNamespaceCompileUnit mp\n line <- liftIO $ cMetaNamespaceLine mp\n\n ctxt' <- translateMetadataRec finalState ctxt\n cu' <- translateMetadataRec finalState cu\n\n return MetaDWNamespace { metaNamespaceContext = ctxt'\n , metaNamespaceName = name\n , metaNamespaceCompileUnit = cu'\n , metaNamespaceLine = line\n }\n MetaLexicalblock -> do\n ctxt <- liftIO $ cMetaLexicalBlockContext mp\n line <- liftIO $ cMetaLexicalBlockLine mp\n col <- liftIO $ cMetaLexicalBlockColumn mp\n\n ctxt' <- translateMetadataRec finalState ctxt\n\n return MetaDWLexicalBlock { metaLexicalBlockRow = line\n , metaLexicalBlockCol = col\n , metaLexicalBlockContext = ctxt'\n }\n MetaSubrange -> do\n lo <- liftIO $ cMetaSubrangeLo mp\n hi <- liftIO $ cMetaSubrangeHi mp\n return MetaDWSubrange { metaSubrangeLow = lo\n , metaSubrangeHigh = hi\n }\n MetaEnumerator -> do\n name <- cMetaEnumeratorName mp\n val <- liftIO $ cMetaEnumeratorValue mp\n return MetaDWEnumerator { metaEnumeratorName = name\n , metaEnumeratorValue = val\n }\n MetaArray -> do\n elts <- liftIO $ cMetaArrayElts mp\n elts' <- mapM (translateMetadataRec finalState) elts\n return $ MetadataList elts'\n MetaTemplatetypeparameter -> do\n ctxt <- liftIO $ cMetaTemplateTypeContext mp\n name <- cMetaTemplateTypeName mp\n ty <- liftIO $ cMetaTemplateTypeType mp\n line <- liftIO $ cMetaTemplateTypeLine mp\n col <- liftIO $ cMetaTemplateTypeColumn mp\n\n ctxt' <- translateMetadataRec finalState ctxt\n ty' <- translateMetadataRec finalState ty\n\n return MetaDWTemplateTypeParameter { metaTemplateTypeParameterContext = ctxt'\n , metaTemplateTypeParameterType = ty'\n , metaTemplateTypeParameterLine = line\n , metaTemplateTypeParameterCol = col\n , metaTemplateTypeParameterName = name\n }\n MetaTemplatevalueparameter -> do\n ctxt <- liftIO $ cMetaTemplateValueContext mp\n name <- cMetaTemplateValueName mp\n ty <- liftIO $ cMetaTemplateValueType mp\n val <- liftIO $ cMetaTemplateValueValue mp\n line <- liftIO $ cMetaTemplateValueLine mp\n col <- liftIO $ cMetaTemplateValueColumn mp\n\n ctxt' <- translateMetadataRec finalState ctxt\n ty' <- translateMetadataRec finalState ty\n\n return MetaDWTemplateValueParameter { metaTemplateValueParameterContext = ctxt'\n , metaTemplateValueParameterType = ty'\n , metaTemplateValueParameterLine = line\n , metaTemplateValueParameterCol = col\n , metaTemplateValueParameterValue = val\n , metaTemplateValueParameterName = name\n }\n\n uid <- nextMetaId\n let md = Metadata { metaValueContent = content\n , metaValueUniqueId = uid\n }\n st <- get\n put st { metaMap = M.insert ip md (metaMap st) }\n return md\n","old_contents":"-- | This module converts the C form of the LLVM IR into a fully\n-- referential Haskell version of the IR. The translation is slightly\n-- lossy around integral types in some cases, as Haskell Ints do not\n-- have the same range as C ints. In the vast majority of cases this\n-- should not really be an issue, but it is possible to lose\n-- information. If it is an issue it can be changed.\n{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, RankNTypes #-}\nmodule Data.LLVM.Private.Parser.Unmarshal ( parseLLVMBitcodeFile ) where\n\n#include \"c++\/marshal.h\"\n\nimport Prelude hiding ( catch )\n\nimport Control.Applicative\nimport Control.DeepSeq\nimport Control.Exception\nimport Control.Monad.State\nimport Data.Array.Storable\nimport Data.ByteString.Char8 ( ByteString )\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport Data.IORef\nimport Data.Map ( Map )\nimport Data.Set ( Set )\nimport qualified Data.Map as M\nimport qualified Data.Set as S\nimport Data.Maybe ( catMaybes, isJust )\nimport Data.Typeable\nimport Foreign.C\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Data.LLVM.Private.Parser.Options\nimport Data.LLVM.Types\nimport Data.LLVM.Private.Types.Dwarf\n\ndata TranslationException = TooManyReturnValues\n | InvalidBranchInst\n | InvalidSwitchLayout\n | InvalidIndirectBranchOperands\n | KnotTyingFailure ValueTag\n | TypeKnotTyingFailure TypeTag\n | InvalidSelectArgs !Int\n | InvalidExtractElementInst !Int\n | InvalidInsertElementInst !Int\n | InvalidShuffleVectorInst !Int\n | InvalidFunctionInTranslateValue\n | InvalidAliasInTranslateValue\n | InvalidGlobalVarInTranslateValue\n | InvalidBinaryOp !Int\n | InvalidUnaryOp !Int\n | InvalidGEPInst !Int\n | InvalidExtractValueInst !Int\n | InvalidInsertValueInst !Int\n deriving (Show, Typeable)\ninstance Exception TranslationException\n\n\n{#enum TypeTag {} deriving (Show, Eq) #}\n{#enum ValueTag {underscoreToCase} deriving (Show, Eq) #}\n{#enum MetaTag {underscoreToCase} deriving (Show, Eq) #}\n\ndata CModule\n{#pointer *CModule as ModulePtr -> CModule #}\n\ncModuleIdentifier :: ModulePtr -> IO ByteString\ncModuleIdentifier m = ({#get CModule->moduleIdentifier#} m) >>= BS.packCString\n\ncModuleDataLayout :: ModulePtr -> IO ByteString\ncModuleDataLayout m = ({#get CModule->moduleDataLayout#} m) >>= BS.packCString\n\ncModuleTargetTriple :: ModulePtr -> IO ByteString\ncModuleTargetTriple m = ({#get CModule->targetTriple#} m) >>= BS.packCString\n\ncModuleInlineAsm :: ModulePtr -> IO ByteString\ncModuleInlineAsm m = ({#get CModule->moduleInlineAsm#} m) >>= BS.packCString\n\ncModuleHasError :: ModulePtr -> IO Bool\ncModuleHasError m = toBool <$> ({#get CModule->hasError#} m)\n\ncModuleErrorMessage :: ModulePtr -> IO (Maybe String)\ncModuleErrorMessage m = do\n hasError <- cModuleHasError m\n case hasError of\n True -> do\n msgPtr <- ({#get CModule->errMsg#} m)\n s <- peekCString msgPtr\n return (Just s)\n False -> return Nothing\n\ncModuleLittleEndian :: ModulePtr -> IO Bool\ncModuleLittleEndian m = toBool <$> ({#get CModule->littleEndian#} m)\n\ncModulePointerSize :: ModulePtr -> IO Int\ncModulePointerSize m = fromIntegral <$> ({#get CModule->pointerSize#} m)\n\ncModuleGlobalVariables :: ModulePtr -> IO [ValuePtr]\ncModuleGlobalVariables m =\n peekArray m {#get CModule->globalVariables#} {#get CModule->numGlobalVariables#}\n\ncModuleGlobalAliases :: ModulePtr -> IO [ValuePtr]\ncModuleGlobalAliases m =\n peekArray m ({#get CModule->globalAliases#}) ({#get CModule->numGlobalAliases#})\n\ncModuleFunctions :: ModulePtr -> IO [ValuePtr]\ncModuleFunctions m =\n peekArray m ({#get CModule->functions#}) ({#get CModule->numFunctions#})\n\npeekArray :: forall a b c e . (Integral c, Storable e) =>\n a -> (a -> IO (Ptr b)) -> (a -> IO c) -> IO [e]\npeekArray obj arrAccessor sizeAccessor = do\n nElts <- sizeAccessor obj\n arrPtr <- arrAccessor obj\n case nElts == 0 || arrPtr == nullPtr of\n True -> return []\n False -> do\n fArrPtr <- newForeignPtr_ (castPtr arrPtr)\n arr <- unsafeForeignPtrToStorableArray fArrPtr (1, fromIntegral nElts)\n getElems arr\n\ndata CType\n{#pointer *CType as TypePtr -> CType #}\ncTypeTag :: TypePtr -> IO TypeTag\ncTypeTag t = toEnum . fromIntegral <$> {#get CType->typeTag#} t\ncTypeSize :: TypePtr -> IO Int\ncTypeSize t = fromIntegral <$> {#get CType->size#} t\ncTypeIsVarArg :: TypePtr -> IO Bool\ncTypeIsVarArg t = toBool <$> {#get CType->isVarArg#} t\ncTypeIsPacked :: TypePtr -> IO Bool\ncTypeIsPacked t = toBool <$> {#get CType->isPacked#} t\ncTypeList :: TypePtr -> IO [TypePtr]\ncTypeList t =\n peekArray t {#get CType->typeList#} {#get CType->typeListLen#}\ncTypeInner :: TypePtr -> IO TypePtr\ncTypeInner = {#get CType->innerType#}\ncTypeName :: TypePtr -> IO String\ncTypeName t = {#get CType->name#} t >>= peekCString\ncTypeAddrSpace :: TypePtr -> IO Int\ncTypeAddrSpace t = fromIntegral <$> {#get CType->addrSpace#} t\n\ndata CValue\n{#pointer *CValue as ValuePtr -> CValue #}\n\ncValueTag :: ValuePtr -> IO ValueTag\ncValueTag v = toEnum . fromIntegral <$> ({#get CValue->valueTag#} v)\ncValueType :: ValuePtr -> IO TypePtr\ncValueType = {#get CValue->valueType#}\ncValueName :: ValuePtr -> IO (Maybe Identifier)\ncValueName v = do\n tag <- cValueTag v\n namePtr <- ({#get CValue->name#}) v\n case namePtr == nullPtr of\n True -> return Nothing\n False -> do\n name <- BS.packCString namePtr\n case tag of\n ValFunction -> return $! (Just . makeGlobalIdentifier) name\n ValGlobalvariable -> return $! (Just . makeGlobalIdentifier) name\n ValAlias -> return $! (Just . makeGlobalIdentifier) name\n _ -> return $! (Just . makeLocalIdentifier) name\ncValueMetadata :: ValuePtr -> IO [MetaPtr]\ncValueMetadata v = peekArray v {#get CValue->md#} {#get CValue->numMetadata#}\ncValueData :: ValuePtr -> IO (Ptr ())\ncValueData = {#get CValue->data#}\n\ndata CMeta\n{#pointer *CMeta as MetaPtr -> CMeta #}\n\ncMetaTypeTag :: MetaPtr -> IO MetaTag\ncMetaTypeTag v = toEnum . fromIntegral <$> {#get CMeta->metaTag #} v\n\ncMetaTag :: MetaPtr -> IO DW_TAG\ncMetaTag p = dw_tag <$> {#get CMeta->tag#} p\n\ncMetaArrayElts :: MetaPtr -> IO [MetaPtr]\ncMetaArrayElts p =\n peekArray p {#get CMeta->u.metaArrayInfo.arrayElts#} {#get CMeta->u.metaArrayInfo.arrayLen#}\ncMetaEnumeratorName :: MetaPtr -> KnotMonad ByteString\ncMetaEnumeratorName = shareString {#get CMeta->u.metaEnumeratorInfo.enumName#}\ncMetaEnumeratorValue :: MetaPtr -> IO Int64\ncMetaEnumeratorValue p = fromIntegral <$> {#get CMeta->u.metaEnumeratorInfo.enumValue#} p\ncMetaGlobalContext :: MetaPtr -> IO MetaPtr\ncMetaGlobalContext = {#get CMeta->u.metaGlobalInfo.context #}\ncMetaGlobalName :: MetaPtr -> KnotMonad ByteString\ncMetaGlobalName = shareString {#get CMeta->u.metaGlobalInfo.name#}\ncMetaGlobalDisplayName :: MetaPtr -> KnotMonad ByteString\ncMetaGlobalDisplayName = shareString {#get CMeta->u.metaGlobalInfo.displayName#}\ncMetaGlobalLinkageName :: MetaPtr -> KnotMonad ByteString\ncMetaGlobalLinkageName = shareString {#get CMeta->u.metaGlobalInfo.linkageName#}\ncMetaGlobalCompileUnit :: MetaPtr -> IO MetaPtr\ncMetaGlobalCompileUnit = {#get CMeta->u.metaGlobalInfo.compileUnit#}\ncMetaGlobalLine :: MetaPtr -> IO Int32\ncMetaGlobalLine p = fromIntegral <$> {#get CMeta->u.metaGlobalInfo.lineNumber#} p\ncMetaGlobalType :: MetaPtr -> IO MetaPtr\ncMetaGlobalType = {#get CMeta->u.metaGlobalInfo.globalType#}\ncMetaGlobalIsLocal :: MetaPtr -> IO Bool\ncMetaGlobalIsLocal p = toBool <$> {#get CMeta->u.metaGlobalInfo.isLocalToUnit#} p\ncMetaGlobalIsDefinition :: MetaPtr -> IO Bool\ncMetaGlobalIsDefinition p = toBool <$> {#get CMeta->u.metaGlobalInfo.isDefinition#} p\ncMetaLocationLine :: MetaPtr -> IO Int32\ncMetaLocationLine p = fromIntegral <$> {#get CMeta->u.metaLocationInfo.lineNumber#} p\ncMetaLocationColumn :: MetaPtr -> IO Int32\ncMetaLocationColumn p = fromIntegral <$> {#get CMeta->u.metaLocationInfo.columnNumber#} p\ncMetaLocationScope :: MetaPtr -> IO MetaPtr\ncMetaLocationScope = {#get CMeta->u.metaLocationInfo.scope#}\ncMetaSubrangeLo :: MetaPtr -> IO Int64\ncMetaSubrangeLo p = fromIntegral <$> {#get CMeta->u.metaSubrangeInfo.lo#} p\ncMetaSubrangeHi :: MetaPtr -> IO Int64\ncMetaSubrangeHi p = fromIntegral <$> {#get CMeta->u.metaSubrangeInfo.hi#} p\ncMetaTemplateTypeContext :: MetaPtr -> IO MetaPtr\ncMetaTemplateTypeContext = {#get CMeta->u.metaTemplateTypeInfo.context#}\ncMetaTemplateTypeName :: MetaPtr -> KnotMonad ByteString\ncMetaTemplateTypeName = shareString {#get CMeta->u.metaTemplateTypeInfo.name#}\ncMetaTemplateTypeType :: MetaPtr -> IO MetaPtr\ncMetaTemplateTypeType = {#get CMeta->u.metaTemplateTypeInfo.type#}\ncMetaTemplateTypeLine :: MetaPtr -> IO Int32\ncMetaTemplateTypeLine p = fromIntegral <$> {#get CMeta->u.metaTemplateTypeInfo.lineNumber#} p\ncMetaTemplateTypeColumn :: MetaPtr -> IO Int32\ncMetaTemplateTypeColumn p = fromIntegral <$> {#get CMeta->u.metaTemplateTypeInfo.columnNumber#} p\ncMetaTemplateValueContext :: MetaPtr -> IO MetaPtr\ncMetaTemplateValueContext = {#get CMeta->u.metaTemplateValueInfo.context#}\ncMetaTemplateValueName :: MetaPtr -> KnotMonad ByteString\ncMetaTemplateValueName = shareString {#get CMeta->u.metaTemplateValueInfo.name#}\ncMetaTemplateValueType :: MetaPtr -> IO MetaPtr\ncMetaTemplateValueType = {#get CMeta->u.metaTemplateValueInfo.type#}\ncMetaTemplateValueValue :: MetaPtr -> IO Int64\ncMetaTemplateValueValue p = fromIntegral <$> {#get CMeta->u.metaTemplateValueInfo.value#} p\ncMetaTemplateValueLine :: MetaPtr -> IO Int32\ncMetaTemplateValueLine p = fromIntegral <$> {#get CMeta->u.metaTemplateValueInfo.lineNumber#} p\ncMetaTemplateValueColumn :: MetaPtr -> IO Int32\ncMetaTemplateValueColumn p = fromIntegral <$> {#get CMeta->u.metaTemplateValueInfo.columnNumber#} p\ncMetaVariableContext :: MetaPtr -> IO MetaPtr\ncMetaVariableContext = {#get CMeta->u.metaVariableInfo.context#}\ncMetaVariableName :: MetaPtr -> KnotMonad ByteString\ncMetaVariableName = shareString {#get CMeta->u.metaVariableInfo.name#}\ncMetaVariableCompileUnit :: MetaPtr -> IO MetaPtr\ncMetaVariableCompileUnit = {#get CMeta->u.metaVariableInfo.compileUnit#}\ncMetaVariableLine :: MetaPtr -> IO Int32\ncMetaVariableLine p = fromIntegral <$> {#get CMeta->u.metaVariableInfo.lineNumber#} p\ncMetaVariableArgNumber :: MetaPtr -> IO Int32\ncMetaVariableArgNumber p = fromIntegral <$> {#get CMeta->u.metaVariableInfo.argNumber#} p\ncMetaVariableType :: MetaPtr -> IO MetaPtr\ncMetaVariableType = {#get CMeta->u.metaVariableInfo.type#}\ncMetaVariableIsArtificial :: MetaPtr -> IO Bool\ncMetaVariableIsArtificial p = toBool <$> {#get CMeta->u.metaVariableInfo.isArtificial#} p\ncMetaVariableHasComplexAddress :: MetaPtr -> IO Bool\ncMetaVariableHasComplexAddress p = toBool <$> {#get CMeta->u.metaVariableInfo.hasComplexAddress #} p\ncMetaVariableAddrElements :: MetaPtr -> IO [Int64]\ncMetaVariableAddrElements p = do\n ca <- cMetaVariableHasComplexAddress p\n case ca of\n True -> peekArray p {#get CMeta->u.metaVariableInfo.addrElements#} {#get CMeta->u.metaVariableInfo.numAddrElements#}\n False -> return []\ncMetaVariableIsBlockByRefVar :: MetaPtr -> IO Bool\ncMetaVariableIsBlockByRefVar p = toBool <$> {#get CMeta->u.metaVariableInfo.isBlockByRefVar#} p\ncMetaCompileUnitLanguage :: MetaPtr -> IO DW_LANG\ncMetaCompileUnitLanguage p = dw_lang <$> {#get CMeta->u.metaCompileUnitInfo.language#} p\ncMetaCompileUnitFilename :: MetaPtr -> KnotMonad ByteString\ncMetaCompileUnitFilename = shareString {#get CMeta->u.metaCompileUnitInfo.filename#}\ncMetaCompileUnitDirectory :: MetaPtr -> KnotMonad ByteString\ncMetaCompileUnitDirectory = shareString {#get CMeta->u.metaCompileUnitInfo.directory#}\ncMetaCompileUnitProducer :: MetaPtr -> KnotMonad ByteString\ncMetaCompileUnitProducer = shareString {#get CMeta->u.metaCompileUnitInfo.producer#}\ncMetaCompileUnitIsMain :: MetaPtr -> IO Bool\ncMetaCompileUnitIsMain p = toBool <$> {#get CMeta->u.metaCompileUnitInfo.isMain#} p\ncMetaCompileUnitIsOptimized :: MetaPtr -> IO Bool\ncMetaCompileUnitIsOptimized p = toBool <$> {#get CMeta->u.metaCompileUnitInfo.isOptimized#} p\ncMetaCompileUnitFlags :: MetaPtr -> KnotMonad ByteString\ncMetaCompileUnitFlags = shareString {#get CMeta->u.metaCompileUnitInfo.flags#}\ncMetaCompileUnitRuntimeVersion :: MetaPtr -> IO Int32\ncMetaCompileUnitRuntimeVersion p = fromIntegral <$> {#get CMeta->u.metaCompileUnitInfo.runtimeVersion#} p\ncMetaFileFilename :: MetaPtr -> KnotMonad ByteString\ncMetaFileFilename = shareString {#get CMeta->u.metaFileInfo.filename#}\ncMetaFileDirectory :: MetaPtr -> KnotMonad ByteString\ncMetaFileDirectory = shareString {#get CMeta->u.metaFileInfo.directory#}\ncMetaFileCompileUnit :: MetaPtr -> IO MetaPtr\ncMetaFileCompileUnit = {#get CMeta->u.metaFileInfo.compileUnit#}\ncMetaLexicalBlockContext :: MetaPtr -> IO MetaPtr\ncMetaLexicalBlockContext = {#get CMeta->u.metaLexicalBlockInfo.context#}\ncMetaLexicalBlockLine :: MetaPtr -> IO Int32\ncMetaLexicalBlockLine p = fromIntegral <$> {#get CMeta->u.metaLexicalBlockInfo.lineNumber#} p\ncMetaLexicalBlockColumn :: MetaPtr -> IO Int32\ncMetaLexicalBlockColumn p = fromIntegral <$> {#get CMeta->u.metaLexicalBlockInfo.columnNumber#} p\ncMetaNamespaceContext :: MetaPtr -> IO MetaPtr\ncMetaNamespaceContext = {#get CMeta->u.metaNamespaceInfo.context#}\ncMetaNamespaceName :: MetaPtr -> KnotMonad ByteString\ncMetaNamespaceName = shareString {#get CMeta->u.metaNamespaceInfo.name#}\ncMetaNamespaceCompileUnit :: MetaPtr -> IO MetaPtr\ncMetaNamespaceCompileUnit = {#get CMeta->u.metaNamespaceInfo.compileUnit#}\ncMetaNamespaceLine :: MetaPtr -> IO Int32\ncMetaNamespaceLine p = fromIntegral <$> {#get CMeta->u.metaNamespaceInfo.lineNumber#} p\ncMetaSubprogramContext :: MetaPtr -> IO MetaPtr\ncMetaSubprogramContext = {#get CMeta->u.metaSubprogramInfo.context#}\ncMetaSubprogramName :: MetaPtr -> KnotMonad ByteString\ncMetaSubprogramName = shareString {#get CMeta->u.metaSubprogramInfo.name#}\ncMetaSubprogramDisplayName :: MetaPtr -> KnotMonad ByteString\ncMetaSubprogramDisplayName = shareString {#get CMeta->u.metaSubprogramInfo.displayName#}\ncMetaSubprogramLinkageName :: MetaPtr -> KnotMonad ByteString\ncMetaSubprogramLinkageName = shareString {#get CMeta->u.metaSubprogramInfo.linkageName#}\ncMetaSubprogramCompileUnit :: MetaPtr -> IO MetaPtr\ncMetaSubprogramCompileUnit = {#get CMeta->u.metaSubprogramInfo.compileUnit#}\ncMetaSubprogramLine :: MetaPtr -> IO Int32\ncMetaSubprogramLine p = fromIntegral <$> {#get CMeta->u.metaSubprogramInfo.lineNumber#} p\ncMetaSubprogramType :: MetaPtr -> IO MetaPtr\ncMetaSubprogramType = {#get CMeta->u.metaSubprogramInfo.type#}\ncMetaSubprogramIsLocal :: MetaPtr -> IO Bool\ncMetaSubprogramIsLocal p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isLocalToUnit#} p\ncMetaSubprogramIsDefinition :: MetaPtr -> IO Bool\ncMetaSubprogramIsDefinition p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isDefinition#} p\ncMetaSubprogramVirtuality :: MetaPtr -> IO DW_VIRTUALITY\ncMetaSubprogramVirtuality p = dw_virtuality <$> {#get CMeta->u.metaSubprogramInfo.virtuality#} p\ncMetaSubprogramVirtualIndex :: MetaPtr -> IO Int32\ncMetaSubprogramVirtualIndex p = fromIntegral <$> {#get CMeta->u.metaSubprogramInfo.virtualIndex#} p\ncMetaSubprogramContainingType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaSubprogramContainingType = optionalField {#get CMeta->u.metaSubprogramInfo.containingType#}\ncMetaSubprogramIsArtificial :: MetaPtr -> IO Bool\ncMetaSubprogramIsArtificial p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isArtificial#} p\ncMetaSubprogramIsPrivate :: MetaPtr -> IO Bool\ncMetaSubprogramIsPrivate p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isPrivate#} p\ncMetaSubprogramIsProtected :: MetaPtr -> IO Bool\ncMetaSubprogramIsProtected p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isProtected#} p\ncMetaSubprogramIsExplicit :: MetaPtr -> IO Bool\ncMetaSubprogramIsExplicit p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isExplicit#} p\ncMetaSubprogramIsPrototyped :: MetaPtr -> IO Bool\ncMetaSubprogramIsPrototyped p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isPrototyped#} p\ncMetaSubprogramIsOptimized :: MetaPtr -> IO Bool\ncMetaSubprogramIsOptimized p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isOptimized#} p\ncMetaTypeContext :: MetaPtr -> IO MetaPtr\ncMetaTypeContext = {#get CMeta->u.metaTypeInfo.context#}\ncMetaTypeName :: MetaPtr -> KnotMonad ByteString\ncMetaTypeName = shareString {#get CMeta->u.metaTypeInfo.name#}\ncMetaTypeCompileUnit :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeCompileUnit = optionalField {#get CMeta->u.metaTypeInfo.compileUnit#}\ncMetaTypeFile :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeFile = optionalField {#get CMeta->u.metaTypeInfo.file#}\ncMetaTypeLine :: MetaPtr -> IO Int32\ncMetaTypeLine p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.lineNumber#} p\ncMetaTypeSize :: MetaPtr -> IO Int64\ncMetaTypeSize p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.sizeInBits#} p\ncMetaTypeAlign :: MetaPtr -> IO Int64\ncMetaTypeAlign p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.alignInBits#} p\ncMetaTypeOffset :: MetaPtr -> IO Int64\ncMetaTypeOffset p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.offsetInBits#} p\ncMetaTypeFlags :: MetaPtr -> IO Int32\ncMetaTypeFlags p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.flags#} p\ncMetaTypeIsPrivate :: MetaPtr -> IO Bool\ncMetaTypeIsPrivate p = toBool <$> {#get CMeta->u.metaTypeInfo.isPrivate#} p\ncMetaTypeIsProtected :: MetaPtr -> IO Bool\ncMetaTypeIsProtected p = toBool <$> {#get CMeta->u.metaTypeInfo.isProtected#} p\ncMetaTypeIsForward :: MetaPtr -> IO Bool\ncMetaTypeIsForward p = toBool <$> {#get CMeta->u.metaTypeInfo.isForward#} p\ncMetaTypeIsByRefStruct :: MetaPtr -> IO Bool\ncMetaTypeIsByRefStruct p = toBool <$> {#get CMeta->u.metaTypeInfo.isByRefStruct#} p\ncMetaTypeIsVirtual :: MetaPtr -> IO Bool\ncMetaTypeIsVirtual p = toBool <$> {#get CMeta->u.metaTypeInfo.isVirtual#} p\ncMetaTypeIsArtificial :: MetaPtr -> IO Bool\ncMetaTypeIsArtificial p = toBool <$> {#get CMeta->u.metaTypeInfo.isArtificial#} p\ncMetaTypeEncoding :: MetaPtr -> IO DW_ATE\ncMetaTypeEncoding p = dw_ate <$> {#get CMeta->u.metaTypeInfo.encoding#} p\ncMetaTypeDerivedFrom :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeDerivedFrom = optionalField {#get CMeta->u.metaTypeInfo.typeDerivedFrom#}\ncMetaTypeCompositeComponents :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeCompositeComponents = optionalField {#get CMeta->u.metaTypeInfo.typeArray#}\ncMetaTypeRuntimeLanguage :: MetaPtr -> IO Int32\ncMetaTypeRuntimeLanguage p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.runTimeLang#} p\ncMetaTypeContainingType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeContainingType = optionalField {#get CMeta->u.metaTypeInfo.containingType#}\ncMetaTypeTemplateParams :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeTemplateParams = optionalField {#get CMeta->u.metaTypeInfo.templateParams#}\n\noptionalField :: (a -> IO (Ptr b)) -> a -> IO (Maybe (Ptr b))\noptionalField accessor p = do\n v <- accessor p\n case v == nullPtr of\n True -> return Nothing\n False -> return (Just v)\n\n-- | This helper converts C char* strings into ByteStrings, sharing\n-- identical bytestrings on the Haskell side. This is a simple\n-- space-saving optimization (assuming the entire cache is garbage\n-- collected)\nshareString :: (a -> IO CString) -> a -> KnotMonad ByteString\nshareString accessor ptr = do\n str <- liftIO $ accessor ptr >>= BS.packCString\n s <- get\n let cache = stringCache s\n case M.lookup str cache of\n Just cval -> return cval\n Nothing -> do\n put s { stringCache = M.insert str str cache }\n return str\n\ndata CGlobalInfo\n{#pointer *CGlobalInfo as GlobalInfoPtr -> CGlobalInfo #}\ncGlobalIsExternal :: GlobalInfoPtr -> IO Bool\ncGlobalIsExternal g = toBool <$> ({#get CGlobalInfo->isExternal#} g)\ncGlobalAlignment :: GlobalInfoPtr -> IO Int64\ncGlobalAlignment g = fromIntegral <$> ({#get CGlobalInfo->alignment#} g)\ncGlobalVisibility :: GlobalInfoPtr -> IO VisibilityStyle\ncGlobalVisibility g = toEnum . fromIntegral <$> ({#get CGlobalInfo->visibility#} g)\ncGlobalLinkage :: GlobalInfoPtr -> IO LinkageType\ncGlobalLinkage g = toEnum . fromIntegral <$> ({#get CGlobalInfo->linkage#} g)\ncGlobalSection :: GlobalInfoPtr -> IO (Maybe ByteString)\ncGlobalSection g = do\n s <- {#get CGlobalInfo->section#} g\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just bs\ncGlobalInitializer :: GlobalInfoPtr -> IO ValuePtr\ncGlobalInitializer = {#get CGlobalInfo->initializer#}\ncGlobalIsThreadLocal :: GlobalInfoPtr -> IO Bool\ncGlobalIsThreadLocal g = toBool <$> ({#get CGlobalInfo->isThreadLocal#} g)\ncGlobalAliasee :: GlobalInfoPtr -> IO ValuePtr\ncGlobalAliasee = {#get CGlobalInfo->aliasee#}\ncGlobalIsConstant :: GlobalInfoPtr -> IO Bool\ncGlobalIsConstant g = toBool <$> {#get CGlobalInfo->isConstant#} g\n\ndata CFunctionInfo\n{#pointer *CFunctionInfo as FunctionInfoPtr -> CFunctionInfo #}\ncFunctionIsExternal :: FunctionInfoPtr -> IO Bool\ncFunctionIsExternal f = toBool <$> {#get CFunctionInfo->isExternal#} f\ncFunctionAlignment :: FunctionInfoPtr -> IO Int64\ncFunctionAlignment f = fromIntegral <$> {#get CFunctionInfo->alignment#} f\ncFunctionVisibility :: FunctionInfoPtr -> IO VisibilityStyle\ncFunctionVisibility f = toEnum . fromIntegral <$> {#get CFunctionInfo->visibility#} f\ncFunctionLinkage :: FunctionInfoPtr -> IO LinkageType\ncFunctionLinkage f = toEnum . fromIntegral <$> {#get CFunctionInfo->linkage#} f\ncFunctionSection :: FunctionInfoPtr -> IO (Maybe ByteString)\ncFunctionSection f = do\n s <- {#get CFunctionInfo->section#} f\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just bs\ncFunctionIsVarArg :: FunctionInfoPtr -> IO Bool\ncFunctionIsVarArg f = toBool <$> {#get CFunctionInfo->isVarArg#} f\ncFunctionCallingConvention :: FunctionInfoPtr -> IO CallingConvention\ncFunctionCallingConvention f = toEnum . fromIntegral <$> {#get CFunctionInfo->callingConvention#} f\ncFunctionGCName :: FunctionInfoPtr -> IO (Maybe ByteString)\ncFunctionGCName f = do\n s <- {#get CFunctionInfo->gcName#} f\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just bs\ncFunctionArguments :: FunctionInfoPtr -> IO [ValuePtr]\ncFunctionArguments f =\n peekArray f {#get CFunctionInfo->arguments#} {#get CFunctionInfo->argListLen#}\ncFunctionBlocks :: FunctionInfoPtr -> IO [ValuePtr]\ncFunctionBlocks f =\n peekArray f {#get CFunctionInfo->body#} {#get CFunctionInfo->blockListLen#}\n\ndata CArgInfo\n{#pointer *CArgumentInfo as ArgInfoPtr -> CArgInfo #}\ncArgInfoHasSRet :: ArgInfoPtr -> IO Bool\ncArgInfoHasSRet a = toBool <$> ({#get CArgumentInfo->hasSRet#} a)\ncArgInfoHasByVal :: ArgInfoPtr -> IO Bool\ncArgInfoHasByVal a = toBool <$> ({#get CArgumentInfo->hasByVal#} a)\ncArgInfoHasNest :: ArgInfoPtr -> IO Bool\ncArgInfoHasNest a = toBool <$> ({#get CArgumentInfo->hasNest#} a)\ncArgInfoHasNoAlias :: ArgInfoPtr -> IO Bool\ncArgInfoHasNoAlias a = toBool <$> ({#get CArgumentInfo->hasNoAlias#} a)\ncArgInfoHasNoCapture :: ArgInfoPtr -> IO Bool\ncArgInfoHasNoCapture a = toBool <$> ({#get CArgumentInfo->hasNoCapture#} a)\n\ndata CBasicBlockInfo\n{#pointer *CBasicBlockInfo as BasicBlockPtr -> CBasicBlockInfo #}\n\ncBasicBlockInstructions :: BasicBlockPtr -> IO [ValuePtr]\ncBasicBlockInstructions b =\n peekArray b {#get CBasicBlockInfo->instructions#} {#get CBasicBlockInfo->blockLen#}\n\ndata CInlineAsmInfo\n{#pointer *CInlineAsmInfo as InlineAsmInfoPtr -> CInlineAsmInfo #}\n\ncInlineAsmString :: InlineAsmInfoPtr -> IO ByteString\ncInlineAsmString a =\n ({#get CInlineAsmInfo->asmString#} a) >>= BS.packCString\ncInlineAsmConstraints :: InlineAsmInfoPtr -> IO ByteString\ncInlineAsmConstraints a =\n ({#get CInlineAsmInfo->constraintString#} a) >>= BS.packCString\n\ndata CBlockAddrInfo\n{#pointer *CBlockAddrInfo as BlockAddrInfoPtr -> CBlockAddrInfo #}\n\ncBlockAddrFunc :: BlockAddrInfoPtr -> IO ValuePtr\ncBlockAddrFunc = {#get CBlockAddrInfo->func #}\ncBlockAddrBlock :: BlockAddrInfoPtr -> IO ValuePtr\ncBlockAddrBlock = {#get CBlockAddrInfo->block #}\n\ndata CAggregateInfo\n{#pointer *CConstAggregate as AggregateInfoPtr -> CAggregateInfo #}\n\ncAggregateValues :: AggregateInfoPtr -> IO [ValuePtr]\ncAggregateValues a =\n peekArray a {#get CConstAggregate->constants#} {#get CConstAggregate->numElements#}\n\ndata CConstFP\n{#pointer *CConstFP as FPInfoPtr -> CConstFP #}\ncFPVal :: FPInfoPtr -> IO Double\ncFPVal f = realToFrac <$> ({#get CConstFP->val#} f)\n\ndata CConstInt\n{#pointer *CConstInt as IntInfoPtr -> CConstInt #}\ncIntVal :: IntInfoPtr -> IO Integer\ncIntVal i = fromIntegral <$> ({#get CConstInt->val#} i)\n\ndata CInstructionInfo\n{#pointer *CInstructionInfo as InstInfoPtr -> CInstructionInfo #}\ncInstructionOperands :: InstInfoPtr -> IO [ValuePtr]\ncInstructionOperands i =\n peekArray i {#get CInstructionInfo->operands#} {#get CInstructionInfo->numOperands#}\ncInstructionArithFlags :: InstInfoPtr -> IO ArithFlags\ncInstructionArithFlags o = toEnum . fromIntegral <$> {#get CInstructionInfo->flags#} o\ncInstructionAlign :: InstInfoPtr -> IO Int64\ncInstructionAlign u = fromIntegral <$> {#get CInstructionInfo->align#} u\ncInstructionIsVolatile :: InstInfoPtr -> IO Bool\ncInstructionIsVolatile u = toBool <$> {#get CInstructionInfo->isVolatile#} u\ncInstructionAddrSpace :: InstInfoPtr -> IO Int\ncInstructionAddrSpace u = fromIntegral <$> {#get CInstructionInfo->addrSpace#} u\ncInstructionCmpPred :: InstInfoPtr -> IO CmpPredicate\ncInstructionCmpPred c = toEnum . fromIntegral <$> {#get CInstructionInfo->cmpPred#} c\ncInstructionInBounds :: InstInfoPtr -> IO Bool\ncInstructionInBounds g = toBool <$> {#get CInstructionInfo->inBounds#} g\ncInstructionIndices :: InstInfoPtr -> IO [Int]\ncInstructionIndices i =\n peekArray i {#get CInstructionInfo->indices#} {#get CInstructionInfo->numIndices#}\n\ndata CConstExprInfo\n{#pointer *CConstExprInfo as ConstExprPtr -> CConstExprInfo #}\ncConstExprTag :: ConstExprPtr -> IO ValueTag\ncConstExprTag e = toEnum . fromIntegral <$> {#get CConstExprInfo->instrType#} e\ncConstExprInstInfo :: ConstExprPtr -> IO InstInfoPtr\ncConstExprInstInfo = {#get CConstExprInfo->ii#}\n\ndata CPHIInfo\n{#pointer *CPHIInfo as PHIInfoPtr -> CPHIInfo #}\ncPHIValues :: PHIInfoPtr -> IO [ValuePtr]\ncPHIValues p =\n peekArray p {#get CPHIInfo->incomingValues#} {#get CPHIInfo->numIncomingValues#}\ncPHIBlocks :: PHIInfoPtr -> IO [ValuePtr]\ncPHIBlocks p =\n peekArray p {#get CPHIInfo->valueBlocks#} {#get CPHIInfo->numIncomingValues#}\n\ndata CCallInfo\n{#pointer *CCallInfo as CallInfoPtr -> CCallInfo #}\ncCallValue :: CallInfoPtr -> IO ValuePtr\ncCallValue = {#get CCallInfo->calledValue #}\ncCallArguments :: CallInfoPtr -> IO [ValuePtr]\ncCallArguments c =\n peekArray c {#get CCallInfo->arguments#} {#get CCallInfo->argListLen#}\ncCallConvention :: CallInfoPtr -> IO CallingConvention\ncCallConvention c = toEnum . fromIntegral <$> {#get CCallInfo->callingConvention#} c\ncCallHasSRet :: CallInfoPtr -> IO Bool\ncCallHasSRet c = toBool <$> {#get CCallInfo->hasSRet#} c\ncCallIsTail :: CallInfoPtr -> IO Bool\ncCallIsTail c = toBool <$> {#get CCallInfo->isTail#} c\ncCallUnwindDest :: CallInfoPtr -> IO ValuePtr\ncCallUnwindDest = {#get CCallInfo->unwindDest#}\ncCallNormalDest :: CallInfoPtr -> IO ValuePtr\ncCallNormalDest = {#get CCallInfo->normalDest#}\n\n-- | Parse the named file into an FFI-friendly representation of an\n-- LLVM module.\n{#fun marshalLLVM { `String', fromBool `Bool' } -> `ModulePtr' id #}\n\n-- | Free all of the resources allocated by 'marshalLLVM'\n{#fun disposeCModule { id `ModulePtr' } -> `()' #}\n\ntype KnotMonad = StateT KnotState IO\ndata KnotState = KnotState { valueMap :: Map IntPtr Value\n , typeMap :: Map IntPtr Type\n , metaMap :: Map IntPtr Metadata\n , idSrc :: IORef Int\n , typeIdSrc :: IORef Int\n , metaIdSrc :: IORef Int\n , result :: Maybe Module\n , visitedTypes :: Set IntPtr\n , localId :: Int\n , constantTranslationDepth :: Int\n , stringCache :: Map ByteString ByteString\n }\nemptyState :: IORef Int -> IORef Int -> IORef Int -> KnotState\nemptyState r1 r2 r3 =\n KnotState { valueMap = M.empty\n , typeMap = M.empty\n , metaMap = M.empty\n , idSrc = r1\n , typeIdSrc = r2\n , metaIdSrc = r3\n , result = Nothing\n , visitedTypes = S.empty\n , localId = 0\n , constantTranslationDepth = 0\n , stringCache = M.empty\n }\n\nnextId :: KnotMonad Int\nnextId = do\n s <- get\n let r = idSrc s\n thisId <- liftIO $ readIORef r\n liftIO $ modifyIORef r (+1)\n\n return thisId\n\nnextTypeId :: KnotMonad Int\nnextTypeId = do\n s <- get\n let r = typeIdSrc s\n thisId <- liftIO $ readIORef r\n liftIO $ modifyIORef r (+1)\n\n return thisId\n\nnextMetaId :: KnotMonad Int\nnextMetaId = do\n s <- get\n let r = metaIdSrc s\n thisId <- liftIO $ readIORef r\n liftIO $ modifyIORef r (+1)\n\n return thisId\n\n-- | Parse the named LLVM bitcode file into the LLVM form of the IR (a\n-- 'Module'). In the case of an error, a descriptive string will be\n-- returned.\nparseLLVMBitcodeFile :: ParserOptions -> FilePath -> IO (Either String Module)\nparseLLVMBitcodeFile opts bitcodefile = do\n let includeLineNumbers = metaPositionPrecision opts == PositionPrecise\n m <- marshalLLVM bitcodefile includeLineNumbers\n\n hasError <- cModuleHasError m\n case hasError of\n True -> do\n Just err <- cModuleErrorMessage m\n disposeCModule m\n return $ Left err\n False -> catch (doParse m) exHandler\n where\n exHandler :: TranslationException -> IO (Either String Module)\n exHandler ex = return $ Left (show ex)\n doParse m = do\n idref <- newIORef 0\n tref <- newIORef 0\n mref <- newIORef 0\n res <- evalStateT (mfix (tieKnot m)) (emptyState idref tref mref)\n\n disposeCModule m\n case result res of\n Just r -> return $ Right (r `deepseq` r)\n Nothing -> return $ Left \"No module in result\"\n\n\ntieKnot :: ModulePtr -> KnotState -> KnotMonad KnotState\ntieKnot m finalState = do\n modIdent <- liftIO $ cModuleIdentifier m\n dataLayout <- liftIO $ cModuleDataLayout m\n triple <- liftIO $ cModuleTargetTriple m\n inlineAsm <- liftIO $ cModuleInlineAsm m\n\n vars <- liftIO $ cModuleGlobalVariables m\n aliases <- liftIO $ cModuleGlobalAliases m\n funcs <- liftIO $ cModuleFunctions m\n\n vars' <- mapM (translateGlobalVariable finalState) vars\n aliases' <- mapM (translateAlias finalState) aliases\n funcs' <- mapM (translateFunction finalState) funcs\n\n let ir = Module { moduleIdentifier = modIdent\n , moduleDataLayout = dataLayout\n , moduleTarget = triple\n , moduleAssembly = Assembly inlineAsm\n , moduleAliases = aliases'\n , moduleGlobalVariables = vars'\n , moduleFunctions = funcs'\n }\n s <- get\n return s { result = Just ir }\n\ntranslateType :: KnotState -> TypePtr -> KnotMonad Type\ntranslateType finalState tp = do\n s <- get\n let ip = ptrToIntPtr tp\n -- This top-level translateType function is never called\n -- recursively, so the set it introduces here will be valid for the\n -- entire duration of the translateType call. It will be\n -- overwritten on the next call.\n put s { visitedTypes = S.singleton ip }\n case M.lookup ip (typeMap s) of\n Just t -> return t\n Nothing -> do\n t <- translateType' finalState tp\n st <- get\n put st { typeMap = M.insert ip t (typeMap st) }\n return t\n\ntranslateTypeRec :: KnotState -> TypePtr -> KnotMonad Type\ntranslateTypeRec finalState tp = do\n s <- get\n let ip = ptrToIntPtr tp\n -- Mark this type as visited in the state - the pattern match below\n -- refers to the version of the map *before* this insertion.\n put s { visitedTypes = S.insert ip (visitedTypes s) }\n case M.lookup ip (typeMap s) of\n -- If we already translated, just do the simple thing.\n Just t -> return t\n Nothing -> do\n tag <- liftIO $ cTypeTag tp\n case (S.member ip (visitedTypes s), tag) of\n -- This is a cyclic reference - look it up in the final result\n (False, TYPE_NAMED) -> do\n -- If we have never seen a reference to this named type\n -- before, we need to create it.\n name <- liftIO $ cTypeName tp\n itp <- liftIO $ cTypeInner tp\n innerType <- translateTypeRec finalState itp\n\n let t = TypeNamed name innerType\n\n st <- get\n let m = typeMap st\n m' = M.insert (ptrToIntPtr itp) innerType m\n m'' = M.insert ip t m'\n put st { typeMap = m'' }\n\n return t\n\n (True, TYPE_NAMED) -> do\n -- Otherwise, if we *have* seen it before, we can just look\n -- it up. This handles the case of seeing the same named\n -- type for the first time within e.g., a TypeStruct\n return $ M.findWithDefault (throw (TypeKnotTyingFailure tag)) ip (typeMap finalState)\n (True, _) -> do\n -- Here we have detected a cycle in a type that isn't broken\n -- up by a NamedType. We introduce an artificial name (a\n -- type upref) to break the cycle. This makes it a lot\n -- easier to print out types later on, as we don't have to\n -- do on-the-fly cycle detection everywhere we want to work\n -- with types.\n let innerType = M.findWithDefault (throw (TypeKnotTyingFailure tag)) ip (typeMap finalState)\n uprefName <- nextTypeId\n let t = TypeNamed (show uprefName) innerType\n st <- get\n put st { typeMap = M.insert ip t (typeMap st) }\n return t\n _ -> translateType' finalState tp\n\ntranslateType' :: KnotState -> TypePtr -> KnotMonad Type\ntranslateType' finalState tp = do\n s <- get\n tag <- liftIO $ cTypeTag tp\n t <- case tag of\n TYPE_VOID -> return TypeVoid\n TYPE_FLOAT -> return TypeFloat\n TYPE_DOUBLE -> return TypeDouble\n TYPE_X86_FP80 -> return TypeX86FP80\n TYPE_FP128 -> return TypeFP128\n TYPE_PPC_FP128 -> return TypePPCFP128\n TYPE_LABEL -> return TypeLabel\n TYPE_METADATA -> return TypeMetadata\n TYPE_X86_MMX -> return TypeX86MMX\n TYPE_OPAQUE -> return TypeOpaque\n TYPE_INTEGER -> do\n sz <- liftIO $ cTypeSize tp\n return $ TypeInteger sz\n TYPE_FUNCTION -> do\n isVa <- liftIO $ cTypeIsVarArg tp\n rtp <- liftIO $ cTypeInner tp\n argTypePtrs <- liftIO $ cTypeList tp\n\n rType <- translateTypeRec finalState rtp\n argTypes <- mapM (translateTypeRec finalState) argTypePtrs\n\n return $ TypeFunction rType argTypes isVa\n TYPE_STRUCT -> do\n isPacked <- liftIO $ cTypeIsPacked tp\n ptrs <- liftIO $ cTypeList tp\n\n types <- mapM (translateTypeRec finalState) ptrs\n\n return $ TypeStruct types isPacked\n TYPE_ARRAY -> do\n sz <- liftIO $ cTypeSize tp\n itp <- liftIO $ cTypeInner tp\n innerType <- translateTypeRec finalState itp\n\n return $ TypeArray sz innerType\n TYPE_POINTER -> do\n itp <- liftIO $ cTypeInner tp\n addrSpc <- liftIO $ cTypeAddrSpace tp\n innerType <- translateTypeRec finalState itp\n\n return $ TypePointer innerType addrSpc\n TYPE_VECTOR -> do\n sz <- liftIO $ cTypeSize tp\n itp <- liftIO $ cTypeInner tp\n innerType <- translateTypeRec finalState itp\n\n return $ TypeVector sz innerType\n TYPE_NAMED -> do\n name <- liftIO $ cTypeName tp\n itp <- liftIO $ cTypeInner tp\n innerType <- translateTypeRec finalState itp\n\n return $ TypeNamed name innerType\n -- Need to get the latest state that exists after processing all\n -- inner types above, otherwise we'll erase their updates from the\n -- map.\n s' <- get\n put s' { typeMap = M.insert (ptrToIntPtr tp) t (typeMap s') }\n return t\n\nrecordValue :: ValuePtr -> Value -> KnotMonad ()\nrecordValue vp v = do\n s <- get\n let key = ptrToIntPtr vp\n oldMap = valueMap s\n put s { valueMap = M.insert key v oldMap }\n\ntranslateAlias :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateAlias finalState vp = do\n name <- liftIO $ cValueName vp\n typePtr <- liftIO $ cValueType vp\n dataPtr <- liftIO $ cValueData vp\n metaPtr <- liftIO $ cValueMetadata vp\n let dataPtr' = castPtr dataPtr\n\n mds <- mapM translateMetadata metaPtr\n\n vis <- liftIO $ cGlobalVisibility dataPtr'\n link <- liftIO $ cGlobalLinkage dataPtr'\n aliasee <- liftIO $ cGlobalAliasee dataPtr'\n\n ta <- translateConstOrRef finalState aliasee\n tt <- translateType finalState typePtr\n\n uid <- nextId\n\n let ga = GlobalAlias { globalAliasLinkage = link\n , globalAliasVisibility = vis\n , globalAliasValue = ta\n }\n v = Value { valueType = tt\n , valueName = name\n , valueMetadata = mds\n , valueContent = ga\n , valueUniqueId = uid\n }\n\n recordValue vp v\n\n return v\n\ntranslateGlobalVariable :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateGlobalVariable finalState vp = do\n name <- liftIO $ cValueName vp\n typePtr <- liftIO $ cValueType vp\n dataPtr <- liftIO $ cValueData vp\n metaPtr <- liftIO $ cValueMetadata vp\n tt <- translateType finalState typePtr\n\n mds <- mapM translateMetadata metaPtr\n uid <- nextId\n\n let dataPtr' = castPtr dataPtr\n basicVal = Value { valueName = name\n , valueType = tt\n , valueMetadata = mds\n , valueContent = ExternalValue\n , valueUniqueId = uid\n }\n isExtern <- liftIO $ cGlobalIsExternal dataPtr'\n\n case isExtern of\n True -> do\n recordValue vp basicVal\n return basicVal\n False -> do\n align <- liftIO $ cGlobalAlignment dataPtr'\n vis <- liftIO $ cGlobalVisibility dataPtr'\n link <- liftIO $ cGlobalLinkage dataPtr'\n section <- liftIO $ cGlobalSection dataPtr'\n isThreadLocal <- liftIO $ cGlobalIsThreadLocal dataPtr'\n initializer <- liftIO $ cGlobalInitializer dataPtr'\n isConst <- liftIO $ cGlobalIsConstant dataPtr'\n\n ti <- case initializer == nullPtr of\n True -> return Nothing\n False -> do\n tv <- translateConstOrRef finalState initializer\n return $ Just tv\n\n let gv = GlobalDeclaration { globalVariableLinkage = link\n , globalVariableVisibility = vis\n , globalVariableInitializer = ti\n , globalVariableAlignment = align\n , globalVariableSection = section\n , globalVariableIsThreadLocal = isThreadLocal\n , globalVariableIsConstant = isConst\n }\n v = basicVal { valueContent = gv }\n recordValue vp v\n return v\n\nresetLocalIdCounter :: KnotMonad ()\nresetLocalIdCounter = do\n s <- get\n put s { localId = 0 }\n\ntranslateFunction :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateFunction finalState vp = do\n name <- liftIO $ cValueName vp\n typePtr <- liftIO $ cValueType vp\n dataPtr <- liftIO $ cValueData vp\n metaPtr <- liftIO $ cValueMetadata vp\n tt <- translateType finalState typePtr\n\n mds <- mapM translateMetadata metaPtr\n\n uid <- nextId\n\n resetLocalIdCounter\n\n let dataPtr' = castPtr dataPtr\n basicVal = Value { valueName = name\n , valueType = tt\n , valueMetadata = mds\n , valueContent = ExternalFunction [] -- FIXME: there are attributes here\n , valueUniqueId = uid\n }\n isExtern <- liftIO $ cFunctionIsExternal dataPtr'\n\n case isExtern of\n True -> do\n recordValue vp basicVal\n return basicVal\n False -> do\n align <- liftIO $ cFunctionAlignment dataPtr'\n vis <- liftIO $ cFunctionVisibility dataPtr'\n link <- liftIO $ cFunctionLinkage dataPtr'\n section <- liftIO $ cFunctionSection dataPtr'\n cc <- liftIO $ cFunctionCallingConvention dataPtr'\n gcname <- liftIO $ cFunctionGCName dataPtr'\n args <- liftIO $ cFunctionArguments dataPtr'\n blocks <- liftIO $ cFunctionBlocks dataPtr'\n isVarArg <- liftIO $ cFunctionIsVarArg dataPtr'\n\n args' <- mapM (translateValue finalState) args\n blocks' <- mapM (translateValue finalState) blocks\n\n let f = Function { functionParameters = args'\n , functionBody = blocks'\n , functionLinkage = link\n , functionVisibility = vis\n , functionCC = cc\n , functionRetAttrs = [] -- FIXME\n , functionAttrs = [] -- FIXME\n , functionSection = section\n , functionAlign = align\n , functionGCName = gcname\n , functionIsVararg = isVarArg\n }\n v = basicVal { valueContent = f }\n recordValue vp v\n return v\n\nconstantBracket :: KnotMonad ValueT -> KnotMonad ValueT\nconstantBracket c = do\n s <- get\n let tdepth = constantTranslationDepth s\n put s { constantTranslationDepth = tdepth + 1 }\n ret <- c\n s' <- get\n let tdepth' = constantTranslationDepth s'\n put s' { constantTranslationDepth = tdepth' - 1 }\n return ret\n\n-- | This wrapper checks to see if we have translated the value yet\n-- (but not against the final state - only the internal running\n-- state). This way we really translate it if it hasn't been seen\n-- yet, but get the translated value if we have touched it before.\ntranslateValue :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateValue finalState vp = do\n s <- get\n case M.lookup (ptrToIntPtr vp) (valueMap s) of\n Nothing -> translateValue' finalState vp\n Just v -> return v\n\n-- | Only the top-level translators should call this: Globals and BasicBlocks\n-- (Or translateConstOrRef when translating constants)\ntranslateValue' :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateValue' finalState vp = do\n tag <- liftIO $ cValueTag vp\n name <- liftIO $ cValueName vp\n typePtr <- liftIO $ cValueType vp\n dataPtr <- liftIO $ cValueData vp\n metaPtr <- liftIO $ cValueMetadata vp\n\n mds <- mapM translateMetadata metaPtr\n\n s <- get\n let cdepth = constantTranslationDepth s\n idCtr = localId s\n realName <- case isJust name || isGlobal tag || isConstant tag || cdepth > 0 of\n True -> return name\n False -> do\n put s { localId = idCtr + 1 }\n return $ Just $ makeLocalIdentifier $ BS.pack (show idCtr)\n\n tt <- translateType finalState typePtr\n\n content <- case tag of\n ValArgument -> translateArgument finalState (castPtr dataPtr)\n ValBasicblock -> translateBasicBlock finalState (castPtr dataPtr)\n ValInlineasm -> constantBracket $ translateInlineAsm finalState (castPtr dataPtr)\n ValBlockaddress -> constantBracket $ translateBlockAddress finalState (castPtr dataPtr)\n ValConstantaggregatezero -> return ConstantAggregateZero\n ValConstantpointernull -> return ConstantPointerNull\n ValUndefvalue -> return UndefValue\n ValConstantarray -> constantBracket $ translateConstantAggregate finalState ConstantArray (castPtr dataPtr)\n ValConstantstruct -> constantBracket $ translateConstantAggregate finalState ConstantStruct (castPtr dataPtr)\n ValConstantvector -> constantBracket $ translateConstantAggregate finalState ConstantVector (castPtr dataPtr)\n ValConstantfp -> translateConstantFP finalState (castPtr dataPtr)\n ValConstantint -> translateConstantInt finalState (castPtr dataPtr)\n ValRetinst -> translateRetInst finalState (castPtr dataPtr)\n ValBranchinst -> translateBranchInst finalState (castPtr dataPtr)\n ValSwitchinst -> translateSwitchInst finalState (castPtr dataPtr)\n ValIndirectbrinst -> translateIndirectBrInst finalState (castPtr dataPtr)\n ValInvokeinst -> translateInvokeInst finalState (castPtr dataPtr)\n ValUnwindinst -> return UnwindInst\n ValUnreachableinst -> return UnreachableInst\n ValAddinst -> translateFlaggedBinaryOp finalState AddInst (castPtr dataPtr)\n ValFaddinst -> translateFlaggedBinaryOp finalState AddInst (castPtr dataPtr)\n ValSubinst -> translateFlaggedBinaryOp finalState SubInst (castPtr dataPtr)\n ValFsubinst -> translateFlaggedBinaryOp finalState SubInst (castPtr dataPtr)\n ValMulinst -> translateFlaggedBinaryOp finalState MulInst (castPtr dataPtr)\n ValFmulinst -> translateFlaggedBinaryOp finalState MulInst (castPtr dataPtr)\n ValUdivinst -> translateBinaryOp finalState DivInst (castPtr dataPtr)\n ValSdivinst -> translateBinaryOp finalState DivInst (castPtr dataPtr)\n ValFdivinst -> translateBinaryOp finalState DivInst (castPtr dataPtr)\n ValUreminst -> translateBinaryOp finalState RemInst (castPtr dataPtr)\n ValSreminst -> translateBinaryOp finalState RemInst (castPtr dataPtr)\n ValFreminst -> translateBinaryOp finalState RemInst (castPtr dataPtr)\n ValShlinst -> translateBinaryOp finalState ShlInst (castPtr dataPtr)\n ValLshrinst -> translateBinaryOp finalState LshrInst (castPtr dataPtr)\n ValAshrinst -> translateBinaryOp finalState AshrInst (castPtr dataPtr)\n ValAndinst -> translateBinaryOp finalState AndInst (castPtr dataPtr)\n ValOrinst -> translateBinaryOp finalState OrInst (castPtr dataPtr)\n ValXorinst -> translateBinaryOp finalState XorInst (castPtr dataPtr)\n ValAllocainst -> translateAllocaInst finalState (castPtr dataPtr)\n ValLoadinst -> translateLoadInst finalState (castPtr dataPtr)\n ValStoreinst -> translateStoreInst finalState (castPtr dataPtr)\n ValGetelementptrinst -> translateGEPInst finalState (castPtr dataPtr)\n ValTruncinst -> translateCastInst finalState TruncInst (castPtr dataPtr)\n ValZextinst -> translateCastInst finalState ZExtInst (castPtr dataPtr)\n ValSextinst -> translateCastInst finalState SExtInst (castPtr dataPtr)\n ValFptruncinst -> translateCastInst finalState FPTruncInst (castPtr dataPtr)\n ValFpextinst -> translateCastInst finalState FPExtInst (castPtr dataPtr)\n ValFptouiinst -> translateCastInst finalState FPToUIInst (castPtr dataPtr)\n ValFptosiinst -> translateCastInst finalState FPToSIInst (castPtr dataPtr)\n ValUitofpinst -> translateCastInst finalState UIToFPInst (castPtr dataPtr)\n ValSitofpinst -> translateCastInst finalState SIToFPInst (castPtr dataPtr)\n ValPtrtointinst -> translateCastInst finalState PtrToIntInst (castPtr dataPtr)\n ValInttoptrinst -> translateCastInst finalState IntToPtrInst (castPtr dataPtr)\n ValBitcastinst -> translateCastInst finalState BitcastInst (castPtr dataPtr)\n ValIcmpinst -> translateCmpInst finalState ICmpInst (castPtr dataPtr)\n ValFcmpinst -> translateCmpInst finalState FCmpInst (castPtr dataPtr)\n ValPhinode -> translatePhiNode finalState (castPtr dataPtr)\n ValCallinst -> translateCallInst finalState (castPtr dataPtr)\n ValSelectinst -> translateSelectInst finalState (castPtr dataPtr)\n ValVaarginst -> translateVarArgInst finalState (castPtr dataPtr)\n ValExtractelementinst -> translateExtractElementInst finalState (castPtr dataPtr)\n ValInsertelementinst -> translateInsertElementInst finalState (castPtr dataPtr)\n ValShufflevectorinst -> translateShuffleVectorInst finalState (castPtr dataPtr)\n ValExtractvalueinst -> translateExtractValueInst finalState (castPtr dataPtr)\n ValInsertvalueinst -> translateInsertValueInst finalState (castPtr dataPtr)\n ValFunction -> throw InvalidFunctionInTranslateValue\n ValAlias -> throw InvalidAliasInTranslateValue\n ValGlobalvariable -> throw InvalidGlobalVarInTranslateValue\n ValConstantexpr -> constantBracket $ translateConstantExpr finalState (castPtr dataPtr)\n\n uid <- nextId\n\n let tv = Value { valueType = tt\n , valueName = realName\n , valueMetadata = mds\n , valueContent = content\n , valueUniqueId = uid\n }\n\n recordValue vp tv\n\n return tv\n\nisGlobal :: ValueTag -> Bool\nisGlobal vt = case vt of\n ValFunction -> True\n ValAlias -> True\n ValGlobalvariable -> True\n _ -> False\n\nisConstant :: ValueTag -> Bool\nisConstant vt = case vt of\n ValConstantaggregatezero -> True\n ValConstantarray -> True\n ValConstantfp -> True\n ValConstantint -> True\n ValConstantpointernull -> True\n ValConstantstruct -> True\n ValConstantvector -> True\n ValUndefvalue -> True\n ValConstantexpr -> True\n ValBlockaddress -> True\n ValInlineasm -> True\n _ -> False\n\ntranslateConstOrRef :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateConstOrRef finalState vp = do\n tag <- liftIO $ cValueTag vp\n let ip = ptrToIntPtr vp\n case isConstant tag of\n True -> translateValue finalState vp\n False ->\n return $ M.findWithDefault (throw (KnotTyingFailure tag)) ip (valueMap finalState)\n\n\ntranslateArgument :: KnotState -> ArgInfoPtr -> KnotMonad ValueT\ntranslateArgument _ dataPtr = do\n hasSRet <- liftIO $ cArgInfoHasSRet dataPtr\n hasByVal <- liftIO $ cArgInfoHasByVal dataPtr\n hasNest <- liftIO $ cArgInfoHasNest dataPtr\n hasNoAlias <- liftIO $ cArgInfoHasNoAlias dataPtr\n hasNoCapture <- liftIO $ cArgInfoHasNoCapture dataPtr\n let attrOrNothing b att = if b then Just att else Nothing\n atts = [ attrOrNothing hasSRet PASRet\n , attrOrNothing hasByVal PAByVal\n , attrOrNothing hasNest PANest\n , attrOrNothing hasNoAlias PANoAlias\n , attrOrNothing hasNoCapture PANoCapture\n ]\n return $ Argument (catMaybes atts)\n\ntranslateBasicBlock :: KnotState -> BasicBlockPtr -> KnotMonad ValueT\ntranslateBasicBlock finalState dataPtr = do\n insts <- liftIO $ cBasicBlockInstructions dataPtr\n tinsts <- mapM (translateValue finalState) insts\n return $ BasicBlock tinsts\n\ntranslateInlineAsm :: KnotState -> InlineAsmInfoPtr -> KnotMonad ValueT\ntranslateInlineAsm _ dataPtr = do\n asmString <- liftIO $ cInlineAsmString dataPtr\n constraints <- liftIO $ cInlineAsmConstraints dataPtr\n return $ InlineAsm asmString constraints\n\ntranslateBlockAddress :: KnotState -> BlockAddrInfoPtr -> KnotMonad ValueT\ntranslateBlockAddress finalState dataPtr = do\n fval <- liftIO $ cBlockAddrFunc dataPtr\n bval <- liftIO $ cBlockAddrBlock dataPtr\n f' <- translateConstOrRef finalState fval\n b' <- translateConstOrRef finalState bval\n return $ BlockAddress f' b'\n\ntranslateConstantAggregate :: KnotState -> ([Value] -> ValueT) -> AggregateInfoPtr -> KnotMonad ValueT\ntranslateConstantAggregate finalState constructor dataPtr = do\n vals <- liftIO $ cAggregateValues dataPtr\n vals' <- mapM (translateConstOrRef finalState) vals\n return $ constructor vals'\n\ntranslateConstantFP :: KnotState -> FPInfoPtr -> KnotMonad ValueT\ntranslateConstantFP _ dataPtr = do\n fpval <- liftIO $ cFPVal dataPtr\n return $ ConstantFP fpval\n\ntranslateConstantInt :: KnotState -> IntInfoPtr -> KnotMonad ValueT\ntranslateConstantInt _ dataPtr = do\n intval <- liftIO $ cIntVal dataPtr\n return $ ConstantInt intval\n\ntranslateRetInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateRetInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n case opPtrs of\n [] -> return $ RetInst Nothing\n [val] -> do\n val' <- translateConstOrRef finalState val\n return $ RetInst (Just val')\n _ -> throw TooManyReturnValues\n\n-- | Note, in LLVM the operands of the Branch instruction are ordered as\n--\n-- [Condition, FalseTarget,] TrueTarget\n--\n-- This is not exactly as expected.\ntranslateBranchInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateBranchInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n case opPtrs of\n [dst] -> do\n dst' <- translateConstOrRef finalState dst\n return $ UnconditionalBranchInst dst'\n [val, f, t] -> do\n val' <- translateConstOrRef finalState val\n fbranch <- translateConstOrRef finalState f\n tbranch <- translateConstOrRef finalState t\n return $ BranchInst { branchCondition = val'\n , branchTrueTarget = tbranch\n , branchFalseTarget = fbranch\n }\n _ -> throw InvalidBranchInst\n\ntranslateSwitchInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateSwitchInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n case opPtrs of\n (swVal:defTarget:cases) -> do\n val' <- translateConstOrRef finalState swVal\n def' <- translateConstOrRef finalState defTarget\n -- Process the rest of the list in pairs since that is how LLVM\n -- stores them, but transform it into a nice list of actual\n -- pairs\n let tpairs acc (v1:dest:rest) = do\n v1' <- translateConstOrRef finalState v1\n dest' <- translateConstOrRef finalState dest\n tpairs ((v1', dest'):acc) rest\n tpairs acc [] = return $ reverse acc\n tpairs _ _ = throw InvalidSwitchLayout\n cases' <- tpairs [] cases\n return $ SwitchInst { switchValue = val'\n , switchDefaultTarget = def'\n , switchCases = cases'\n }\n _ -> throw InvalidSwitchLayout\n\ntranslateIndirectBrInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateIndirectBrInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n case opPtrs of\n (addr:targets) -> do\n addr' <- translateConstOrRef finalState addr\n targets' <- mapM (translateConstOrRef finalState) targets\n return $ IndirectBranchInst { indirectBranchAddress = addr'\n , indirectBranchTargets = targets'\n }\n _ -> throw InvalidIndirectBranchOperands\n\ntranslateInvokeInst :: KnotState -> CallInfoPtr -> KnotMonad ValueT\ntranslateInvokeInst finalState dataPtr = do\n func <- liftIO $ cCallValue dataPtr\n args <- liftIO $ cCallArguments dataPtr\n cc <- liftIO $ cCallConvention dataPtr\n hasSRet <- liftIO $ cCallHasSRet dataPtr\n ndest <- liftIO $ cCallNormalDest dataPtr\n udest <- liftIO $ cCallUnwindDest dataPtr\n\n f' <- translateConstOrRef finalState func\n args' <- mapM (translateConstOrRef finalState) args\n n' <- translateConstOrRef finalState ndest\n u' <- translateConstOrRef finalState udest\n\n return $ InvokeInst { invokeConvention = cc\n , invokeParamAttrs = [] -- FIXME\n , invokeFunction = f'\n , invokeArguments = zip args' (repeat []) -- FIXME\n , invokeAttrs = [] -- FIXME\n , invokeNormalLabel = n'\n , invokeUnwindLabel = u'\n , invokeHasSRet = hasSRet\n }\n\ntranslateFlaggedBinaryOp :: KnotState -> (ArithFlags -> Value -> Value -> ValueT) ->\n InstInfoPtr -> KnotMonad ValueT\ntranslateFlaggedBinaryOp finalState constructor dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n flags <- liftIO $ cInstructionArithFlags dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [lhs, rhs] -> return $ constructor flags lhs rhs\n _ -> throw $ InvalidBinaryOp (length ops)\n\ntranslateBinaryOp :: KnotState -> (Value -> Value -> ValueT) ->\n InstInfoPtr -> KnotMonad ValueT\ntranslateBinaryOp finalState constructor dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [lhs, rhs] -> return $ constructor lhs rhs\n _ -> throw $ InvalidBinaryOp (length ops)\n\ntranslateAllocaInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateAllocaInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n align <- liftIO $ cInstructionAlign dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [val] -> return $ AllocaInst val align\n _ -> throw $ InvalidUnaryOp (length ops)\n\n\ntranslateLoadInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateLoadInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n align <- liftIO $ cInstructionAlign dataPtr\n vol <- liftIO $ cInstructionIsVolatile dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [addr] -> return $ LoadInst { loadIsVolatile = vol\n , loadAddress = addr\n , loadAlignment = align\n }\n _ -> throw $ InvalidUnaryOp (length ops)\n\ntranslateStoreInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateStoreInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n addrSpace <- liftIO $ cInstructionAddrSpace dataPtr\n align <- liftIO $ cInstructionAlign dataPtr\n isVol <- liftIO $ cInstructionIsVolatile dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [val, ptr] -> return $ StoreInst { storeIsVolatile = isVol\n , storeValue = val\n , storeAddress = ptr\n , storeAlignment = align\n , storeAddrSpace = addrSpace\n }\n _ -> throw $ InvalidBinaryOp (length ops)\n\ntranslateGEPInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateGEPInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n inBounds <- liftIO $ cInstructionInBounds dataPtr\n addrSpace <- liftIO $ cInstructionAddrSpace dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n (val:indices) -> return $ GetElementPtrInst { getElementPtrInBounds = inBounds\n , getElementPtrValue = val\n , getElementPtrIndices = indices\n , getElementPtrAddrSpace = addrSpace\n }\n _ -> throw $ InvalidGEPInst (length ops)\n\ntranslateCastInst :: KnotState -> (Value -> ValueT) -> InstInfoPtr -> KnotMonad ValueT\ntranslateCastInst finalState constructor dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [v] -> return $ constructor v\n _ -> throw $ InvalidUnaryOp (length ops)\n\ntranslateCmpInst :: KnotState -> (CmpPredicate -> Value -> Value -> ValueT) ->\n InstInfoPtr -> KnotMonad ValueT\ntranslateCmpInst finalState constructor dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n predicate <- liftIO $ cInstructionCmpPred dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [op1, op2] -> return $ constructor predicate op1 op2\n _ -> throw $ InvalidBinaryOp (length ops)\n\ntranslatePhiNode :: KnotState -> PHIInfoPtr -> KnotMonad ValueT\ntranslatePhiNode finalState dataPtr = do\n vptrs <- liftIO $ cPHIValues dataPtr\n bptrs <- liftIO $ cPHIBlocks dataPtr\n\n vals <- mapM (translateConstOrRef finalState) vptrs\n blocks <- mapM (translateConstOrRef finalState) bptrs\n\n return $ PhiNode $ zip vals blocks\n\ntranslateCallInst :: KnotState -> CallInfoPtr -> KnotMonad ValueT\ntranslateCallInst finalState dataPtr = do\n vptr <- liftIO $ cCallValue dataPtr\n aptrs <- liftIO $ cCallArguments dataPtr\n cc <- liftIO $ cCallConvention dataPtr\n hasSRet <- liftIO $ cCallHasSRet dataPtr\n isTail <- liftIO $ cCallIsTail dataPtr\n\n val <- translateConstOrRef finalState vptr\n args <- mapM (translateConstOrRef finalState) aptrs\n\n return $ CallInst { callIsTail = isTail\n , callConvention = cc\n , callParamAttrs = [] -- FIXME\n , callFunction = val\n , callArguments = zip args (repeat []) -- FIXME\n , callAttrs = [] -- FIXME\n , callHasSRet = hasSRet\n }\n\ntranslateSelectInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateSelectInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [cond, trueval, falseval] -> do\n return $ SelectInst cond trueval falseval\n _ -> throw $ InvalidSelectArgs (length ops)\n\ntranslateVarArgInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateVarArgInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [op] -> return $ VaArgInst op\n _ -> throw $ InvalidUnaryOp (length ops)\n\ntranslateExtractElementInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateExtractElementInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [vec, idx] -> do\n return $ ExtractElementInst { extractElementVector = vec\n , extractElementIndex = idx\n }\n _ -> throw $ InvalidExtractElementInst (length ops)\n\ntranslateInsertElementInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateInsertElementInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [vec, val, idx] -> do\n return $ InsertElementInst { insertElementVector = vec\n , insertElementValue = val\n , insertElementIndex = idx\n }\n _ -> throw $ InvalidInsertElementInst (length ops)\n\ntranslateShuffleVectorInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateShuffleVectorInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [v1, v2, vecMask] -> do\n return $ ShuffleVectorInst { shuffleVectorV1 = v1\n , shuffleVectorV2 = v2\n , shuffleVectorMask = vecMask\n }\n _ -> throw $ InvalidShuffleVectorInst (length ops)\n\ntranslateExtractValueInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateExtractValueInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n indices <- liftIO $ cInstructionIndices dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [agg] -> return $ ExtractValueInst { extractValueAggregate = agg\n , extractValueIndices = indices\n }\n _ -> throw $ InvalidExtractValueInst (length ops)\n\ntranslateInsertValueInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateInsertValueInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n indices <- liftIO $ cInstructionIndices dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [agg, val] ->\n return $ InsertValueInst { insertValueAggregate = agg\n , insertValueValue = val\n , insertValueIndices = indices\n }\n _ -> throw $ InvalidInsertValueInst (length ops)\n\ntranslateConstantExpr :: KnotState -> ConstExprPtr -> KnotMonad ValueT\ntranslateConstantExpr finalState dataPtr = do\n ii <- liftIO $ cConstExprInstInfo dataPtr\n tag <- liftIO $ cConstExprTag dataPtr\n vt <- case tag of\n ValAddinst -> translateFlaggedBinaryOp finalState AddInst ii\n ValFaddinst -> translateFlaggedBinaryOp finalState AddInst ii\n ValSubinst -> translateFlaggedBinaryOp finalState SubInst ii\n ValFsubinst -> translateFlaggedBinaryOp finalState SubInst ii\n ValMulinst -> translateFlaggedBinaryOp finalState MulInst ii\n ValFmulinst -> translateFlaggedBinaryOp finalState MulInst ii\n ValUdivinst -> translateBinaryOp finalState DivInst ii\n ValSdivinst -> translateBinaryOp finalState DivInst ii\n ValFdivinst -> translateBinaryOp finalState DivInst ii\n ValUreminst -> translateBinaryOp finalState RemInst ii\n ValSreminst -> translateBinaryOp finalState RemInst ii\n ValFreminst -> translateBinaryOp finalState RemInst ii\n ValShlinst -> translateBinaryOp finalState ShlInst ii\n ValLshrinst -> translateBinaryOp finalState LshrInst ii\n ValAshrinst -> translateBinaryOp finalState AshrInst ii\n ValAndinst -> translateBinaryOp finalState AndInst ii\n ValOrinst -> translateBinaryOp finalState OrInst ii\n ValXorinst -> translateBinaryOp finalState XorInst ii\n ValGetelementptrinst -> translateGEPInst finalState ii\n ValTruncinst -> translateCastInst finalState TruncInst ii\n ValZextinst -> translateCastInst finalState ZExtInst ii\n ValSextinst -> translateCastInst finalState SExtInst ii\n ValFptruncinst -> translateCastInst finalState FPTruncInst ii\n ValFpextinst -> translateCastInst finalState FPExtInst ii\n ValFptouiinst -> translateCastInst finalState FPToUIInst ii\n ValFptosiinst -> translateCastInst finalState FPToSIInst ii\n ValUitofpinst -> translateCastInst finalState UIToFPInst ii\n ValSitofpinst -> translateCastInst finalState SIToFPInst ii\n ValPtrtointinst -> translateCastInst finalState PtrToIntInst ii\n ValInttoptrinst -> translateCastInst finalState IntToPtrInst ii\n ValBitcastinst -> translateCastInst finalState BitcastInst ii\n ValIcmpinst -> translateCmpInst finalState ICmpInst ii\n ValFcmpinst -> translateCmpInst finalState FCmpInst ii\n ValSelectinst -> translateSelectInst finalState ii\n ValVaarginst -> translateVarArgInst finalState ii\n ValExtractelementinst -> translateExtractElementInst finalState ii\n ValInsertelementinst -> translateInsertElementInst finalState ii\n ValShufflevectorinst -> translateShuffleVectorInst finalState ii\n ValExtractvalueinst -> translateExtractValueInst finalState ii\n ValInsertvalueinst -> translateInsertValueInst finalState ii\n return $ ConstantValue vt\n\ntranslateMetadata :: MetaPtr -> KnotMonad Metadata\ntranslateMetadata mp = do\n s <- get\n let ip = ptrToIntPtr mp\n case M.lookup ip (metaMap s) of\n Just m -> return m\n Nothing -> translateMetadata' mp\n\nmaybeTranslateMetadata :: Maybe MetaPtr -> KnotMonad (Maybe Metadata)\nmaybeTranslateMetadata Nothing = return Nothing\nmaybeTranslateMetadata (Just mp) = Just <$> translateMetadata mp\n\ntranslateMetadata' :: MetaPtr -> KnotMonad Metadata\ntranslateMetadata' mp = do\n let ip = ptrToIntPtr mp\n metaTag <- liftIO $ cMetaTypeTag mp\n tag <- liftIO $ cMetaTag mp\n content <- case metaTag of\n MetaLocation -> do\n line <- liftIO $ cMetaLocationLine mp\n col <- liftIO $ cMetaLocationColumn mp\n scope <- liftIO $ cMetaLocationScope mp\n\n scope' <- translateMetadata scope\n return MetaSourceLocation { metaSourceRow = line\n , metaSourceCol = col\n , metaSourceScope = scope'\n }\n MetaDerivedtype -> do\n ctxt <- liftIO $ cMetaTypeContext mp\n name <- cMetaTypeName mp\n f <- liftIO $ cMetaTypeFile mp\n line <- liftIO $ cMetaTypeLine mp\n size <- liftIO $ cMetaTypeSize mp\n align <- liftIO $ cMetaTypeAlign mp\n off <- liftIO $ cMetaTypeOffset mp\n parent <- liftIO $ cMetaTypeDerivedFrom mp\n\n cu <- liftIO $ cMetaTypeCompileUnit mp\n isArtif <- liftIO $ cMetaTypeIsArtificial mp\n isVirt <- liftIO $ cMetaTypeIsVirtual mp\n isForward <- liftIO $ cMetaTypeIsForward mp\n isProt <- liftIO $ cMetaTypeIsProtected mp\n isPriv <- liftIO $ cMetaTypeIsPrivate mp\n\n f' <- maybeTranslateMetadata f\n ctxt' <- translateMetadata ctxt\n parent' <- maybeTranslateMetadata parent\n cu' <- maybeTranslateMetadata cu\n\n return MetaDWDerivedType { metaDerivedTypeContext = ctxt'\n , metaDerivedTypeName = name\n , metaDerivedTypeFile = f'\n , metaDerivedTypeLine = line\n , metaDerivedTypeSize = size\n , metaDerivedTypeAlign = align\n , metaDerivedTypeOffset = off\n , metaDerivedTypeParent = parent'\n , metaDerivedTypeTag = tag\n , metaDerivedTypeCompileUnit = cu'\n , metaDerivedTypeIsArtificial = isArtif\n , metaDerivedTypeIsVirtual = isVirt\n , metaDerivedTypeIsForward = isForward\n , metaDerivedTypeIsProtected = isProt\n , metaDerivedTypeIsPrivate = isPriv\n }\n MetaCompositetype -> do\n ctxt <- liftIO $ cMetaTypeContext mp\n name <- cMetaTypeName mp\n f <- liftIO $ cMetaTypeFile mp\n line <- liftIO $ cMetaTypeLine mp\n size <- liftIO $ cMetaTypeSize mp\n align <- liftIO $ cMetaTypeAlign mp\n off <- liftIO $ cMetaTypeOffset mp\n parent <- liftIO $ cMetaTypeDerivedFrom mp\n flags <- liftIO $ cMetaTypeFlags mp\n members <- liftIO $ cMetaTypeCompositeComponents mp\n rlang <- liftIO $ cMetaTypeRuntimeLanguage mp\n ctype <- liftIO $ cMetaTypeContainingType mp\n tparams <- liftIO $ cMetaTypeTemplateParams mp\n cu <- liftIO $ cMetaTypeCompileUnit mp\n isArtif <- liftIO $ cMetaTypeIsArtificial mp\n isVirtual <- liftIO $ cMetaTypeIsVirtual mp\n isForward <- liftIO $ cMetaTypeIsForward mp\n isProt <- liftIO $ cMetaTypeIsProtected mp\n isPriv <- liftIO $ cMetaTypeIsPrivate mp\n isByRef <- liftIO $ cMetaTypeIsByRefStruct mp\n\n ctxt' <- translateMetadata ctxt\n f' <- maybeTranslateMetadata f\n parent' <- maybeTranslateMetadata parent\n members' <- maybeTranslateMetadata members\n ctype' <- maybeTranslateMetadata ctype\n tparams' <- maybeTranslateMetadata tparams\n cu' <- maybeTranslateMetadata cu\n\n return MetaDWCompositeType { metaCompositeTypeTag = tag\n , metaCompositeTypeContext = ctxt'\n , metaCompositeTypeName = name\n , metaCompositeTypeFile = f'\n , metaCompositeTypeLine = line\n , metaCompositeTypeSize = size\n , metaCompositeTypeAlign = align\n , metaCompositeTypeOffset = off\n , metaCompositeTypeFlags = flags\n , metaCompositeTypeParent = parent'\n , metaCompositeTypeMembers = members'\n , metaCompositeTypeRuntime = rlang\n , metaCompositeTypeContainer = ctype'\n , metaCompositeTypeTemplateParams = tparams'\n , metaCompositeTypeCompileUnit = cu'\n , metaCompositeTypeIsArtificial = isArtif\n , metaCompositeTypeIsVirtual = isVirtual\n , metaCompositeTypeIsForward = isForward\n , metaCompositeTypeIsProtected = isProt\n , metaCompositeTypeIsPrivate = isPriv\n , metaCompositeTypeIsByRefStruct = isByRef\n }\n MetaBasictype -> do\n ctxt <- liftIO $ cMetaTypeContext mp\n name <- cMetaTypeName mp\n f <- liftIO $ cMetaTypeFile mp\n line <- liftIO $ cMetaTypeLine mp\n size <- liftIO $ cMetaTypeSize mp\n align <- liftIO $ cMetaTypeAlign mp\n off <- liftIO $ cMetaTypeOffset mp\n flags <- liftIO $ cMetaTypeFlags mp\n encoding <- liftIO $ cMetaTypeEncoding mp\n\n ctxt' <- translateMetadata ctxt\n f' <- maybeTranslateMetadata f\n\n return MetaDWBaseType { metaBaseTypeContext = ctxt'\n , metaBaseTypeName = name\n , metaBaseTypeFile = f'\n , metaBaseTypeLine = line\n , metaBaseTypeSize = size\n , metaBaseTypeAlign = align\n , metaBaseTypeOffset = off\n , metaBaseTypeFlags = flags\n , metaBaseTypeEncoding = encoding\n }\n MetaVariable -> do\n ctxt <- liftIO $ cMetaVariableContext mp\n name <- cMetaVariableName mp\n file <- liftIO $ cMetaVariableCompileUnit mp\n line <- liftIO $ cMetaVariableLine mp\n argNo <- liftIO $ cMetaVariableArgNumber mp\n ty <- liftIO $ cMetaVariableType mp\n isArtif <- liftIO $ cMetaVariableIsArtificial mp\n cplxAddr <- liftIO $ cMetaVariableAddrElements mp\n byRef <- liftIO $ cMetaVariableIsBlockByRefVar mp\n\n ctxt' <- translateMetadata ctxt\n file' <- translateMetadata file\n ty' <- translateMetadata ty\n\n return MetaDWLocal { metaLocalTag = tag\n , metaLocalContext = ctxt'\n , metaLocalName = name\n , metaLocalFile = file'\n , metaLocalLine = line\n , metaLocalArgNo = argNo\n , metaLocalType = ty'\n , metaLocalIsArtificial = isArtif\n , metaLocalIsBlockByRefVar = byRef\n , metaLocalAddrElements = cplxAddr\n }\n MetaSubprogram -> do\n ctxt <- liftIO $ cMetaSubprogramContext mp\n name <- cMetaSubprogramName mp\n displayName <- cMetaSubprogramDisplayName mp\n linkageName <- cMetaSubprogramLinkageName mp\n compUnit <- liftIO $ cMetaSubprogramCompileUnit mp\n line <- liftIO $ cMetaSubprogramLine mp\n ty <- liftIO $ cMetaSubprogramType mp\n isLocal <- liftIO $ cMetaSubprogramIsLocal mp\n isDef <- liftIO $ cMetaSubprogramIsDefinition mp\n virt <- liftIO $ cMetaSubprogramVirtuality mp\n virtIdx <- liftIO $ cMetaSubprogramVirtualIndex mp\n baseType <- liftIO $ cMetaSubprogramContainingType mp\n isArtif <- liftIO $ cMetaSubprogramIsArtificial mp\n isOpt <- liftIO $ cMetaSubprogramIsOptimized mp\n isPrivate <- liftIO $ cMetaSubprogramIsPrivate mp\n isProtected <- liftIO $ cMetaSubprogramIsProtected mp\n isExplicit <- liftIO $ cMetaSubprogramIsExplicit mp\n isPrototyped <- liftIO $ cMetaSubprogramIsPrototyped mp\n\n ctxt' <- translateMetadata ctxt\n compUnit' <- translateMetadata compUnit\n ty' <- translateMetadata ty\n baseType' <- maybeTranslateMetadata baseType\n\n return MetaDWSubprogram { metaSubprogramContext = ctxt'\n , metaSubprogramName = name\n , metaSubprogramDisplayName = displayName\n , metaSubprogramLinkageName = linkageName\n , metaSubprogramFile = compUnit'\n , metaSubprogramLine = line\n , metaSubprogramType = ty'\n , metaSubprogramStatic = isLocal\n , metaSubprogramNotExtern = not isPrivate && not isProtected\n , metaSubprogramVirtuality = virt\n , metaSubprogramVirtIndex = virtIdx\n , metaSubprogramBaseType = baseType'\n , metaSubprogramArtificial = isArtif\n , metaSubprogramOptimized = isOpt\n , metaSubprogramIsExplicit = isExplicit\n , metaSubprogramIsPrototyped = isPrototyped\n }\n MetaGlobalvariable -> do\n ctxt <- liftIO $ cMetaGlobalContext mp\n name <- cMetaGlobalName mp\n displayName <- cMetaGlobalDisplayName mp\n linkageName <- cMetaGlobalLinkageName mp\n file <- liftIO $ cMetaGlobalCompileUnit mp\n line <- liftIO $ cMetaGlobalLine mp\n ty <- liftIO $ cMetaGlobalType mp\n isLocal <- liftIO $ cMetaGlobalIsLocal mp\n def <- liftIO $ cMetaGlobalIsDefinition mp\n\n ctxt' <- translateMetadata ctxt\n file' <- translateMetadata file\n ty' <- translateMetadata ty\n\n return MetaDWVariable { metaGlobalVarContext = ctxt'\n , metaGlobalVarName = name\n , metaGlobalVarDisplayName = displayName\n , metaGlobalVarLinkageName = linkageName\n , metaGlobalVarFile = file'\n , metaGlobalVarLine = line\n , metaGlobalVarType = ty'\n , metaGlobalVarStatic = isLocal\n , metaGlobalVarNotExtern = not def\n }\n MetaFile -> do\n file <- cMetaFileFilename mp\n dir <- cMetaFileDirectory mp\n cu <- liftIO $ cMetaFileCompileUnit mp\n\n cu' <- translateMetadata cu\n\n return MetaDWFile { metaFileSourceFile = file\n , metaFileSourceDir = dir\n , metaFileCompileUnit = cu'\n }\n MetaCompileunit -> do\n lang <- liftIO $ cMetaCompileUnitLanguage mp\n fname <- cMetaCompileUnitFilename mp\n dir <- cMetaCompileUnitDirectory mp\n producer <- cMetaCompileUnitProducer mp\n isMain <- liftIO $ cMetaCompileUnitIsMain mp\n isOpt <- liftIO $ cMetaCompileUnitIsOptimized mp\n flags <- cMetaCompileUnitFlags mp\n rv <- liftIO $ cMetaCompileUnitRuntimeVersion mp\n\n return MetaDWCompileUnit { metaCompileUnitLanguage = lang\n , metaCompileUnitSourceFile = fname\n , metaCompileUnitCompileDir = dir\n , metaCompileUnitProducer = producer\n , metaCompileUnitIsMain = isMain\n , metaCompileUnitIsOpt = isOpt\n , metaCompileUnitFlags = flags\n , metaCompileUnitVersion = rv\n }\n MetaNamespace -> do\n ctxt <- liftIO $ cMetaNamespaceContext mp\n name <- cMetaNamespaceName mp\n cu <- liftIO $ cMetaNamespaceCompileUnit mp\n line <- liftIO $ cMetaNamespaceLine mp\n\n ctxt' <- translateMetadata ctxt\n cu' <- translateMetadata cu\n\n return MetaDWNamespace { metaNamespaceContext = ctxt'\n , metaNamespaceName = name\n , metaNamespaceCompileUnit = cu'\n , metaNamespaceLine = line\n }\n MetaLexicalblock -> do\n ctxt <- liftIO $ cMetaLexicalBlockContext mp\n line <- liftIO $ cMetaLexicalBlockLine mp\n col <- liftIO $ cMetaLexicalBlockColumn mp\n\n ctxt' <- translateMetadata ctxt\n\n return MetaDWLexicalBlock { metaLexicalBlockRow = line\n , metaLexicalBlockCol = col\n , metaLexicalBlockContext = ctxt'\n }\n MetaSubrange -> do\n lo <- liftIO $ cMetaSubrangeLo mp\n hi <- liftIO $ cMetaSubrangeHi mp\n return MetaDWSubrange { metaSubrangeLow = lo\n , metaSubrangeHigh = hi\n }\n MetaEnumerator -> do\n name <- cMetaEnumeratorName mp\n val <- liftIO $ cMetaEnumeratorValue mp\n return MetaDWEnumerator { metaEnumeratorName = name\n , metaEnumeratorValue = val\n }\n MetaArray -> do\n elts <- liftIO $ cMetaArrayElts mp\n elts' <- mapM translateMetadata elts\n return $ MetadataList elts'\n MetaTemplatetypeparameter -> do\n ctxt <- liftIO $ cMetaTemplateTypeContext mp\n name <- cMetaTemplateTypeName mp\n ty <- liftIO $ cMetaTemplateTypeType mp\n line <- liftIO $ cMetaTemplateTypeLine mp\n col <- liftIO $ cMetaTemplateTypeColumn mp\n\n ctxt' <- translateMetadata ctxt\n ty' <- translateMetadata ty\n\n return MetaDWTemplateTypeParameter { metaTemplateTypeParameterContext = ctxt'\n , metaTemplateTypeParameterType = ty'\n , metaTemplateTypeParameterLine = line\n , metaTemplateTypeParameterCol = col\n , metaTemplateTypeParameterName = name\n }\n MetaTemplatevalueparameter -> do\n ctxt <- liftIO $ cMetaTemplateValueContext mp\n name <- cMetaTemplateValueName mp\n ty <- liftIO $ cMetaTemplateValueType mp\n val <- liftIO $ cMetaTemplateValueValue mp\n line <- liftIO $ cMetaTemplateValueLine mp\n col <- liftIO $ cMetaTemplateValueColumn mp\n\n ctxt' <- translateMetadata ctxt\n ty' <- translateMetadata ty\n\n return MetaDWTemplateValueParameter { metaTemplateValueParameterContext = ctxt'\n , metaTemplateValueParameterType = ty'\n , metaTemplateValueParameterLine = line\n , metaTemplateValueParameterCol = col\n , metaTemplateValueParameterValue = val\n , metaTemplateValueParameterName = name\n }\n\n uid <- nextMetaId\n let md = Metadata { metaValueContent = content\n , metaValueUniqueId = uid\n }\n s <- get\n put s { metaMap = M.insert ip md (metaMap s) }\n return md\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"52dd621cd1ff722b571e9e50595b0e0c1da91df8","subject":"Make constructor safe since it may trigger a signal on the given Adjustment.","message":"Make constructor safe since it may trigger a signal on the given Adjustment.\n\ndarcs-hash:20070314152626-e1dd6-ecaea302e9658b5ecbae389144e75d8b4747cfb5.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/Graphics\/UI\/Gtk\/Entry\/SpinButton.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Entry\/SpinButton.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SpinButton\n--\n-- Author : Axel Simon\n--\n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.10 $ from $Date: 2005\/10\/19 12:57:37 $\n--\n-- Copyright (C) 1999-2005 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Retrieve an integer or floating-point number from the user\n--\nmodule Graphics.UI.Gtk.Entry.SpinButton (\n-- * Detail\n-- \n-- | A 'SpinButton' is an ideal way to allow the user to set the value of some\n-- attribute. Rather than having to directly type a number into a 'Entry',\n-- 'SpinButton' allows the user to click on one of two arrows to increment or\n-- decrement the displayed value. A value can still be typed in, with the bonus\n-- that it can be checked to ensure it is in a given range.\n--\n-- The main properties of a 'SpinButton' are through a 'Adjustment'. See the\n-- 'Adjustment' section for more details about an adjustment's properties.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Entry'\n-- | +----SpinButton\n-- @\n\n-- * Types\n SpinButton,\n SpinButtonClass,\n castToSpinButton,\n toSpinButton,\n\n-- * Constructors\n spinButtonNew,\n spinButtonNewWithRange,\n\n-- * Methods\n spinButtonConfigure,\n spinButtonSetAdjustment,\n spinButtonGetAdjustment,\n spinButtonSetDigits,\n spinButtonGetDigits,\n spinButtonSetIncrements,\n spinButtonGetIncrements,\n spinButtonSetRange,\n spinButtonGetRange,\n spinButtonGetValue,\n spinButtonGetValueAsInt,\n spinButtonSetValue,\n SpinButtonUpdatePolicy(..),\n spinButtonSetUpdatePolicy,\n spinButtonGetUpdatePolicy,\n spinButtonSetNumeric,\n spinButtonGetNumeric,\n SpinType(..),\n spinButtonSpin,\n spinButtonSetWrap,\n spinButtonGetWrap,\n spinButtonSetSnapToTicks,\n spinButtonGetSnapToTicks,\n spinButtonUpdate,\n\n-- * Attributes\n spinButtonAdjustment,\n spinButtonClimbRate,\n spinButtonDigits,\n spinButtonSnapToTicks,\n spinButtonNumeric,\n spinButtonWrap,\n spinButtonUpdatePolicy,\n spinButtonValue,\n\n-- * Signals\n onInput,\n afterInput,\n onOutput,\n afterOutput,\n onValueSpinned,\n afterValueSpinned\n ) where\n\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.General.Structs\t(inputError)\nimport Graphics.UI.Gtk.General.Enums\t(SpinButtonUpdatePolicy(..), SpinType(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Interfaces\n\ninstance EditableClass SpinButton\n\n--------------------\n-- Constructors\n\n-- | Creates a new 'SpinButton'.\n--\nspinButtonNew :: \n Adjustment -- ^ @adjustment@ - the 'Adjustment' object that this spin\n -- button should use.\n -> Double -- ^ @climbRate@ - specifies how much the spin button\n -- changes when an arrow is clicked on.\n -> Int -- ^ @digits@ - the number of decimal places to display.\n -> IO SpinButton\nspinButtonNew adjustment climbRate digits =\n makeNewObject mkSpinButton $\n liftM (castPtr :: Ptr Widget -> Ptr SpinButton) $\n {# call spin_button_new #}\n adjustment\n (realToFrac climbRate)\n (fromIntegral digits)\n\n-- | This is a convenience constructor that allows creation of a numeric\n-- 'SpinButton' without manually creating an adjustment. The value is initially\n-- set to the minimum value and a page increment of 10 * @step@ is the default.\n-- The precision of the spin button is equivalent to the precision of @step@.\n--\n-- Note that the way in which the precision is derived works best if @step@\n-- is a power of ten. If the resulting precision is not suitable for your\n-- needs, use 'spinButtonSetDigits' to correct it.\n--\nspinButtonNewWithRange :: \n Double -- ^ @min@ - Minimum allowable value\n -> Double -- ^ @max@ - Maximum allowable value\n -> Double -- ^ @step@ - Increment added or subtracted by spinning the\n -- widget\n -> IO SpinButton\nspinButtonNewWithRange min max step =\n makeNewObject mkSpinButton $\n liftM (castPtr :: Ptr Widget -> Ptr SpinButton) $\n {# call unsafe spin_button_new_with_range #}\n (realToFrac min)\n (realToFrac max)\n (realToFrac step)\n\n--------------------\n-- Methods\n\n-- | Changes the properties of an existing spin button. The adjustment, climb\n-- rate, and number of decimal places are all changed accordingly, after this\n-- function call.\n--\nspinButtonConfigure :: SpinButtonClass self => self\n -> Adjustment -- ^ @adjustment@ - a 'Adjustment'.\n -> Double -- ^ @climbRate@ - the new climb rate.\n -> Int -- ^ @digits@ - the number of decimal places to display in the\n -- spin button.\n -> IO ()\nspinButtonConfigure self adjustment climbRate digits =\n {# call spin_button_configure #}\n (toSpinButton self)\n adjustment\n (realToFrac climbRate)\n (fromIntegral digits)\n\n-- | Replaces the 'Adjustment' associated with the spin button.\n--\nspinButtonSetAdjustment :: SpinButtonClass self => self\n -> Adjustment -- ^ @adjustment@ - a 'Adjustment' to replace the existing\n -- adjustment\n -> IO ()\nspinButtonSetAdjustment self adjustment =\n {# call spin_button_set_adjustment #}\n (toSpinButton self)\n adjustment\n\n-- | Get the adjustment associated with a 'SpinButton'\n--\nspinButtonGetAdjustment :: SpinButtonClass self => self\n -> IO Adjustment -- ^ returns the 'Adjustment' of @spinButton@\nspinButtonGetAdjustment self =\n makeNewObject mkAdjustment $\n {# call unsafe spin_button_get_adjustment #}\n (toSpinButton self)\n\n-- | Set the precision to be displayed by @spinButton@. Up to 20 digit\n-- precision is allowed.\n--\nspinButtonSetDigits :: SpinButtonClass self => self\n -> Int -- ^ @digits@ - the number of digits after the decimal point to be\n -- displayed for the spin button's value\n -> IO ()\nspinButtonSetDigits self digits =\n {# call spin_button_set_digits #}\n (toSpinButton self)\n (fromIntegral digits)\n\n-- | Fetches the precision of @spinButton@. See 'spinButtonSetDigits'.\n--\nspinButtonGetDigits :: SpinButtonClass self => self\n -> IO Int -- ^ returns the current precision\nspinButtonGetDigits self =\n liftM fromIntegral $\n {# call spin_button_get_digits #}\n (toSpinButton self)\n\n-- | Sets the step and page increments for the spin button. This affects how\n-- quickly the value changes when the spin button's arrows are activated.\n--\nspinButtonSetIncrements :: SpinButtonClass self => self\n -> Double -- ^ @step@ - increment applied for a button 1 press.\n -> Double -- ^ @page@ - increment applied for a button 2 press.\n -> IO ()\nspinButtonSetIncrements self step page =\n {# call spin_button_set_increments #}\n (toSpinButton self)\n (realToFrac step)\n (realToFrac page)\n\n-- | Gets the current step and page the increments used by the spin button. See\n-- 'spinButtonSetIncrements'.\n--\nspinButtonGetIncrements :: SpinButtonClass self => self\n -> IO (Double, Double) -- ^ @(step, page)@ - step increment and page increment\nspinButtonGetIncrements self =\n alloca $ \\stepPtr ->\n alloca $ \\pagePtr -> do\n {# call unsafe spin_button_get_increments #}\n (toSpinButton self)\n stepPtr\n pagePtr\n step <- peek stepPtr\n page <- peek pagePtr\n return (realToFrac step, realToFrac page)\n\n-- | Sets the minimum and maximum allowable values for the spin button\n--\nspinButtonSetRange :: SpinButtonClass self => self\n -> Double -- ^ @min@ - minimum allowable value\n -> Double -- ^ @max@ - maximum allowable value\n -> IO ()\nspinButtonSetRange self min max =\n {# call spin_button_set_range #}\n (toSpinButton self)\n (realToFrac min)\n (realToFrac max)\n\n-- | Gets the range allowed for the spin button. See 'spinButtonSetRange'.\n--\nspinButtonGetRange :: SpinButtonClass self => self\n -> IO (Double, Double) -- ^ @(min, max)@ - minimum and maximum allowed value\nspinButtonGetRange self =\n alloca $ \\minPtr ->\n alloca $ \\maxPtr -> do\n {# call unsafe spin_button_get_range #}\n (toSpinButton self)\n minPtr\n maxPtr\n min <- peek minPtr\n max <- peek maxPtr\n return (realToFrac min, realToFrac max)\n\n-- | Get the value of the spin button as a floating point value.\n--\nspinButtonGetValue :: SpinButtonClass self => self -> IO Double\nspinButtonGetValue self =\n liftM realToFrac $\n {# call unsafe spin_button_get_value #}\n (toSpinButton self)\n\n-- | Get the value of the spin button as an integral value.\n--\nspinButtonGetValueAsInt :: SpinButtonClass self => self -> IO Int\nspinButtonGetValueAsInt self =\n liftM fromIntegral $\n {# call unsafe spin_button_get_value_as_int #}\n (toSpinButton self)\n\n-- | Set the value of the spin button.\n--\nspinButtonSetValue :: SpinButtonClass self => self -> Double -> IO ()\nspinButtonSetValue self value =\n {# call spin_button_set_value #}\n (toSpinButton self)\n (realToFrac value)\n\n-- | Sets the update behavior of a spin button. This determines whether the\n-- spin button is always updated or only when a valid value is set.\n--\nspinButtonSetUpdatePolicy :: SpinButtonClass self => self\n -> SpinButtonUpdatePolicy -- ^ @policy@ - a 'SpinButtonUpdatePolicy' value\n -> IO ()\nspinButtonSetUpdatePolicy self policy =\n {# call spin_button_set_update_policy #}\n (toSpinButton self)\n ((fromIntegral . fromEnum) policy)\n\n-- | Gets the update behavior of a spin button. See\n-- 'spinButtonSetUpdatePolicy'.\n--\nspinButtonGetUpdatePolicy :: SpinButtonClass self => self\n -> IO SpinButtonUpdatePolicy -- ^ returns the current update policy\nspinButtonGetUpdatePolicy self =\n liftM (toEnum . fromIntegral) $\n {# call unsafe spin_button_get_update_policy #}\n (toSpinButton self)\n\n-- | Sets the flag that determines if non-numeric text can be typed into the\n-- spin button.\n--\nspinButtonSetNumeric :: SpinButtonClass self => self\n -> Bool -- ^ @numeric@ - flag indicating if only numeric entry is allowed.\n -> IO ()\nspinButtonSetNumeric self numeric =\n {# call spin_button_set_numeric #}\n (toSpinButton self)\n (fromBool numeric)\n\n-- | Returns whether non-numeric text can be typed into the spin button. See\n-- 'spinButtonSetNumeric'.\n--\nspinButtonGetNumeric :: SpinButtonClass self => self\n -> IO Bool -- ^ returns @True@ if only numeric text can be entered\nspinButtonGetNumeric self =\n liftM toBool $\n {# call unsafe spin_button_get_numeric #}\n (toSpinButton self)\n\n-- | Increment or decrement a spin button's value in a specified direction by\n-- a specified amount.\n--\nspinButtonSpin :: SpinButtonClass self => self\n -> SpinType -- ^ @direction@ - a 'SpinType' indicating the direction to spin.\n -> Double -- ^ @increment@ - step increment to apply in the specified\n -- direction.\n -> IO ()\nspinButtonSpin self direction increment =\n {# call spin_button_spin #}\n (toSpinButton self)\n ((fromIntegral . fromEnum) direction)\n (realToFrac increment)\n\n-- | Sets the flag that determines if a spin button value wraps around to the\n-- opposite limit when the upper or lower limit of the range is exceeded.\n--\nspinButtonSetWrap :: SpinButtonClass self => self\n -> Bool -- ^ @wrap@ - a flag indicating if wrapping behavior is performed.\n -> IO ()\nspinButtonSetWrap self wrap =\n {# call spin_button_set_wrap #}\n (toSpinButton self)\n (fromBool wrap)\n\n-- | Returns whether the spin button's value wraps around to the opposite\n-- limit when the upper or lower limit of the range is exceeded. See\n-- 'spinButtonSetWrap'.\n--\nspinButtonGetWrap :: SpinButtonClass self => self\n -> IO Bool -- ^ returns @True@ if the spin button wraps around\nspinButtonGetWrap self =\n liftM toBool $\n {# call spin_button_get_wrap #}\n (toSpinButton self)\n\n-- | Sets the policy as to whether values are corrected to the nearest step\n-- increment when a spin button is activated after providing an invalid value.\n--\nspinButtonSetSnapToTicks :: SpinButtonClass self => self\n -> Bool -- ^ @snapToTicks@ - a flag indicating if invalid values should be\n -- corrected.\n -> IO ()\nspinButtonSetSnapToTicks self snapToTicks =\n {# call spin_button_set_snap_to_ticks #}\n (toSpinButton self)\n (fromBool snapToTicks)\n\n-- | Returns whether the values are corrected to the nearest step. See\n-- 'spinButtonSetSnapToTicks'.\n--\nspinButtonGetSnapToTicks :: SpinButtonClass self => self\n -> IO Bool -- ^ returns @True@ if values are snapped to the nearest step.\nspinButtonGetSnapToTicks self =\n liftM toBool $\n {# call unsafe spin_button_get_snap_to_ticks #}\n (toSpinButton self)\n\n-- | Manually force an update of the spin button.\n--\nspinButtonUpdate :: SpinButtonClass self => self -> IO ()\nspinButtonUpdate self =\n {# call spin_button_update #}\n (toSpinButton self)\n\n--------------------\n-- Attributes\n\n-- | The adjustment that holds the value of the spinbutton.\n--\nspinButtonAdjustment :: SpinButtonClass self => Attr self Adjustment\nspinButtonAdjustment = newAttr\n spinButtonGetAdjustment\n spinButtonSetAdjustment\n\n-- | The acceleration rate when you hold down a button.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\nspinButtonClimbRate :: SpinButtonClass self => Attr self Double\nspinButtonClimbRate = newAttrFromDoubleProperty \"climb-rate\"\n\n-- | The number of decimal places to display.\n--\n-- Allowed values: \\<= 20\n--\n-- Default value: 0\n--\nspinButtonDigits :: SpinButtonClass self => Attr self Int\nspinButtonDigits = newAttr\n spinButtonGetDigits\n spinButtonSetDigits\n\n-- | Whether erroneous values are automatically changed to a spin button's\n-- nearest step increment.\n--\n-- Default value: @False@\n--\nspinButtonSnapToTicks :: SpinButtonClass self => Attr self Bool\nspinButtonSnapToTicks = newAttr\n spinButtonGetSnapToTicks\n spinButtonSetSnapToTicks\n\n-- | Whether non-numeric characters should be ignored.\n--\n-- Default value: @False@\n--\nspinButtonNumeric :: SpinButtonClass self => Attr self Bool\nspinButtonNumeric = newAttr\n spinButtonGetNumeric\n spinButtonSetNumeric\n\n-- | Whether a spin button should wrap upon reaching its limits.\n--\n-- Default value: @False@\n--\nspinButtonWrap :: SpinButtonClass self => Attr self Bool\nspinButtonWrap = newAttr\n spinButtonGetWrap\n spinButtonSetWrap\n\n-- | Whether the spin button should update always, or only when the value is\n-- legal.\n--\n-- Default value: 'UpdateAlways'\n--\nspinButtonUpdatePolicy :: SpinButtonClass self => Attr self SpinButtonUpdatePolicy\nspinButtonUpdatePolicy = newAttr\n spinButtonGetUpdatePolicy\n spinButtonSetUpdatePolicy\n\n-- | Reads the current value, or sets a new value.\n--\n-- Default value: 0\n--\nspinButtonValue :: SpinButtonClass self => Attr self Double\nspinButtonValue = newAttr\n spinButtonGetValue\n spinButtonSetValue\n\n--------------------\n-- Signals\n\n-- | Install a custom input handler.\n--\n-- * This signal is called upon each time the value of the SpinButton is set\n-- by spinButtonSetValue. The function can return Nothing if the value is no\n-- good.\n--\nonInput, afterInput :: SpinButtonClass sb => sb -> (IO (Maybe Double)) ->\n IO (ConnectId sb)\nonInput sb user = connect_PTR__INT \"input\" False sb $ \\dPtr -> do\n mVal <- user\n case mVal of\n (Just val) -> do\n poke dPtr ((realToFrac val)::{#type gdouble#})\n return 0\n Nothing -> return (fromIntegral inputError)\nafterInput sb user = connect_PTR__INT \"input\" True sb $ \\dPtr -> do\n mVal <- user\n case mVal of\n (Just val) -> do\n poke dPtr ((realToFrac val)::{#type gdouble#})\n return 0\n Nothing -> return (fromIntegral inputError)\n\n-- | Install a custom output handler.\n--\n-- * This handler makes it possible to query the current value and to render\n-- something completely different to the screen using entrySetText. The\n-- return value must be False in order to let the default output routine run\n-- after this signal returns.\n--\nonOutput, afterOutput :: SpinButtonClass sb => sb -> IO Bool ->\n IO (ConnectId sb)\nonOutput = connect_NONE__BOOL \"output\" False\nafterOutput = connect_NONE__BOOL \"output\" True\n\n-- | The value of the spin button has changed.\n--\nonValueSpinned, afterValueSpinned :: SpinButtonClass sb => sb -> IO () ->\n IO (ConnectId sb)\nonValueSpinned = connect_NONE__NONE \"value-changed\" False\nafterValueSpinned = connect_NONE__NONE \"value-changed\" True\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget SpinButton\n--\n-- Author : Axel Simon\n--\n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.10 $ from $Date: 2005\/10\/19 12:57:37 $\n--\n-- Copyright (C) 1999-2005 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Retrieve an integer or floating-point number from the user\n--\nmodule Graphics.UI.Gtk.Entry.SpinButton (\n-- * Detail\n-- \n-- | A 'SpinButton' is an ideal way to allow the user to set the value of some\n-- attribute. Rather than having to directly type a number into a 'Entry',\n-- 'SpinButton' allows the user to click on one of two arrows to increment or\n-- decrement the displayed value. A value can still be typed in, with the bonus\n-- that it can be checked to ensure it is in a given range.\n--\n-- The main properties of a 'SpinButton' are through a 'Adjustment'. See the\n-- 'Adjustment' section for more details about an adjustment's properties.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Entry'\n-- | +----SpinButton\n-- @\n\n-- * Types\n SpinButton,\n SpinButtonClass,\n castToSpinButton,\n toSpinButton,\n\n-- * Constructors\n spinButtonNew,\n spinButtonNewWithRange,\n\n-- * Methods\n spinButtonConfigure,\n spinButtonSetAdjustment,\n spinButtonGetAdjustment,\n spinButtonSetDigits,\n spinButtonGetDigits,\n spinButtonSetIncrements,\n spinButtonGetIncrements,\n spinButtonSetRange,\n spinButtonGetRange,\n spinButtonGetValue,\n spinButtonGetValueAsInt,\n spinButtonSetValue,\n SpinButtonUpdatePolicy(..),\n spinButtonSetUpdatePolicy,\n spinButtonGetUpdatePolicy,\n spinButtonSetNumeric,\n spinButtonGetNumeric,\n SpinType(..),\n spinButtonSpin,\n spinButtonSetWrap,\n spinButtonGetWrap,\n spinButtonSetSnapToTicks,\n spinButtonGetSnapToTicks,\n spinButtonUpdate,\n\n-- * Attributes\n spinButtonAdjustment,\n spinButtonClimbRate,\n spinButtonDigits,\n spinButtonSnapToTicks,\n spinButtonNumeric,\n spinButtonWrap,\n spinButtonUpdatePolicy,\n spinButtonValue,\n\n-- * Signals\n onInput,\n afterInput,\n onOutput,\n afterOutput,\n onValueSpinned,\n afterValueSpinned\n ) where\n\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.General.Structs\t(inputError)\nimport Graphics.UI.Gtk.General.Enums\t(SpinButtonUpdatePolicy(..), SpinType(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Interfaces\n\ninstance EditableClass SpinButton\n\n--------------------\n-- Constructors\n\n-- | Creates a new 'SpinButton'.\n--\nspinButtonNew :: \n Adjustment -- ^ @adjustment@ - the 'Adjustment' object that this spin\n -- button should use.\n -> Double -- ^ @climbRate@ - specifies how much the spin button\n -- changes when an arrow is clicked on.\n -> Int -- ^ @digits@ - the number of decimal places to display.\n -> IO SpinButton\nspinButtonNew adjustment climbRate digits =\n makeNewObject mkSpinButton $\n liftM (castPtr :: Ptr Widget -> Ptr SpinButton) $\n {# call unsafe spin_button_new #}\n adjustment\n (realToFrac climbRate)\n (fromIntegral digits)\n\n-- | This is a convenience constructor that allows creation of a numeric\n-- 'SpinButton' without manually creating an adjustment. The value is initially\n-- set to the minimum value and a page increment of 10 * @step@ is the default.\n-- The precision of the spin button is equivalent to the precision of @step@.\n--\n-- Note that the way in which the precision is derived works best if @step@\n-- is a power of ten. If the resulting precision is not suitable for your\n-- needs, use 'spinButtonSetDigits' to correct it.\n--\nspinButtonNewWithRange :: \n Double -- ^ @min@ - Minimum allowable value\n -> Double -- ^ @max@ - Maximum allowable value\n -> Double -- ^ @step@ - Increment added or subtracted by spinning the\n -- widget\n -> IO SpinButton\nspinButtonNewWithRange min max step =\n makeNewObject mkSpinButton $\n liftM (castPtr :: Ptr Widget -> Ptr SpinButton) $\n {# call unsafe spin_button_new_with_range #}\n (realToFrac min)\n (realToFrac max)\n (realToFrac step)\n\n--------------------\n-- Methods\n\n-- | Changes the properties of an existing spin button. The adjustment, climb\n-- rate, and number of decimal places are all changed accordingly, after this\n-- function call.\n--\nspinButtonConfigure :: SpinButtonClass self => self\n -> Adjustment -- ^ @adjustment@ - a 'Adjustment'.\n -> Double -- ^ @climbRate@ - the new climb rate.\n -> Int -- ^ @digits@ - the number of decimal places to display in the\n -- spin button.\n -> IO ()\nspinButtonConfigure self adjustment climbRate digits =\n {# call spin_button_configure #}\n (toSpinButton self)\n adjustment\n (realToFrac climbRate)\n (fromIntegral digits)\n\n-- | Replaces the 'Adjustment' associated with the spin button.\n--\nspinButtonSetAdjustment :: SpinButtonClass self => self\n -> Adjustment -- ^ @adjustment@ - a 'Adjustment' to replace the existing\n -- adjustment\n -> IO ()\nspinButtonSetAdjustment self adjustment =\n {# call spin_button_set_adjustment #}\n (toSpinButton self)\n adjustment\n\n-- | Get the adjustment associated with a 'SpinButton'\n--\nspinButtonGetAdjustment :: SpinButtonClass self => self\n -> IO Adjustment -- ^ returns the 'Adjustment' of @spinButton@\nspinButtonGetAdjustment self =\n makeNewObject mkAdjustment $\n {# call unsafe spin_button_get_adjustment #}\n (toSpinButton self)\n\n-- | Set the precision to be displayed by @spinButton@. Up to 20 digit\n-- precision is allowed.\n--\nspinButtonSetDigits :: SpinButtonClass self => self\n -> Int -- ^ @digits@ - the number of digits after the decimal point to be\n -- displayed for the spin button's value\n -> IO ()\nspinButtonSetDigits self digits =\n {# call spin_button_set_digits #}\n (toSpinButton self)\n (fromIntegral digits)\n\n-- | Fetches the precision of @spinButton@. See 'spinButtonSetDigits'.\n--\nspinButtonGetDigits :: SpinButtonClass self => self\n -> IO Int -- ^ returns the current precision\nspinButtonGetDigits self =\n liftM fromIntegral $\n {# call spin_button_get_digits #}\n (toSpinButton self)\n\n-- | Sets the step and page increments for the spin button. This affects how\n-- quickly the value changes when the spin button's arrows are activated.\n--\nspinButtonSetIncrements :: SpinButtonClass self => self\n -> Double -- ^ @step@ - increment applied for a button 1 press.\n -> Double -- ^ @page@ - increment applied for a button 2 press.\n -> IO ()\nspinButtonSetIncrements self step page =\n {# call spin_button_set_increments #}\n (toSpinButton self)\n (realToFrac step)\n (realToFrac page)\n\n-- | Gets the current step and page the increments used by the spin button. See\n-- 'spinButtonSetIncrements'.\n--\nspinButtonGetIncrements :: SpinButtonClass self => self\n -> IO (Double, Double) -- ^ @(step, page)@ - step increment and page increment\nspinButtonGetIncrements self =\n alloca $ \\stepPtr ->\n alloca $ \\pagePtr -> do\n {# call unsafe spin_button_get_increments #}\n (toSpinButton self)\n stepPtr\n pagePtr\n step <- peek stepPtr\n page <- peek pagePtr\n return (realToFrac step, realToFrac page)\n\n-- | Sets the minimum and maximum allowable values for the spin button\n--\nspinButtonSetRange :: SpinButtonClass self => self\n -> Double -- ^ @min@ - minimum allowable value\n -> Double -- ^ @max@ - maximum allowable value\n -> IO ()\nspinButtonSetRange self min max =\n {# call spin_button_set_range #}\n (toSpinButton self)\n (realToFrac min)\n (realToFrac max)\n\n-- | Gets the range allowed for the spin button. See 'spinButtonSetRange'.\n--\nspinButtonGetRange :: SpinButtonClass self => self\n -> IO (Double, Double) -- ^ @(min, max)@ - minimum and maximum allowed value\nspinButtonGetRange self =\n alloca $ \\minPtr ->\n alloca $ \\maxPtr -> do\n {# call unsafe spin_button_get_range #}\n (toSpinButton self)\n minPtr\n maxPtr\n min <- peek minPtr\n max <- peek maxPtr\n return (realToFrac min, realToFrac max)\n\n-- | Get the value of the spin button as a floating point value.\n--\nspinButtonGetValue :: SpinButtonClass self => self -> IO Double\nspinButtonGetValue self =\n liftM realToFrac $\n {# call unsafe spin_button_get_value #}\n (toSpinButton self)\n\n-- | Get the value of the spin button as an integral value.\n--\nspinButtonGetValueAsInt :: SpinButtonClass self => self -> IO Int\nspinButtonGetValueAsInt self =\n liftM fromIntegral $\n {# call unsafe spin_button_get_value_as_int #}\n (toSpinButton self)\n\n-- | Set the value of the spin button.\n--\nspinButtonSetValue :: SpinButtonClass self => self -> Double -> IO ()\nspinButtonSetValue self value =\n {# call spin_button_set_value #}\n (toSpinButton self)\n (realToFrac value)\n\n-- | Sets the update behavior of a spin button. This determines whether the\n-- spin button is always updated or only when a valid value is set.\n--\nspinButtonSetUpdatePolicy :: SpinButtonClass self => self\n -> SpinButtonUpdatePolicy -- ^ @policy@ - a 'SpinButtonUpdatePolicy' value\n -> IO ()\nspinButtonSetUpdatePolicy self policy =\n {# call spin_button_set_update_policy #}\n (toSpinButton self)\n ((fromIntegral . fromEnum) policy)\n\n-- | Gets the update behavior of a spin button. See\n-- 'spinButtonSetUpdatePolicy'.\n--\nspinButtonGetUpdatePolicy :: SpinButtonClass self => self\n -> IO SpinButtonUpdatePolicy -- ^ returns the current update policy\nspinButtonGetUpdatePolicy self =\n liftM (toEnum . fromIntegral) $\n {# call unsafe spin_button_get_update_policy #}\n (toSpinButton self)\n\n-- | Sets the flag that determines if non-numeric text can be typed into the\n-- spin button.\n--\nspinButtonSetNumeric :: SpinButtonClass self => self\n -> Bool -- ^ @numeric@ - flag indicating if only numeric entry is allowed.\n -> IO ()\nspinButtonSetNumeric self numeric =\n {# call spin_button_set_numeric #}\n (toSpinButton self)\n (fromBool numeric)\n\n-- | Returns whether non-numeric text can be typed into the spin button. See\n-- 'spinButtonSetNumeric'.\n--\nspinButtonGetNumeric :: SpinButtonClass self => self\n -> IO Bool -- ^ returns @True@ if only numeric text can be entered\nspinButtonGetNumeric self =\n liftM toBool $\n {# call unsafe spin_button_get_numeric #}\n (toSpinButton self)\n\n-- | Increment or decrement a spin button's value in a specified direction by\n-- a specified amount.\n--\nspinButtonSpin :: SpinButtonClass self => self\n -> SpinType -- ^ @direction@ - a 'SpinType' indicating the direction to spin.\n -> Double -- ^ @increment@ - step increment to apply in the specified\n -- direction.\n -> IO ()\nspinButtonSpin self direction increment =\n {# call spin_button_spin #}\n (toSpinButton self)\n ((fromIntegral . fromEnum) direction)\n (realToFrac increment)\n\n-- | Sets the flag that determines if a spin button value wraps around to the\n-- opposite limit when the upper or lower limit of the range is exceeded.\n--\nspinButtonSetWrap :: SpinButtonClass self => self\n -> Bool -- ^ @wrap@ - a flag indicating if wrapping behavior is performed.\n -> IO ()\nspinButtonSetWrap self wrap =\n {# call spin_button_set_wrap #}\n (toSpinButton self)\n (fromBool wrap)\n\n-- | Returns whether the spin button's value wraps around to the opposite\n-- limit when the upper or lower limit of the range is exceeded. See\n-- 'spinButtonSetWrap'.\n--\nspinButtonGetWrap :: SpinButtonClass self => self\n -> IO Bool -- ^ returns @True@ if the spin button wraps around\nspinButtonGetWrap self =\n liftM toBool $\n {# call spin_button_get_wrap #}\n (toSpinButton self)\n\n-- | Sets the policy as to whether values are corrected to the nearest step\n-- increment when a spin button is activated after providing an invalid value.\n--\nspinButtonSetSnapToTicks :: SpinButtonClass self => self\n -> Bool -- ^ @snapToTicks@ - a flag indicating if invalid values should be\n -- corrected.\n -> IO ()\nspinButtonSetSnapToTicks self snapToTicks =\n {# call spin_button_set_snap_to_ticks #}\n (toSpinButton self)\n (fromBool snapToTicks)\n\n-- | Returns whether the values are corrected to the nearest step. See\n-- 'spinButtonSetSnapToTicks'.\n--\nspinButtonGetSnapToTicks :: SpinButtonClass self => self\n -> IO Bool -- ^ returns @True@ if values are snapped to the nearest step.\nspinButtonGetSnapToTicks self =\n liftM toBool $\n {# call unsafe spin_button_get_snap_to_ticks #}\n (toSpinButton self)\n\n-- | Manually force an update of the spin button.\n--\nspinButtonUpdate :: SpinButtonClass self => self -> IO ()\nspinButtonUpdate self =\n {# call spin_button_update #}\n (toSpinButton self)\n\n--------------------\n-- Attributes\n\n-- | The adjustment that holds the value of the spinbutton.\n--\nspinButtonAdjustment :: SpinButtonClass self => Attr self Adjustment\nspinButtonAdjustment = newAttr\n spinButtonGetAdjustment\n spinButtonSetAdjustment\n\n-- | The acceleration rate when you hold down a button.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\nspinButtonClimbRate :: SpinButtonClass self => Attr self Double\nspinButtonClimbRate = newAttrFromDoubleProperty \"climb-rate\"\n\n-- | The number of decimal places to display.\n--\n-- Allowed values: \\<= 20\n--\n-- Default value: 0\n--\nspinButtonDigits :: SpinButtonClass self => Attr self Int\nspinButtonDigits = newAttr\n spinButtonGetDigits\n spinButtonSetDigits\n\n-- | Whether erroneous values are automatically changed to a spin button's\n-- nearest step increment.\n--\n-- Default value: @False@\n--\nspinButtonSnapToTicks :: SpinButtonClass self => Attr self Bool\nspinButtonSnapToTicks = newAttr\n spinButtonGetSnapToTicks\n spinButtonSetSnapToTicks\n\n-- | Whether non-numeric characters should be ignored.\n--\n-- Default value: @False@\n--\nspinButtonNumeric :: SpinButtonClass self => Attr self Bool\nspinButtonNumeric = newAttr\n spinButtonGetNumeric\n spinButtonSetNumeric\n\n-- | Whether a spin button should wrap upon reaching its limits.\n--\n-- Default value: @False@\n--\nspinButtonWrap :: SpinButtonClass self => Attr self Bool\nspinButtonWrap = newAttr\n spinButtonGetWrap\n spinButtonSetWrap\n\n-- | Whether the spin button should update always, or only when the value is\n-- legal.\n--\n-- Default value: 'UpdateAlways'\n--\nspinButtonUpdatePolicy :: SpinButtonClass self => Attr self SpinButtonUpdatePolicy\nspinButtonUpdatePolicy = newAttr\n spinButtonGetUpdatePolicy\n spinButtonSetUpdatePolicy\n\n-- | Reads the current value, or sets a new value.\n--\n-- Default value: 0\n--\nspinButtonValue :: SpinButtonClass self => Attr self Double\nspinButtonValue = newAttr\n spinButtonGetValue\n spinButtonSetValue\n\n--------------------\n-- Signals\n\n-- | Install a custom input handler.\n--\n-- * This signal is called upon each time the value of the SpinButton is set\n-- by spinButtonSetValue. The function can return Nothing if the value is no\n-- good.\n--\nonInput, afterInput :: SpinButtonClass sb => sb -> (IO (Maybe Double)) ->\n IO (ConnectId sb)\nonInput sb user = connect_PTR__INT \"input\" False sb $ \\dPtr -> do\n mVal <- user\n case mVal of\n (Just val) -> do\n poke dPtr ((realToFrac val)::{#type gdouble#})\n return 0\n Nothing -> return (fromIntegral inputError)\nafterInput sb user = connect_PTR__INT \"input\" True sb $ \\dPtr -> do\n mVal <- user\n case mVal of\n (Just val) -> do\n poke dPtr ((realToFrac val)::{#type gdouble#})\n return 0\n Nothing -> return (fromIntegral inputError)\n\n-- | Install a custom output handler.\n--\n-- * This handler makes it possible to query the current value and to render\n-- something completely different to the screen using entrySetText. The\n-- return value must be False in order to let the default output routine run\n-- after this signal returns.\n--\nonOutput, afterOutput :: SpinButtonClass sb => sb -> IO Bool ->\n IO (ConnectId sb)\nonOutput = connect_NONE__BOOL \"output\" False\nafterOutput = connect_NONE__BOOL \"output\" True\n\n-- | The value of the spin button has changed.\n--\nonValueSpinned, afterValueSpinned :: SpinButtonClass sb => sb -> IO () ->\n IO (ConnectId sb)\nonValueSpinned = connect_NONE__NONE \"value-changed\" False\nafterValueSpinned = connect_NONE__NONE \"value-changed\" True\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"b4f9e861398af208c4f40586342cd1436fab57be","subject":"Fixed remaining NULLable params not being Maybe","message":"Fixed remaining NULLable params not being Maybe\n\nAffects terminalSetColorCursor and terminalSetColorHighlight.\n","repos":"haasn\/haskell-vte","old_file":"Graphics\/UI\/Gtk\/Vte\/Vte.chs","new_file":"Graphics\/UI\/Gtk\/Vte\/Vte.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) widget for VTE\n--\n-- Author : Andy Stewart\n--\n-- Created: 20 Sep 2009\n--\n-- Copyright (C) 2009 Andy Stewart \n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- A terminal widget\n-- \n-----------------------------------------------------------------------------\n-- \nmodule Graphics.UI.Gtk.Vte.Vte (\n-- * Types\n Terminal,\n VteSelect,\n VteChar(..),\n\n-- * Enums\n TerminalEraseBinding(..),\n TerminalCursorBlinkMode(..),\n TerminalCursorShape(..),\n RegexCompileFlags(..),\n RegexMatchFlags(..),\n\n-- * Constructors\n terminalNew,\n\n-- * Methods\n terminalImAppendMenuitems,\n terminalForkCommand,\n terminalForkpty,\n terminalSetPty,\n terminalGetPty,\n terminalFeed,\n terminalFeedChild,\n terminalFeedChildBinary,\n terminalGetChildExitStatus,\n terminalSelectAll,\n terminalSelectNone,\n terminalCopyClipboard,\n terminalPasteClipboard,\n terminalCopyPrimary,\n terminalPastePrimary,\n terminalSetSize,\n terminalSetAudibleBell,\n terminalGetAudibleBell,\n terminalSetVisibleBell,\n terminalGetVisibleBell,\n terminalSetAllowBold,\n terminalGetAllowBold,\n terminalSetScrollOnOutput,\n terminalSetScrollOnKeystroke,\n terminalSetColorBold,\n terminalSetColorForeground,\n terminalSetColorBackground,\n terminalSetColorDim,\n terminalSetColorCursor,\n terminalSetColorHighlight,\n terminalSetColors,\n terminalSetDefaultColors,\n terminalSetOpacity,\n terminalSetBackgroundImage,\n terminalSetBackgroundImageFile,\n terminalSetBackgroundSaturation,\n terminalSetBackgroundTransparent,\n terminalSetBackgroundTintColor,\n terminalSetScrollBackground,\n terminalSetCursorShape,\n terminalGetCursorShape,\n terminalSetCursorBlinkMode,\n terminalGetCursorBlinkMode,\n terminalSetScrollbackLines,\n terminalSetFont,\n terminalSetFontFromString,\n terminalGetFont,\n terminalGetHasSelection,\n terminalSetWordChars,\n terminalIsWordChar,\n terminalSetBackspaceBinding,\n terminalSetDeleteBinding,\n terminalSetMouseAutohide,\n terminalGetMouseAutohide,\n terminalReset,\n terminalGetText,\n terminalGetTextIncludeTrailingSpaces,\n terminalGetTextRange,\n terminalGetCursorPosition,\n terminalMatchClearAll,\n terminalMatchAddRegex,\n terminalMatchRemove,\n terminalMatchCheck,\n terminalMatchSetCursor,\n terminalMatchSetCursorType,\n terminalMatchSetCursorName,\n terminalSetEmulation,\n terminalGetEmulation,\n terminalGetDefaultEmulation,\n terminalSetEncoding,\n terminalGetEncoding,\n terminalGetStatusLine,\n terminalGetPadding,\n terminalGetAdjustment,\n terminalGetCharHeight,\n terminalGetCharWidth,\n terminalGetColumnCount,\n terminalGetRowCount,\n terminalGetIconTitle,\n terminalGetWindowTitle,\n\n-- * Attributes\n terminalAllowBold,\n terminalAudibleBell,\n terminalBackgroundImageFile,\n terminalBackgroundImagePixbuf,\n terminalBackgroundOpacity,\n terminalBackgroundSaturation,\n terminalBackgroundTintColor,\n terminalBackgroundTransparent,\n terminalBackspaceBinding,\n terminalCursorBlinkMode,\n terminalCursorShape,\n terminalDeleteBinding,\n terminalEmulation,\n terminalEncoding,\n terminalFontDesc,\n terminalIconTitle,\n terminalPointerAutohide,\n terminalPty,\n terminalScrollBackground,\n terminalScrollOnKeystroke,\n terminalScrollOnOutput,\n terminalScrollbackLines,\n terminalVisibleBell,\n terminalWindowTitle,\n terminalWordChars,\n\n-- * Signals\n beep,\n charSizeChanged,\n childExited,\n commit,\n contentsChanged,\n copyClipboard,\n cursorMoved,\n decreaseFontSize,\n deiconifyWindow,\n emulationChanged,\n encodingChanged,\n eof,\n iconTitleChanged,\n iconifyWindow,\n increaseFontSize,\n lowerWindow,\n maximizeWindow,\n moveWindow,\n pasteClipboard,\n raiseWindow,\n refreshWindow,\n resizeWidnow,\n restoreWindow,\n selectionChanged,\n setScrollAdjustments,\n statusLineChanged,\n textDeleted,\n textInserted,\n textModified,\n textScrolled,\n windowTitleChanged,\n ) where\n\nimport Control.Monad\t\t(liftM, unless)\nimport Data.Char\nimport Data.Word\n\nimport System.Glib.Attributes\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Properties\nimport System.Glib.GError\nimport System.Glib.Flags (Flags, fromFlags) \nimport Graphics.UI.Gtk.Abstract.Widget (Color)\nimport Graphics.UI.Gtk.Gdk.Cursor\nimport Graphics.Rendering.Pango.BasicTypes (FontDescription(FontDescription), makeNewFontDescription)\nimport Graphics.UI.Gtk.Vte.Structs\n\n{#import Graphics.UI.Gtk.General.Clipboard#} (selectionPrimary,\n selectionClipboard)\n{#import Graphics.UI.Gtk.Abstract.Object#}\t(makeNewObject)\n{#import Graphics.UI.Gtk.Vte.Types#}\n{#import Graphics.UI.Gtk.Vte.Signals#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GError#} (propagateGError)\n\n{#context lib= \"vte\" prefix= \"vte\"#}\n\n--------------------\n-- Types\n\n-- | A predicate that states which characters are of interest. The predicate\n-- @p c r@ where @p :: VteSelect@, should return @True@ if the character at\n-- column @c@ and row @r@ should be extracted.\ntype VteSelect =\n Int\n -> Int \n -> Bool\n\n{#pointer SelectionFunc#}\n\n-- | A structure describing the individual characters in the visible part of\n-- a terminal window.\n--\ndata VteChar = VteChar {\n vcRow :: Int,\n vcCol :: Int,\n vcChar :: Char,\n vcFore :: Color,\n vcBack :: Color,\n vcUnderline :: Bool,\n vcStrikethrough :: Bool\n }\n\n--------------------\n-- Utils\n\n-- | Utils function to transform 'VteAttributes' to 'VteChar'.\nattrToChar :: Char -> VteAttributes -> VteChar\nattrToChar ch (VteAttributes r c f b u s) = VteChar r c ch f b u s\n \nforeign import ccall \"wrapper\" mkVteSelectionFunc ::\n (Ptr Terminal -> {#type glong#} -> {#type glong#} -> Ptr () -> IO {#type gboolean#})\n -> IO SelectionFunc\n \n--------------------\n-- Enums\n\n-- | Values for what should happen when the user presses backspace\\\/delete. \n-- Use 'EraseAuto' unless the user can cause them to be overridden.\n{#enum VteTerminalEraseBinding as TerminalEraseBinding {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n-- | Values for the cursor blink setting.\n{#enum VteTerminalCursorBlinkMode as TerminalCursorBlinkMode {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n-- | Values for the cursor shape setting.\n{#enum VteTerminalCursorShape as TerminalCursorShape {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n-- | Flags determining how the regular expression is to be interpreted. See\n-- \n-- for an explanation of these flags.\n--\n{#enum GRegexCompileFlags as RegexCompileFlags {underscoreToCase} deriving (Bounded,Eq,Show) #}\ninstance Flags RegexCompileFlags\n\n-- | Flags determining how the string is matched against the regular\n-- expression. See\n-- \n-- for an explanation of these flags.\n--\n{#enum GRegexMatchFlags as RegexMatchFlags {underscoreToCase} deriving (Bounded,Eq,Show) #}\ninstance Flags RegexMatchFlags\n\n--------------------\n-- Constructors\n-- | Create a new terminal widget.\nterminalNew :: IO Terminal\nterminalNew = \n makeNewObject mkTerminal $ liftM castPtr {#call terminal_new#}\n\n--------------------\n-- Methods\n-- | Appends menu items for various input methods to the given menu. \n-- The user can select one of these items to modify the input method used by the terminal.\nterminalImAppendMenuitems :: \n TerminalClass self => self\n -> MenuShell -- ^ @menushell@ - a menu shell of 'MenuShell'\n -> IO () \nterminalImAppendMenuitems terminal menushell =\n {#call terminal_im_append_menuitems#} (toTerminal terminal) menushell\n\n-- | Starts the specified command under a newly-allocated controlling pseudo-terminal. \nterminalForkCommand :: \n TerminalClass self => self\n -> (Maybe String) -- ^ @command@ - the name of a binary to run, or @Nothing@ to get user's shell \n -> (Maybe [String]) -- ^ @argv@ - the argument list to be passed to command, or @Nothing@\n -> (Maybe [String]) -- ^ @envv@ - a list of environment variables to be added to the environment before starting command, or @Nothing@\n -> (Maybe String) -- ^ @directory@ - the name of a directory the command should start in, or @Nothing@ \n -> Bool -- ^ @lastlog@ - @True@ if the session should be logged to the lastlog\n -> Bool -- ^ @utmp@ - @True@ if the session should be logged to the utmp\/utmpx log \n -> Bool -- ^ @wtmp@ - @True@ if the session should be logged to the wtmp\/wtmpx log \n -> IO Int -- ^ return the ID of the new process\nterminalForkCommand terminal command argv envv directory lastlog utmp wtmp =\n liftM fromIntegral $\n maybeWith withUTFString command $ \\commandPtr ->\n maybeWith withUTFString directory $ \\dirPtr ->\n maybeWith withUTFStringArray argv $ \\argvPtrPtr ->\n maybeWith withUTFStringArray envv $ \\envvPtrPtr ->\n {#call terminal_fork_command#} \n (toTerminal terminal) \n commandPtr\n argvPtrPtr\n envvPtrPtr\n dirPtr\n (fromBool lastlog) \n (fromBool utmp)\n (fromBool wtmp)\n\n-- | Starts a new child process under a newly-allocated controlling pseudo-terminal. \n--\n-- * Available since Vte version 0.11.11\n-- \nterminalForkpty :: \n TerminalClass self => self\n -> (Maybe [String]) -- ^ @envv@ - a list of environment variables to be added to the environment before starting returning in the child process, or @Nothing@\n -> (Maybe String) -- ^ @directory@ - the name of a directory the child process should change to, or @Nothing@ \n -> Bool -- ^ @lastlog@ - @True@ if the session should be logged to the lastlog \n -> Bool -- ^ @utmp@ - @True@ if the session should be logged to the utmp\/utmpx log \n -> Bool -- ^ @wtmp@ - @True@ if the session should be logged to the wtmp\/wtmpx log \n -> IO Int -- ^ return the ID of the new process in the parent, 0 in the child, and -1 if there was an error \nterminalForkpty terminal envv directory lastlog utmp wtmp =\n liftM fromIntegral $\n maybeWith withUTFString directory $ \\dirPtr ->\n maybeWith withUTFStringArray envv $ \\envvPtrPtr ->\n {#call terminal_forkpty#} \n (toTerminal terminal)\n envvPtrPtr\n dirPtr\n (fromBool lastlog)\n (fromBool utmp)\n (fromBool wtmp)\n\n-- | Attach an existing PTY master side to the terminal widget. \n-- Use instead of 'terminalForkCommand' or 'terminalForkpty'.\n--\n-- * Available since Vte version 0.12.1\n--\nterminalSetPty :: \n TerminalClass self => self \n -> Int -- ^ @ptyMaster@ - a file descriptor of the master end of a PTY \n -> IO ()\nterminalSetPty terminal ptyMaster =\n {#call terminal_set_pty#} (toTerminal terminal) (fromIntegral ptyMaster)\n\n-- | Returns the file descriptor of the master end of terminal's PTY.\n--\n-- * Available since Vte version 0.19.1\n--\nterminalGetPty ::\n TerminalClass self => self\n -> IO Int -- ^ return the file descriptor, or -1 if the terminal has no PTY. \nterminalGetPty terminal = \n liftM fromIntegral $ \n {#call terminal_get_pty#} (toTerminal terminal)\n\n-- | Interprets data as if it were data received from a child process. This\n-- can either be used to drive the terminal without a child process, or just\n-- to mess with your users.\nterminalFeed :: \n TerminalClass self => self \n -> String -- ^ @string@ - a string in the terminal's current encoding \n -> IO ()\nterminalFeed terminal string =\n withUTFStringLen string $ \\(strPtr, len) ->\n {#call terminal_feed#} (toTerminal terminal) strPtr (fromIntegral len)\n\n-- | Sends a block of UTF-8 text to the child as if it were entered by the\n-- user at the keyboard.\nterminalFeedChild :: \n TerminalClass self => self \n -> String -- ^ @string@ - data to send to the child \n -> IO ()\nterminalFeedChild terminal string =\n withUTFStringLen string $ \\(strPtr, len) ->\n {#call terminal_feed_child#} (toTerminal terminal) strPtr (fromIntegral len)\n\n-- | Sends a block of binary data to the child.\n--\n-- * Available since Vte version 0.12.1\n--\nterminalFeedChildBinary :: \n TerminalClass self => self \n -> [Word8] -- ^ @data@ - data to send to the child \n -> IO ()\nterminalFeedChildBinary terminal string =\n withArrayLen string $ \\len strPtr ->\n {#call terminal_feed_child_binary#} (toTerminal terminal) (castPtr strPtr) (fromIntegral len)\n \n-- | Gets the exit status of the command started by 'terminalForkCommand'. \n--\n-- * Available since Vte version 0.19.1\n--\nterminalGetChildExitStatus ::\n TerminalClass self => self \n -> IO Int -- ^ return the child's exit status \nterminalGetChildExitStatus terminal =\n liftM fromIntegral $\n {#call terminal_get_child_exit_status#} (toTerminal terminal)\n\n-- | Selects all text within the terminal (including the scrollback buffer).\n--\n-- * Available since Vte version 0.16\n--\nterminalSelectAll :: TerminalClass self => self -> IO () \nterminalSelectAll terminal =\n {#call terminal_select_all#} (toTerminal terminal)\n \n-- | Clears the current selection.\n--\n-- * Available since Vte version 0.16\n--\nterminalSelectNone :: TerminalClass self => self -> IO () \nterminalSelectNone terminal =\n {#call terminal_select_none#} (toTerminal terminal)\n\n-- | Places the selected text in the terminal in the 'selectionClipboard'\n-- selection.\nterminalCopyClipboard :: TerminalClass self => self -> IO ()\nterminalCopyClipboard terminal = \n {#call terminal_copy_clipboard#} (toTerminal terminal)\n \n-- | Sends the contents of the 'selectionClipboard' selection to the\n-- terminal's child. If necessary, the data is converted from UTF-8 to the\n-- terminal's current encoding. It's called on paste menu item, or when user\n-- presses Shift+Insert.\nterminalPasteClipboard :: TerminalClass self => self -> IO ()\nterminalPasteClipboard terminal =\n {#call terminal_paste_clipboard#} (toTerminal terminal)\n\n-- | Places the selected text in the terminal in the\n-- 'selectionPrimary' selection.\nterminalCopyPrimary :: TerminalClass self => self -> IO ()\nterminalCopyPrimary terminal =\n {#call terminal_copy_primary#} (toTerminal terminal)\n\n-- | Sends the contents of the\n-- 'selectionPrimary' selection to the\n-- terminal's child. If necessary, the data is converted from UTF-8 to the\n-- terminal's current encoding. The terminal will call also paste the\n-- 'SelectionPrimary' selection when the user clicks with the the second mouse\n-- button.\nterminalPastePrimary :: TerminalClass self => self -> IO ()\nterminalPastePrimary terminal =\n {#call terminal_paste_primary#} (toTerminal terminal)\n \n-- | Attempts to change the terminal's size in terms of rows and columns. \n-- If the attempt succeeds, the widget will resize itself to the proper size.\nterminalSetSize :: \n TerminalClass self => self \n -> Int -- ^ @columns@ - the desired number of columns \n -> Int -- ^ @rows@ - the desired number of rows \n -> IO ()\nterminalSetSize terminal columns rows =\n {#call terminal_set_size#} \n (toTerminal terminal)\n (fromIntegral columns)\n (fromIntegral rows)\n \n-- | Controls whether or not the terminal will beep when the child outputs the \\\"bl\\\" sequence.\nterminalSetAudibleBell :: \n TerminalClass self => self \n -> Bool -- ^ @isAudible@ - @True@ if the terminal should beep \n -> IO () \nterminalSetAudibleBell terminal isAudible =\n {#call terminal_set_audible_bell#} (toTerminal terminal) (fromBool isAudible)\n \n-- | Checks whether or not the terminal will beep when the child outputs the \\\"bl\\\" sequence.\nterminalGetAudibleBell :: \n TerminalClass self => self \n -> IO Bool -- ^ return @True@ if audible bell is enabled, @False@ if not \nterminalGetAudibleBell terminal =\n liftM toBool $\n {#call terminal_get_audible_bell#} (toTerminal terminal)\n \n-- | Controls whether or not the terminal will present a visible bell to the user when the child outputs the \\\"bl\\\" sequence. \n-- The terminal will clear itself to the default foreground color and then repaint itself.\nterminalSetVisibleBell :: \n TerminalClass self => self \n -> Bool -- ^ @isVisible@ - @True@ if the terminal should flash \n -> IO () \nterminalSetVisibleBell terminal isVisible =\n {#call terminal_set_visible_bell#} (toTerminal terminal) (fromBool isVisible)\n \n-- | Checks whether or not the terminal will present a visible bell to the user when the child outputs the \\\"bl\\\" sequence. \n-- The terminal will clear itself to the default foreground color and then repaint itself.\nterminalGetVisibleBell :: \n TerminalClass self => self \n -> IO Bool -- ^ return @True@ if visible bell is enabled, @False@ if not \nterminalGetVisibleBell terminal =\n liftM toBool $\n {#call terminal_get_visible_bell#} (toTerminal terminal)\n \n-- | Controls whether or not the terminal will attempt to draw bold text, \n-- either by using a bold font variant or by repainting text with a different offset.\nterminalSetAllowBold :: \n TerminalClass self => self \n -> Bool -- ^ @allowBold@ - @True@ if the terminal should attempt to draw bold text \n -> IO () \nterminalSetAllowBold terminal allowBold =\n {#call terminal_set_allow_bold#} (toTerminal terminal) (fromBool allowBold)\n \n-- | Checks whether or not the terminal will attempt to draw bold text by repainting text with a one-pixel offset.\nterminalGetAllowBold :: \n TerminalClass self => self \n -> IO Bool -- ^ return @True@ if bolding is enabled, @False@ if not \nterminalGetAllowBold terminal =\n liftM toBool $\n {#call terminal_get_allow_bold#} (toTerminal terminal)\n \n-- | Controls whether or not the terminal will forcibly scroll to the bottom of the viewable history when the new data is received from the child.\nterminalSetScrollOnOutput :: \n TerminalClass self => self \n -> Bool -- ^ @scroll@ - @True@ if the terminal should scroll on output \n -> IO () \nterminalSetScrollOnOutput terminal scroll =\n {#call terminal_set_scroll_on_output#} (toTerminal terminal) (fromBool scroll)\n \n-- | Controls whether or not the terminal will forcibly scroll to the bottom of the viewable history when the user presses a key. \n-- Modifier keys do not trigger this behavior.\nterminalSetScrollOnKeystroke :: \n TerminalClass self => self \n -> Bool -- ^ @scroll@ - @True@ if the terminal should scroll on keystrokes \n -> IO ()\nterminalSetScrollOnKeystroke terminal scroll =\n {#call terminal_set_scroll_on_keystroke#} (toTerminal terminal) (fromBool scroll)\n \n-- | Sets the color used to draw bold text in the default foreground color.\nterminalSetColorBold :: \n TerminalClass self => self \n -> Color -- ^ @bold@ - the new bold color \n -> IO ()\nterminalSetColorBold terminal bold =\n with bold $ \\boldPtr ->\n {#call terminal_set_color_bold#} (toTerminal terminal) (castPtr boldPtr)\n\n-- | Sets the foreground color used to draw normal text\nterminalSetColorForeground :: \n TerminalClass self => self \n -> Color -- ^ @foreground@ - the new foreground color \n -> IO ()\nterminalSetColorForeground terminal foreground =\n with foreground $ \\fgPtr -> \n {#call terminal_set_color_foreground#} (toTerminal terminal) (castPtr fgPtr)\n\n-- | Sets the background color for text which does not have a specific background color assigned. \n-- Only has effect when no background image is set and when the terminal is not transparent.\nterminalSetColorBackground :: \n TerminalClass self => self \n -> Color -- ^ @background@ - the new background color \n -> IO ()\nterminalSetColorBackground terminal background =\n with background $ \\bgPtr ->\n {#call terminal_set_color_background#} (toTerminal terminal) (castPtr bgPtr)\n\n-- | Sets the color used to draw dim text in the default foreground color.\nterminalSetColorDim :: \n TerminalClass self => self \n -> Color -- ^ @dim@ - the nw dim color\n -> IO ()\nterminalSetColorDim terminal dim =\n with dim $ \\dimPtr -> \n {#call terminal_set_color_dim#} (toTerminal terminal) (castPtr dimPtr)\n\n-- | Sets the background color for text which is under the cursor. \n-- If @Nothing@, text under the cursor will be drawn with foreground and background colors reversed.\n--\n-- * Available since Vte version 0.11.11\n--\nterminalSetColorCursor :: \n TerminalClass self => self \n -> Maybe Color -- ^ @cursor@ - the new color to use for the text cursor \n -> IO ()\nterminalSetColorCursor terminal cursor =\n maybeWith with cursor $ \\cursorPtr -> \n {#call terminal_set_color_cursor#} (toTerminal terminal) (castPtr cursorPtr)\n\n-- | Sets the background color for text which is highlighted. \n-- If @Nothing@, highlighted text (which is usually highlighted because it is selected) will be drawn with foreground and background colors reversed.\n--\n-- * Available since Vte version 0.11.11\n--\nterminalSetColorHighlight :: \n TerminalClass self => self \n -> Maybe Color -- ^ @highlight@ - the new color to use for highlighted text \n -> IO ()\nterminalSetColorHighlight terminal highlight =\n maybeWith with highlight $ \\hlPtr -> \n {#call terminal_set_color_highlight#} (toTerminal terminal) (castPtr hlPtr)\n\n-- | The terminal widget uses a 28-color model comprised of the default foreground and background colors, \n-- the bold foreground color, the dim foreground color, an eight color palette, \n-- bold versions of the eight color palette, and a dim version of the the eight color palette. palette_size must be either 0, 8, 16, or 24. \n-- If foreground is @Nothing@ and palette_size is greater than 0, the new foreground color is taken from palette[7]. \n-- If background is @Nothing@ and palette_size is greater than 0, the new background color is taken from palette[0]. \n-- If palette_size is 8 or 16, the third (dim) and possibly the second (bold) 8-color palettes are extrapolated from the new background color and the items in palette.\nterminalSetColors :: \n TerminalClass self => self \n -> Maybe Color -- ^ @foreground@ - the new foreground color, or @Nothing@ \n -> Maybe Color -- ^ @background@ - the new background color, or @Nothing@ \n -> [Color] -- ^ @palette@ - the color palette \n -> IO ()\nterminalSetColors terminal foreground background palette =\n maybeWith with foreground $ \\fPtr ->\n maybeWith with background $ \\bPtr ->\n withArrayLen palette $ \\len pPtr ->\n {#call terminal_set_colors#} \n (toTerminal terminal) \n (castPtr fPtr)\n (castPtr bPtr)\n (castPtr pPtr)\n (fromIntegral len)\n\n-- | Reset the terminal palette to reasonable compiled-in defaults.\nterminalSetDefaultColors :: TerminalClass self => self -> IO ()\nterminalSetDefaultColors terminal =\n {#call terminal_set_default_colors#} (toTerminal terminal)\n \n-- | Sets the opacity of the terminal background, were 0 means completely transparent and 65535 means completely opaque.\nterminalSetOpacity :: \n TerminalClass self => self\n -> Int -- ^ @opacity@ - the new opacity \n -> IO ()\nterminalSetOpacity terminal opacity =\n {#call terminal_set_opacity#} (toTerminal terminal) (fromIntegral opacity)\n\n-- | Sets a background image for the widget. \n-- Text which would otherwise be drawn using the default background color will instead be drawn over the specified image. \n-- If necessary, the image will be tiled to cover the widget's entire visible area. \n-- If specified by 'terminalSetBackgroundSaturation' the terminal will tint its in-memory copy of the image before applying it to the terminal.\nterminalSetBackgroundImage :: \n TerminalClass self => self\n -> Maybe Pixbuf -- ^ @image@ - a 'Pixbuf' to use, or @Nothing@ to use the default background\n -> IO ()\nterminalSetBackgroundImage terminal (Just image) =\n {#call terminal_set_background_image#} (toTerminal terminal) image\nterminalSetBackgroundImage terminal Nothing =\n {#call terminal_set_background_image#} (toTerminal terminal) (Pixbuf nullForeignPtr)\n \n-- | Sets a background image for the widget. \n-- If specified by 'terminalSetBackgroundSaturation', the terminal will tint its in-memory copy of the image before applying it to the terminal.\nterminalSetBackgroundImageFile :: \n TerminalClass self => self\n -> String -- ^ @path@ - path to an image file \n -> IO ()\nterminalSetBackgroundImageFile terminal path =\n withUTFString path $ \\pathPtr ->\n {#call terminal_set_background_image_file#} (toTerminal terminal) pathPtr\n \n-- | If a background image has been set using 'terminalSetBackgroundImage', 'terminalSetBackgroundImageFile', or 'terminalSetBackgroundTransparent', \n-- and the saturation value is less than 1.0, the terminal will adjust the colors of the image before drawing the image. \n-- To do so, the terminal will create a copy of the background image (or snapshot of the root window) and modify its pixel values.\nterminalSetBackgroundSaturation :: \n TerminalClass self => self\n -> Double -- ^ @saturation@ - a floating point value between 0.0 and 1.0. \n -> IO () \nterminalSetBackgroundSaturation terminal saturation =\n {#call terminal_set_background_saturation#} (toTerminal terminal) (realToFrac saturation)\n \n-- | Sets the terminal's background image to the pixmap stored in the root window, adjusted so that if there are no windows below your application, \n-- the widget will appear to be transparent.\nterminalSetBackgroundTransparent :: \n TerminalClass self => self\n -> Bool -- ^ @transparent@ - @True@ if the terminal should fake transparency \n -> IO ()\nterminalSetBackgroundTransparent terminal transparent =\n {#call terminal_set_background_transparent#} (toTerminal terminal) (fromBool transparent)\n \n-- | If a background image has been set using 'terminalSetBackgroundImage', 'terminalSetBackgroundImageFile', or 'terminalSetBackgroundTransparent', \n-- and the value set by 'terminalSetBackgroundSaturation' is less than one, the terminal will adjust the color of the image before drawing the image. \n-- To do so, the terminal will create a copy of the background image (or snapshot of the root window) and modify its pixel values. \n-- The initial tint color is black.\n--\n-- * Available since Vte version 0.11\n--\nterminalSetBackgroundTintColor :: \n TerminalClass self => self\n -> Color -- ^ @color@ - a color which the terminal background should be tinted to if its saturation is not 1.0. \n -> IO ()\nterminalSetBackgroundTintColor terminal color =\n with color $ \\cPtr ->\n {#call terminal_set_background_tint_color#} (toTerminal terminal) (castPtr cPtr)\n\n-- | Controls whether or not the terminal will scroll the background image (if one is set) when the text in the window must be scrolled.\n--\n-- * Available since Vte version 0.11\n--\nterminalSetScrollBackground :: \n TerminalClass self => self\n -> Bool -- ^ @scroll@ - @True@ if the terminal should scroll the background image along with text. \n -> IO ()\nterminalSetScrollBackground terminal scroll =\n {#call terminal_set_scroll_background#} (toTerminal terminal) (fromBool scroll)\n \n-- | Sets the shape of the cursor drawn.\n--\n-- * Available since Vte version 0.19.1\n--\nterminalSetCursorShape ::\n TerminalClass self => self \n -> TerminalCursorShape -- ^ @shape@ - the 'TerminalCursorShape' to use \n -> IO ()\nterminalSetCursorShape terminal shape = \n {#call terminal_set_cursor_shape#} (toTerminal terminal) $fromIntegral (fromEnum shape)\n\n-- | Returns the currently set cursor shape.\n--\n-- * Available since Vte version 0.17.6\n--\nterminalGetCursorShape ::\n TerminalClass self => self\n -> IO TerminalCursorShape -- ^ return cursor shape\nterminalGetCursorShape terminal = \n liftM (toEnum.fromIntegral) $\n {#call terminal_get_cursor_shape#} (toTerminal terminal)\n\n-- | Returns the currently set cursor blink mode.\n--\n-- * Available since Vte version 0.17.1\n--\nterminalGetCursorBlinkMode :: \n TerminalClass self => self\n -> IO TerminalCursorBlinkMode -- ^ return cursor blink mode. \nterminalGetCursorBlinkMode terminal = \n liftM (toEnum.fromIntegral) $\n {#call terminal_get_cursor_blink_mode#} (toTerminal terminal)\n\n-- | Sets whether or not the cursor will blink. \n--\n-- * Available since Vte version 0.17.1\n--\nterminalSetCursorBlinkMode :: \n TerminalClass self => self\n -> TerminalCursorBlinkMode -- ^ @mode@ - the 'TerminalCursorBlinkMode' to use \n -> IO ()\nterminalSetCursorBlinkMode terminal mode =\n {#call terminal_set_cursor_blink_mode#} (toTerminal terminal) $fromIntegral (fromEnum mode)\n\n-- | Sets the length of the scrollback buffer used by the terminal. \n-- The size of the scrollback buffer will be set to the larger of this value and the number of visible rows the widget can display, \n-- so 0 can safely be used to disable scrollback. \n-- Note that this setting only affects the normal screen buffer. \n-- For terminal types which have an alternate screen buffer, no scrollback is allowed on the alternate screen buffer.\nterminalSetScrollbackLines :: \n TerminalClass self => self\n -> Int -- ^ @lines@ - the length of the history buffer \n -> IO ()\nterminalSetScrollbackLines terminal lines =\n {#call terminal_set_scrollback_lines#} (toTerminal terminal) (fromIntegral lines)\n\n-- | Sets the font used for rendering all text displayed by the terminal, overriding any fonts set using 'widgetModifyFont'.\n-- The terminal will immediately attempt to load the desired font, retrieve its metrics, and attempt to resize itself to keep the same number of rows and columns.\nterminalSetFont :: \n TerminalClass self => self\n -> FontDescription -- ^ @fontDesc@ - the 'FontDescription' of the desired font. \n -> IO ()\nterminalSetFont terminal (FontDescription fontDesc) =\n {#call terminal_set_font#} (toTerminal terminal) (castPtr $ unsafeForeignPtrToPtr fontDesc)\n\n-- | A convenience function which converts name into a 'FontDescription' and passes it to 'terminalSetFont'.\nterminalSetFontFromString :: \n TerminalClass self => self\n -> String -- ^ @name@ - a string describing the font. \n -> IO ()\nterminalSetFontFromString terminal name =\n withUTFString name $ \\namePtr -> \n {#call terminal_set_font_from_string#} (toTerminal terminal) namePtr\n \n-- | Queries the terminal for information about the fonts which will be used to draw text in the terminal.\nterminalGetFont :: \n TerminalClass self => self\n -> IO FontDescription -- ^ return a 'FontDescription' describing the font the terminal is currently using to render text. \nterminalGetFont terminal = do\n fdPtr <- {#call unsafe terminal_get_font#} (toTerminal terminal) \n makeNewFontDescription (castPtr fdPtr) \n\n-- | Checks if the terminal currently contains selected text. \n-- Note that this is different from determining if the terminal is the owner of any 'GtkClipboard' items.\nterminalGetHasSelection :: \n TerminalClass self => self\n -> IO Bool -- ^ return @True@ if part of the text in the terminal is selected. \nterminalGetHasSelection terminal =\n liftM toBool $\n {#call terminal_get_has_selection#} (toTerminal terminal)\n \n-- | When the user double-clicks to start selection, the terminal will extend the selection on word boundaries. \n-- It will treat characters included in spec as parts of words, and all other characters as word separators. \n-- Ranges of characters can be specified by separating them with a hyphen.\n-- As a special case, if @spec@ is the empty string, the terminal will treat all graphic non-punctuation non-space characters as word characters.\nterminalSetWordChars :: \n TerminalClass self => self\n -> String -- ^ @spec@ - a specification \n -> IO () \nterminalSetWordChars terminal spec =\n withUTFString spec $ \\specPtr ->\n {#call terminal_set_word_chars#} (toTerminal terminal) specPtr\n \n-- | Checks if a particular character is considered to be part of a word or not, based on the values last passed to 'terminalSetWordChars'.\nterminalIsWordChar :: \n TerminalClass self => self\n -> Char -- ^ @c@ - a candidate Unicode code point \n -> IO Bool -- ^ return @True@ if the character is considered to be part of a word \nterminalIsWordChar terminal c =\n liftM toBool $\n {#call terminal_is_word_char#} (toTerminal terminal) (fromIntegral $ ord c)\n\n-- | Modifies the terminal's backspace key binding, \n-- which controls what string or control sequence the terminal sends to its child when the user presses the backspace key.\nterminalSetBackspaceBinding :: \n TerminalClass self => self\n -> TerminalEraseBinding -- ^ @binding@ - a 'TerminalEraseBinding' for the backspace key \n -> IO ()\nterminalSetBackspaceBinding terminal binding =\n {#call terminal_set_backspace_binding#} (toTerminal terminal) (fromIntegral (fromEnum binding))\n\n-- | Modifies the terminal's delete key binding, \n-- which controls what string or control sequence the terminal sends to its child when the user presses the delete key.\nterminalSetDeleteBinding :: \n TerminalClass self => self\n -> TerminalEraseBinding -- ^ @bindign@ - a 'TerminalEraseBinding' for the delete key \n -> IO ()\nterminalSetDeleteBinding terminal binding =\n {#call terminal_set_delete_binding#} (toTerminal terminal) (fromIntegral (fromEnum binding))\n \n-- | Changes the value of the terminal's mouse autohide setting. \n-- When autohiding is enabled, the mouse cursor will be hidden when the user presses a key and shown when the user moves the mouse. \n-- This setting can be read using 'terminalGetMouseAutohide'.\nterminalSetMouseAutohide :: \n TerminalClass self => self\n -> Bool -- ^ @autohide@ - @True@ if the autohide should be enabled \n -> IO ()\nterminalSetMouseAutohide terminal autohide =\n {#call terminal_set_mouse_autohide#} (toTerminal terminal) (fromBool autohide)\n \n-- | Determines the value of the terminal's mouse autohide setting. \n-- When autohiding is enabled, the mouse cursor will be hidden when the user presses a key and shown when the user moves the mouse. \n-- This setting can be changed using 'terminalSetMouseAutohide'.\nterminalGetMouseAutohide :: TerminalClass self => self -> IO Bool\nterminalGetMouseAutohide terminal =\n liftM toBool $\n {#call terminal_get_mouse_autohide#} (toTerminal terminal)\n \n-- | Resets as much of the terminal's internal state as possible, discarding any unprocessed input data, \n-- resetting character attributes, cursor state, national character set state, status line, \n-- terminal modes (insert\/delete), selection state, and encoding.\nterminalReset :: \n TerminalClass self => self\n -> Bool -- ^ @full@ - @True@ to reset tabstops \n -> Bool -- ^ @clearHistory@ - @True@ to empty the terminal's scrollback buffer \n -> IO ()\nterminalReset terminal full clearHistory =\n {#call terminal_reset#} (toTerminal terminal) (fromBool full) (fromBool clearHistory)\n\n-- | Extracts a view of the visible part of the terminal. A selection\n-- predicate may be supplied to restrict the inspected characters. The\n-- return value is a list of 'VteChar' structures, each detailing the\n-- character's position, colors, and other characteristics.\n--\nterminalGetText ::\n TerminalClass self => self\n -> Maybe VteSelect -- ^ @Just p@ for a predicate @p@ that determines\n -- which character should be extracted or @Nothing@\n -- to select all characters\n -> IO [VteChar] -- ^ return a text string\nterminalGetText terminal mCB = do\n cbPtr <- case mCB of\n Just cb -> mkVteSelectionFunc $ \\_ c r _ ->\n return (fromBool (cb (fromIntegral c) (fromIntegral r)))\n Nothing -> return nullFunPtr\n gArrPtr <- {#call unsafe g_array_new#} 0 0\n (fromIntegral (sizeOf (undefined :: VteAttributes)))\n strPtr <- {#call terminal_get_text #} (toTerminal terminal) cbPtr nullPtr gArrPtr\n str <- if strPtr==nullPtr then return \"\" else peekUTFString strPtr\n (len,elemPtr) <- gArrayContent (castPtr gArrPtr)\n attrs <- (flip mapM) [0..len-1] $ peekElemOff elemPtr\n unless (cbPtr==nullFunPtr) $ freeHaskellFunPtr cbPtr\n {#call unsafe g_free#} (castPtr strPtr)\n {#call unsafe g_array_free#} gArrPtr 1\n return (zipWith attrToChar str attrs)\n \n-- | Extracts a view of the visible part of the terminal. \n-- If is_selected is not @Nothing@, characters will only be read if is_selected returns @True@ after being passed the column and row, respectively. \n-- A 'CharAttributes' structure is added to attributes for each byte added to the returned string detailing the character's position, colors, and other characteristics. \n-- This function differs from 'terminalGetText' in that trailing spaces at the end of lines are included.\n--\n-- * Available since Vte version 0.11.11\n--\nterminalGetTextIncludeTrailingSpaces :: \n TerminalClass self => self\n -> Maybe VteSelect -- ^ @Just p@ for a predicate @p@ that determines\n -- which character should be extracted or @Nothing@\n -- to select all characters \n -> IO [VteChar] -- ^ return a text string\nterminalGetTextIncludeTrailingSpaces terminal mCB = do\n cbPtr <- case mCB of\n Just cb -> mkVteSelectionFunc $ \\_ c r _ ->\n return (fromBool (cb (fromIntegral c) (fromIntegral r)))\n Nothing -> return nullFunPtr\n gArrPtr <- {#call unsafe g_array_new#} 0 0\n (fromIntegral (sizeOf (undefined :: VteAttributes)))\n strPtr <- {#call terminal_get_text_include_trailing_spaces #} (toTerminal terminal) cbPtr nullPtr gArrPtr\n str <- if strPtr==nullPtr then return \"\" else peekUTFString strPtr\n (len,elemPtr) <- gArrayContent (castPtr gArrPtr)\n attrs <- (flip mapM) [0..len-1] $ peekElemOff elemPtr\n unless (cbPtr==nullFunPtr) $ freeHaskellFunPtr cbPtr\n {#call unsafe g_free#} (castPtr strPtr)\n {#call unsafe g_array_free#} gArrPtr 1\n return (zipWith attrToChar str attrs)\n\n-- | Extracts a view of the visible part of the terminal. \n-- If is_selected is not @Nothing@, characters will only be read if is_selected returns @True@ after being passed the column and row, respectively. \n-- A 'CharAttributes' structure is added to attributes for each byte added to the returned string detailing the character's position, colors, and other characteristics. \n-- The entire scrollback buffer is scanned, so it is possible to read the entire contents of the buffer using this function.\n--\nterminalGetTextRange ::\n TerminalClass self => self\n -> Int -- ^ @sRow@ first row to search for data \n -> Int -- ^ @sCol@ first column to search for data \n -> Int -- ^ @eRow@ last row to search for data \n -> Int -- ^ @eCol@ last column to search for data \n -> Maybe VteSelect -- ^ @Just p@ for a predicate @p@ that determines\n -- which character should be extracted or @Nothing@\n -- to select all characters\n -> IO [VteChar] -- ^ return a text string\nterminalGetTextRange terminal sRow sCol eRow eCol mCB = do \n cbPtr <- case mCB of\n Just cb -> mkVteSelectionFunc $ \\_ c r _ ->\n return (fromBool (cb (fromIntegral c) (fromIntegral r)))\n Nothing -> return nullFunPtr\n gArrPtr <- {#call unsafe g_array_new#} 0 0\n (fromIntegral (sizeOf (undefined :: VteAttributes)))\n strPtr <- {#call terminal_get_text_range #} (toTerminal terminal) (fromIntegral sRow) (fromIntegral sCol) (fromIntegral eRow) (fromIntegral eCol) cbPtr nullPtr gArrPtr\n str <- if strPtr==nullPtr then return \"\" else peekUTFString strPtr\n (len,elemPtr) <- gArrayContent (castPtr gArrPtr)\n attrs <- (flip mapM) [0..len-1] $ peekElemOff elemPtr\n unless (cbPtr==nullFunPtr) $ freeHaskellFunPtr cbPtr\n {#call unsafe g_free#} (castPtr strPtr)\n {#call unsafe g_array_free#} gArrPtr 1\n return (zipWith attrToChar str attrs)\n\n-- | Reads the location of the insertion cursor and returns it. The row\n-- coordinate is absolute.\nterminalGetCursorPosition :: \n TerminalClass self => self\n -> IO (Int, Int) -- ^ @(column,row)@ the position of the cursor\nterminalGetCursorPosition terminal = do\n alloca $ \\cPtr ->\n alloca $ \\rPtr -> do\n {#call terminal_get_cursor_position#} (toTerminal terminal) cPtr rPtr\n column <- peek cPtr\n row <- peek rPtr\n return (fromIntegral column,fromIntegral row)\n\n-- | Clears the list of regular expressions the terminal uses to highlight\n-- text when the user moves the mouse cursor.\nterminalMatchClearAll :: TerminalClass self => self -> IO ()\nterminalMatchClearAll terminal =\n {#call terminal_match_clear_all#} (toTerminal terminal)\n \n-- | Adds the regular expression to the list of matching expressions.\n-- When the user moves the mouse cursor over a section of displayed text which\n-- matches this expression, the text will be highlighted.\n--\n-- See for\n-- details about the accepted syntex.\n--\n-- * Available since Vte version 0.17.1\n--\nterminalMatchAddRegex ::\n TerminalClass self => self\n -> String -- ^ @pattern@ - a regular expression\n -> [RegexCompileFlags] -- ^ @flags@ - specify how to interpret the pattern\n -> [RegexMatchFlags] -- ^ @flags@ - specify how to match\n -> IO Int -- ^ return an integer associated with this expression\nterminalMatchAddRegex terminal pattern cFlags mFlags =\n withUTFString pattern $ \\pat -> do\n regexPtr <- propagateGError $\n {#call g_regex_new#} pat (fromIntegral (fromFlags cFlags))\n (fromIntegral (fromFlags mFlags))\n liftM fromIntegral $ {#call terminal_match_add_gregex#}\n (toTerminal terminal) regexPtr (fromIntegral (fromFlags mFlags))\n\n-- | Removes the regular expression which is associated with the given tag from the list of expressions which the terminal will highlight when the user moves the mouse cursor over matching text.\nterminalMatchRemove :: \n TerminalClass self => self\n -> Int -- ^ @tag@ - the tag of the regex to remove \n -> IO ()\nterminalMatchRemove terminal tag =\n {#call terminal_match_remove#} (toTerminal terminal) (fromIntegral tag)\n\n-- | Checks if the text in and around the specified position matches any of\n-- the regular expressions previously registered using\n-- 'terminalMatchAddRegex'. If a match exists, the matching string is returned\n-- together with the number associated with the matched regular expression. If\n-- more than one regular expression matches, the expressions that was\n-- registered first will be returned.\n--\nterminalMatchCheck :: \n TerminalClass self => self\n -> Int -- ^ @column@ - the text column \n -> Int -- ^ @row@ - the text row \n -> IO (Maybe (String, Int))\n -- ^ @Just (str, tag)@ - the string that matched one of the previously set\n -- regular expressions together with the number @tag@ that was returned by\n -- 'terminalMatchAddRegex'\nterminalMatchCheck terminal column row = alloca $ \\tagPtr -> do\n strPtr <- {#call terminal_match_check#} (toTerminal terminal)\n (fromIntegral column) (fromIntegral row) tagPtr\n if strPtr==nullPtr then return Nothing else do\n str <- peekCString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n if tagPtr==nullPtr then return Nothing else do\n tag <- peek tagPtr\n return (Just (str,fromIntegral tag))\n\n-- | Sets which cursor the terminal will use if the pointer is over the pattern specified by tag. \n-- The terminal keeps a reference to cursor.\n--\n-- * Available since Vte version 0.11\n--\nterminalMatchSetCursor :: \n TerminalClass self => self\n -> Int -- ^ @tag@ - the tag of the regex which should use the specified cursor \n -> Cursor -- ^ @cursor@ - the 'Cursor' which the terminal should use when the pattern is highlighted \n -> IO ()\nterminalMatchSetCursor terminal tag (Cursor cur) =\n with (unsafeForeignPtrToPtr cur) $ \\curPtr ->\n {#call terminal_match_set_cursor#} (toTerminal terminal) (fromIntegral tag) (castPtr curPtr)\n\n-- | Sets which cursor the terminal will use if the pointer is over the pattern specified by tag.\n--\n-- * Available since Vte version 0.11.9\n--\nterminalMatchSetCursorType :: \n TerminalClass self => self\n -> Int -- ^ @tag@ the tag of the regex which should use the specified cursor \n -> CursorType -- ^ @cursorType@ a 'CursorType'\n -> IO ()\nterminalMatchSetCursorType terminal tag cursorType = \n {#call terminal_match_set_cursor_type#} (toTerminal terminal) (fromIntegral tag) $fromIntegral (fromEnum cursorType) \n\n-- | Sets which cursor the terminal will use if the pointer is over the pattern specified by tag.\n--\n-- * Available since Vte version 0.17.1\n--\nterminalMatchSetCursorName :: \n TerminalClass self => self\n -> Int -- ^ @tag@ - the tag of the regex which should use the specified cursor \n -> String -- ^ @name@ - the name of the cursor \n -> IO ()\nterminalMatchSetCursorName terminal tag name =\n withUTFString name $ \\namePtr ->\n {#call terminal_match_set_cursor_name#} (toTerminal terminal) (fromIntegral tag) namePtr\n \n-- | Sets what type of terminal the widget attempts to emulate by scanning for control sequences defined in the system's termcap file. \n-- Unless you are interested in this feature, always use \"xterm\".\nterminalSetEmulation :: \n TerminalClass self => self\n -> String -- ^ @emulation@ - the name of a terminal description \n -> IO () \nterminalSetEmulation terminal emulation =\n withUTFString emulation $ \\emulationPtr ->\n {#call terminal_set_emulation#} (toTerminal terminal) emulationPtr\n \n-- | Queries the terminal for its current emulation, as last set by a call to 'terminalSetEmulation'.\nterminalGetEmulation :: \n TerminalClass self => self\n -> IO String -- ^ return the name of the terminal type the widget is attempting to emulate \nterminalGetEmulation terminal =\n {#call terminal_get_emulation#} (toTerminal terminal) >>= peekCString\n \n-- | Queries the terminal for its default emulation, which is attempted if the terminal type passed to 'terminalSetEmulation' emptry string.\n--\n-- * Available since Vte version 0.11.11\n--\nterminalGetDefaultEmulation :: \n TerminalClass self => self\n -> IO String -- ^ return the name of the default terminal type the widget attempts to emulate \nterminalGetDefaultEmulation terminal =\n {#call terminal_get_default_emulation#} (toTerminal terminal) >>= peekCString\n \n-- | Changes the encoding the terminal will expect data from the child to be encoded with. \n-- For certain terminal types, applications executing in the terminal can change the encoding. \n-- The default encoding is defined by the application's locale settings.\nterminalSetEncoding ::\n TerminalClass self => self\n -> String -- ^ @codeset@ - a valid g_iconv target \n -> IO () \nterminalSetEncoding terminal codeset =\n withUTFString codeset $ \\codesetPtr ->\n {#call terminal_set_encoding#} (toTerminal terminal) codesetPtr\n \n-- | Determines the name of the encoding in which the terminal expects data to be encoded.\nterminalGetEncoding :: \n TerminalClass self => self\n -> IO String -- ^ return the current encoding for the terminal. \nterminalGetEncoding terminal =\n {#call terminal_get_encoding#} (toTerminal terminal) >>= peekCString\n \n-- | Some terminal emulations specify a status line which is separate from the main display area, \n-- and define a means for applications to move the cursor to the status line and back.\nterminalGetStatusLine :: \n TerminalClass self => self\n -> IO String -- ^ The current content of the terminal's status line. For terminals like \"xterm\", this will usually be the empty string.\nterminalGetStatusLine terminal =\n {#call terminal_get_status_line#} (toTerminal terminal) >>= peekCString\n \n-- | Determines the amount of additional space the widget is using to pad the edges of its visible area. \n-- This is necessary for cases where characters in the selected font don't themselves include a padding area and the text itself would otherwise be contiguous with the window border. \n-- Applications which use the widget's row_count, column_count, char_height, and char_width fields to set geometry hints using 'windowSetGeometryHints' will need to add this value to the base size. \n-- The values returned in xpad and ypad are the total padding used in each direction, and do not need to be doubled.\nterminalGetPadding :: \n TerminalClass self => self\n -> IO (Int, Int) -- ^ @(lr,tb)@ - the left\\\/right-edge and top\\\/bottom-edge padding \nterminalGetPadding terminal =\n alloca $ \\xPtr ->\n alloca $ \\yPtr -> do\n {#call terminal_get_padding#} (toTerminal terminal) xPtr yPtr\n xpad <- peek xPtr\n ypad <- peek yPtr\n return (fromIntegral xpad,fromIntegral ypad)\n\n-- | Get 'Adjustment' of terminal widget.\nterminalGetAdjustment :: \n TerminalClass self => self\n -> IO Adjustment -- ^ return the contents of terminal's adjustment field \nterminalGetAdjustment terminal =\n makeNewObject mkAdjustment $ {#call terminal_get_adjustment#} (toTerminal terminal)\n\n-- | Get terminal's char height.\nterminalGetCharHeight :: \n TerminalClass self => self\n -> IO Int -- ^ return the contents of terminal's char_height field \nterminalGetCharHeight terminal =\n liftM fromIntegral $\n {#call terminal_get_char_height#} (toTerminal terminal)\n\n-- | Get terminal's char width.\nterminalGetCharWidth :: \n TerminalClass self => self\n -> IO Int -- ^ return the contents of terminal's char_width field \nterminalGetCharWidth terminal =\n liftM fromIntegral $\n {#call terminal_get_char_width#} (toTerminal terminal)\n\n-- | Get terminal's column count.\nterminalGetColumnCount :: \n TerminalClass self => self\n -> IO Int -- ^ return the contents of terminal's column_count field \nterminalGetColumnCount terminal =\n liftM fromIntegral $\n {#call terminal_get_column_count#} (toTerminal terminal)\n \n-- | Get terminal's row count.\nterminalGetRowCount :: \n TerminalClass self => self\n -> IO Int -- ^ return the contents of terminal's row_count field \nterminalGetRowCount terminal =\n liftM fromIntegral $\n {#call terminal_get_row_count#} (toTerminal terminal)\n\n-- | Get icon title.\nterminalGetIconTitle :: \n TerminalClass self => self\n -> IO String -- ^ return the contents of terminal's icon_title field \nterminalGetIconTitle terminal =\n {#call terminal_get_icon_title#} (toTerminal terminal) >>= peekCString\n \n-- | Get window title.\nterminalGetWindowTitle :: \n TerminalClass self => self\n -> IO String -- ^ return the contents of terminal's window_title field \nterminalGetWindowTitle terminal =\n {#call terminal_get_window_title#} (toTerminal terminal) >>= peekCString\n\n--------------------\n-- Attributes\n-- | Controls whether or not the terminal will attempt to draw bold text. \n-- This may happen either by using a bold font variant, or by repainting text with a different offset.\n--\n-- Default value: @True@\n--\n-- * Available since Vte version 0.19.1\n--\nterminalAllowBold :: TerminalClass self => Attr self Bool\nterminalAllowBold = newAttr\n terminalGetAllowBold\n terminalSetAllowBold\n\n-- | Controls whether or not the terminal will beep when the child outputs the \\\"bl\\\" sequence.\n--\n-- Default value: @True@\n--\n--\n-- * Available since Vte version 0.19.1\n--\nterminalAudibleBell :: TerminalClass self => Attr self Bool\nterminalAudibleBell = newAttr\n terminalGetAudibleBell\n terminalSetAudibleBell\n\n-- | Sets a background image file for the widget. \n-- If specified by \"background-saturation:\", the terminal will tint its in-memory copy of the image before applying it to the terminal.\n--\n-- Default value: \\\"\\\"\n--\n-- * Available since Vte version 0.19.1\n--\nterminalBackgroundImageFile :: TerminalClass self => Attr self String\nterminalBackgroundImageFile = \n newAttrFromStringProperty \"background-image-file\" \n\n-- | Sets a background image for the widget. \n-- Text which would otherwise be drawn using the default background color will instead be drawn over the specified image. \n-- If necessary, the image will be tiled to cover the widget's entire visible area. \n-- If specified by \"background-saturation:\", the terminal will tint its in-memory copy of the image before applying it to the terminal.\n--\n-- * Available since Vte version 0.19.1\n--\nterminalBackgroundImagePixbuf :: TerminalClass self => Attr self (Maybe Pixbuf)\nterminalBackgroundImagePixbuf =\n newAttrFromMaybeObjectProperty \"background-image-pixbuf\" \n {#call pure gdk_pixbuf_get_type#}\n\n-- | Sets the opacity of the terminal background, were 0.0 means completely transparent and 1.0 means completely opaque.\n-- \n-- Allowed values: [0,1]\n--\n-- Default values: 1\n--\n-- * Available since Vte version 0.19.1\n--\nterminalBackgroundOpacity :: TerminalClass self => Attr self Double\nterminalBackgroundOpacity =\n newAttrFromDoubleProperty \"background-opacity\"\n\n-- | If a background image has been set using \"background-image-file:\" or \"background-image-pixbuf:\", or \"background-transparent:\", \n-- and the saturation value is less than 1.0, the terminal will adjust the colors of the image before drawing the image. \n-- To do so, the terminal will create a copy of the background image (or snapshot of the root window) and modify its pixel values.\n--\n-- Allowed values: [0,1]\n--\n-- Default value: 0.4\n--\n-- * Available since Vte version 0.19.1\n--\nterminalBackgroundSaturation :: TerminalClass self => Attr self Double\nterminalBackgroundSaturation =\n newAttrFromDoubleProperty \"background-saturation\"\n\n-- | If a background image has been set using \"background-image-file:\" or \"background-image-pixbuf:\", or \"background-transparent:\", \n-- and the value set by 'Terminal' background-saturation: is less than 1.0, the terminal will adjust the color of the image before drawing the image. \n-- To do so, the terminal will create a copy of the background image (or snapshot of the root window) and modify its pixel values. \n-- The initial tint color is black.\n--\n-- * Available since Vte version 0.19.1\n--\nterminalBackgroundTintColor :: TerminalClass self => Attr self Color\nterminalBackgroundTintColor =\n newAttrFromBoxedStorableProperty \"background-tint-color\"\n {#call pure unsafe gdk_color_get_type#}\n\n-- | Sets whther the terminal uses the pixmap stored in the root window as the background, \n-- adjusted so that if there are no windows below your application, the widget will appear to be transparent.\n--\n-- NOTE: When using a compositing window manager, you should instead set a RGBA colourmap on the toplevel window, so you get real transparency.\n-- \n-- Default value: @False@\n--\n-- * Available since Vte version 0.19.1\n--\nterminalBackgroundTransparent :: TerminalClass self => Attr self Bool\nterminalBackgroundTransparent =\n newAttrFromBoolProperty \"background-transparent\"\n\n-- | *Controls what string or control sequence the terminal sends to its child when the user presses the backspace key.\n--\n-- Default value: 'EraseAuto'\n--\n-- * Available since Vte version 0.19.1\n--\nterminalBackspaceBinding :: TerminalClass self => Attr self TerminalEraseBinding\nterminalBackspaceBinding =\n newAttrFromEnumProperty \"backspace-binding\" \n {#call pure unsafe terminal_erase_binding_get_type#}\n\n-- | Sets whether or not the cursor will blink. \n-- Using 'CursorBlinkSystem' will use the \"gtk-cursor-blink\" setting.\n--\n-- Default value: 'CursorBlinkSystem'\n--\n-- * Available since Vte version 0.19.1\n--\nterminalCursorBlinkMode :: TerminalClass self => Attr self TerminalCursorBlinkMode\nterminalCursorBlinkMode = newAttr\n terminalGetCursorBlinkMode\n terminalSetCursorBlinkMode\n\n-- | Controls the shape of the cursor.\n--\n-- Default value: 'CursorShapeBlock'\n--\n-- * Available since Vte version 0.19.1\n--\nterminalCursorShape :: TerminalClass self => Attr self TerminalCursorShape\nterminalCursorShape = newAttr\n terminalGetCursorShape\n terminalSetCursorShape\n\n-- | Controls what string or control sequence the terminal sends to its child when the user presses the delete key.\n--\n-- Default value: 'EraseAuto'\n-- \n-- * Available since Vte version 0.19.1\n--\nterminalDeleteBinding :: TerminalClass self => Attr self TerminalEraseBinding\nterminalDeleteBinding =\n newAttrFromEnumProperty \"delete-binding\"\n {#call pure unsafe terminal_erase_binding_get_type#}\n\n-- | Sets what type of terminal the widget attempts to emulate by scanning for control sequences defined in the system's termcap file. \n-- Unless you are interested in this feature, always use the default which is \"xterm\".\n--\n-- Default value: \"xterm\"\n--\n-- * Available since Vte version 0.19.1\n--\nterminalEmulation :: TerminalClass self => Attr self String\nterminalEmulation = newAttr\n terminalGetEmulation\n terminalSetEmulation\n\n-- | Controls the encoding the terminal will expect data from the child to be encoded with. \n-- For certain terminal types, applications executing in the terminal can change the encoding. \n-- The default is defined by the application's locale settings.\n--\n-- Default value: \\\"\\\"\n--\n-- * Available since Vte version 0.19.1\n--\nterminalEncoding :: TerminalClass self => Attr self String\nterminalEncoding = newAttr\n terminalGetEncoding\n terminalSetEncoding\n\n-- | Specifies the font used for rendering all text displayed by the terminal, overriding any fonts set using 'widgetModifyFont'.\n-- The terminal will immediately attempt to load the desired font, retrieve its metrics, \n-- and attempt to resize itself to keep the same number of rows and columns.\n--\n-- * Available since Vte version 0.19.1\n--\nterminalFontDesc :: TerminalClass self => Attr self FontDescription\nterminalFontDesc = newAttr\n terminalGetFont\n terminalSetFont\n\n-- | The terminal's so-called icon title, or empty if no icon title has been set.\n--\n-- Default value: \\\"\\\"\n--\n-- * Available since Vte version 0.19.1\n--\nterminalIconTitle :: TerminalClass self => ReadAttr self String\nterminalIconTitle = readAttrFromStringProperty \"icon-title\"\n\n-- | Controls the value of the terminal's mouse autohide setting. \n-- When autohiding is enabled, the mouse cursor will be hidden when the user presses a key and shown when the user moves the mouse.\n--\n-- Default value: @False@\n--\n-- * Available since Vte version 0.19.1\n--\nterminalPointerAutohide :: TerminalClass self => Attr self Bool\nterminalPointerAutohide = newAttr\n terminalGetMouseAutohide\n terminalSetMouseAutohide\n\n-- | The file descriptor of the master end of the terminal's PTY.\n--\n-- Allowed values: [-1 ...]\n--\n-- Default values: -1\n--\n-- * Available since Vte version 0.19.1\n--\nterminalPty :: TerminalClass self => Attr self Int\nterminalPty = newAttr\n terminalGetPty\n terminalSetPty\n\n-- | Controls the value of the terminal's mouse autohide setting. \n-- When autohiding is enabled, the mouse cursor will be hidden when the user presses a key and shown when the user moves the mouse.\n--\n-- Default value: @False@\n--\n-- * Available since Vte version 0.19.1\n--\nterminalScrollBackground :: TerminalClass self => Attr self Bool\nterminalScrollBackground =\n newAttrFromBoolProperty \"scroll-background\"\n\n-- | Controls whether or not the terminal will forcibly scroll to the bottom of the viewable history when the user presses a key. \n-- Modifier keys do not trigger this behavior.\n--\n-- Default value: @False@\n--\n-- * Available since Vte version 0.19.1\n--\nterminalScrollOnKeystroke :: TerminalClass self => Attr self Bool\nterminalScrollOnKeystroke =\n newAttrFromBoolProperty \"scroll-on-keystroke\"\n\n-- | Controls whether or not the terminal will forcibly scroll to the bottom of the viewable history when the new data is received from the child.\n-- \n-- Default value: @True@\n--\n-- * Available since Vte version 0.19.1\n--\nterminalScrollOnOutput :: TerminalClass self => Attr self Bool\nterminalScrollOnOutput =\n newAttrFromBoolProperty \"scroll-on-output\"\n\n-- | The length of the scrollback buffer used by the terminal. The size of the\n-- scrollback buffer will be set to the larger of this value and the number of\n-- visible rows the widget can display, so 0 can safely be used to disable\n-- scrollback. Note that this setting only affects the normal screen buffer.\n-- For terminal types which have an alternate screen buffer, no scrollback is\n-- allowed on the alternate screen buffer.\n--\n-- Default value: 100\n--\n-- * Available since Vte version 0.19.1\n--\nterminalScrollbackLines :: TerminalClass self => Attr self Int\nterminalScrollbackLines =\n newAttrFromUIntProperty \"scrollback-lines\"\n\n-- | Controls whether the terminal will present a visible bell to the user when the child outputs the \\\"bl\\\" sequence. \n-- The terminal will clear itself to the default foreground color and then repaint itself.\n--\n-- Default value: @False@\n--\n-- * Available since Vte version 0.19.1\n--\nterminalVisibleBell :: TerminalClass self => Attr self Bool\nterminalVisibleBell = newAttr\n terminalGetVisibleBell\n terminalSetVisibleBell\n\n-- | The terminal's title.\n--\n-- Default value: \\\"\\\"\n--\n-- * Available since Vte version 0.19.1\n--\nterminalWindowTitle :: TerminalClass self => ReadAttr self String\nterminalWindowTitle = readAttrFromStringProperty \"window-title\"\n\n-- | When the user double-clicks to start selection, the terminal will extend the selection on word boundaries. \n-- It will treat characters the word-chars characters as parts of words, and all other characters as word separators. \n-- Ranges of characters can be specified by separating them with a hyphen.\n-- As a special case, when setting this to the empty string, the terminal will treat all graphic non-punctuation non-space characters as word\n-- characters.\n-- \n-- Defalut value: \\\"\\\"\n--\n-- * Available since Vte version 0.19.1\n--\nterminalWordChars :: TerminalClass self => Attr self String\nterminalWordChars =\n newAttrFromStringProperty \"word-chars\" \n\n--------------------\n-- Signals\n\n-- | This signal is emitted when the a child sends a beep request to the terminal.\nbeep :: TerminalClass self => Signal self (IO ())\nbeep = Signal (connect_NONE__NONE \"beep\")\n\n-- | Emitted whenever selection of a new font causes the values of the char_width or char_height fields to change.\ncharSizeChanged :: TerminalClass self => Signal self (Int -> Int -> IO ())\ncharSizeChanged = Signal (connect_INT_INT__NONE \"char-size-changed\")\n\n-- | This signal is emitted when the terminal detects that a child started using 'terminalForkCommand' has exited.\nchildExited :: TerminalClass self => Signal self (IO ())\nchildExited = Signal (connect_NONE__NONE \"child-exited\")\n\n-- | Emitted whenever the terminal receives input from the user and prepares to send it to the child process. \n-- The signal is emitted even when there is no child process.\ncommit :: TerminalClass self => Signal self (String -> Int -> IO ())\ncommit = Signal (connect_STRING_INT__NONE \"commit\")\n\n-- | Emitted whenever the visible appearance of the terminal has changed. Used primarily by 'TerminalAccessible'.\ncontentsChanged :: TerminalClass self => Signal self (IO ())\ncontentsChanged = Signal (connect_NONE__NONE \"contents-changed\")\n\n-- | Emitted whenever 'terminalCopyClipboard' is called.\ncopyClipboard :: TerminalClass self => Signal self (IO ())\ncopyClipboard = Signal (connect_NONE__NONE \"copy-clipboard\")\n\n-- | Emitted whenever the cursor moves to a new character cell. Used primarily by 'TerminalAccessible'.\ncursorMoved :: TerminalClass self => Signal self (IO ())\ncursorMoved = Signal (connect_NONE__NONE \"cursor-moved\")\n\n-- | Emitted when the user hits the '-' key while holding the Control key.\ndecreaseFontSize :: TerminalClass self => Signal self (IO ())\ndecreaseFontSize = Signal (connect_NONE__NONE \"decrease-font-size\")\n\n-- | Emitted at the child application's request.\ndeiconifyWindow :: TerminalClass self => Signal self (IO ())\ndeiconifyWindow = Signal (connect_NONE__NONE \"deiconify-window\")\n\n-- | Emitted whenever the terminal's emulation changes, only possible at the parent application's request.\nemulationChanged :: TerminalClass self => Signal self (IO ())\nemulationChanged = Signal (connect_NONE__NONE \"emulation-changed\")\n\n-- | Emitted whenever the terminal's current encoding has changed, \n-- either as a result of receiving a control sequence which toggled between the local and UTF-8 encodings, or at the parent application's request.\nencodingChanged :: TerminalClass self => Signal self (IO ())\nencodingChanged = Signal (connect_NONE__NONE \"encoding-changed\")\n\n-- | Emitted when the terminal receives an end-of-file from a child which is running in the terminal. \n-- This signal is frequently (but not always) emitted with a 'childExited' signal.\neof :: TerminalClass self => Signal self (IO ())\neof = Signal (connect_NONE__NONE \"eof\")\n\n-- | Emitted when the terminal's icon_title field is modified.\niconTitleChanged :: TerminalClass self => Signal self (IO ())\niconTitleChanged = Signal (connect_NONE__NONE \"icon-title-changed\")\n\n-- | Emitted at the child application's request.\niconifyWindow :: TerminalClass self => Signal self (IO ())\niconifyWindow = Signal (connect_NONE__NONE \"iconify-window\")\n\n-- | Emitted when the user hits the '+' key while holding the Control key.\nincreaseFontSize :: TerminalClass self => Signal self (IO ())\nincreaseFontSize = Signal (connect_NONE__NONE \"increase-font-size\")\n\n-- | Emitted at the child application's request.\nlowerWindow :: TerminalClass self => Signal self (IO ())\nlowerWindow = Signal (connect_NONE__NONE \"lower-window\")\n\n-- | Emitted at the child application's request.\nmaximizeWindow :: TerminalClass self => Signal self (IO ())\nmaximizeWindow = Signal (connect_NONE__NONE \"maximize-window\")\n\n-- | Emitted when user move terminal window.\nmoveWindow :: TerminalClass self => Signal self (Word -> Word -> IO ())\nmoveWindow = Signal (connect_WORD_WORD__NONE \"move-window\")\n\n-- | Emitted whenever 'terminalPasteClipboard' is called.\npasteClipboard :: TerminalClass self => Signal self (IO ())\npasteClipboard = Signal (connect_NONE__NONE \"paste-clipboard\")\n\n-- | Emitted at the child application's request.\nraiseWindow :: TerminalClass self => Signal self (IO ())\nraiseWindow = Signal (connect_NONE__NONE \"raise-window\")\n\n-- | Emitted at the child application's request.\nrefreshWindow :: TerminalClass self => Signal self (IO ())\nrefreshWindow = Signal (connect_NONE__NONE \"refresh-window\")\n\n-- | Emitted at the child application's request.\nresizeWidnow :: TerminalClass self => Signal self (Int -> Int -> IO ()) \nresizeWidnow = Signal (connect_INT_INT__NONE \"resize-window\")\n\n-- | Emitted at the child application's request.\nrestoreWindow :: TerminalClass self => Signal self (IO ())\nrestoreWindow = Signal (connect_NONE__NONE \"restore-window\")\n\n-- | Emitted at the child application's request.\nselectionChanged :: TerminalClass self => Signal self (IO ())\nselectionChanged = Signal (connect_NONE__NONE \"selection-changed\")\n\n-- | Set the scroll adjustments for the terminal. \n-- Usually scrolled containers like 'ScrolledWindow' will emit this \n-- signal to connect two instances of 'Scrollbar' to the scroll directions of the 'Terminal'.\nsetScrollAdjustments :: TerminalClass self => Signal self (Adjustment -> Adjustment -> IO ())\nsetScrollAdjustments = Signal (connect_OBJECT_OBJECT__NONE \"set-scroll-adjustments\")\n\n-- | Emitted whenever the contents of the status line are modified or cleared.\nstatusLineChanged :: TerminalClass self => Signal self (IO ())\nstatusLineChanged = Signal (connect_NONE__NONE \"status-line-changed\")\n\n-- | An internal signal used for communication between the terminal and its accessibility peer. \n-- May not be emitted under certain circumstances.\ntextDeleted :: TerminalClass self => Signal self (IO ())\ntextDeleted = Signal (connect_NONE__NONE \"text-deleted\")\n\n-- | An internal signal used for communication between the terminal and its accessibility peer. \n-- May not be emitted under certain circumstances.\ntextInserted :: TerminalClass self => Signal self (IO ())\ntextInserted = Signal (connect_NONE__NONE \"text-inserted\")\n\n-- | An internal signal used for communication between the terminal and its accessibility peer. \n-- May not be emitted under certain circumstances.\ntextModified :: TerminalClass self => Signal self (IO ())\ntextModified = Signal (connect_NONE__NONE \"text-modified\")\n\n-- | An internal signal used for communication between the terminal and its accessibility peer. \n-- May not be emitted under certain circumstances.\ntextScrolled :: TerminalClass self => Signal self (Int -> IO ())\ntextScrolled = Signal (connect_INT__NONE \"text-scrolled\")\n\n-- | Emitted when the terminal's window_title field is modified.\nwindowTitleChanged :: TerminalClass self => Signal self (IO ())\nwindowTitleChanged = Signal (connect_NONE__NONE \"window-title-changed\")\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) widget for VTE\n--\n-- Author : Andy Stewart\n--\n-- Created: 20 Sep 2009\n--\n-- Copyright (C) 2009 Andy Stewart \n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- A terminal widget\n-- \n-----------------------------------------------------------------------------\n-- \nmodule Graphics.UI.Gtk.Vte.Vte (\n-- * Types\n Terminal,\n VteSelect,\n VteChar(..),\n\n-- * Enums\n TerminalEraseBinding(..),\n TerminalCursorBlinkMode(..),\n TerminalCursorShape(..),\n RegexCompileFlags(..),\n RegexMatchFlags(..),\n\n-- * Constructors\n terminalNew,\n\n-- * Methods\n terminalImAppendMenuitems,\n terminalForkCommand,\n terminalForkpty,\n terminalSetPty,\n terminalGetPty,\n terminalFeed,\n terminalFeedChild,\n terminalFeedChildBinary,\n terminalGetChildExitStatus,\n terminalSelectAll,\n terminalSelectNone,\n terminalCopyClipboard,\n terminalPasteClipboard,\n terminalCopyPrimary,\n terminalPastePrimary,\n terminalSetSize,\n terminalSetAudibleBell,\n terminalGetAudibleBell,\n terminalSetVisibleBell,\n terminalGetVisibleBell,\n terminalSetAllowBold,\n terminalGetAllowBold,\n terminalSetScrollOnOutput,\n terminalSetScrollOnKeystroke,\n terminalSetColorBold,\n terminalSetColorForeground,\n terminalSetColorBackground,\n terminalSetColorDim,\n terminalSetColorCursor,\n terminalSetColorHighlight,\n terminalSetColors,\n terminalSetDefaultColors,\n terminalSetOpacity,\n terminalSetBackgroundImage,\n terminalSetBackgroundImageFile,\n terminalSetBackgroundSaturation,\n terminalSetBackgroundTransparent,\n terminalSetBackgroundTintColor,\n terminalSetScrollBackground,\n terminalSetCursorShape,\n terminalGetCursorShape,\n terminalSetCursorBlinkMode,\n terminalGetCursorBlinkMode,\n terminalSetScrollbackLines,\n terminalSetFont,\n terminalSetFontFromString,\n terminalGetFont,\n terminalGetHasSelection,\n terminalSetWordChars,\n terminalIsWordChar,\n terminalSetBackspaceBinding,\n terminalSetDeleteBinding,\n terminalSetMouseAutohide,\n terminalGetMouseAutohide,\n terminalReset,\n terminalGetText,\n terminalGetTextIncludeTrailingSpaces,\n terminalGetTextRange,\n terminalGetCursorPosition,\n terminalMatchClearAll,\n terminalMatchAddRegex,\n terminalMatchRemove,\n terminalMatchCheck,\n terminalMatchSetCursor,\n terminalMatchSetCursorType,\n terminalMatchSetCursorName,\n terminalSetEmulation,\n terminalGetEmulation,\n terminalGetDefaultEmulation,\n terminalSetEncoding,\n terminalGetEncoding,\n terminalGetStatusLine,\n terminalGetPadding,\n terminalGetAdjustment,\n terminalGetCharHeight,\n terminalGetCharWidth,\n terminalGetColumnCount,\n terminalGetRowCount,\n terminalGetIconTitle,\n terminalGetWindowTitle,\n\n-- * Attributes\n terminalAllowBold,\n terminalAudibleBell,\n terminalBackgroundImageFile,\n terminalBackgroundImagePixbuf,\n terminalBackgroundOpacity,\n terminalBackgroundSaturation,\n terminalBackgroundTintColor,\n terminalBackgroundTransparent,\n terminalBackspaceBinding,\n terminalCursorBlinkMode,\n terminalCursorShape,\n terminalDeleteBinding,\n terminalEmulation,\n terminalEncoding,\n terminalFontDesc,\n terminalIconTitle,\n terminalPointerAutohide,\n terminalPty,\n terminalScrollBackground,\n terminalScrollOnKeystroke,\n terminalScrollOnOutput,\n terminalScrollbackLines,\n terminalVisibleBell,\n terminalWindowTitle,\n terminalWordChars,\n\n-- * Signals\n beep,\n charSizeChanged,\n childExited,\n commit,\n contentsChanged,\n copyClipboard,\n cursorMoved,\n decreaseFontSize,\n deiconifyWindow,\n emulationChanged,\n encodingChanged,\n eof,\n iconTitleChanged,\n iconifyWindow,\n increaseFontSize,\n lowerWindow,\n maximizeWindow,\n moveWindow,\n pasteClipboard,\n raiseWindow,\n refreshWindow,\n resizeWidnow,\n restoreWindow,\n selectionChanged,\n setScrollAdjustments,\n statusLineChanged,\n textDeleted,\n textInserted,\n textModified,\n textScrolled,\n windowTitleChanged,\n ) where\n\nimport Control.Monad\t\t(liftM, unless)\nimport Data.Char\nimport Data.Word\n\nimport System.Glib.Attributes\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Properties\nimport System.Glib.GError\nimport System.Glib.Flags (Flags, fromFlags) \nimport Graphics.UI.Gtk.Abstract.Widget (Color)\nimport Graphics.UI.Gtk.Gdk.Cursor\nimport Graphics.Rendering.Pango.BasicTypes (FontDescription(FontDescription), makeNewFontDescription)\nimport Graphics.UI.Gtk.Vte.Structs\n\n{#import Graphics.UI.Gtk.General.Clipboard#} (selectionPrimary,\n selectionClipboard)\n{#import Graphics.UI.Gtk.Abstract.Object#}\t(makeNewObject)\n{#import Graphics.UI.Gtk.Vte.Types#}\n{#import Graphics.UI.Gtk.Vte.Signals#}\n{#import System.Glib.GObject#}\n{#import System.Glib.GError#} (propagateGError)\n\n{#context lib= \"vte\" prefix= \"vte\"#}\n\n--------------------\n-- Types\n\n-- | A predicate that states which characters are of interest. The predicate\n-- @p c r@ where @p :: VteSelect@, should return @True@ if the character at\n-- column @c@ and row @r@ should be extracted.\ntype VteSelect =\n Int\n -> Int \n -> Bool\n\n{#pointer SelectionFunc#}\n\n-- | A structure describing the individual characters in the visible part of\n-- a terminal window.\n--\ndata VteChar = VteChar {\n vcRow :: Int,\n vcCol :: Int,\n vcChar :: Char,\n vcFore :: Color,\n vcBack :: Color,\n vcUnderline :: Bool,\n vcStrikethrough :: Bool\n }\n\n--------------------\n-- Utils\n\n-- | Utils function to transform 'VteAttributes' to 'VteChar'.\nattrToChar :: Char -> VteAttributes -> VteChar\nattrToChar ch (VteAttributes r c f b u s) = VteChar r c ch f b u s\n \nforeign import ccall \"wrapper\" mkVteSelectionFunc ::\n (Ptr Terminal -> {#type glong#} -> {#type glong#} -> Ptr () -> IO {#type gboolean#})\n -> IO SelectionFunc\n \n--------------------\n-- Enums\n\n-- | Values for what should happen when the user presses backspace\\\/delete. \n-- Use 'EraseAuto' unless the user can cause them to be overridden.\n{#enum VteTerminalEraseBinding as TerminalEraseBinding {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n-- | Values for the cursor blink setting.\n{#enum VteTerminalCursorBlinkMode as TerminalCursorBlinkMode {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n-- | Values for the cursor shape setting.\n{#enum VteTerminalCursorShape as TerminalCursorShape {underscoreToCase} deriving (Bounded,Eq,Show)#}\n\n-- | Flags determining how the regular expression is to be interpreted. See\n-- \n-- for an explanation of these flags.\n--\n{#enum GRegexCompileFlags as RegexCompileFlags {underscoreToCase} deriving (Bounded,Eq,Show) #}\ninstance Flags RegexCompileFlags\n\n-- | Flags determining how the string is matched against the regular\n-- expression. See\n-- \n-- for an explanation of these flags.\n--\n{#enum GRegexMatchFlags as RegexMatchFlags {underscoreToCase} deriving (Bounded,Eq,Show) #}\ninstance Flags RegexMatchFlags\n\n--------------------\n-- Constructors\n-- | Create a new terminal widget.\nterminalNew :: IO Terminal\nterminalNew = \n makeNewObject mkTerminal $ liftM castPtr {#call terminal_new#}\n\n--------------------\n-- Methods\n-- | Appends menu items for various input methods to the given menu. \n-- The user can select one of these items to modify the input method used by the terminal.\nterminalImAppendMenuitems :: \n TerminalClass self => self\n -> MenuShell -- ^ @menushell@ - a menu shell of 'MenuShell'\n -> IO () \nterminalImAppendMenuitems terminal menushell =\n {#call terminal_im_append_menuitems#} (toTerminal terminal) menushell\n\n-- | Starts the specified command under a newly-allocated controlling pseudo-terminal. \nterminalForkCommand :: \n TerminalClass self => self\n -> (Maybe String) -- ^ @command@ - the name of a binary to run, or @Nothing@ to get user's shell \n -> (Maybe [String]) -- ^ @argv@ - the argument list to be passed to command, or @Nothing@\n -> (Maybe [String]) -- ^ @envv@ - a list of environment variables to be added to the environment before starting command, or @Nothing@\n -> (Maybe String) -- ^ @directory@ - the name of a directory the command should start in, or @Nothing@ \n -> Bool -- ^ @lastlog@ - @True@ if the session should be logged to the lastlog\n -> Bool -- ^ @utmp@ - @True@ if the session should be logged to the utmp\/utmpx log \n -> Bool -- ^ @wtmp@ - @True@ if the session should be logged to the wtmp\/wtmpx log \n -> IO Int -- ^ return the ID of the new process\nterminalForkCommand terminal command argv envv directory lastlog utmp wtmp =\n liftM fromIntegral $\n maybeWith withUTFString command $ \\commandPtr ->\n maybeWith withUTFString directory $ \\dirPtr ->\n maybeWith withUTFStringArray argv $ \\argvPtrPtr ->\n maybeWith withUTFStringArray envv $ \\envvPtrPtr ->\n {#call terminal_fork_command#} \n (toTerminal terminal) \n commandPtr\n argvPtrPtr\n envvPtrPtr\n dirPtr\n (fromBool lastlog) \n (fromBool utmp)\n (fromBool wtmp)\n\n-- | Starts a new child process under a newly-allocated controlling pseudo-terminal. \n--\n-- * Available since Vte version 0.11.11\n-- \nterminalForkpty :: \n TerminalClass self => self\n -> (Maybe [String]) -- ^ @envv@ - a list of environment variables to be added to the environment before starting returning in the child process, or @Nothing@\n -> (Maybe String) -- ^ @directory@ - the name of a directory the child process should change to, or @Nothing@ \n -> Bool -- ^ @lastlog@ - @True@ if the session should be logged to the lastlog \n -> Bool -- ^ @utmp@ - @True@ if the session should be logged to the utmp\/utmpx log \n -> Bool -- ^ @wtmp@ - @True@ if the session should be logged to the wtmp\/wtmpx log \n -> IO Int -- ^ return the ID of the new process in the parent, 0 in the child, and -1 if there was an error \nterminalForkpty terminal envv directory lastlog utmp wtmp =\n liftM fromIntegral $\n maybeWith withUTFString directory $ \\dirPtr ->\n maybeWith withUTFStringArray envv $ \\envvPtrPtr ->\n {#call terminal_forkpty#} \n (toTerminal terminal)\n envvPtrPtr\n dirPtr\n (fromBool lastlog)\n (fromBool utmp)\n (fromBool wtmp)\n\n-- | Attach an existing PTY master side to the terminal widget. \n-- Use instead of 'terminalForkCommand' or 'terminalForkpty'.\n--\n-- * Available since Vte version 0.12.1\n--\nterminalSetPty :: \n TerminalClass self => self \n -> Int -- ^ @ptyMaster@ - a file descriptor of the master end of a PTY \n -> IO ()\nterminalSetPty terminal ptyMaster =\n {#call terminal_set_pty#} (toTerminal terminal) (fromIntegral ptyMaster)\n\n-- | Returns the file descriptor of the master end of terminal's PTY.\n--\n-- * Available since Vte version 0.19.1\n--\nterminalGetPty ::\n TerminalClass self => self\n -> IO Int -- ^ return the file descriptor, or -1 if the terminal has no PTY. \nterminalGetPty terminal = \n liftM fromIntegral $ \n {#call terminal_get_pty#} (toTerminal terminal)\n\n-- | Interprets data as if it were data received from a child process. This\n-- can either be used to drive the terminal without a child process, or just\n-- to mess with your users.\nterminalFeed :: \n TerminalClass self => self \n -> String -- ^ @string@ - a string in the terminal's current encoding \n -> IO ()\nterminalFeed terminal string =\n withUTFStringLen string $ \\(strPtr, len) ->\n {#call terminal_feed#} (toTerminal terminal) strPtr (fromIntegral len)\n\n-- | Sends a block of UTF-8 text to the child as if it were entered by the\n-- user at the keyboard.\nterminalFeedChild :: \n TerminalClass self => self \n -> String -- ^ @string@ - data to send to the child \n -> IO ()\nterminalFeedChild terminal string =\n withUTFStringLen string $ \\(strPtr, len) ->\n {#call terminal_feed_child#} (toTerminal terminal) strPtr (fromIntegral len)\n\n-- | Sends a block of binary data to the child.\n--\n-- * Available since Vte version 0.12.1\n--\nterminalFeedChildBinary :: \n TerminalClass self => self \n -> [Word8] -- ^ @data@ - data to send to the child \n -> IO ()\nterminalFeedChildBinary terminal string =\n withArrayLen string $ \\len strPtr ->\n {#call terminal_feed_child_binary#} (toTerminal terminal) (castPtr strPtr) (fromIntegral len)\n \n-- | Gets the exit status of the command started by 'terminalForkCommand'. \n--\n-- * Available since Vte version 0.19.1\n--\nterminalGetChildExitStatus ::\n TerminalClass self => self \n -> IO Int -- ^ return the child's exit status \nterminalGetChildExitStatus terminal =\n liftM fromIntegral $\n {#call terminal_get_child_exit_status#} (toTerminal terminal)\n\n-- | Selects all text within the terminal (including the scrollback buffer).\n--\n-- * Available since Vte version 0.16\n--\nterminalSelectAll :: TerminalClass self => self -> IO () \nterminalSelectAll terminal =\n {#call terminal_select_all#} (toTerminal terminal)\n \n-- | Clears the current selection.\n--\n-- * Available since Vte version 0.16\n--\nterminalSelectNone :: TerminalClass self => self -> IO () \nterminalSelectNone terminal =\n {#call terminal_select_none#} (toTerminal terminal)\n\n-- | Places the selected text in the terminal in the 'selectionClipboard'\n-- selection.\nterminalCopyClipboard :: TerminalClass self => self -> IO ()\nterminalCopyClipboard terminal = \n {#call terminal_copy_clipboard#} (toTerminal terminal)\n \n-- | Sends the contents of the 'selectionClipboard' selection to the\n-- terminal's child. If necessary, the data is converted from UTF-8 to the\n-- terminal's current encoding. It's called on paste menu item, or when user\n-- presses Shift+Insert.\nterminalPasteClipboard :: TerminalClass self => self -> IO ()\nterminalPasteClipboard terminal =\n {#call terminal_paste_clipboard#} (toTerminal terminal)\n\n-- | Places the selected text in the terminal in the\n-- 'selectionPrimary' selection.\nterminalCopyPrimary :: TerminalClass self => self -> IO ()\nterminalCopyPrimary terminal =\n {#call terminal_copy_primary#} (toTerminal terminal)\n\n-- | Sends the contents of the\n-- 'selectionPrimary' selection to the\n-- terminal's child. If necessary, the data is converted from UTF-8 to the\n-- terminal's current encoding. The terminal will call also paste the\n-- 'SelectionPrimary' selection when the user clicks with the the second mouse\n-- button.\nterminalPastePrimary :: TerminalClass self => self -> IO ()\nterminalPastePrimary terminal =\n {#call terminal_paste_primary#} (toTerminal terminal)\n \n-- | Attempts to change the terminal's size in terms of rows and columns. \n-- If the attempt succeeds, the widget will resize itself to the proper size.\nterminalSetSize :: \n TerminalClass self => self \n -> Int -- ^ @columns@ - the desired number of columns \n -> Int -- ^ @rows@ - the desired number of rows \n -> IO ()\nterminalSetSize terminal columns rows =\n {#call terminal_set_size#} \n (toTerminal terminal)\n (fromIntegral columns)\n (fromIntegral rows)\n \n-- | Controls whether or not the terminal will beep when the child outputs the \\\"bl\\\" sequence.\nterminalSetAudibleBell :: \n TerminalClass self => self \n -> Bool -- ^ @isAudible@ - @True@ if the terminal should beep \n -> IO () \nterminalSetAudibleBell terminal isAudible =\n {#call terminal_set_audible_bell#} (toTerminal terminal) (fromBool isAudible)\n \n-- | Checks whether or not the terminal will beep when the child outputs the \\\"bl\\\" sequence.\nterminalGetAudibleBell :: \n TerminalClass self => self \n -> IO Bool -- ^ return @True@ if audible bell is enabled, @False@ if not \nterminalGetAudibleBell terminal =\n liftM toBool $\n {#call terminal_get_audible_bell#} (toTerminal terminal)\n \n-- | Controls whether or not the terminal will present a visible bell to the user when the child outputs the \\\"bl\\\" sequence. \n-- The terminal will clear itself to the default foreground color and then repaint itself.\nterminalSetVisibleBell :: \n TerminalClass self => self \n -> Bool -- ^ @isVisible@ - @True@ if the terminal should flash \n -> IO () \nterminalSetVisibleBell terminal isVisible =\n {#call terminal_set_visible_bell#} (toTerminal terminal) (fromBool isVisible)\n \n-- | Checks whether or not the terminal will present a visible bell to the user when the child outputs the \\\"bl\\\" sequence. \n-- The terminal will clear itself to the default foreground color and then repaint itself.\nterminalGetVisibleBell :: \n TerminalClass self => self \n -> IO Bool -- ^ return @True@ if visible bell is enabled, @False@ if not \nterminalGetVisibleBell terminal =\n liftM toBool $\n {#call terminal_get_visible_bell#} (toTerminal terminal)\n \n-- | Controls whether or not the terminal will attempt to draw bold text, \n-- either by using a bold font variant or by repainting text with a different offset.\nterminalSetAllowBold :: \n TerminalClass self => self \n -> Bool -- ^ @allowBold@ - @True@ if the terminal should attempt to draw bold text \n -> IO () \nterminalSetAllowBold terminal allowBold =\n {#call terminal_set_allow_bold#} (toTerminal terminal) (fromBool allowBold)\n \n-- | Checks whether or not the terminal will attempt to draw bold text by repainting text with a one-pixel offset.\nterminalGetAllowBold :: \n TerminalClass self => self \n -> IO Bool -- ^ return @True@ if bolding is enabled, @False@ if not \nterminalGetAllowBold terminal =\n liftM toBool $\n {#call terminal_get_allow_bold#} (toTerminal terminal)\n \n-- | Controls whether or not the terminal will forcibly scroll to the bottom of the viewable history when the new data is received from the child.\nterminalSetScrollOnOutput :: \n TerminalClass self => self \n -> Bool -- ^ @scroll@ - @True@ if the terminal should scroll on output \n -> IO () \nterminalSetScrollOnOutput terminal scroll =\n {#call terminal_set_scroll_on_output#} (toTerminal terminal) (fromBool scroll)\n \n-- | Controls whether or not the terminal will forcibly scroll to the bottom of the viewable history when the user presses a key. \n-- Modifier keys do not trigger this behavior.\nterminalSetScrollOnKeystroke :: \n TerminalClass self => self \n -> Bool -- ^ @scroll@ - @True@ if the terminal should scroll on keystrokes \n -> IO ()\nterminalSetScrollOnKeystroke terminal scroll =\n {#call terminal_set_scroll_on_keystroke#} (toTerminal terminal) (fromBool scroll)\n \n-- | Sets the color used to draw bold text in the default foreground color.\nterminalSetColorBold :: \n TerminalClass self => self \n -> Color -- ^ @bold@ - the new bold color \n -> IO ()\nterminalSetColorBold terminal bold =\n with bold $ \\boldPtr ->\n {#call terminal_set_color_bold#} (toTerminal terminal) (castPtr boldPtr)\n\n-- | Sets the foreground color used to draw normal text\nterminalSetColorForeground :: \n TerminalClass self => self \n -> Color -- ^ @foreground@ - the new foreground color \n -> IO ()\nterminalSetColorForeground terminal foreground =\n with foreground $ \\fgPtr -> \n {#call terminal_set_color_foreground#} (toTerminal terminal) (castPtr fgPtr)\n\n-- | Sets the background color for text which does not have a specific background color assigned. \n-- Only has effect when no background image is set and when the terminal is not transparent.\nterminalSetColorBackground :: \n TerminalClass self => self \n -> Color -- ^ @background@ - the new background color \n -> IO ()\nterminalSetColorBackground terminal background =\n with background $ \\bgPtr ->\n {#call terminal_set_color_background#} (toTerminal terminal) (castPtr bgPtr)\n\n-- | Sets the color used to draw dim text in the default foreground color.\nterminalSetColorDim :: \n TerminalClass self => self \n -> Color -- ^ @dim@ - the nw dim color\n -> IO ()\nterminalSetColorDim terminal dim =\n with dim $ \\dimPtr -> \n {#call terminal_set_color_dim#} (toTerminal terminal) (castPtr dimPtr)\n\n-- | Sets the background color for text which is under the cursor. \n-- If @Nothing@, text under the cursor will be drawn with foreground and background colors reversed.\n--\n-- * Available since Vte version 0.11.11\n--\nterminalSetColorCursor :: \n TerminalClass self => self \n -> Color -- ^ @cursor@ - the new color to use for the text cursor \n -> IO ()\nterminalSetColorCursor terminal cursor =\n with cursor $ \\cursorPtr -> \n {#call terminal_set_color_cursor#} (toTerminal terminal) (castPtr cursorPtr)\n\n-- | Sets the background color for text which is highlighted. \n-- If @Nothing@, highlighted text (which is usually highlighted because it is selected) will be drawn with foreground and background colors reversed.\n--\n-- * Available since Vte version 0.11.11\n--\nterminalSetColorHighlight :: \n TerminalClass self => self \n -> Color -- ^ @highlight@ - the new color to use for highlighted text \n -> IO ()\nterminalSetColorHighlight terminal highlight =\n with highlight $ \\hlPtr -> \n {#call terminal_set_color_highlight#} (toTerminal terminal) (castPtr hlPtr)\n\n-- | The terminal widget uses a 28-color model comprised of the default foreground and background colors, \n-- the bold foreground color, the dim foreground color, an eight color palette, \n-- bold versions of the eight color palette, and a dim version of the the eight color palette. palette_size must be either 0, 8, 16, or 24. \n-- If foreground is @Nothing@ and palette_size is greater than 0, the new foreground color is taken from palette[7]. \n-- If background is @Nothing@ and palette_size is greater than 0, the new background color is taken from palette[0]. \n-- If palette_size is 8 or 16, the third (dim) and possibly the second (bold) 8-color palettes are extrapolated from the new background color and the items in palette.\nterminalSetColors :: \n TerminalClass self => self \n -> Maybe Color -- ^ @foreground@ - the new foreground color, or @Nothing@ \n -> Maybe Color -- ^ @background@ - the new background color, or @Nothing@ \n -> [Color] -- ^ @palette@ - the color palette \n -> IO ()\nterminalSetColors terminal foreground background palette =\n maybeWith with foreground $ \\fPtr ->\n maybeWith with background $ \\bPtr ->\n withArrayLen palette $ \\len pPtr ->\n {#call terminal_set_colors#} \n (toTerminal terminal) \n (castPtr fPtr)\n (castPtr bPtr)\n (castPtr pPtr)\n (fromIntegral len)\n\n-- | Reset the terminal palette to reasonable compiled-in defaults.\nterminalSetDefaultColors :: TerminalClass self => self -> IO ()\nterminalSetDefaultColors terminal =\n {#call terminal_set_default_colors#} (toTerminal terminal)\n \n-- | Sets the opacity of the terminal background, were 0 means completely transparent and 65535 means completely opaque.\nterminalSetOpacity :: \n TerminalClass self => self\n -> Int -- ^ @opacity@ - the new opacity \n -> IO ()\nterminalSetOpacity terminal opacity =\n {#call terminal_set_opacity#} (toTerminal terminal) (fromIntegral opacity)\n\n-- | Sets a background image for the widget. \n-- Text which would otherwise be drawn using the default background color will instead be drawn over the specified image. \n-- If necessary, the image will be tiled to cover the widget's entire visible area. \n-- If specified by 'terminalSetBackgroundSaturation' the terminal will tint its in-memory copy of the image before applying it to the terminal.\nterminalSetBackgroundImage :: \n TerminalClass self => self\n -> Maybe Pixbuf -- ^ @image@ - a 'Pixbuf' to use, or @Nothing@ to use the default background\n -> IO ()\nterminalSetBackgroundImage terminal (Just image) =\n {#call terminal_set_background_image#} (toTerminal terminal) image\nterminalSetBackgroundImage terminal Nothing =\n {#call terminal_set_background_image#} (toTerminal terminal) (Pixbuf nullForeignPtr)\n \n-- | Sets a background image for the widget. \n-- If specified by 'terminalSetBackgroundSaturation', the terminal will tint its in-memory copy of the image before applying it to the terminal.\nterminalSetBackgroundImageFile :: \n TerminalClass self => self\n -> String -- ^ @path@ - path to an image file \n -> IO ()\nterminalSetBackgroundImageFile terminal path =\n withUTFString path $ \\pathPtr ->\n {#call terminal_set_background_image_file#} (toTerminal terminal) pathPtr\n \n-- | If a background image has been set using 'terminalSetBackgroundImage', 'terminalSetBackgroundImageFile', or 'terminalSetBackgroundTransparent', \n-- and the saturation value is less than 1.0, the terminal will adjust the colors of the image before drawing the image. \n-- To do so, the terminal will create a copy of the background image (or snapshot of the root window) and modify its pixel values.\nterminalSetBackgroundSaturation :: \n TerminalClass self => self\n -> Double -- ^ @saturation@ - a floating point value between 0.0 and 1.0. \n -> IO () \nterminalSetBackgroundSaturation terminal saturation =\n {#call terminal_set_background_saturation#} (toTerminal terminal) (realToFrac saturation)\n \n-- | Sets the terminal's background image to the pixmap stored in the root window, adjusted so that if there are no windows below your application, \n-- the widget will appear to be transparent.\nterminalSetBackgroundTransparent :: \n TerminalClass self => self\n -> Bool -- ^ @transparent@ - @True@ if the terminal should fake transparency \n -> IO ()\nterminalSetBackgroundTransparent terminal transparent =\n {#call terminal_set_background_transparent#} (toTerminal terminal) (fromBool transparent)\n \n-- | If a background image has been set using 'terminalSetBackgroundImage', 'terminalSetBackgroundImageFile', or 'terminalSetBackgroundTransparent', \n-- and the value set by 'terminalSetBackgroundSaturation' is less than one, the terminal will adjust the color of the image before drawing the image. \n-- To do so, the terminal will create a copy of the background image (or snapshot of the root window) and modify its pixel values. \n-- The initial tint color is black.\n--\n-- * Available since Vte version 0.11\n--\nterminalSetBackgroundTintColor :: \n TerminalClass self => self\n -> Color -- ^ @color@ - a color which the terminal background should be tinted to if its saturation is not 1.0. \n -> IO ()\nterminalSetBackgroundTintColor terminal color =\n with color $ \\cPtr ->\n {#call terminal_set_background_tint_color#} (toTerminal terminal) (castPtr cPtr)\n\n-- | Controls whether or not the terminal will scroll the background image (if one is set) when the text in the window must be scrolled.\n--\n-- * Available since Vte version 0.11\n--\nterminalSetScrollBackground :: \n TerminalClass self => self\n -> Bool -- ^ @scroll@ - @True@ if the terminal should scroll the background image along with text. \n -> IO ()\nterminalSetScrollBackground terminal scroll =\n {#call terminal_set_scroll_background#} (toTerminal terminal) (fromBool scroll)\n \n-- | Sets the shape of the cursor drawn.\n--\n-- * Available since Vte version 0.19.1\n--\nterminalSetCursorShape ::\n TerminalClass self => self \n -> TerminalCursorShape -- ^ @shape@ - the 'TerminalCursorShape' to use \n -> IO ()\nterminalSetCursorShape terminal shape = \n {#call terminal_set_cursor_shape#} (toTerminal terminal) $fromIntegral (fromEnum shape)\n\n-- | Returns the currently set cursor shape.\n--\n-- * Available since Vte version 0.17.6\n--\nterminalGetCursorShape ::\n TerminalClass self => self\n -> IO TerminalCursorShape -- ^ return cursor shape\nterminalGetCursorShape terminal = \n liftM (toEnum.fromIntegral) $\n {#call terminal_get_cursor_shape#} (toTerminal terminal)\n\n-- | Returns the currently set cursor blink mode.\n--\n-- * Available since Vte version 0.17.1\n--\nterminalGetCursorBlinkMode :: \n TerminalClass self => self\n -> IO TerminalCursorBlinkMode -- ^ return cursor blink mode. \nterminalGetCursorBlinkMode terminal = \n liftM (toEnum.fromIntegral) $\n {#call terminal_get_cursor_blink_mode#} (toTerminal terminal)\n\n-- | Sets whether or not the cursor will blink. \n--\n-- * Available since Vte version 0.17.1\n--\nterminalSetCursorBlinkMode :: \n TerminalClass self => self\n -> TerminalCursorBlinkMode -- ^ @mode@ - the 'TerminalCursorBlinkMode' to use \n -> IO ()\nterminalSetCursorBlinkMode terminal mode =\n {#call terminal_set_cursor_blink_mode#} (toTerminal terminal) $fromIntegral (fromEnum mode)\n\n-- | Sets the length of the scrollback buffer used by the terminal. \n-- The size of the scrollback buffer will be set to the larger of this value and the number of visible rows the widget can display, \n-- so 0 can safely be used to disable scrollback. \n-- Note that this setting only affects the normal screen buffer. \n-- For terminal types which have an alternate screen buffer, no scrollback is allowed on the alternate screen buffer.\nterminalSetScrollbackLines :: \n TerminalClass self => self\n -> Int -- ^ @lines@ - the length of the history buffer \n -> IO ()\nterminalSetScrollbackLines terminal lines =\n {#call terminal_set_scrollback_lines#} (toTerminal terminal) (fromIntegral lines)\n\n-- | Sets the font used for rendering all text displayed by the terminal, overriding any fonts set using 'widgetModifyFont'.\n-- The terminal will immediately attempt to load the desired font, retrieve its metrics, and attempt to resize itself to keep the same number of rows and columns.\nterminalSetFont :: \n TerminalClass self => self\n -> FontDescription -- ^ @fontDesc@ - the 'FontDescription' of the desired font. \n -> IO ()\nterminalSetFont terminal (FontDescription fontDesc) =\n {#call terminal_set_font#} (toTerminal terminal) (castPtr $ unsafeForeignPtrToPtr fontDesc)\n\n-- | A convenience function which converts name into a 'FontDescription' and passes it to 'terminalSetFont'.\nterminalSetFontFromString :: \n TerminalClass self => self\n -> String -- ^ @name@ - a string describing the font. \n -> IO ()\nterminalSetFontFromString terminal name =\n withUTFString name $ \\namePtr -> \n {#call terminal_set_font_from_string#} (toTerminal terminal) namePtr\n \n-- | Queries the terminal for information about the fonts which will be used to draw text in the terminal.\nterminalGetFont :: \n TerminalClass self => self\n -> IO FontDescription -- ^ return a 'FontDescription' describing the font the terminal is currently using to render text. \nterminalGetFont terminal = do\n fdPtr <- {#call unsafe terminal_get_font#} (toTerminal terminal) \n makeNewFontDescription (castPtr fdPtr) \n\n-- | Checks if the terminal currently contains selected text. \n-- Note that this is different from determining if the terminal is the owner of any 'GtkClipboard' items.\nterminalGetHasSelection :: \n TerminalClass self => self\n -> IO Bool -- ^ return @True@ if part of the text in the terminal is selected. \nterminalGetHasSelection terminal =\n liftM toBool $\n {#call terminal_get_has_selection#} (toTerminal terminal)\n \n-- | When the user double-clicks to start selection, the terminal will extend the selection on word boundaries. \n-- It will treat characters included in spec as parts of words, and all other characters as word separators. \n-- Ranges of characters can be specified by separating them with a hyphen.\n-- As a special case, if @spec@ is the empty string, the terminal will treat all graphic non-punctuation non-space characters as word characters.\nterminalSetWordChars :: \n TerminalClass self => self\n -> String -- ^ @spec@ - a specification \n -> IO () \nterminalSetWordChars terminal spec =\n withUTFString spec $ \\specPtr ->\n {#call terminal_set_word_chars#} (toTerminal terminal) specPtr\n \n-- | Checks if a particular character is considered to be part of a word or not, based on the values last passed to 'terminalSetWordChars'.\nterminalIsWordChar :: \n TerminalClass self => self\n -> Char -- ^ @c@ - a candidate Unicode code point \n -> IO Bool -- ^ return @True@ if the character is considered to be part of a word \nterminalIsWordChar terminal c =\n liftM toBool $\n {#call terminal_is_word_char#} (toTerminal terminal) (fromIntegral $ ord c)\n\n-- | Modifies the terminal's backspace key binding, \n-- which controls what string or control sequence the terminal sends to its child when the user presses the backspace key.\nterminalSetBackspaceBinding :: \n TerminalClass self => self\n -> TerminalEraseBinding -- ^ @binding@ - a 'TerminalEraseBinding' for the backspace key \n -> IO ()\nterminalSetBackspaceBinding terminal binding =\n {#call terminal_set_backspace_binding#} (toTerminal terminal) (fromIntegral (fromEnum binding))\n\n-- | Modifies the terminal's delete key binding, \n-- which controls what string or control sequence the terminal sends to its child when the user presses the delete key.\nterminalSetDeleteBinding :: \n TerminalClass self => self\n -> TerminalEraseBinding -- ^ @bindign@ - a 'TerminalEraseBinding' for the delete key \n -> IO ()\nterminalSetDeleteBinding terminal binding =\n {#call terminal_set_delete_binding#} (toTerminal terminal) (fromIntegral (fromEnum binding))\n \n-- | Changes the value of the terminal's mouse autohide setting. \n-- When autohiding is enabled, the mouse cursor will be hidden when the user presses a key and shown when the user moves the mouse. \n-- This setting can be read using 'terminalGetMouseAutohide'.\nterminalSetMouseAutohide :: \n TerminalClass self => self\n -> Bool -- ^ @autohide@ - @True@ if the autohide should be enabled \n -> IO ()\nterminalSetMouseAutohide terminal autohide =\n {#call terminal_set_mouse_autohide#} (toTerminal terminal) (fromBool autohide)\n \n-- | Determines the value of the terminal's mouse autohide setting. \n-- When autohiding is enabled, the mouse cursor will be hidden when the user presses a key and shown when the user moves the mouse. \n-- This setting can be changed using 'terminalSetMouseAutohide'.\nterminalGetMouseAutohide :: TerminalClass self => self -> IO Bool\nterminalGetMouseAutohide terminal =\n liftM toBool $\n {#call terminal_get_mouse_autohide#} (toTerminal terminal)\n \n-- | Resets as much of the terminal's internal state as possible, discarding any unprocessed input data, \n-- resetting character attributes, cursor state, national character set state, status line, \n-- terminal modes (insert\/delete), selection state, and encoding.\nterminalReset :: \n TerminalClass self => self\n -> Bool -- ^ @full@ - @True@ to reset tabstops \n -> Bool -- ^ @clearHistory@ - @True@ to empty the terminal's scrollback buffer \n -> IO ()\nterminalReset terminal full clearHistory =\n {#call terminal_reset#} (toTerminal terminal) (fromBool full) (fromBool clearHistory)\n\n-- | Extracts a view of the visible part of the terminal. A selection\n-- predicate may be supplied to restrict the inspected characters. The\n-- return value is a list of 'VteChar' structures, each detailing the\n-- character's position, colors, and other characteristics.\n--\nterminalGetText ::\n TerminalClass self => self\n -> Maybe VteSelect -- ^ @Just p@ for a predicate @p@ that determines\n -- which character should be extracted or @Nothing@\n -- to select all characters\n -> IO [VteChar] -- ^ return a text string\nterminalGetText terminal mCB = do\n cbPtr <- case mCB of\n Just cb -> mkVteSelectionFunc $ \\_ c r _ ->\n return (fromBool (cb (fromIntegral c) (fromIntegral r)))\n Nothing -> return nullFunPtr\n gArrPtr <- {#call unsafe g_array_new#} 0 0\n (fromIntegral (sizeOf (undefined :: VteAttributes)))\n strPtr <- {#call terminal_get_text #} (toTerminal terminal) cbPtr nullPtr gArrPtr\n str <- if strPtr==nullPtr then return \"\" else peekUTFString strPtr\n (len,elemPtr) <- gArrayContent (castPtr gArrPtr)\n attrs <- (flip mapM) [0..len-1] $ peekElemOff elemPtr\n unless (cbPtr==nullFunPtr) $ freeHaskellFunPtr cbPtr\n {#call unsafe g_free#} (castPtr strPtr)\n {#call unsafe g_array_free#} gArrPtr 1\n return (zipWith attrToChar str attrs)\n \n-- | Extracts a view of the visible part of the terminal. \n-- If is_selected is not @Nothing@, characters will only be read if is_selected returns @True@ after being passed the column and row, respectively. \n-- A 'CharAttributes' structure is added to attributes for each byte added to the returned string detailing the character's position, colors, and other characteristics. \n-- This function differs from 'terminalGetText' in that trailing spaces at the end of lines are included.\n--\n-- * Available since Vte version 0.11.11\n--\nterminalGetTextIncludeTrailingSpaces :: \n TerminalClass self => self\n -> Maybe VteSelect -- ^ @Just p@ for a predicate @p@ that determines\n -- which character should be extracted or @Nothing@\n -- to select all characters \n -> IO [VteChar] -- ^ return a text string\nterminalGetTextIncludeTrailingSpaces terminal mCB = do\n cbPtr <- case mCB of\n Just cb -> mkVteSelectionFunc $ \\_ c r _ ->\n return (fromBool (cb (fromIntegral c) (fromIntegral r)))\n Nothing -> return nullFunPtr\n gArrPtr <- {#call unsafe g_array_new#} 0 0\n (fromIntegral (sizeOf (undefined :: VteAttributes)))\n strPtr <- {#call terminal_get_text_include_trailing_spaces #} (toTerminal terminal) cbPtr nullPtr gArrPtr\n str <- if strPtr==nullPtr then return \"\" else peekUTFString strPtr\n (len,elemPtr) <- gArrayContent (castPtr gArrPtr)\n attrs <- (flip mapM) [0..len-1] $ peekElemOff elemPtr\n unless (cbPtr==nullFunPtr) $ freeHaskellFunPtr cbPtr\n {#call unsafe g_free#} (castPtr strPtr)\n {#call unsafe g_array_free#} gArrPtr 1\n return (zipWith attrToChar str attrs)\n\n-- | Extracts a view of the visible part of the terminal. \n-- If is_selected is not @Nothing@, characters will only be read if is_selected returns @True@ after being passed the column and row, respectively. \n-- A 'CharAttributes' structure is added to attributes for each byte added to the returned string detailing the character's position, colors, and other characteristics. \n-- The entire scrollback buffer is scanned, so it is possible to read the entire contents of the buffer using this function.\n--\nterminalGetTextRange ::\n TerminalClass self => self\n -> Int -- ^ @sRow@ first row to search for data \n -> Int -- ^ @sCol@ first column to search for data \n -> Int -- ^ @eRow@ last row to search for data \n -> Int -- ^ @eCol@ last column to search for data \n -> Maybe VteSelect -- ^ @Just p@ for a predicate @p@ that determines\n -- which character should be extracted or @Nothing@\n -- to select all characters\n -> IO [VteChar] -- ^ return a text string\nterminalGetTextRange terminal sRow sCol eRow eCol mCB = do \n cbPtr <- case mCB of\n Just cb -> mkVteSelectionFunc $ \\_ c r _ ->\n return (fromBool (cb (fromIntegral c) (fromIntegral r)))\n Nothing -> return nullFunPtr\n gArrPtr <- {#call unsafe g_array_new#} 0 0\n (fromIntegral (sizeOf (undefined :: VteAttributes)))\n strPtr <- {#call terminal_get_text_range #} (toTerminal terminal) (fromIntegral sRow) (fromIntegral sCol) (fromIntegral eRow) (fromIntegral eCol) cbPtr nullPtr gArrPtr\n str <- if strPtr==nullPtr then return \"\" else peekUTFString strPtr\n (len,elemPtr) <- gArrayContent (castPtr gArrPtr)\n attrs <- (flip mapM) [0..len-1] $ peekElemOff elemPtr\n unless (cbPtr==nullFunPtr) $ freeHaskellFunPtr cbPtr\n {#call unsafe g_free#} (castPtr strPtr)\n {#call unsafe g_array_free#} gArrPtr 1\n return (zipWith attrToChar str attrs)\n\n-- | Reads the location of the insertion cursor and returns it. The row\n-- coordinate is absolute.\nterminalGetCursorPosition :: \n TerminalClass self => self\n -> IO (Int, Int) -- ^ @(column,row)@ the position of the cursor\nterminalGetCursorPosition terminal = do\n alloca $ \\cPtr ->\n alloca $ \\rPtr -> do\n {#call terminal_get_cursor_position#} (toTerminal terminal) cPtr rPtr\n column <- peek cPtr\n row <- peek rPtr\n return (fromIntegral column,fromIntegral row)\n\n-- | Clears the list of regular expressions the terminal uses to highlight\n-- text when the user moves the mouse cursor.\nterminalMatchClearAll :: TerminalClass self => self -> IO ()\nterminalMatchClearAll terminal =\n {#call terminal_match_clear_all#} (toTerminal terminal)\n \n-- | Adds the regular expression to the list of matching expressions.\n-- When the user moves the mouse cursor over a section of displayed text which\n-- matches this expression, the text will be highlighted.\n--\n-- See for\n-- details about the accepted syntex.\n--\n-- * Available since Vte version 0.17.1\n--\nterminalMatchAddRegex ::\n TerminalClass self => self\n -> String -- ^ @pattern@ - a regular expression\n -> [RegexCompileFlags] -- ^ @flags@ - specify how to interpret the pattern\n -> [RegexMatchFlags] -- ^ @flags@ - specify how to match\n -> IO Int -- ^ return an integer associated with this expression\nterminalMatchAddRegex terminal pattern cFlags mFlags =\n withUTFString pattern $ \\pat -> do\n regexPtr <- propagateGError $\n {#call g_regex_new#} pat (fromIntegral (fromFlags cFlags))\n (fromIntegral (fromFlags mFlags))\n liftM fromIntegral $ {#call terminal_match_add_gregex#}\n (toTerminal terminal) regexPtr (fromIntegral (fromFlags mFlags))\n\n-- | Removes the regular expression which is associated with the given tag from the list of expressions which the terminal will highlight when the user moves the mouse cursor over matching text.\nterminalMatchRemove :: \n TerminalClass self => self\n -> Int -- ^ @tag@ - the tag of the regex to remove \n -> IO ()\nterminalMatchRemove terminal tag =\n {#call terminal_match_remove#} (toTerminal terminal) (fromIntegral tag)\n\n-- | Checks if the text in and around the specified position matches any of\n-- the regular expressions previously registered using\n-- 'terminalMatchAddRegex'. If a match exists, the matching string is returned\n-- together with the number associated with the matched regular expression. If\n-- more than one regular expression matches, the expressions that was\n-- registered first will be returned.\n--\nterminalMatchCheck :: \n TerminalClass self => self\n -> Int -- ^ @column@ - the text column \n -> Int -- ^ @row@ - the text row \n -> IO (Maybe (String, Int))\n -- ^ @Just (str, tag)@ - the string that matched one of the previously set\n -- regular expressions together with the number @tag@ that was returned by\n -- 'terminalMatchAddRegex'\nterminalMatchCheck terminal column row = alloca $ \\tagPtr -> do\n strPtr <- {#call terminal_match_check#} (toTerminal terminal)\n (fromIntegral column) (fromIntegral row) tagPtr\n if strPtr==nullPtr then return Nothing else do\n str <- peekCString strPtr\n {#call unsafe g_free#} (castPtr strPtr)\n if tagPtr==nullPtr then return Nothing else do\n tag <- peek tagPtr\n return (Just (str,fromIntegral tag))\n\n-- | Sets which cursor the terminal will use if the pointer is over the pattern specified by tag. \n-- The terminal keeps a reference to cursor.\n--\n-- * Available since Vte version 0.11\n--\nterminalMatchSetCursor :: \n TerminalClass self => self\n -> Int -- ^ @tag@ - the tag of the regex which should use the specified cursor \n -> Cursor -- ^ @cursor@ - the 'Cursor' which the terminal should use when the pattern is highlighted \n -> IO ()\nterminalMatchSetCursor terminal tag (Cursor cur) =\n with (unsafeForeignPtrToPtr cur) $ \\curPtr ->\n {#call terminal_match_set_cursor#} (toTerminal terminal) (fromIntegral tag) (castPtr curPtr)\n\n-- | Sets which cursor the terminal will use if the pointer is over the pattern specified by tag.\n--\n-- * Available since Vte version 0.11.9\n--\nterminalMatchSetCursorType :: \n TerminalClass self => self\n -> Int -- ^ @tag@ the tag of the regex which should use the specified cursor \n -> CursorType -- ^ @cursorType@ a 'CursorType'\n -> IO ()\nterminalMatchSetCursorType terminal tag cursorType = \n {#call terminal_match_set_cursor_type#} (toTerminal terminal) (fromIntegral tag) $fromIntegral (fromEnum cursorType) \n\n-- | Sets which cursor the terminal will use if the pointer is over the pattern specified by tag.\n--\n-- * Available since Vte version 0.17.1\n--\nterminalMatchSetCursorName :: \n TerminalClass self => self\n -> Int -- ^ @tag@ - the tag of the regex which should use the specified cursor \n -> String -- ^ @name@ - the name of the cursor \n -> IO ()\nterminalMatchSetCursorName terminal tag name =\n withUTFString name $ \\namePtr ->\n {#call terminal_match_set_cursor_name#} (toTerminal terminal) (fromIntegral tag) namePtr\n \n-- | Sets what type of terminal the widget attempts to emulate by scanning for control sequences defined in the system's termcap file. \n-- Unless you are interested in this feature, always use \"xterm\".\nterminalSetEmulation :: \n TerminalClass self => self\n -> String -- ^ @emulation@ - the name of a terminal description \n -> IO () \nterminalSetEmulation terminal emulation =\n withUTFString emulation $ \\emulationPtr ->\n {#call terminal_set_emulation#} (toTerminal terminal) emulationPtr\n \n-- | Queries the terminal for its current emulation, as last set by a call to 'terminalSetEmulation'.\nterminalGetEmulation :: \n TerminalClass self => self\n -> IO String -- ^ return the name of the terminal type the widget is attempting to emulate \nterminalGetEmulation terminal =\n {#call terminal_get_emulation#} (toTerminal terminal) >>= peekCString\n \n-- | Queries the terminal for its default emulation, which is attempted if the terminal type passed to 'terminalSetEmulation' emptry string.\n--\n-- * Available since Vte version 0.11.11\n--\nterminalGetDefaultEmulation :: \n TerminalClass self => self\n -> IO String -- ^ return the name of the default terminal type the widget attempts to emulate \nterminalGetDefaultEmulation terminal =\n {#call terminal_get_default_emulation#} (toTerminal terminal) >>= peekCString\n \n-- | Changes the encoding the terminal will expect data from the child to be encoded with. \n-- For certain terminal types, applications executing in the terminal can change the encoding. \n-- The default encoding is defined by the application's locale settings.\nterminalSetEncoding ::\n TerminalClass self => self\n -> String -- ^ @codeset@ - a valid g_iconv target \n -> IO () \nterminalSetEncoding terminal codeset =\n withUTFString codeset $ \\codesetPtr ->\n {#call terminal_set_encoding#} (toTerminal terminal) codesetPtr\n \n-- | Determines the name of the encoding in which the terminal expects data to be encoded.\nterminalGetEncoding :: \n TerminalClass self => self\n -> IO String -- ^ return the current encoding for the terminal. \nterminalGetEncoding terminal =\n {#call terminal_get_encoding#} (toTerminal terminal) >>= peekCString\n \n-- | Some terminal emulations specify a status line which is separate from the main display area, \n-- and define a means for applications to move the cursor to the status line and back.\nterminalGetStatusLine :: \n TerminalClass self => self\n -> IO String -- ^ The current content of the terminal's status line. For terminals like \"xterm\", this will usually be the empty string.\nterminalGetStatusLine terminal =\n {#call terminal_get_status_line#} (toTerminal terminal) >>= peekCString\n \n-- | Determines the amount of additional space the widget is using to pad the edges of its visible area. \n-- This is necessary for cases where characters in the selected font don't themselves include a padding area and the text itself would otherwise be contiguous with the window border. \n-- Applications which use the widget's row_count, column_count, char_height, and char_width fields to set geometry hints using 'windowSetGeometryHints' will need to add this value to the base size. \n-- The values returned in xpad and ypad are the total padding used in each direction, and do not need to be doubled.\nterminalGetPadding :: \n TerminalClass self => self\n -> IO (Int, Int) -- ^ @(lr,tb)@ - the left\\\/right-edge and top\\\/bottom-edge padding \nterminalGetPadding terminal =\n alloca $ \\xPtr ->\n alloca $ \\yPtr -> do\n {#call terminal_get_padding#} (toTerminal terminal) xPtr yPtr\n xpad <- peek xPtr\n ypad <- peek yPtr\n return (fromIntegral xpad,fromIntegral ypad)\n\n-- | Get 'Adjustment' of terminal widget.\nterminalGetAdjustment :: \n TerminalClass self => self\n -> IO Adjustment -- ^ return the contents of terminal's adjustment field \nterminalGetAdjustment terminal =\n makeNewObject mkAdjustment $ {#call terminal_get_adjustment#} (toTerminal terminal)\n\n-- | Get terminal's char height.\nterminalGetCharHeight :: \n TerminalClass self => self\n -> IO Int -- ^ return the contents of terminal's char_height field \nterminalGetCharHeight terminal =\n liftM fromIntegral $\n {#call terminal_get_char_height#} (toTerminal terminal)\n\n-- | Get terminal's char width.\nterminalGetCharWidth :: \n TerminalClass self => self\n -> IO Int -- ^ return the contents of terminal's char_width field \nterminalGetCharWidth terminal =\n liftM fromIntegral $\n {#call terminal_get_char_width#} (toTerminal terminal)\n\n-- | Get terminal's column count.\nterminalGetColumnCount :: \n TerminalClass self => self\n -> IO Int -- ^ return the contents of terminal's column_count field \nterminalGetColumnCount terminal =\n liftM fromIntegral $\n {#call terminal_get_column_count#} (toTerminal terminal)\n \n-- | Get terminal's row count.\nterminalGetRowCount :: \n TerminalClass self => self\n -> IO Int -- ^ return the contents of terminal's row_count field \nterminalGetRowCount terminal =\n liftM fromIntegral $\n {#call terminal_get_row_count#} (toTerminal terminal)\n\n-- | Get icon title.\nterminalGetIconTitle :: \n TerminalClass self => self\n -> IO String -- ^ return the contents of terminal's icon_title field \nterminalGetIconTitle terminal =\n {#call terminal_get_icon_title#} (toTerminal terminal) >>= peekCString\n \n-- | Get window title.\nterminalGetWindowTitle :: \n TerminalClass self => self\n -> IO String -- ^ return the contents of terminal's window_title field \nterminalGetWindowTitle terminal =\n {#call terminal_get_window_title#} (toTerminal terminal) >>= peekCString\n\n--------------------\n-- Attributes\n-- | Controls whether or not the terminal will attempt to draw bold text. \n-- This may happen either by using a bold font variant, or by repainting text with a different offset.\n--\n-- Default value: @True@\n--\n-- * Available since Vte version 0.19.1\n--\nterminalAllowBold :: TerminalClass self => Attr self Bool\nterminalAllowBold = newAttr\n terminalGetAllowBold\n terminalSetAllowBold\n\n-- | Controls whether or not the terminal will beep when the child outputs the \\\"bl\\\" sequence.\n--\n-- Default value: @True@\n--\n--\n-- * Available since Vte version 0.19.1\n--\nterminalAudibleBell :: TerminalClass self => Attr self Bool\nterminalAudibleBell = newAttr\n terminalGetAudibleBell\n terminalSetAudibleBell\n\n-- | Sets a background image file for the widget. \n-- If specified by \"background-saturation:\", the terminal will tint its in-memory copy of the image before applying it to the terminal.\n--\n-- Default value: \\\"\\\"\n--\n-- * Available since Vte version 0.19.1\n--\nterminalBackgroundImageFile :: TerminalClass self => Attr self String\nterminalBackgroundImageFile = \n newAttrFromStringProperty \"background-image-file\" \n\n-- | Sets a background image for the widget. \n-- Text which would otherwise be drawn using the default background color will instead be drawn over the specified image. \n-- If necessary, the image will be tiled to cover the widget's entire visible area. \n-- If specified by \"background-saturation:\", the terminal will tint its in-memory copy of the image before applying it to the terminal.\n--\n-- * Available since Vte version 0.19.1\n--\nterminalBackgroundImagePixbuf :: TerminalClass self => Attr self (Maybe Pixbuf)\nterminalBackgroundImagePixbuf =\n newAttrFromMaybeObjectProperty \"background-image-pixbuf\" \n {#call pure gdk_pixbuf_get_type#}\n\n-- | Sets the opacity of the terminal background, were 0.0 means completely transparent and 1.0 means completely opaque.\n-- \n-- Allowed values: [0,1]\n--\n-- Default values: 1\n--\n-- * Available since Vte version 0.19.1\n--\nterminalBackgroundOpacity :: TerminalClass self => Attr self Double\nterminalBackgroundOpacity =\n newAttrFromDoubleProperty \"background-opacity\"\n\n-- | If a background image has been set using \"background-image-file:\" or \"background-image-pixbuf:\", or \"background-transparent:\", \n-- and the saturation value is less than 1.0, the terminal will adjust the colors of the image before drawing the image. \n-- To do so, the terminal will create a copy of the background image (or snapshot of the root window) and modify its pixel values.\n--\n-- Allowed values: [0,1]\n--\n-- Default value: 0.4\n--\n-- * Available since Vte version 0.19.1\n--\nterminalBackgroundSaturation :: TerminalClass self => Attr self Double\nterminalBackgroundSaturation =\n newAttrFromDoubleProperty \"background-saturation\"\n\n-- | If a background image has been set using \"background-image-file:\" or \"background-image-pixbuf:\", or \"background-transparent:\", \n-- and the value set by 'Terminal' background-saturation: is less than 1.0, the terminal will adjust the color of the image before drawing the image. \n-- To do so, the terminal will create a copy of the background image (or snapshot of the root window) and modify its pixel values. \n-- The initial tint color is black.\n--\n-- * Available since Vte version 0.19.1\n--\nterminalBackgroundTintColor :: TerminalClass self => Attr self Color\nterminalBackgroundTintColor =\n newAttrFromBoxedStorableProperty \"background-tint-color\"\n {#call pure unsafe gdk_color_get_type#}\n\n-- | Sets whther the terminal uses the pixmap stored in the root window as the background, \n-- adjusted so that if there are no windows below your application, the widget will appear to be transparent.\n--\n-- NOTE: When using a compositing window manager, you should instead set a RGBA colourmap on the toplevel window, so you get real transparency.\n-- \n-- Default value: @False@\n--\n-- * Available since Vte version 0.19.1\n--\nterminalBackgroundTransparent :: TerminalClass self => Attr self Bool\nterminalBackgroundTransparent =\n newAttrFromBoolProperty \"background-transparent\"\n\n-- | *Controls what string or control sequence the terminal sends to its child when the user presses the backspace key.\n--\n-- Default value: 'EraseAuto'\n--\n-- * Available since Vte version 0.19.1\n--\nterminalBackspaceBinding :: TerminalClass self => Attr self TerminalEraseBinding\nterminalBackspaceBinding =\n newAttrFromEnumProperty \"backspace-binding\" \n {#call pure unsafe terminal_erase_binding_get_type#}\n\n-- | Sets whether or not the cursor will blink. \n-- Using 'CursorBlinkSystem' will use the \"gtk-cursor-blink\" setting.\n--\n-- Default value: 'CursorBlinkSystem'\n--\n-- * Available since Vte version 0.19.1\n--\nterminalCursorBlinkMode :: TerminalClass self => Attr self TerminalCursorBlinkMode\nterminalCursorBlinkMode = newAttr\n terminalGetCursorBlinkMode\n terminalSetCursorBlinkMode\n\n-- | Controls the shape of the cursor.\n--\n-- Default value: 'CursorShapeBlock'\n--\n-- * Available since Vte version 0.19.1\n--\nterminalCursorShape :: TerminalClass self => Attr self TerminalCursorShape\nterminalCursorShape = newAttr\n terminalGetCursorShape\n terminalSetCursorShape\n\n-- | Controls what string or control sequence the terminal sends to its child when the user presses the delete key.\n--\n-- Default value: 'EraseAuto'\n-- \n-- * Available since Vte version 0.19.1\n--\nterminalDeleteBinding :: TerminalClass self => Attr self TerminalEraseBinding\nterminalDeleteBinding =\n newAttrFromEnumProperty \"delete-binding\"\n {#call pure unsafe terminal_erase_binding_get_type#}\n\n-- | Sets what type of terminal the widget attempts to emulate by scanning for control sequences defined in the system's termcap file. \n-- Unless you are interested in this feature, always use the default which is \"xterm\".\n--\n-- Default value: \"xterm\"\n--\n-- * Available since Vte version 0.19.1\n--\nterminalEmulation :: TerminalClass self => Attr self String\nterminalEmulation = newAttr\n terminalGetEmulation\n terminalSetEmulation\n\n-- | Controls the encoding the terminal will expect data from the child to be encoded with. \n-- For certain terminal types, applications executing in the terminal can change the encoding. \n-- The default is defined by the application's locale settings.\n--\n-- Default value: \\\"\\\"\n--\n-- * Available since Vte version 0.19.1\n--\nterminalEncoding :: TerminalClass self => Attr self String\nterminalEncoding = newAttr\n terminalGetEncoding\n terminalSetEncoding\n\n-- | Specifies the font used for rendering all text displayed by the terminal, overriding any fonts set using 'widgetModifyFont'.\n-- The terminal will immediately attempt to load the desired font, retrieve its metrics, \n-- and attempt to resize itself to keep the same number of rows and columns.\n--\n-- * Available since Vte version 0.19.1\n--\nterminalFontDesc :: TerminalClass self => Attr self FontDescription\nterminalFontDesc = newAttr\n terminalGetFont\n terminalSetFont\n\n-- | The terminal's so-called icon title, or empty if no icon title has been set.\n--\n-- Default value: \\\"\\\"\n--\n-- * Available since Vte version 0.19.1\n--\nterminalIconTitle :: TerminalClass self => ReadAttr self String\nterminalIconTitle = readAttrFromStringProperty \"icon-title\"\n\n-- | Controls the value of the terminal's mouse autohide setting. \n-- When autohiding is enabled, the mouse cursor will be hidden when the user presses a key and shown when the user moves the mouse.\n--\n-- Default value: @False@\n--\n-- * Available since Vte version 0.19.1\n--\nterminalPointerAutohide :: TerminalClass self => Attr self Bool\nterminalPointerAutohide = newAttr\n terminalGetMouseAutohide\n terminalSetMouseAutohide\n\n-- | The file descriptor of the master end of the terminal's PTY.\n--\n-- Allowed values: [-1 ...]\n--\n-- Default values: -1\n--\n-- * Available since Vte version 0.19.1\n--\nterminalPty :: TerminalClass self => Attr self Int\nterminalPty = newAttr\n terminalGetPty\n terminalSetPty\n\n-- | Controls the value of the terminal's mouse autohide setting. \n-- When autohiding is enabled, the mouse cursor will be hidden when the user presses a key and shown when the user moves the mouse.\n--\n-- Default value: @False@\n--\n-- * Available since Vte version 0.19.1\n--\nterminalScrollBackground :: TerminalClass self => Attr self Bool\nterminalScrollBackground =\n newAttrFromBoolProperty \"scroll-background\"\n\n-- | Controls whether or not the terminal will forcibly scroll to the bottom of the viewable history when the user presses a key. \n-- Modifier keys do not trigger this behavior.\n--\n-- Default value: @False@\n--\n-- * Available since Vte version 0.19.1\n--\nterminalScrollOnKeystroke :: TerminalClass self => Attr self Bool\nterminalScrollOnKeystroke =\n newAttrFromBoolProperty \"scroll-on-keystroke\"\n\n-- | Controls whether or not the terminal will forcibly scroll to the bottom of the viewable history when the new data is received from the child.\n-- \n-- Default value: @True@\n--\n-- * Available since Vte version 0.19.1\n--\nterminalScrollOnOutput :: TerminalClass self => Attr self Bool\nterminalScrollOnOutput =\n newAttrFromBoolProperty \"scroll-on-output\"\n\n-- | The length of the scrollback buffer used by the terminal. The size of the\n-- scrollback buffer will be set to the larger of this value and the number of\n-- visible rows the widget can display, so 0 can safely be used to disable\n-- scrollback. Note that this setting only affects the normal screen buffer.\n-- For terminal types which have an alternate screen buffer, no scrollback is\n-- allowed on the alternate screen buffer.\n--\n-- Default value: 100\n--\n-- * Available since Vte version 0.19.1\n--\nterminalScrollbackLines :: TerminalClass self => Attr self Int\nterminalScrollbackLines =\n newAttrFromUIntProperty \"scrollback-lines\"\n\n-- | Controls whether the terminal will present a visible bell to the user when the child outputs the \\\"bl\\\" sequence. \n-- The terminal will clear itself to the default foreground color and then repaint itself.\n--\n-- Default value: @False@\n--\n-- * Available since Vte version 0.19.1\n--\nterminalVisibleBell :: TerminalClass self => Attr self Bool\nterminalVisibleBell = newAttr\n terminalGetVisibleBell\n terminalSetVisibleBell\n\n-- | The terminal's title.\n--\n-- Default value: \\\"\\\"\n--\n-- * Available since Vte version 0.19.1\n--\nterminalWindowTitle :: TerminalClass self => ReadAttr self String\nterminalWindowTitle = readAttrFromStringProperty \"window-title\"\n\n-- | When the user double-clicks to start selection, the terminal will extend the selection on word boundaries. \n-- It will treat characters the word-chars characters as parts of words, and all other characters as word separators. \n-- Ranges of characters can be specified by separating them with a hyphen.\n-- As a special case, when setting this to the empty string, the terminal will treat all graphic non-punctuation non-space characters as word\n-- characters.\n-- \n-- Defalut value: \\\"\\\"\n--\n-- * Available since Vte version 0.19.1\n--\nterminalWordChars :: TerminalClass self => Attr self String\nterminalWordChars =\n newAttrFromStringProperty \"word-chars\" \n\n--------------------\n-- Signals\n\n-- | This signal is emitted when the a child sends a beep request to the terminal.\nbeep :: TerminalClass self => Signal self (IO ())\nbeep = Signal (connect_NONE__NONE \"beep\")\n\n-- | Emitted whenever selection of a new font causes the values of the char_width or char_height fields to change.\ncharSizeChanged :: TerminalClass self => Signal self (Int -> Int -> IO ())\ncharSizeChanged = Signal (connect_INT_INT__NONE \"char-size-changed\")\n\n-- | This signal is emitted when the terminal detects that a child started using 'terminalForkCommand' has exited.\nchildExited :: TerminalClass self => Signal self (IO ())\nchildExited = Signal (connect_NONE__NONE \"child-exited\")\n\n-- | Emitted whenever the terminal receives input from the user and prepares to send it to the child process. \n-- The signal is emitted even when there is no child process.\ncommit :: TerminalClass self => Signal self (String -> Int -> IO ())\ncommit = Signal (connect_STRING_INT__NONE \"commit\")\n\n-- | Emitted whenever the visible appearance of the terminal has changed. Used primarily by 'TerminalAccessible'.\ncontentsChanged :: TerminalClass self => Signal self (IO ())\ncontentsChanged = Signal (connect_NONE__NONE \"contents-changed\")\n\n-- | Emitted whenever 'terminalCopyClipboard' is called.\ncopyClipboard :: TerminalClass self => Signal self (IO ())\ncopyClipboard = Signal (connect_NONE__NONE \"copy-clipboard\")\n\n-- | Emitted whenever the cursor moves to a new character cell. Used primarily by 'TerminalAccessible'.\ncursorMoved :: TerminalClass self => Signal self (IO ())\ncursorMoved = Signal (connect_NONE__NONE \"cursor-moved\")\n\n-- | Emitted when the user hits the '-' key while holding the Control key.\ndecreaseFontSize :: TerminalClass self => Signal self (IO ())\ndecreaseFontSize = Signal (connect_NONE__NONE \"decrease-font-size\")\n\n-- | Emitted at the child application's request.\ndeiconifyWindow :: TerminalClass self => Signal self (IO ())\ndeiconifyWindow = Signal (connect_NONE__NONE \"deiconify-window\")\n\n-- | Emitted whenever the terminal's emulation changes, only possible at the parent application's request.\nemulationChanged :: TerminalClass self => Signal self (IO ())\nemulationChanged = Signal (connect_NONE__NONE \"emulation-changed\")\n\n-- | Emitted whenever the terminal's current encoding has changed, \n-- either as a result of receiving a control sequence which toggled between the local and UTF-8 encodings, or at the parent application's request.\nencodingChanged :: TerminalClass self => Signal self (IO ())\nencodingChanged = Signal (connect_NONE__NONE \"encoding-changed\")\n\n-- | Emitted when the terminal receives an end-of-file from a child which is running in the terminal. \n-- This signal is frequently (but not always) emitted with a 'childExited' signal.\neof :: TerminalClass self => Signal self (IO ())\neof = Signal (connect_NONE__NONE \"eof\")\n\n-- | Emitted when the terminal's icon_title field is modified.\niconTitleChanged :: TerminalClass self => Signal self (IO ())\niconTitleChanged = Signal (connect_NONE__NONE \"icon-title-changed\")\n\n-- | Emitted at the child application's request.\niconifyWindow :: TerminalClass self => Signal self (IO ())\niconifyWindow = Signal (connect_NONE__NONE \"iconify-window\")\n\n-- | Emitted when the user hits the '+' key while holding the Control key.\nincreaseFontSize :: TerminalClass self => Signal self (IO ())\nincreaseFontSize = Signal (connect_NONE__NONE \"increase-font-size\")\n\n-- | Emitted at the child application's request.\nlowerWindow :: TerminalClass self => Signal self (IO ())\nlowerWindow = Signal (connect_NONE__NONE \"lower-window\")\n\n-- | Emitted at the child application's request.\nmaximizeWindow :: TerminalClass self => Signal self (IO ())\nmaximizeWindow = Signal (connect_NONE__NONE \"maximize-window\")\n\n-- | Emitted when user move terminal window.\nmoveWindow :: TerminalClass self => Signal self (Word -> Word -> IO ())\nmoveWindow = Signal (connect_WORD_WORD__NONE \"move-window\")\n\n-- | Emitted whenever 'terminalPasteClipboard' is called.\npasteClipboard :: TerminalClass self => Signal self (IO ())\npasteClipboard = Signal (connect_NONE__NONE \"paste-clipboard\")\n\n-- | Emitted at the child application's request.\nraiseWindow :: TerminalClass self => Signal self (IO ())\nraiseWindow = Signal (connect_NONE__NONE \"raise-window\")\n\n-- | Emitted at the child application's request.\nrefreshWindow :: TerminalClass self => Signal self (IO ())\nrefreshWindow = Signal (connect_NONE__NONE \"refresh-window\")\n\n-- | Emitted at the child application's request.\nresizeWidnow :: TerminalClass self => Signal self (Int -> Int -> IO ()) \nresizeWidnow = Signal (connect_INT_INT__NONE \"resize-window\")\n\n-- | Emitted at the child application's request.\nrestoreWindow :: TerminalClass self => Signal self (IO ())\nrestoreWindow = Signal (connect_NONE__NONE \"restore-window\")\n\n-- | Emitted at the child application's request.\nselectionChanged :: TerminalClass self => Signal self (IO ())\nselectionChanged = Signal (connect_NONE__NONE \"selection-changed\")\n\n-- | Set the scroll adjustments for the terminal. \n-- Usually scrolled containers like 'ScrolledWindow' will emit this \n-- signal to connect two instances of 'Scrollbar' to the scroll directions of the 'Terminal'.\nsetScrollAdjustments :: TerminalClass self => Signal self (Adjustment -> Adjustment -> IO ())\nsetScrollAdjustments = Signal (connect_OBJECT_OBJECT__NONE \"set-scroll-adjustments\")\n\n-- | Emitted whenever the contents of the status line are modified or cleared.\nstatusLineChanged :: TerminalClass self => Signal self (IO ())\nstatusLineChanged = Signal (connect_NONE__NONE \"status-line-changed\")\n\n-- | An internal signal used for communication between the terminal and its accessibility peer. \n-- May not be emitted under certain circumstances.\ntextDeleted :: TerminalClass self => Signal self (IO ())\ntextDeleted = Signal (connect_NONE__NONE \"text-deleted\")\n\n-- | An internal signal used for communication between the terminal and its accessibility peer. \n-- May not be emitted under certain circumstances.\ntextInserted :: TerminalClass self => Signal self (IO ())\ntextInserted = Signal (connect_NONE__NONE \"text-inserted\")\n\n-- | An internal signal used for communication between the terminal and its accessibility peer. \n-- May not be emitted under certain circumstances.\ntextModified :: TerminalClass self => Signal self (IO ())\ntextModified = Signal (connect_NONE__NONE \"text-modified\")\n\n-- | An internal signal used for communication between the terminal and its accessibility peer. \n-- May not be emitted under certain circumstances.\ntextScrolled :: TerminalClass self => Signal self (Int -> IO ())\ntextScrolled = Signal (connect_INT__NONE \"text-scrolled\")\n\n-- | Emitted when the terminal's window_title field is modified.\nwindowTitleChanged :: TerminalClass self => Signal self (IO ())\nwindowTitleChanged = Signal (connect_NONE__NONE \"window-title-changed\")\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"9916a505437773f6a896468a76f90c98d81cc566","subject":"Add xine_stream_master_slave","message":"Add xine_stream_master_slave\n","repos":"joachifm\/hxine,joachifm\/hxine","old_file":"Xine\/Foreign.chs","new_file":"Xine\/Foreign.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\n-- |\n-- Module : Xine.Foreign\n-- Copyright : (c) Joachim Fasting 2010\n-- License : LGPL\n-- Maintainer : Joachim Fasting \n-- Stability : unstable\n-- Portability : not portable\n--\n-- A simple binding to xine-lib. Low-level bindings.\n\nmodule Xine.Foreign (\n -- * Version information\n xine_get_version_string, xine_get_version, xine_check_version,\n -- * Global engine handling\n Engine, AudioPort, VideoPort, VisualType(..),\n xine_new, xine_init, xine_open_audio_driver, xine_open_video_driver,\n xine_close_audio_driver, xine_close_video_driver, xine_exit,\n -- * Stream handling\n Stream, StreamParam(..), Speed(..), NormalSpeed(..), Zoom(..),\n AspectRatio(..), MRL, EngineParam(..), Affection(..),\n xine_stream_new, xine_stream_master_slave, xine_open, xine_play,\n xine_stop, xine_close, xine_engine_set_param, xine_engine_get_param,\n xine_set_param, xine_get_param,\n -- * Information retrieval\n EngineStatus(..), XineError(..),\n xine_get_error, xine_get_status\n ) where\n\nimport Control.Monad (liftM)\nimport Data.Bits\nimport Foreign\nimport Foreign.C\n\n#include \n\n-- Define the name of the dynamic library that has to be loaded before any of\n-- the external C functions may be invoked.\n-- The prefix declaration allows us to refer to identifiers while omitting the\n-- prefix. Prefix matching is case insensitive and any underscore characters\n-- between the prefix and the stem of the identifiers are also removed.\n{#context lib=\"xine\" prefix=\"xine\"#}\n\n-- Opaque types used for structures that are never dereferenced on the\n-- Haskell side.\n{#pointer *xine_t as Engine foreign newtype#}\n{#pointer *xine_audio_port_t as AudioPort foreign newtype#}\n{#pointer *xine_video_port_t as VideoPort foreign newtype#}\n{#pointer *xine_stream_t as Stream foreign newtype#}\n\nnewtype Data = Data (Ptr Data)\n\n-- | Media Resource Locator.\n-- Describes the media to read from. Valid MRLs may be plain file names or\n-- one of the following:\n--\n-- * Filesystem:\n--\n-- file:\\\n--\n-- fifo:\\\n--\n-- stdin:\\\/\n--\n-- * CD and DVD:\n--\n-- dvd:\\\/[device_name][\\\/title[.part]]\n--\n-- dvd:\\\/DVD_image_file[\\\/title[.part]]\n--\n-- dvd:\\\/DVD_directory[\\\/title[.part]]\n--\n-- vcd:\\\/\\\/[CD_image_or_device_name][\\@[letter]number]\n--\n-- vcdo:\\\/\\\/track_number\n--\n-- cdda:\\\/[device][\\\/track_number]\n--\n-- * Video devices:\n--\n-- v4l:\\\/\\\/[tuner_device\\\/frequency\n--\n-- v4l2:\\\/\\\/tuner_device\n--\n-- dvb:\\\/\\\/channel_number\n--\n-- dvb:\\\/\\\/channel_name\n--\n-- dvbc:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvbs:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvbt:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvba:\\\/\\\/channel_name:tuning_parameters\n--\n-- pvr:\\\/tmp_files_path!saved_files_path!max_page_age\n--\n-- * Network:\n--\n-- http:\\\/\\\/host\n--\n-- tcp:\\\/\\\/host[:port]\n--\n-- udp:\\\/\\\/host[:port[?iface=interface]]\n--\n-- rtp:\\\/\\\/host[:port[?iface=interface]]\n--\n-- smb:\\\/\\\/\n--\n-- mms:\\\/\\\/host\n--\n-- pnm:\\\/\\\/host\n--\n-- rtsp:\\\/\\\/host\ntype MRL = String\n\n------------------------------------------------------------------------------\n-- Marshalling\n------------------------------------------------------------------------------\n\nint2bool = (\/= 0)\n\ncint2enum :: Enum a => CInt -> a\ncint2enum = toEnum . fromIntegral\n\nenum2cint :: Enum a => a -> CInt\nenum2cint = fromIntegral . fromEnum\n\npeekInt = liftM fromIntegral . peek\n\nmaybeForeignPtr_ c x | x == nullPtr = return Nothing\n | otherwise = (Just . c) `liftM` newForeignPtr_ x\n\npeekEngine = liftM Engine . newForeignPtr_\n\npeekAudioPort = maybeForeignPtr_ AudioPort\n\npeekVideoPort = maybeForeignPtr_ VideoPort\n\npeekStream = maybeForeignPtr_ Stream\n\nwithData f = f nullPtr\n\nwithMaybeString :: Maybe String -> (CString -> IO a) -> IO a\nwithMaybeString Nothing f = f nullPtr\nwithMaybeString (Just s) f = withCString s f\n\n------------------------------------------------------------------------------\n-- Version information\n------------------------------------------------------------------------------\n\n-- | Get xine-lib version string.\n--\n-- Header declaration:\n--\n-- const char *xine_get_version_string (void)\n{#fun pure xine_get_version_string {} -> `String' peekCString*#}\n\n-- | Get version as a triple: major, minor, sub\n--\n-- Header declaration:\n--\n-- void xine_get_version (int *major, int *minor, int *sub)\n{#fun pure xine_get_version\n {alloca- `Int' peekInt*,\n alloca- `Int' peekInt*,\n alloca- `Int' peekInt*} -> `()'#}\n\n-- | Compare given version to xine-lib version (major, minor, sub).\n--\n-- Header declaration:\n--\n-- int xine_check_version (int major, int minor, int sub)\n--\n-- returns 1 if compatible, 0 otherwise.\n{#fun pure xine_check_version\n {fromIntegral `Int',\n fromIntegral `Int',\n fromIntegral `Int'} -> `Bool' int2bool#}\n\n------------------------------------------------------------------------------\n-- Global engine handling\n------------------------------------------------------------------------------\n\n-- | Valid visual types\n{#enum define VisualType {XINE_VISUAL_TYPE_NONE as None\n ,XINE_VISUAL_TYPE_X11 as X11\n ,XINE_VISUAL_TYPE_X11_2 as X11_2\n ,XINE_VISUAL_TYPE_AA as AA\n ,XINE_VISUAL_TYPE_FB as FB\n ,XINE_VISUAL_TYPE_GTK as GTK\n ,XINE_VISUAL_TYPE_DFB as DFB\n ,XINE_VISUAL_TYPE_PM as PM\n ,XINE_VISUAL_TYPE_DIRECTX as DirectX\n ,XINE_VISUAL_TYPE_CACA as CACA\n ,XINE_VISUAL_TYPE_MACOSX as MacOSX\n ,XINE_VISUAL_TYPE_XCB as XCB\n ,XINE_VISUAL_TYPE_RAW as Raw\n }#}\n\n-- | Pre-init the Xine engine.\n--\n-- Header declaration:\n--\n-- xine_t *xine_new (void)\n{#fun unsafe xine_new {} -> `Engine' peekEngine*#}\n\n-- | Post-init the Xine engine.\n--\n-- Header declaration:\n--\n-- void xine_init (xine_t *self)\n{#fun unsafe xine_init {withEngine* `Engine'} -> `()'#}\n\n-- | Initialise audio driver.\n--\n-- Header declaration:\n--\n-- xine_audio_port_t *xine_open_audio_driver (xine_t *self, const char *id,\n-- void *data)\n--\n-- id: identifier of the driver, may be NULL for auto-detection\n--\n-- data: special data struct for ui\/driver communication\n--\n-- May return NULL if the driver failed to load.\n{#fun unsafe xine_open_audio_driver\n {withEngine* `Engine'\n ,withMaybeString* `(Maybe String)'\n ,withData- `Data'} -> `(Maybe AudioPort)' peekAudioPort*#}\n\n-- | Initialise video driver.\n--\n-- Header declaration:\n--\n-- xine_video_port_t *xine_open_video_driver (xine_t *self, const char *id,\n-- int visual, void *data)\n--\n-- id: identifier of the driver, may be NULL for auto-detection\n--\n-- data: special data struct for ui\/driver communication\n--\n-- visual : video driver flavor selector\n--\n-- May return NULL if the driver failed to load.\n{#fun unsafe xine_open_video_driver\n {withEngine* `Engine'\n ,withMaybeString* `(Maybe String)'\n ,enum2cint `VisualType'\n ,withData- `Data'} -> `(Maybe VideoPort)' peekVideoPort*#}\n\n-- | Close audio port.\n--\n-- Header declaration:\n--\n-- void xine_close_audio_driver (xine_t *self, xine_audio_port_t *driver)\n{#fun unsafe xine_close_audio_driver\n {withEngine* `Engine'\n ,withAudioPort* `AudioPort'} -> `()'#}\n\n-- | Close video port.\n--\n-- Header declaration:\n--\n-- void xine_close_video_driver (xine_t *self, xine_video_port_t *driver)\n{#fun unsafe xine_close_video_driver\n {withEngine* `Engine'\n ,withVideoPort* `VideoPort'} -> `()'#}\n\n-- | Free all resources, close all plugins, close engine.\n--\n-- Header declaration:\n--\n-- void xine_exit (xine_t *self)\n{#fun unsafe xine_exit {withEngine* `Engine'} -> `()'#}\n\n------------------------------------------------------------------------------\n-- Stream handling\n------------------------------------------------------------------------------\n\n-- | Engine parameter enumeration.\n{#enum define EngineParam\n {XINE_ENGINE_PARAM_VERBOSITY as EngineVerbosity}#}\n\n-- | Stream parameter enumeration.\n{#enum define StreamParam\n {XINE_PARAM_SPEED as Speed\n ,XINE_PARAM_AV_OFFSET as AvOffset\n ,XINE_PARAM_AUDIO_CHANNEL_LOGICAL as AudioChannelLogical\n ,XINE_PARAM_SPU_CHANNEL as SpuChannel\n ,XINE_PARAM_AUDIO_VOLUME as AudioVolume\n ,XINE_PARAM_AUDIO_MUTE as AudioMute\n ,XINE_PARAM_AUDIO_COMPR_LEVEL as AudioComprLevel\n ,XINE_PARAM_AUDIO_REPORT_LEVEL as AudioReportLevel\n ,XINE_PARAM_VERBOSITY as Verbosity\n ,XINE_PARAM_SPU_OFFSET as SpuOffset\n ,XINE_PARAM_IGNORE_VIDEO as IgnoreVideo\n ,XINE_PARAM_IGNORE_AUDIO as IgnoreAudio\n ,XINE_PARAM_BROADCASTER_PORT as BroadcasterPort\n ,XINE_PARAM_METRONOM_PREBUFFER as MetronomPrebuffer\n ,XINE_PARAM_EQ_30HZ as Eq30Hz\n ,XINE_PARAM_EQ_60HZ as Eq60Hz\n ,XINE_PARAM_EQ_125HZ as Eq125Hz\n ,XINE_PARAM_EQ_500HZ as Eq500Hz\n ,XINE_PARAM_EQ_1000HZ as Eq1000Hz\n ,XINE_PARAM_EQ_2000HZ as Eq2000Hz\n ,XINE_PARAM_EQ_4000HZ as Eq4000Hz\n ,XINE_PARAM_EQ_8000HZ as Eq8000Hz\n ,XINE_PARAM_EQ_16000HZ as Eq16000Hz\n ,XINE_PARAM_AUDIO_CLOSE_DEVICE as AudioCloseDevice\n ,XINE_PARAM_AUDIO_AMP_MUTE as AmpMute\n ,XINE_PARAM_FINE_SPEED as FineSpeed\n ,XINE_PARAM_EARLY_FINISHED_EVENT as EarlyFinishedEvent\n ,XINE_PARAM_GAPLESS_SWITCH as GaplessSwitch\n ,XINE_PARAM_DELAY_FINISHED_EVENT as DelayFinishedEvent\n ,XINE_PARAM_VO_DEINTERLACE as Deinterlace\n ,XINE_PARAM_VO_ASPECT_RATIO as AspectRatio\n ,XINE_PARAM_VO_HUE as Hue\n ,XINE_PARAM_VO_SATURATION as Saturation\n ,XINE_PARAM_VO_CONTRAST as Contrast\n ,XINE_PARAM_VO_BRIGHTNESS as Brightness\n ,XINE_PARAM_VO_ZOOM_X as ZoomX\n ,XINE_PARAM_VO_ZOOM_Y as ZoomY\n ,XINE_PARAM_VO_PAN_SCAN as PanScan\n ,XINE_PARAM_VO_TVMODE as TvMode\n ,XINE_PARAM_VO_WINDOW_WIDTH as WindowWidth\n ,XINE_PARAM_VO_WINDOW_HEIGHT as WindowHeight\n ,XINE_PARAM_VO_CROP_LEFT as CropLeft\n ,XINE_PARAM_VO_CROP_RIGHT as CropRight\n ,XINE_PARAM_VO_CROP_TOP as CropTop\n ,XINE_PARAM_VO_CROP_BOTTOM as CropBottom\n }#}\n\n-- | Values for XINE_PARAM_SPEED parameter.\n{#enum define Speed\n {XINE_SPEED_PAUSE as Pause\n ,XINE_SPEED_SLOW_4 as Slow4\n ,XINE_SPEED_SLOW_2 as Slow2\n ,XINE_SPEED_NORMAL as Normal\n ,XINE_SPEED_FAST_2 as Fast2\n ,XINE_SPEED_FAST_4 as Fast4\n }#}\n\nderiving instance Eq Speed\n\n-- | Value for XINE_PARAM_FINE_SPEED\n{#enum define NormalSpeed\n {XINE_FINE_SPEED_NORMAL as NormalSpeed}#}\n\n-- | Values for XINE_PARAM_VO_ZOOM_\n{#enum define Zoom\n {XINE_VO_ZOOM_STEP as ZoomStep\n ,XINE_VO_ZOOM_MAX as ZoomMax\n ,XINE_VO_ZOOM_MIN as ZoomMin}#}\n\n-- | Values for XINE_PARAM_VO_ASPECT_RATIO\n{#enum define AspectRatio\n {XINE_VO_ASPECT_AUTO as AspectAuto\n ,XINE_VO_ASPECT_SQUARE as AspectSquare\n ,XINE_VO_ASPECT_4_3 as Aspect43\n ,XINE_VO_ASPECT_ANAMORPHIC as AspectAnamorphic\n ,XINE_VO_ASPECT_DVB as AspectDvb\n ,XINE_VO_ASPECT_NUM_RATIOS as AspectNumRatios\n }#}\n\n-- | Create a new stream for media playback.\n--\n-- Header declaration:\n--\n-- xine_stream_t *xine_stream_new (xine_t *self,\n-- xine_audio_port *ao, xine_video_port_t *vo)\n--\n-- Returns xine_stream_t* if OK, NULL on error.\n{#fun unsafe xine_stream_new\n {withEngine* `Engine'\n ,withAudioPort* `AudioPort'\n ,withVideoPort* `VideoPort'} -> `(Maybe Stream)' peekStream*#}\n\n-- | Make one stream the slave of another.\n-- Certain operations on the master stream are also applied to the slave\n-- stream.\n--\n-- Header declaration:\n--\n-- int xine_stream_master_slave (xine_stream_t *master, xine_stream_t *slave,\n-- int affection)\n--\n-- returns 1 on success, 0 on failure.\n{#fun unsafe xine_stream_master_slave\n {withStream* `Stream'\n ,withStream* `Stream'\n ,combineAffection `[Affection]'} -> `Int' fromIntegral#}\n\n-- | The affection determines which actions on the master stream\n-- are also to be applied to the slave stream. See 'xine_stream_master_slave'.\n{#enum define Affection\n {XINE_MASTER_SLAVE_PLAY as AffectionPlay\n ,XINE_MASTER_SLAVE_STOP as AffectionStop\n ,XINE_MASTER_SLAVE_SPEED as AffectionSpeed}#}\n\n-- | Affections can be ORed together.\ncombineAffection :: [Affection] -> CInt\ncombineAffection [] = enum2cint AffectionSpeed\ncombineAffection xs = foldr1 (.&.) (map enum2cint xs)\n\n-- | Open a stream.\n--\n-- Header declaration:\n--\n-- int xine_open (xine_stream_t *stream, const char *mrl)\n--\n-- Returns 1 if OK, 0 on error.\n{#fun unsafe xine_open\n {withStream* `Stream'\n ,withCAString* `MRL'} -> `Int' fromIntegral#}\n\n-- | Play a stream from a given position.\n--\n-- Header declaration:\n--\n-- int xine_play (xine_stream_t *stream, int start_pos, int start_time)\n--\n-- Returns 1 if OK, 0 on error.\n{#fun unsafe xine_play\n {withStream* `Stream'\n ,fromIntegral `Int'\n ,fromIntegral `Int'} -> `Int' fromIntegral#}\n\n-- | Stop stream playback.\n-- The stream stays valid for new 'xine_open' or 'xine_play'.\n--\n-- Header declaration:\n--\n-- void xine_stop (xine_stream *stream)\n{#fun unsafe xine_stop {withStream* `Stream'} -> `()'#}\n\n-- | Free all stream-related resources.\n-- The stream stays valid for new xine_open.\n--\n-- Header declaration:\n--\n-- void xine_close (xine_stream_t *stream)\n{#fun unsafe xine_close {withStream* `Stream'} -> `()'#}\n\n-- | Set engine parameter.\n--\n-- Header declaration:\n--\n-- void xine_engine_set_param (xine_t *self, int param, int value)\n{#fun unsafe xine_engine_set_param\n {withEngine* `Engine'\n ,enum2cint `EngineParam'\n ,fromIntegral `Int'} -> `()'#}\n\n-- | Get engine parameter.\n--\n-- Header declaration:\n--\n-- int xine_engine_get_param(xine_t *self, int param)\n{#fun unsafe xine_engine_get_param\n {withEngine* `Engine'\n ,enum2cint `EngineParam'} -> `Int' fromIntegral#}\n\n-- | Set stream parameter.\n--\n-- Header declaration:\n--\n-- void xine_set_param (xine_stream_t *stream, int param, int value)\n{#fun unsafe xine_set_param\n `(Enum a)' =>\n {withStream* `Stream'\n ,enum2cint `StreamParam'\n ,enum2cint `a'} -> `()'#}\n\n-- | Get stream parameter.\n--\n-- Header declaration:\n--\n-- int xine_get_param (xine_stream_t *stream, int param)\n{#fun unsafe xine_get_param\n `(Enum a)' =>\n {withStream* `Stream'\n ,enum2cint `StreamParam'} -> `a' cint2enum#}\n\n------------------------------------------------------------------------------\n-- Information retrieval\n------------------------------------------------------------------------------\n\n-- | Engine status codes.\n{#enum define EngineStatus\n {XINE_STATUS_IDLE as Idle\n ,XINE_STATUS_STOP as Stopped\n ,XINE_STATUS_PLAY as Playing\n ,XINE_STATUS_QUIT as Quitting}#}\n\nderiving instance Eq EngineStatus\nderiving instance Show EngineStatus\n\n-- | Xine error codes.\n{#enum define XineError\n {XINE_ERROR_NONE as NoError\n ,XINE_ERROR_NO_INPUT_PLUGIN as NoInputPlugin\n ,XINE_ERROR_NO_DEMUX_PLUGIN as NoDemuxPlugin\n ,XINE_ERROR_MALFORMED_MRL as MalformedMrl\n ,XINE_ERROR_INPUT_FAILED as InputFailed}#}\n\nderiving instance Eq XineError\nderiving instance Show XineError\n\n-- | Return last error.\n--\n-- Header declaration:\n--\n-- int xine_get_error (xine_stream_t *stream)\n{#fun unsafe xine_get_error\n {withStream* `Stream'} -> `XineError' cint2enum#}\n\n-- | Get current xine engine status.\n--\n-- int xine_get_status (xine_stream_t *stream)\n{#fun unsafe xine_get_status\n {withStream* `Stream'} -> `EngineStatus' cint2enum#}\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\n-- |\n-- Module : Xine.Foreign\n-- Copyright : (c) Joachim Fasting 2010\n-- License : LGPL\n-- Maintainer : Joachim Fasting \n-- Stability : unstable\n-- Portability : not portable\n--\n-- A simple binding to xine-lib. Low-level bindings.\n\nmodule Xine.Foreign (\n -- * Version information\n xine_get_version_string, xine_get_version, xine_check_version,\n -- * Global engine handling\n Engine, AudioPort, VideoPort, VisualType(..),\n xine_new, xine_init, xine_open_audio_driver, xine_open_video_driver,\n xine_close_audio_driver, xine_close_video_driver, xine_exit,\n -- * Stream handling\n Stream, StreamParam(..), Speed(..), NormalSpeed(..), Zoom(..),\n AspectRatio(..), MRL, EngineParam(..),\n xine_stream_new, xine_open, xine_play, xine_stop, xine_close,\n xine_engine_set_param, xine_engine_get_param,\n xine_set_param, xine_get_param,\n -- * Information retrieval\n EngineStatus(..), XineError(..),\n xine_get_error, xine_get_status\n ) where\n\nimport Control.Monad (liftM)\nimport Foreign\nimport Foreign.C\n\n#include \n\n-- Define the name of the dynamic library that has to be loaded before any of\n-- the external C functions may be invoked.\n-- The prefix declaration allows us to refer to identifiers while omitting the\n-- prefix. Prefix matching is case insensitive and any underscore characters\n-- between the prefix and the stem of the identifiers are also removed.\n{#context lib=\"xine\" prefix=\"xine\"#}\n\n-- Opaque types used for structures that are never dereferenced on the\n-- Haskell side.\n{#pointer *xine_t as Engine foreign newtype#}\n{#pointer *xine_audio_port_t as AudioPort foreign newtype#}\n{#pointer *xine_video_port_t as VideoPort foreign newtype#}\n{#pointer *xine_stream_t as Stream foreign newtype#}\n\nnewtype Data = Data (Ptr Data)\n\n-- | Media Resource Locator.\n-- Describes the media to read from. Valid MRLs may be plain file names or\n-- one of the following:\n--\n-- * Filesystem:\n--\n-- file:\\\n--\n-- fifo:\\\n--\n-- stdin:\\\/\n--\n-- * CD and DVD:\n--\n-- dvd:\\\/[device_name][\\\/title[.part]]\n--\n-- dvd:\\\/DVD_image_file[\\\/title[.part]]\n--\n-- dvd:\\\/DVD_directory[\\\/title[.part]]\n--\n-- vcd:\\\/\\\/[CD_image_or_device_name][\\@[letter]number]\n--\n-- vcdo:\\\/\\\/track_number\n--\n-- cdda:\\\/[device][\\\/track_number]\n--\n-- * Video devices:\n--\n-- v4l:\\\/\\\/[tuner_device\\\/frequency\n--\n-- v4l2:\\\/\\\/tuner_device\n--\n-- dvb:\\\/\\\/channel_number\n--\n-- dvb:\\\/\\\/channel_name\n--\n-- dvbc:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvbs:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvbt:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvba:\\\/\\\/channel_name:tuning_parameters\n--\n-- pvr:\\\/tmp_files_path!saved_files_path!max_page_age\n--\n-- * Network:\n--\n-- http:\\\/\\\/host\n--\n-- tcp:\\\/\\\/host[:port]\n--\n-- udp:\\\/\\\/host[:port[?iface=interface]]\n--\n-- rtp:\\\/\\\/host[:port[?iface=interface]]\n--\n-- smb:\\\/\\\/\n--\n-- mms:\\\/\\\/host\n--\n-- pnm:\\\/\\\/host\n--\n-- rtsp:\\\/\\\/host\ntype MRL = String\n\n------------------------------------------------------------------------------\n-- Marshalling\n------------------------------------------------------------------------------\n\nint2bool = (\/= 0)\n\ncint2enum :: Enum a => CInt -> a\ncint2enum = toEnum . fromIntegral\n\nenum2cint :: Enum a => a -> CInt\nenum2cint = fromIntegral . fromEnum\n\npeekInt = liftM fromIntegral . peek\n\nmaybeForeignPtr_ c x | x == nullPtr = return Nothing\n | otherwise = (Just . c) `liftM` newForeignPtr_ x\n\npeekEngine = liftM Engine . newForeignPtr_\n\npeekAudioPort = maybeForeignPtr_ AudioPort\n\npeekVideoPort = maybeForeignPtr_ VideoPort\n\npeekStream = maybeForeignPtr_ Stream\n\nwithData f = f nullPtr\n\nwithMaybeString :: Maybe String -> (CString -> IO a) -> IO a\nwithMaybeString Nothing f = f nullPtr\nwithMaybeString (Just s) f = withCString s f\n\n------------------------------------------------------------------------------\n-- Version information\n------------------------------------------------------------------------------\n\n-- | Get xine-lib version string.\n--\n-- Header declaration:\n--\n-- const char *xine_get_version_string (void)\n{#fun pure xine_get_version_string {} -> `String' peekCString*#}\n\n-- | Get version as a triple: major, minor, sub\n--\n-- Header declaration:\n--\n-- void xine_get_version (int *major, int *minor, int *sub)\n{#fun pure xine_get_version\n {alloca- `Int' peekInt*,\n alloca- `Int' peekInt*,\n alloca- `Int' peekInt*} -> `()'#}\n\n-- | Compare given version to xine-lib version (major, minor, sub).\n--\n-- Header declaration:\n--\n-- int xine_check_version (int major, int minor, int sub)\n--\n-- returns 1 if compatible, 0 otherwise.\n{#fun pure xine_check_version\n {fromIntegral `Int',\n fromIntegral `Int',\n fromIntegral `Int'} -> `Bool' int2bool#}\n\n------------------------------------------------------------------------------\n-- Global engine handling\n------------------------------------------------------------------------------\n\n-- | Valid visual types\n{#enum define VisualType {XINE_VISUAL_TYPE_NONE as None\n ,XINE_VISUAL_TYPE_X11 as X11\n ,XINE_VISUAL_TYPE_X11_2 as X11_2\n ,XINE_VISUAL_TYPE_AA as AA\n ,XINE_VISUAL_TYPE_FB as FB\n ,XINE_VISUAL_TYPE_GTK as GTK\n ,XINE_VISUAL_TYPE_DFB as DFB\n ,XINE_VISUAL_TYPE_PM as PM\n ,XINE_VISUAL_TYPE_DIRECTX as DirectX\n ,XINE_VISUAL_TYPE_CACA as CACA\n ,XINE_VISUAL_TYPE_MACOSX as MacOSX\n ,XINE_VISUAL_TYPE_XCB as XCB\n ,XINE_VISUAL_TYPE_RAW as Raw\n }#}\n\n-- | Pre-init the Xine engine.\n--\n-- Header declaration:\n--\n-- xine_t *xine_new (void)\n{#fun unsafe xine_new {} -> `Engine' peekEngine*#}\n\n-- | Post-init the Xine engine.\n--\n-- Header declaration:\n--\n-- void xine_init (xine_t *self)\n{#fun unsafe xine_init {withEngine* `Engine'} -> `()'#}\n\n-- | Initialise audio driver.\n--\n-- Header declaration:\n--\n-- xine_audio_port_t *xine_open_audio_driver (xine_t *self, const char *id,\n-- void *data)\n--\n-- id: identifier of the driver, may be NULL for auto-detection\n--\n-- data: special data struct for ui\/driver communication\n--\n-- May return NULL if the driver failed to load.\n{#fun unsafe xine_open_audio_driver\n {withEngine* `Engine'\n ,withMaybeString* `(Maybe String)'\n ,withData- `Data'} -> `(Maybe AudioPort)' peekAudioPort*#}\n\n-- | Initialise video driver.\n--\n-- Header declaration:\n--\n-- xine_video_port_t *xine_open_video_driver (xine_t *self, const char *id,\n-- int visual, void *data)\n--\n-- id: identifier of the driver, may be NULL for auto-detection\n--\n-- data: special data struct for ui\/driver communication\n--\n-- visual : video driver flavor selector\n--\n-- May return NULL if the driver failed to load.\n{#fun unsafe xine_open_video_driver\n {withEngine* `Engine'\n ,withMaybeString* `(Maybe String)'\n ,enum2cint `VisualType'\n ,withData- `Data'} -> `(Maybe VideoPort)' peekVideoPort*#}\n\n-- | Close audio port.\n--\n-- Header declaration:\n--\n-- void xine_close_audio_driver (xine_t *self, xine_audio_port_t *driver)\n{#fun unsafe xine_close_audio_driver\n {withEngine* `Engine'\n ,withAudioPort* `AudioPort'} -> `()'#}\n\n-- | Close video port.\n--\n-- Header declaration:\n--\n-- void xine_close_video_driver (xine_t *self, xine_video_port_t *driver)\n{#fun unsafe xine_close_video_driver\n {withEngine* `Engine'\n ,withVideoPort* `VideoPort'} -> `()'#}\n\n-- | Free all resources, close all plugins, close engine.\n--\n-- Header declaration:\n--\n-- void xine_exit (xine_t *self)\n{#fun unsafe xine_exit {withEngine* `Engine'} -> `()'#}\n\n------------------------------------------------------------------------------\n-- Stream handling\n------------------------------------------------------------------------------\n\n-- | Engine parameter enumeration.\n{#enum define EngineParam\n {XINE_ENGINE_PARAM_VERBOSITY as EngineVerbosity}#}\n\n-- | Stream parameter enumeration.\n{#enum define StreamParam\n {XINE_PARAM_SPEED as Speed\n ,XINE_PARAM_AV_OFFSET as AvOffset\n ,XINE_PARAM_AUDIO_CHANNEL_LOGICAL as AudioChannelLogical\n ,XINE_PARAM_SPU_CHANNEL as SpuChannel\n ,XINE_PARAM_AUDIO_VOLUME as AudioVolume\n ,XINE_PARAM_AUDIO_MUTE as AudioMute\n ,XINE_PARAM_AUDIO_COMPR_LEVEL as AudioComprLevel\n ,XINE_PARAM_AUDIO_REPORT_LEVEL as AudioReportLevel\n ,XINE_PARAM_VERBOSITY as Verbosity\n ,XINE_PARAM_SPU_OFFSET as SpuOffset\n ,XINE_PARAM_IGNORE_VIDEO as IgnoreVideo\n ,XINE_PARAM_IGNORE_AUDIO as IgnoreAudio\n ,XINE_PARAM_BROADCASTER_PORT as BroadcasterPort\n ,XINE_PARAM_METRONOM_PREBUFFER as MetronomPrebuffer\n ,XINE_PARAM_EQ_30HZ as Eq30Hz\n ,XINE_PARAM_EQ_60HZ as Eq60Hz\n ,XINE_PARAM_EQ_125HZ as Eq125Hz\n ,XINE_PARAM_EQ_500HZ as Eq500Hz\n ,XINE_PARAM_EQ_1000HZ as Eq1000Hz\n ,XINE_PARAM_EQ_2000HZ as Eq2000Hz\n ,XINE_PARAM_EQ_4000HZ as Eq4000Hz\n ,XINE_PARAM_EQ_8000HZ as Eq8000Hz\n ,XINE_PARAM_EQ_16000HZ as Eq16000Hz\n ,XINE_PARAM_AUDIO_CLOSE_DEVICE as AudioCloseDevice\n ,XINE_PARAM_AUDIO_AMP_MUTE as AmpMute\n ,XINE_PARAM_FINE_SPEED as FineSpeed\n ,XINE_PARAM_EARLY_FINISHED_EVENT as EarlyFinishedEvent\n ,XINE_PARAM_GAPLESS_SWITCH as GaplessSwitch\n ,XINE_PARAM_DELAY_FINISHED_EVENT as DelayFinishedEvent\n ,XINE_PARAM_VO_DEINTERLACE as Deinterlace\n ,XINE_PARAM_VO_ASPECT_RATIO as AspectRatio\n ,XINE_PARAM_VO_HUE as Hue\n ,XINE_PARAM_VO_SATURATION as Saturation\n ,XINE_PARAM_VO_CONTRAST as Contrast\n ,XINE_PARAM_VO_BRIGHTNESS as Brightness\n ,XINE_PARAM_VO_ZOOM_X as ZoomX\n ,XINE_PARAM_VO_ZOOM_Y as ZoomY\n ,XINE_PARAM_VO_PAN_SCAN as PanScan\n ,XINE_PARAM_VO_TVMODE as TvMode\n ,XINE_PARAM_VO_WINDOW_WIDTH as WindowWidth\n ,XINE_PARAM_VO_WINDOW_HEIGHT as WindowHeight\n ,XINE_PARAM_VO_CROP_LEFT as CropLeft\n ,XINE_PARAM_VO_CROP_RIGHT as CropRight\n ,XINE_PARAM_VO_CROP_TOP as CropTop\n ,XINE_PARAM_VO_CROP_BOTTOM as CropBottom\n }#}\n\n-- | Values for XINE_PARAM_SPEED parameter.\n{#enum define Speed\n {XINE_SPEED_PAUSE as Pause\n ,XINE_SPEED_SLOW_4 as Slow4\n ,XINE_SPEED_SLOW_2 as Slow2\n ,XINE_SPEED_NORMAL as Normal\n ,XINE_SPEED_FAST_2 as Fast2\n ,XINE_SPEED_FAST_4 as Fast4\n }#}\n\nderiving instance Eq Speed\n\n-- | Value for XINE_PARAM_FINE_SPEED\n{#enum define NormalSpeed\n {XINE_FINE_SPEED_NORMAL as NormalSpeed}#}\n\n-- | Values for XINE_PARAM_VO_ZOOM_\n{#enum define Zoom\n {XINE_VO_ZOOM_STEP as ZoomStep\n ,XINE_VO_ZOOM_MAX as ZoomMax\n ,XINE_VO_ZOOM_MIN as ZoomMin}#}\n\n-- | Values for XINE_PARAM_VO_ASPECT_RATIO\n{#enum define AspectRatio\n {XINE_VO_ASPECT_AUTO as AspectAuto\n ,XINE_VO_ASPECT_SQUARE as AspectSquare\n ,XINE_VO_ASPECT_4_3 as Aspect43\n ,XINE_VO_ASPECT_ANAMORPHIC as AspectAnamorphic\n ,XINE_VO_ASPECT_DVB as AspectDvb\n ,XINE_VO_ASPECT_NUM_RATIOS as AspectNumRatios\n }#}\n\n-- | Create a new stream for media playback.\n--\n-- Header declaration:\n--\n-- xine_stream_t *xine_stream_new (xine_t *self,\n-- xine_audio_port *ao, xine_video_port_t *vo)\n--\n-- Returns xine_stream_t* if OK, NULL on error.\n{#fun unsafe xine_stream_new\n {withEngine* `Engine'\n ,withAudioPort* `AudioPort'\n ,withVideoPort* `VideoPort'} -> `(Maybe Stream)' peekStream*#}\n\n-- | Open a stream.\n--\n-- Header declaration:\n--\n-- int xine_open (xine_stream_t *stream, const char *mrl)\n--\n-- Returns 1 if OK, 0 on error.\n{#fun unsafe xine_open\n {withStream* `Stream'\n ,withCAString* `MRL'} -> `Int' fromIntegral#}\n\n-- | Play a stream from a given position.\n--\n-- Header declaration:\n--\n-- int xine_play (xine_stream_t *stream, int start_pos, int start_time)\n--\n-- Returns 1 if OK, 0 on error.\n{#fun unsafe xine_play\n {withStream* `Stream'\n ,fromIntegral `Int'\n ,fromIntegral `Int'} -> `Int' fromIntegral#}\n\n-- | Stop stream playback.\n-- The stream stays valid for new 'xine_open' or 'xine_play'.\n--\n-- Header declaration:\n--\n-- void xine_stop (xine_stream *stream)\n{#fun unsafe xine_stop {withStream* `Stream'} -> `()'#}\n\n-- | Free all stream-related resources.\n-- The stream stays valid for new xine_open.\n--\n-- Header declaration:\n--\n-- void xine_close (xine_stream_t *stream)\n{#fun unsafe xine_close {withStream* `Stream'} -> `()'#}\n\n-- | Set engine parameter.\n--\n-- Header declaration:\n--\n-- void xine_engine_set_param (xine_t *self, int param, int value)\n{#fun unsafe xine_engine_set_param\n {withEngine* `Engine'\n ,enum2cint `EngineParam'\n ,fromIntegral `Int'} -> `()'#}\n\n-- | Get engine parameter.\n--\n-- Header declaration:\n--\n-- int xine_engine_get_param(xine_t *self, int param)\n{#fun unsafe xine_engine_get_param\n {withEngine* `Engine'\n ,enum2cint `EngineParam'} -> `Int' fromIntegral#}\n\n-- | Set stream parameter.\n--\n-- Header declaration:\n--\n-- void xine_set_param (xine_stream_t *stream, int param, int value)\n{#fun unsafe xine_set_param\n `(Enum a)' =>\n {withStream* `Stream'\n ,enum2cint `StreamParam'\n ,enum2cint `a'} -> `()'#}\n\n-- | Get stream parameter.\n--\n-- Header declaration:\n--\n-- int xine_get_param (xine_stream_t *stream, int param)\n{#fun unsafe xine_get_param\n `(Enum a)' =>\n {withStream* `Stream'\n ,enum2cint `StreamParam'} -> `a' cint2enum#}\n\n------------------------------------------------------------------------------\n-- Information retrieval\n------------------------------------------------------------------------------\n\n-- | Engine status codes.\n{#enum define EngineStatus\n {XINE_STATUS_IDLE as Idle\n ,XINE_STATUS_STOP as Stopped\n ,XINE_STATUS_PLAY as Playing\n ,XINE_STATUS_QUIT as Quitting}#}\n\nderiving instance Eq EngineStatus\nderiving instance Show EngineStatus\n\n-- | Xine error codes.\n{#enum define XineError\n {XINE_ERROR_NONE as NoError\n ,XINE_ERROR_NO_INPUT_PLUGIN as NoInputPlugin\n ,XINE_ERROR_NO_DEMUX_PLUGIN as NoDemuxPlugin\n ,XINE_ERROR_MALFORMED_MRL as MalformedMrl\n ,XINE_ERROR_INPUT_FAILED as InputFailed}#}\n\nderiving instance Eq XineError\nderiving instance Show XineError\n\n-- | Return last error.\n--\n-- Header declaration:\n--\n-- int xine_get_error (xine_stream_t *stream)\n{#fun unsafe xine_get_error\n {withStream* `Stream'} -> `XineError' cint2enum#}\n\n-- | Get current xine engine status.\n--\n-- int xine_get_status (xine_stream_t *stream)\n{#fun unsafe xine_get_status\n {withStream* `Stream'} -> `EngineStatus' cint2enum#}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"9530d57061702003cde5482bde784f769d8700b7","subject":"Fix tokenize, it doesn't dereference the array","message":"Fix tokenize, it doesn't dereference the array\n","repos":"chetant\/LibClang,chetant\/LibClang,chetant\/LibClang,chetant\/LibClang","old_file":"src\/Clang\/Internal\/FFI.chs","new_file":"src\/Clang\/Internal\/FFI.chs","new_contents":"{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-matches #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE CPP #-}\n\nmodule Clang.Internal.FFI\n( versionMajor\n, versionMinor\n, encodedVersion\n, Index\n, createIndex\n, GlobalIndexOptions(..)\n, threadBackgroundPriorityForAll\n, cXIndex_setGlobalOptions\n, cXIndex_getGlobalOptions\n, TranslationUnit\n, UnsavedFile\n, unsavedFilename\n, unsavedContents\n, newUnsavedFile\n, updateUnsavedContents\n, AvailabilityKind(..)\n, Version(..)\n, ClangString\n, getString\n, getByteString\n, unsafeGetByteString\n, File(..)\n, getFileName\n, getFileTime\n, UniqueId(..)\n, getFileUniqueID\n, isFileMultipleIncludeGuarded\n, getFile\n, SourceLocation\n, getNullLocation\n, equalLocations\n, getLocation\n, getLocationForOffset\n, location_isInSystemHeader\n, location_isFromMainFile\n, SourceRange\n, getNullRange\n, getRange\n, equalRanges\n, range_isNull\n, getExpansionLocation\n, getPresumedLocation\n, getSpellingLocation\n, getFileLocation\n, getRangeStart\n, getRangeEnd\n, Severity(..)\n, Diagnostic\n, DiagnosticSet\n, getNumDiagnosticsInSet\n, getDiagnosticInSet\n, LoadError(..)\n, loadDiagnostics\n, getChildDiagnostics\n, getNumDiagnostics\n, getDiagnostic\n, getDiagnosticSetFromTU\n, DisplayOptions(..)\n, formatDiagnostic\n, defaultDiagnosticDisplayOptions\n, getDiagnosticSeverity\n, getDiagnosticLocation\n, getDiagnosticSpelling\n, getDiagnosticOption\n, getDiagnosticCategory\n, getDiagnosticCategoryText\n, getDiagnosticNumRanges\n, getDiagnosticRange\n, getDiagnosticNumFixIts\n, getDiagnosticFixIt\n, getTranslationUnitSpelling\n, createTranslationUnitFromSourceFile\n, createTranslationUnit\n, TranslationUnitFlags(..)\n, defaultEditingTranslationUnitOptions\n, parseTranslationUnit\n, SaveTranslationUnitFlags(..)\n, defaultSaveOptions\n, saveTranslationUnit\n, ReparseFlags(..)\n, defaultReparseOptions\n, reparseTranslationUnit\n, CursorKind(..)\n, firstDeclCursor\n, lastDeclCursor\n, firstRefCursor\n, lastRefCursor\n, firstInvalidCursor\n, lastInvalidCursor\n, firstExprCursor\n, lastExprCursor\n, firstStmtCursor\n, lastStmtCursor\n, firstAttrCursor\n, lastAttrCursor\n, firstPreprocessingCursor\n, lastPreprocessingCursor\n, firstExtraDeclCursor\n, lastExtraDeclCursor\n, gccAsmStmtCursor\n, macroInstantiationCursor\n, Comment(..)\n, Cursor\n, getNullCursor\n, getTranslationUnitCursor\n, cursor_isNull\n, hashCursor\n, getCursorKind\n, isDeclaration\n, isReference\n, isExpression\n, isStatement\n, isAttribute\n, isInvalid\n, isTranslationUnit\n, isPreprocessing\n, isUnexposed\n, LinkageKind(..)\n, getCursorLinkage\n, getCursorAvailability\n, PlatformAvailability(..)\n, PlatformAvailabilityInfo(..)\n, getCursorPlatformAvailability\n, LanguageKind(..)\n, getCursorLanguage\n, cursor_getTranslationUnit\n, CursorSet\n, createCXCursorSet\n, cXCursorSet_contains\n, cXCursorSet_insert\n, getCursorSemanticParent\n, getCursorLexicalParent\n, getOverriddenCursors\n, getIncludedFile\n, getCursor\n, getCursorLocation\n, getCursorSpellingLocation\n, getCursorExtent\n, TypeKind(..)\n, type_FirstBuiltin\n, type_LastBuiltin\n, CallingConv(..)\n, Type\n, getTypeKind\n, getCursorType\n, getTypeSpelling\n, getTypedefDeclUnderlyingType\n, getEnumDeclIntegerType\n, getEnumConstantDeclValue\n, getEnumConstantDeclUnsignedValue\n, getFieldDeclBitWidth\n, cursor_getNumArguments\n, cursor_getArgument\n, equalTypes\n, getCanonicalType\n, isConstQualifiedType\n, isVolatileQualifiedType\n, isRestrictQualifiedType\n, getPointeeType\n, getTypeDeclaration\n, getDeclObjCTypeEncoding\n, getTypeKindSpelling\n, getFunctionTypeCallingConv\n, getResultType\n, getNumArgTypes\n, getArgType\n, isFunctionTypeVariadic\n, getCursorResultType\n, isPODType\n, getElementType\n, getNumElements\n, getArrayElementType\n, getArraySize\n, TypeLayoutError(..)\n, type_getAlignOf\n, type_getClassType\n, type_getSizeOf\n, type_getOffsetOf\n, RefQualifierKind(..)\n, type_getCXXRefQualifier\n, isBitField\n, isVirtualBase\n, CXXAccessSpecifier(..)\n, getCXXAccessSpecifier\n, getNumOverloadedDecls\n, getOverloadedDecl\n, getIBOutletCollectionType\n, CursorList\n, getChildren\n, getDescendants\n, getDeclarations\n, getReferences\n, getDeclarationsAndReferences\n, ParentedCursor(..)\n, ParentedCursorList\n, getParentedDescendants\n, getParentedDeclarations\n, getParentedReferences\n, getParentedDeclarationsAndReferences\n, getCursorUSR\n, constructUSR_ObjCClass\n, constructUSR_ObjCCategory\n, constructUSR_ObjCProtocol\n, constructUSR_ObjCIvar\n, constructUSR_ObjCMethod\n, constructUSR_ObjCProperty\n, getCursorSpelling\n, cursor_getSpellingNameRange\n, getCursorDisplayName\n, getCursorReferenced\n, getCursorDefinition\n, isCursorDefinition\n, cursor_isDynamicCall\n, getCanonicalCursor\n, cursor_getObjCSelectorIndex\n, cursor_getReceiverType\n, ObjCPropertyAttrKind(..)\n, cursor_getObjCPropertyAttributes\n, ObjCDeclQualifierKind(..)\n, cursor_getObjCDeclQualifiers\n, cursor_isObjCOptional\n, cursor_isVariadic\n, cursor_getCommentRange\n, cursor_getRawCommentText\n, cursor_getBriefCommentText\n, cursor_getParsedComment\n, Module(..)\n, cursor_getModule\n, module_getASTFile\n, module_getParent\n, module_getName\n, module_getFullName\n, module_getNumTopLevelHeaders\n, module_getTopLevelHeader\n, cXXMethod_isPureVirtual\n, cXXMethod_isStatic\n, cXXMethod_isVirtual\n, getTemplateCursorKind\n, getSpecializedCursorTemplate\n, getCursorReferenceNameRange\n, NameRefFlags(..)\n, CommentKind(..)\n, InlineCommandRenderStyle(..)\n, ParamPassDirectionKind(..)\n, comment_getKind\n, comment_getNumChildren\n, comment_getChild\n, comment_isWhitespace\n, inlineContentComment_hasTrailingNewline\n, textComment_getText\n, inlineCommandComment_getCommandName\n, inlineCommandComment_getRenderKind\n, inlineCommandComment_getNumArgs\n, inlineCommandComment_getArgText\n, hTMLTagComment_getTagName\n, hTMLStartTagComment_isSelfClosing\n, hTMLStartTag_getNumAttrs\n, hTMLStartTag_getAttrName\n, hTMLStartTag_getAttrValue\n, blockCommandComment_getCommandName\n, blockCommandComment_getNumArgs\n, blockCommandComment_getArgText\n, blockCommandComment_getParagraph\n, paramCommandComment_getParamName\n, paramCommandComment_isParamIndexValid\n, paramCommandComment_getParamIndex\n, paramCommandComment_isDirectionExplicit\n, paramCommandComment_getDirection\n, tParamCommandComment_getParamName\n, tParamCommandComment_isParamPositionValid\n, tParamCommandComment_getDepth\n, tParamCommandComment_getIndex\n, verbatimBlockLineComment_getText\n, verbatimLineComment_getText\n, hTMLTagComment_getAsString\n, fullComment_getAsHTML\n, fullComment_getAsXML\n, TokenKind(..)\n, Token\n, TokenList\n, getTokenKind\n, getTokenSpelling\n, getTokenLocation\n, getTokenExtent\n, tokenize\n, annotateTokens\n, getCursorKindSpelling\n, enableStackTraces\n, CompletionString\n, CompletionResult\n, ChunkKind(..)\n, getCompletionChunkKind\n, getCompletionChunkText\n, getCompletionChunkCompletionString\n, getNumCompletionChunks\n, getCompletionPriority\n, getCompletionAvailability\n, getCompletionNumAnnotations\n, getCompletionAnnotation\n, getCompletionParent\n, getCompletionBriefComment\n, getCursorCompletionString\n, CodeCompleteFlags(..)\n, defaultCodeCompleteOptions\n, CodeCompleteResults\n, codeCompleteAt\n, codeCompleteGetNumResults\n, codeCompleteGetResult\n, sortCodeCompletionResults\n, codeCompleteGetNumDiagnostics\n, codeCompleteGetDiagnostic\n, CompletionContext(..)\n, codeCompleteGetContexts\n, codeCompleteGetContainerKind\n, codeCompleteGetContainerUSR\n, codeCompleteGetObjCSelector\n, getClangVersion\n, toggleCrashRecovery\n, Inclusion(..)\n, InclusionList\n, getInclusions\n, Remapping\n, getRemappings\n, getRemappingsFromFileList\n, remap_getNumFiles\n, remap_getFilenames\n) where\n\nimport Control.Applicative\nimport Control.Monad (forM_)\nimport Control.Monad.Trans\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Unsafe as BU\nimport Data.Hashable\nimport Data.Typeable (Typeable)\nimport qualified Data.Vector as DV\nimport qualified Data.Vector.Storable as DVS\nimport qualified Data.Vector.Storable.Mutable as DVSM\nimport Data.Word\nimport Foreign.C\nimport Foreign\nimport Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)\nimport Unsafe.Coerce (unsafeCoerce) -- With GHC 7.8 we can use the safer 'coerce'.\nimport System.IO.Unsafe(unsafePerformIO)\n\nimport Clang.Internal.BitFlags\nimport Clang.Internal.FFIConstants\nimport Clang.Internal.Monad\n\n#include \n#include \n#include \n#include \n#include \n#include \"utils.h\"\n#include \"visitors.h\"\n#include \"wrappers.h\"\n\n{-\nLibClang uses two strategies to create safe, deterministic\nbindings.\n\nFirst, all types that either represent resources managed on the C side\n(for example, TranslationUnit and ClangString) or contain pointers into\nthose resources (for example, Cursor) are tagged with an ST-like\nuniversally quantified phantom type parameter. This prevents them from\nbeing used outside of the scope in which they were allocated. This is\nparticularly important for libclang, which uses an arena allocator to\nstore much of its data; preventing resources from leaking outside\ntheir proper scope is critical to making this safe.\n\nSecond, all operations that allocate a resource that later\nneeds to be freed are wrapped in a type-specific 'register'\nfunction. An example is registerClangString. This function registers a\ncleanup action with the underlying ClangT monad, which is essentially\njust ResourceT in disguise. This not only provides safety, but it also\nenforces prompt finalization of resources which can significantly\nincrease performance by keeping the working set of user programs down.\n\nThere are a few different patterns for the FFI code, depending on what\nkind of value the libclang function we want to wrap returns.\n\nIf it returns a pure value (say an Int), then we don't need to do\nanything special. The greencard-generated function will have a return\ntype of IO Int, and the user-facing wrapper function will use liftIO\nto call it.\n\nIf it returns a value that doesn't represent a newly allocated\nresource, but does need the phantom type parameter (because it\ncontains a pointer into some other resource, generally), then we\ngenerally pass a Proxy value with a type parameter that we'll use to\ntag the return type. This has no runtime cost. The user-facing wrapper\nfunction still needs to call liftIO.\n\nFor values that DO represent a newly allocated resource, we need to\ncall the appropriate 'register' function. This function will return a\nvalue in the ClangT monad, so user-facing wrapper functions don't need\nto use liftIO or Proxy in this case. It's the convention to use '()' for the\nphantom type parameter returned from the greencard-generated function,\nand allow the 'register' function to coerce the value to the correct\ntype. This way we can distinguish values that need to be registered\nfrom other values: if a value's phantom type parameter is '()', it\nneeds to be registered, and it won't typecheck as the return value of\na user-facing wrapper function.\n\nIt's important to keep in mind that it should be legal to use values\nfrom enclosing scopes in an inner scope created by clangScope. In\npractice, this means that the phantom type parameters used by each\nargument to a function should be distinct, and they should all be\ndistinct from the phantom type parameter used in the return value.\nOf course, this doesn't apply to the Proxy parameter, which must\nalways have the same phantom type parameter as the return value.\n-}\n\n-- Marshalling utility functions.\nfromCInt :: Num b => CInt -> b\nfromCInt = fromIntegral\n\ntoCInt :: Integral a => a -> CInt\ntoCInt = fromIntegral\n\n-- Version information.\nversionMajor :: Int\nversionMajor = {# const CINDEX_VERSION_MAJOR #}\nversionMinor :: Int\nversionMinor = {# const CINDEX_VERSION_MINOR #}\nencodedVersion :: Int\nencodedVersion = {# const CINDEX_VERSION #}\n\n-- typedef void *CXIndex;\nnewtype Index s = Index { unIndex :: Ptr () }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue Index\n\nmkIndex :: Ptr () -> Index ()\nmkIndex = Index\n\n-- CXIndex clang_createIndex(int excludeDeclarationsFromPCH, int displayDiagnostics);\n{# fun clang_createIndex { `CInt', `CInt' } -> `Ptr ()' #}\nunsafe_createIndex :: Bool -> Bool -> IO (Index ())\nunsafe_createIndex a b = clang_createIndex (fromBool a) (fromBool b) >>= return . mkIndex\n\ncreateIndex :: ClangBase m => Bool -> Bool -> ClangT s m (Index s)\ncreateIndex = (registerIndex .) . unsafe_createIndex\n\n\n-- void clang_disposeIndex(CXIndex index);\n{# fun clang_disposeIndex { `Ptr ()' } -> `()' #}\ndisposeIndex :: Index s -> IO ()\ndisposeIndex index = clang_disposeIndex (unIndex index)\n\nregisterIndex :: ClangBase m => IO (Index ()) -> ClangT s m (Index s)\nregisterIndex action = do\n (_, idx) <- clangAllocate (action >>= return . unsafeCoerce)\n (\\i -> disposeIndex i)\n return idx\n{-# INLINEABLE registerIndex #-}\n\n-- typedef enum {\n-- CXGlobalOpt_None = 0x0,\n-- CXGlobalOpt_ThreadBackgroundPriorityForIndexing = 0x1,\n-- CXGlobalOpt_ThreadBackgroundPriorityForEditing = 0x2,\n-- CXGlobalOpt_ThreadBackgroundPriorityForAll =\n-- CXGlobalOpt_ThreadBackgroundPriorityForIndexing |\n-- CXGlobalOpt_ThreadBackgroundPriorityForEditing\n--\n-- } CXGlobalOptFlags;\n\n-- | Options that apply globally to every translation unit within an index.\n#c\nenum GlobalIndexOptions\n { DefaultGlobalIndexOptions = CXGlobalOpt_None\n , ThreadBackgroundPriorityForIndexing = CXGlobalOpt_ThreadBackgroundPriorityForIndexing\n , ThreadBackgroundPriorityForEditing = CXGlobalOpt_ThreadBackgroundPriorityForEditing\n };\n#endc\n{# enum GlobalIndexOptions{} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags GlobalIndexOptions where\n toBit DefaultGlobalIndexOptions = 0x0\n toBit ThreadBackgroundPriorityForIndexing = 0x1\n toBit ThreadBackgroundPriorityForEditing = 0x2\n\n-- | A set of global index options that requests background priority for all threads.\nthreadBackgroundPriorityForAll :: [GlobalIndexOptions]\nthreadBackgroundPriorityForAll = [ThreadBackgroundPriorityForEditing,\n ThreadBackgroundPriorityForIndexing]\n\n-- void clang_CXIndex_setGlobalOptions(CXIndex, unsigned options);\n{# fun clang_CXIndex_setGlobalOptions { `Ptr ()', `Int' } -> `()' #}\ncXIndex_setGlobalOptions :: Index s -> Int -> IO ()\ncXIndex_setGlobalOptions index options = clang_CXIndex_setGlobalOptions (unIndex index) options\n\n-- unsigned clang_CXIndex_getGlobalOptions(CXIndex);\n{# fun clang_CXIndex_getGlobalOptions { `Ptr ()' } -> `Int' #}\ncXIndex_getGlobalOptions :: Index s -> IO Int\ncXIndex_getGlobalOptions index = clang_CXIndex_getGlobalOptions (unIndex index)\n\n-- typedef struct CXTranslationUnitImpl *CXTranslationUnit;\nnewtype TranslationUnit s = TranslationUnit { unTranslationUnit :: (Ptr ()) }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue TranslationUnit\n\nmkTranslationUnit :: Ptr () -> TranslationUnit ()\nmkTranslationUnit = TranslationUnit\n\n-- void clang_disposeTranslationUnit(CXTranslationUnit);\n{# fun clang_disposeTranslationUnit { `Ptr ()' } -> `()' #}\ndisposeTranslationUnit :: TranslationUnit s -> IO ()\ndisposeTranslationUnit t = clang_disposeTranslationUnit (unTranslationUnit t)\n\nregisterTranslationUnit :: ClangBase m => IO (TranslationUnit ())\n -> ClangT s m (TranslationUnit s)\nregisterTranslationUnit action = do\n (_, tu) <- clangAllocate (action >>= return . unsafeCoerce)\n (\\t -> disposeTranslationUnit t)\n return tu\n{-# INLINEABLE registerTranslationUnit #-}\n\n-- struct CXUnsavedFile {\n-- const char* Filename;\n-- const char* Contents;\n-- unsigned long Length;\n-- };\n\n-- | A representation of an unsaved file and its contents.\ndata UnsavedFile = UnsavedFile\n { _unsavedFilename :: !B.ByteString\n , _unsavedContents :: !B.ByteString\n } deriving (Eq, Show, Typeable)\n\n-- We maintain the invariant that _unsavedFilename is always\n-- null-terminated. That's why we don't directly expose the record fields.\nunsavedFilename :: UnsavedFile -> B.ByteString\nunsavedFilename = _unsavedFilename\n\nunsavedContents :: UnsavedFile -> B.ByteString\nunsavedContents = _unsavedContents\n\nnewUnsavedFile :: B.ByteString -> B.ByteString -> UnsavedFile\nnewUnsavedFile f c = UnsavedFile (nullTerminate f) c\n\nupdateUnsavedContents :: UnsavedFile -> B.ByteString -> UnsavedFile\nupdateUnsavedContents uf c = UnsavedFile (unsavedFilename uf) c\n\n-- TODO: Use BU.unsafeLast when we can use newer B.ByteString.\nnullTerminate :: B.ByteString -> B.ByteString\nnullTerminate bs\n | B.null bs = B.singleton 0\n | B.last bs == 0 = bs\n | otherwise = B.snoc bs 0\n\n-- Functions which take a Vector UnsavedFile argument are implemented\n-- internally in terms of this function, which temporarily allocates a\n-- Vector CUnsavedFile holding the same data. (But does not copy the\n-- string data itself.)\nwithUnsavedFiles :: DV.Vector UnsavedFile -> (Ptr CUnsavedFile -> Int -> IO a) -> IO a\nwithUnsavedFiles ufs f =\n withCUnsavedFiles ufs $ \\cufs ->\n DVS.unsafeWith cufs $ \\ptr ->\n f ptr (DVS.length cufs)\n\ndata CUnsavedFile = CUnsavedFile\n { cUnsavedFilename :: CString\n , cUnsavedContents :: CString\n , cUnsavedContentsLen :: CULong\n }\n\ninstance Storable CUnsavedFile where\n sizeOf _ = sizeOfCXUnsavedFile\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfCXUnsavedFile\n {-# INLINE alignment #-}\n\n peek p = do\n filename <- peekByteOff p offsetCXUnsavedFileFilename\n contents <- peekByteOff p offsetCXUnsavedFileContents\n contentsLen <- peekByteOff p offsetCXUnsavedFileContentsLen\n return $! CUnsavedFile filename contents contentsLen\n {-# INLINE peek #-}\n\n poke p (CUnsavedFile filename contents contentsLen) = do\n pokeByteOff p offsetCXUnsavedFileFilename filename\n pokeByteOff p offsetCXUnsavedFileContents contents\n pokeByteOff p offsetCXUnsavedFileContentsLen contentsLen\n {-# INLINE poke #-}\n\n\nwithCUnsavedFiles :: DV.Vector UnsavedFile -> (DVS.Vector CUnsavedFile -> IO a) -> IO a\nwithCUnsavedFiles ufs f = do\n let len = DV.length ufs\n v <- DVSM.new len\n go v 0 len\n where\n go v i len\n | i == len = f =<< DVS.unsafeFreeze v\n | otherwise = do let uf = DV.unsafeIndex ufs i\n ufFilename = unsavedFilename uf\n ufContents = unsavedContents uf\n BU.unsafeUseAsCString ufFilename $ \\cufFilename ->\n BU.unsafeUseAsCString ufContents $ \\cufContents -> do\n let contentsLen = fromIntegral $ B.length ufContents\n cuf = CUnsavedFile cufFilename cufContents contentsLen\n DVSM.write v i cuf\n go v (i + 1) len\n\n#c\nenum AvailabilityKind {\n Availability_Available = CXAvailability_Available,\n Availability_Deprecated = CXAvailability_Deprecated,\n Availability_NotAvailable = CXAvailability_NotAvailable,\n Availability_NotAccessible = CXAvailability_NotAccessible\n};\n#endc\n{# enum AvailabilityKind{} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ndata Version = Version\n { majorVersion :: !Int\n , minorVersion :: !Int\n , subminorVersion :: !Int\n } deriving (Eq, Ord, Show, Typeable)\n\ninstance Storable Version where\n sizeOf _ = sizeOfCXVersion\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfCXVersion\n {-# INLINE alignment #-}\n\n peek p = do\n major <- fromCInt <$> peekByteOff p offsetCXVersionMajor\n minor <- fromCInt <$> peekByteOff p offsetCXVersionMinor\n subminor <- fromCInt <$> peekByteOff p offsetCXVersionSubminor\n return $! Version major minor subminor\n {-# INLINE peek #-}\n\n poke p (Version major minor subminor) = do\n pokeByteOff p offsetCXVersionMajor major\n pokeByteOff p offsetCXVersionMinor minor\n pokeByteOff p offsetCXVersionSubminor subminor\n {-# INLINE poke #-}\n\n-- typedef struct {\n-- const void *data;\n-- unsigned private_flags;\n-- } CXString;\ndata ClangString s = ClangString !(Ptr ()) !Word32\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue ClangString\n\ninstance Storable (ClangString s) where\n sizeOf _ = {# sizeof CXString #} -- sizeOfCXString\n {-# INLINE sizeOf #-}\n\n alignment _ = {# alignof CXString #} -- alignOfCXString\n {-# INLINE alignment #-}\n\n peek p = do\n strData <- {#get CXString->data #} p\n strFlags <- {#get CXString->private_flags #} p\n return $! ClangString strData (fromIntegral strFlags)\n {-# INLINE peek #-}\n\n poke p (ClangString d f) = do\n {#set CXString->data #} p d\n {#set CXString->private_flags #} p (fromIntegral f)\n {-# INLINE poke #-}\n\ninstance Hashable (ClangString s) where\n hashWithSalt salt (ClangString p f) = (`hashWithSalt` f)\n . (`hashWithSalt` pInt)\n $ salt\n where\n pInt = (fromIntegral $ ptrToWordPtr p) :: Int\n\nregisterClangString :: ClangBase m => IO (ClangString ()) -> ClangT s m (ClangString s)\nregisterClangString action = do\n (_, str) <- clangAllocate (action >>= return . unsafeCoerce)\n (\\(ClangString d f) -> freeClangString d f)\n return str\n{-# INLINEABLE registerClangString #-}\n\n{#fun freeClangString { id `Ptr ()', `Word32' } -> `()' #}\n\nunmarshall_clangString :: Ptr () -> Word32 -> IO (ClangString ())\nunmarshall_clangString d f = return $ ClangString d f\n\ngetString :: ClangBase m => ClangString s' -> ClangT s m String\ngetString (ClangString d f) = liftIO $ getCStringPtr d f >>= peekCString\n\ngetByteString :: ClangBase m => ClangString s' -> ClangT s m B.ByteString\ngetByteString (ClangString d f) = liftIO $ getCStringPtr d f >>= B.packCString\n\nunsafeGetByteString :: ClangBase m => ClangString s' -> ClangT s m B.ByteString\nunsafeGetByteString (ClangString d f) = liftIO $ getCStringPtr d f >>= BU.unsafePackCString\n\n-- const char *clang_getCString(ClangString string);\n{# fun clang_getCString {withVoided* %`ClangString a' } -> `CString' id #}\ngetCStringPtr :: Ptr () -> Word32 -> IO CString\ngetCStringPtr d f = clang_getCString (ClangString d f)\n\n-- typedef void *CXFile;\nnewtype File s = File { unFile :: Ptr () }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue File\n\ninstance Hashable (File s) where\n hashWithSalt salt (File p) = let !pInt = (fromIntegral $ ptrToWordPtr p) :: Int\n in hashWithSalt salt pInt\n\nmaybeFile :: File s' -> Maybe (File s)\nmaybeFile (File p) | p == nullPtr = Nothing\nmaybeFile f = Just (unsafeCoerce f)\n\nunMaybeFile :: Maybe (File s') -> File s\nunMaybeFile (Just f) = unsafeCoerce f\nunMaybeFile Nothing = File nullPtr\n\n\n-- CXString clang_getFileName(CXFile SFile);\n{# fun wrapped_clang_getFileName as clang_getFileName { `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getFileName :: File s -> IO (ClangString ())\nunsafe_getFileName x = clang_getFileName (unFile x) >>= peek\n\ngetFileName :: ClangBase m => File s' -> ClangT s m (ClangString s)\ngetFileName = registerClangString . unsafe_getFileName\n\n-- time_t clang_getFileTime(CXFile SFile);\nforeign import ccall unsafe \"clang-c\/Index.h clang_getFileTime\" clang_getFileTime :: Ptr () -> IO CTime\n\ngetFileTime :: File s -> IO CTime\ngetFileTime (File ptr) = clang_getFileTime ptr\n\n-- | A unique identifier that can be used to distinguish 'File's.\ndata UniqueId = UniqueId !Word64 !Word64 !Word64\n deriving (Eq, Ord, Show, Typeable)\n\ninstance Hashable UniqueId where\n hashWithSalt salt (UniqueId a b c) = (`hashWithSalt` a)\n . (`hashWithSalt` b)\n . (`hashWithSalt` c)\n $ salt\n {-# INLINE hashWithSalt #-}\n\nmaybeFileUniqueID :: (Int, Word64, Word64, Word64) -> Maybe UniqueId\nmaybeFileUniqueID (v, d1, d2, d3) | v \/= 0 = Nothing\n | otherwise = Just $ UniqueId d1 d2 d3\n\n-- int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID);\n{# fun clang_getFileUniqueID { `Ptr ()', `Ptr ()' } -> `CInt' id #}\ngetFileUniqueID :: File s -> IO (Maybe UniqueId)\ngetFileUniqueID f =\n allocaArray 3 (ptrToFileUniqueId f)\n where\n ptrToFileUniqueId :: File s -> Ptr Word64 -> IO (Maybe UniqueId)\n ptrToFileUniqueId f' ptr = do\n res' <- clang_getFileUniqueID (unFile f') (castPtr ptr)\n ds' <- peekArray 3 ptr\n return (maybeFileUniqueID (fromIntegral res', ds' !! 0, ds' !! 1, ds' !! 2))\n\n-- -- unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file);\n{# fun clang_isFileMultipleIncludeGuarded { `Ptr ()', `Ptr ()' } -> `CInt' #}\nisFileMultipleIncludeGuarded :: TranslationUnit s -> File s' -> IO Bool\nisFileMultipleIncludeGuarded t f = clang_isFileMultipleIncludeGuarded (unTranslationUnit t) (unFile f) >>= return . (toBool :: Int -> Bool) . fromIntegral\n\n-- CXFile clang_getFile(CXTranslationUnit tu, const char *file_name);\n{# fun clang_getFile { `Ptr ()', `CString' } -> `Ptr ()' #}\ngetFile:: Proxy s -> TranslationUnit s' -> String -> IO (File s)\ngetFile _ t s = withCString s (\\cs -> clang_getFile (unTranslationUnit t) cs >>= return . File)\n\n-- typedef struct {\n-- void *ptr_data[2];\n-- unsigned int_data;\n-- } CXSourceLocation;\n\ndata SourceLocation s = SourceLocation !(Ptr ()) !(Ptr ()) !Int\n deriving (Ord, Typeable)\n\ninstance ClangValue SourceLocation\n\ninstance Eq (SourceLocation s) where\n a == b = unsafePerformIO $ equalLocations a b\n\ninstance Storable (SourceLocation s) where\n sizeOf _ = sizeOfCXSourceLocation\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfCXSourceLocation\n {-# INLINE alignment #-}\n\n peek p = do\n ptrArray <- {#get CXSourceLocation->ptr_data #} p >>= peekArray 2\n intData <- {#get CXSourceLocation->int_data #} p\n return $! SourceLocation (ptrArray !! 0) (ptrArray !! 1) (fromIntegral intData)\n {-# INLINE peek #-}\n\n poke p (SourceLocation p0 p1 i )= do\n ptrsArray <- mallocArray 2\n pokeArray ptrsArray [p0,p1]\n {#set CXSourceLocation->ptr_data #} p (castPtr ptrsArray)\n {#set CXSourceLocation->int_data #} p (fromIntegral i)\n {-# INLINE poke #-}\n\n-- typedef struct {\n-- void *ptr_data[2];\n-- unsigned begin_int_data;\n-- unsigned end_int_data;\n-- } CXSourceRange;\ndata SourceRange s = SourceRange !(Ptr ()) !(Ptr ()) !Int !Int\n deriving (Ord, Typeable)\n\ninstance ClangValue SourceRange\n\ninstance Eq (SourceRange s) where\n a == b = unsafePerformIO $ equalRanges a b\n\ninstance Storable (SourceRange s) where\n sizeOf _ = sizeOfCXSourceRange\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfCXSourceRange\n {-# INLINE alignment #-}\n\n peek p = do\n ptrArray <- {#get CXSourceRange->ptr_data #} p >>= peekArray 2\n beginIntData <- {#get CXSourceRange->begin_int_data #} p\n endIntData <- {#get CXSourceRange->end_int_data #} p\n return $! SourceRange (ptrArray !! 0) (ptrArray !! 1) (fromIntegral beginIntData) (fromIntegral endIntData)\n {-# INLINE peek #-}\n\n poke p (SourceRange p0 p1 begin end)= do\n ptrsArray <- mallocArray 2\n pokeArray ptrsArray [p0,p1]\n {#set CXSourceRange->ptr_data #} p (castPtr ptrsArray)\n {#set CXSourceRange->begin_int_data #} p (fromIntegral begin)\n {#set CXSourceRange->end_int_data #} p (fromIntegral end)\n {-# INLINE poke #-}\n\n-- CXSourceLocation wrapped_clang_getNullLocation();\n{# fun wrapped_clang_getNullLocation as clang_getNullLocation { } -> `Ptr (SourceLocation s)' castPtr #}\ngetNullLocation :: Proxy s -> IO (SourceLocation s)\ngetNullLocation _ = clang_getNullLocation >>= peek\n\nwithVoided :: Storable a => a -> (Ptr () -> IO c) -> IO c\nwithVoided a f= with a (\\aPtr -> f (castPtr aPtr))\n\n-- unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2);\n{# fun clang_equalLocations {withVoided* %`SourceLocation a' , withVoided* %`SourceLocation b' } -> `Bool' toBool #}\nequalLocations :: SourceLocation s -> SourceLocation s' -> IO Bool\nequalLocations s1 s2 = clang_equalLocations s1 s2\n\n-- CXSourceLocation clang_getLocation(CXTranslationUnit tu,\n-- CXFile file,\n-- unsigned line,\n-- unsigned column);\n{# fun wrapped_clang_getLocation as clang_getLocation { `Ptr ()' , `Ptr ()', `Int', `Int' } -> `Ptr (SourceLocation s)' castPtr #}\ngetLocation :: Proxy s -> TranslationUnit s' -> File s'' -> Int -> Int -> IO (SourceLocation s)\ngetLocation _ t f i j = clang_getLocation (unTranslationUnit t) (unFile f) i j >>= peek\n\n-- CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,\n-- CXFile file,\n-- unsigned offset);\n{# fun wrapped_clang_getLocationForOffset as clang_getLocationForOffset { `Ptr ()', `Ptr ()', `Int' } -> `Ptr (SourceLocation s)' castPtr #}\ngetLocationForOffset :: Proxy s -> TranslationUnit s' -> File s'' -> Int -> IO (SourceLocation s)\ngetLocationForOffset _ t f i = clang_getLocationForOffset (unTranslationUnit t) (unFile f) i >>= peek\n\n-- int clang_Location_isInSystemHeader(CXSourceLocation location);\n{# fun clang_Location_isInSystemHeader { withVoided* %`SourceLocation a' } -> `Bool' toBool #}\nlocation_isInSystemHeader :: SourceLocation s -> IO Bool\nlocation_isInSystemHeader s = clang_Location_isInSystemHeader s\n\n-- int clang_Location_isFromMainFile(CXSourceLocation location);\n{# fun clang_Location_isFromMainFile { withVoided* %`SourceLocation a' } -> `Bool' toBool #}\nlocation_isFromMainFile :: SourceLocation s -> IO Bool\nlocation_isFromMainFile s = clang_Location_isFromMainFile s\n\n-- CXSourceRange clang_getNullRange();\n{# fun wrapped_clang_getNullRange as clang_getNullRange { } -> `Ptr (SourceRange s)' castPtr #}\ngetNullRange :: Proxy s -> IO (SourceRange s)\ngetNullRange _ = clang_getNullRange >>= peek\n\n-- CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end);\n{# fun wrapped_clang_getRange as clang_getRange { withVoided* %`SourceLocation a', withVoided* %`SourceLocation b' } -> `Ptr (SourceRange s)' castPtr #}\ngetRange :: Proxy s -> SourceLocation s' -> SourceLocation s'' -> IO (SourceRange s)\ngetRange _ sl1 sl2 = clang_getRange sl1 sl2 >>= peek\n\n-- unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2);\n{# fun clang_equalRanges {withVoided* %`SourceRange a', withVoided* %`SourceRange b' } -> `Bool' toBool #}\nequalRanges :: SourceRange s' -> SourceRange s'' -> IO Bool\nequalRanges sr1 sr2 = clang_equalRanges sr1 sr2\n\n-- int clang_Range_isNull(CXSourceRange range);\n{# fun clang_Range_isNull {withVoided* %`SourceRange a ' } -> `Bool' toBool #}\nrange_isNull :: SourceRange s -> IO Bool\nrange_isNull s = clang_Range_isNull s\n\n#c\ntypedef CXFile** PtrPtrCXFile;\n#endc\n\n-- void clang_getExpansionLocation(CXSourceLocation location,\n-- CXFile *file,\n-- unsigned *line,\n-- unsigned *column,\n-- unsigned *offset);\n{# fun clang_getExpansionLocation { withVoided* %`SourceLocation a', id `Ptr (Ptr ())', id `Ptr CUInt', id `Ptr CUInt', id `Ptr CUInt' } -> `()' #}\ngetExpansionLocation :: Proxy s -> SourceLocation s' -> IO (Maybe (File s), Int, Int, Int)\ngetExpansionLocation _ s =\n allocaBytes {#sizeof PtrPtrCXFile #} (\\ptrToFilePtr ->\n alloca (\\(linePtr :: (Ptr CUInt)) ->\n alloca (\\(columnPtr :: (Ptr CUInt)) ->\n alloca (\\(offsetPtr :: (Ptr CUInt)) -> do\n clang_getExpansionLocation s (castPtr ptrToFilePtr) (castPtr linePtr) (castPtr columnPtr) (castPtr offsetPtr)\n filePtr <- {#get *CXFile #} ptrToFilePtr\n let _maybeFile = maybeFile (File filePtr)\n line <- peek linePtr\n column <- peek columnPtr\n offset <- peek offsetPtr\n return (_maybeFile, fromIntegral line, fromIntegral column, fromIntegral offset)))))\n\n-- void clang_getPresumedLocation(CXSourceLocation location,\n-- CXString *filename,\n-- unsigned *line,\n-- unsigned *column);\n\n{# fun clang_getPresumedLocation { withVoided* %`SourceLocation a', id `Ptr ()', alloca- `CUInt' peek*, alloca- `CUInt' peek* } -> `()' #}\nunsafe_getPresumedLocation :: SourceLocation s' -> IO (ClangString (), Int, Int)\nunsafe_getPresumedLocation s =\n alloca (\\(stringPtr :: (Ptr (ClangString ()))) -> do\n (line, column) <- clang_getPresumedLocation s (castPtr stringPtr)\n clangString <- peek stringPtr\n return (clangString, fromIntegral line, fromIntegral column))\n\ngetPresumedLocation :: ClangBase m => SourceLocation s' -> ClangT s m (ClangString s, Int, Int)\ngetPresumedLocation l = do\n (f, ln, c) <- liftIO $ unsafe_getPresumedLocation l\n (,,) <$> registerClangString (return f) <*> return ln <*> return c\n\n-- void clang_getSpellingLocation(CXSourceLocation location,\n-- CXFile *file,\n-- unsigned *line,\n-- unsigned *column,\n-- unsigned *offset);\n{# fun clang_getSpellingLocation { withVoided* %`SourceLocation a', id `Ptr (Ptr ())', id `Ptr CUInt', id `Ptr CUInt', id `Ptr CUInt' } -> `()' #}\ngetSpellingLocation :: Proxy s -> SourceLocation s' -> IO (Maybe (File s), Int, Int, Int)\ngetSpellingLocation _ s =\n allocaBytes {# sizeof PtrPtrCXFile #} (\\ptrToFilePtr ->\n alloca (\\(linePtr :: (Ptr CUInt)) ->\n alloca (\\(columnPtr :: (Ptr CUInt)) ->\n alloca (\\(offsetPtr :: (Ptr CUInt)) -> do\n clang_getSpellingLocation s (castPtr ptrToFilePtr) linePtr columnPtr offsetPtr\n filePtr <- {#get *CXFile #} ptrToFilePtr\n let _maybeFile = maybeFile (File filePtr)\n line <- peek linePtr\n column <- peek columnPtr\n offset <- peek offsetPtr\n return (_maybeFile, fromIntegral line, fromIntegral column, fromIntegral offset)))))\n\n-- void clang_getFileLocation(CXSourceLocation location,\n-- CXFile *file,\n-- unsigned *line,\n-- unsigned *column,\n-- unsigned *offset);\n{# fun clang_getFileLocation { withVoided* %`SourceLocation a', id `Ptr (Ptr ())', id `Ptr CUInt', id `Ptr CUInt', id `Ptr CUInt' } -> `()' #}\ngetFileLocation :: Proxy s -> SourceLocation s' -> IO (Maybe (File s), Int, Int, Int)\ngetFileLocation _ s =\n allocaBytes {#sizeof PtrPtrCXFile #} (\\ptrToFilePtr ->\n alloca (\\(linePtr :: (Ptr CUInt)) ->\n alloca (\\(columnPtr :: (Ptr CUInt)) ->\n alloca (\\(offsetPtr :: (Ptr CUInt)) -> do\n clang_getFileLocation s ptrToFilePtr (castPtr linePtr) (castPtr columnPtr) (castPtr offsetPtr)\n filePtr <- {#get *CXFile #} ptrToFilePtr\n let _maybeFile = maybeFile (File filePtr)\n line <- peek linePtr\n column <- peek columnPtr\n offset <- peek offsetPtr\n return (_maybeFile, fromIntegral line, fromIntegral column, fromIntegral offset)))))\n\n-- CXSourceLocation clang_getRangeStart(CXSourceRange range);\n{# fun wrapped_clang_getRangeStart as clang_getRangeStart {withVoided* %`SourceRange a' } -> `Ptr (SourceLocation s)' castPtr #}\ngetRangeStart :: Proxy s -> SourceRange s' -> IO (SourceLocation s)\ngetRangeStart _ sr = clang_getRangeStart sr >>= peek\n\n-- CXSourceLocation clang_getRangeEnd(CXSourceRange range);\n{# fun wrapped_clang_getRangeEnd as clang_getRangeEnd {withVoided* %`SourceRange a' } -> `Ptr (SourceLocation s)' castPtr #}\ngetRangeEnd :: Proxy s -> SourceRange s' -> IO (SourceLocation s)\ngetRangeEnd _ sr = clang_getRangeEnd sr >>= peek\n\n-- enum CXDiagnosticSeverity {\n-- CXDiagnostic_Ignored = 0,\n-- CXDiagnostic_Note = 1,\n-- CXDiagnostic_Warning = 2,\n-- CXDiagnostic_Error = 3,\n-- CXDiagnostic_Fatal = 4\n-- };\n\n-- | The severity of a diagnostic.\n#c\nenum Severity\n { SeverityIgnored = CXDiagnostic_Ignored\n , SeverityNote = CXDiagnostic_Note\n , SeverityWarning = CXDiagnostic_Warning\n , SeverityError = CXDiagnostic_Error\n , SeverityFatal = CXDiagnostic_Fatal\n };\n#endc\n{# enum Severity {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- typedef void* CXDiagnostic;\nnewtype Diagnostic s = Diagnostic { unDiagnostic :: Ptr () }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue Diagnostic\n\nmkDiagnostic :: Ptr () -> Diagnostic ()\nmkDiagnostic = Diagnostic\n\n-- void clang_disposeDiagnostic(CXDiagnostic);\n{# fun clang_disposeDiagnostic { id `Ptr ()' } -> `()' #}\ndisposeDiagnostic:: Diagnostic s -> IO ()\ndisposeDiagnostic d = clang_disposeDiagnostic (unDiagnostic d)\n\nregisterDiagnostic :: ClangBase m => IO (Diagnostic ()) -> ClangT s m (Diagnostic s)\nregisterDiagnostic action = do\n (_, idx) <- clangAllocate (action >>= return . unsafeCoerce)\n (\\i -> disposeDiagnostic i)\n return idx\n{-# INLINEABLE registerDiagnostic #-}\n\n-- typedef void* CXDiagnosticSet;\nnewtype DiagnosticSet s = DiagnosticSet { unDiagnosticSet :: Ptr () }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue DiagnosticSet\n\nmkDiagnosticSet :: Ptr () -> DiagnosticSet ()\nmkDiagnosticSet = DiagnosticSet\n\n-- void clang_disposeDiagnosticSet(CXDiagnosticSet);\n{# fun clang_disposeDiagnosticSet { id `Ptr ()' } -> `()' #}\ndisposeDiagnosticSet :: DiagnosticSet s -> IO ()\ndisposeDiagnosticSet s = clang_disposeDiagnosticSet (unDiagnosticSet s)\n\nregisterDiagnosticSet :: ClangBase m => IO (DiagnosticSet ()) -> ClangT s m (DiagnosticSet s)\nregisterDiagnosticSet action = do\n (_, idx) <- clangAllocate (action >>= return . unsafeCoerce)\n (\\i -> disposeDiagnosticSet i)\n return idx\n{-# INLINEABLE registerDiagnosticSet #-}\n\n-- unsigned clang_getNumDiagnosticsInSet(CXDiagnosticSet Diags);\n{# fun clang_getNumDiagnosticsInSet { id `Ptr ()' } -> `Int' #}\ngetNumDiagnosticsInSet :: DiagnosticSet s -> IO Int\ngetNumDiagnosticsInSet s = clang_getNumDiagnosticsInSet (unDiagnosticSet s)\n\n-- CXDiagnostic clang_getDiagnosticInSet(CXDiagnosticSet Diags, unsigned Index);\n{# fun clang_getDiagnosticInSet { id `Ptr ()', `Int' } -> `Ptr ()' id #}\nunsafe_getDiagnosticInSet :: DiagnosticSet s -> Int -> IO (Diagnostic ())\nunsafe_getDiagnosticInSet s i = clang_getDiagnosticInSet (unDiagnosticSet s) i >>= return . mkDiagnostic\n\ngetDiagnosticInSet :: ClangBase m => DiagnosticSet s' -> Int -> ClangT s m (Diagnostic s)\ngetDiagnosticInSet = (registerDiagnostic .) . unsafe_getDiagnosticInSet\n\n-- enum CXLoadDiag_Error {\n-- CXLoadDiag_None = 0,\n-- CXLoadDiag_Unknown = 1,\n-- CXLoadDiag_CannotLoad = 2,\n-- CXLoadDiag_InvalidFile = 3\n-- };\n\n-- | An error encountered while loading a serialized diagnostics bitcode file.\n#c\nenum LoadError\n { LoadSuccessful = CXLoadDiag_None\n , LoadUnknownError = CXLoadDiag_Unknown\n , LoadCannotOpen = CXLoadDiag_CannotLoad\n , LoadInvalidFile = CXLoadDiag_InvalidFile\n };\n#endc\n{# enum LoadError {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ndata LoadDiagsResult =\n LoadDiagsResult LoadError (ClangString ()) (DiagnosticSet ())\n\n-- CXDiagnosticSet clang_loadDiagnostics(const char *file,\n-- enum CXLoadDiag_Error *error,\n-- CXString *errorString);\n{# fun clang_loadDiagnostics {`CString', alloca- `CInt' peek*, `Ptr ()' } -> `Ptr ()' id #}\nunsafe_loadDiagnostics :: FilePath -> IO LoadDiagsResult\nunsafe_loadDiagnostics file = withCString file (\\cString -> alloca (go cString))\n where\n go :: CString -> Ptr (ClangString ()) -> IO LoadDiagsResult\n go str ptr = do\n (diagnosticSetPtr, err) <- clang_loadDiagnostics str (castPtr ptr)\n errString <- peek (castPtr ptr)\n return (LoadDiagsResult (toEnum (fromIntegral err)) errString (DiagnosticSet diagnosticSetPtr))\n\nloadDiagnostics :: ClangBase m => FilePath\n -> ClangT s m (Either (LoadError, ClangString s) (DiagnosticSet s))\nloadDiagnostics path = do\n result <- liftIO $ unsafe_loadDiagnostics path\n case result of\n (LoadDiagsResult err errStr ds@(DiagnosticSet p))\n | p == nullPtr -> Left . (err,) <$> registerClangString (return errStr)\n | otherwise -> Right <$> registerDiagnosticSet (return ds)\n\n-- CXDiagnosticSet clang_getChildDiagnostics(CXDiagnostic D);\n{# fun clang_getChildDiagnostics { `Ptr ()' } -> `Ptr ()' id #}\nunsafe_getChildDiagnostics :: Diagnostic s' -> IO (DiagnosticSet ())\nunsafe_getChildDiagnostics d = clang_getChildDiagnostics (unDiagnostic d) >>= return . mkDiagnosticSet\n\n-- Note that as a special case, the DiagnosticSet returned by this\n-- function does not need to be freed, so we intentionally don't\n-- register it.\ngetChildDiagnostics :: ClangBase m => Diagnostic s' -> ClangT s m (DiagnosticSet s)\ngetChildDiagnostics = unsafeCoerce <$> unsafe_getChildDiagnostics\n\n-- unsigned clang_getNumDiagnostics(CXTranslationUnit Unit);\n{# fun clang_getNumDiagnostics { `Ptr ()' } -> `CUInt' id#}\ngetNumDiagnostics :: TranslationUnit s -> IO Int\ngetNumDiagnostics t = clang_getNumDiagnostics (unTranslationUnit t) >>= return . fromIntegral\n\n-- CXDiagnostic clang_getDiagnostic(CXTranslationUnit Unit, unsigned Index);\n{# fun clang_getDiagnostic { `Ptr ()', `CUInt' } -> `Ptr ()' id #}\nunsafe_getDiagnostic :: TranslationUnit s -> Int -> IO (Diagnostic ())\nunsafe_getDiagnostic t i = clang_getDiagnostic (unTranslationUnit t) (fromIntegral i) >>= return . mkDiagnostic\n\ngetDiagnostic :: ClangBase m => TranslationUnit s' -> Int -> ClangT s m (Diagnostic s)\ngetDiagnostic = (registerDiagnostic .) . unsafe_getDiagnostic\n\n-- CXDiagnosticSet clang_getDiagnosticSetFromTU(CXTranslationUnit Unit);\n{# fun clang_getDiagnosticSetFromTU { `Ptr ()' } -> `Ptr ()' id #}\nunsafe_getDiagnosticSetFromTU :: TranslationUnit s -> IO (DiagnosticSet ())\nunsafe_getDiagnosticSetFromTU t = do\n set <- clang_getDiagnosticSetFromTU (unTranslationUnit t)\n return (mkDiagnosticSet set)\n\ngetDiagnosticSetFromTU :: ClangBase m => TranslationUnit s' -> ClangT s m (DiagnosticSet s)\ngetDiagnosticSetFromTU = registerDiagnosticSet . unsafe_getDiagnosticSetFromTU\n\n-- enum CXDiagnosticDisplayOptions {\n-- CXDiagnostic_DisplaySourceLocation = 0x01,\n-- CXDiagnostic_DisplayColumn = 0x02,\n-- CXDiagnostic_DisplaySourceRanges = 0x04,\n-- CXDiagnostic_DisplayOption = 0x08,\n-- CXDiagnostic_DisplayCategoryId = 0x10,\n-- CXDiagnostic_DisplayCategoryName = 0x20\n-- };\n\n-- | Options for rendering of 'Diagnostic' values.\n#c\nenum DisplayOptions\n { DisplaySourceLocation = CXDiagnostic_DisplaySourceLocation\n , DisplayColumn = CXDiagnostic_DisplayColumn\n , DisplaySourceRanges = CXDiagnostic_DisplaySourceRanges\n , DisplayOption = CXDiagnostic_DisplayOption\n , DisplayCategoryId = CXDiagnostic_DisplayCategoryId\n , DisplayCategoryName = CXDiagnostic_DisplayCategoryName\n };\n#endc\n{#enum DisplayOptions {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags DisplayOptions where\n toBit DisplaySourceLocation = 0x1\n toBit DisplayColumn = 0x2\n toBit DisplaySourceRanges = 0x4\n toBit DisplayOption = 0x8\n toBit DisplayCategoryId = 0x10\n toBit DisplayCategoryName = 0x20\n\n-- CXString clang_formatDiagnostic(CXDiagnostic Diagnostic, unsigned Options);\n{# fun wrapped_clang_formatDiagnostic as clang_formatDiagnostic { `Ptr ()' , `Int' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_formatDiagnostic :: Diagnostic s -> Int -> IO (ClangString ())\nunsafe_formatDiagnostic d i = clang_formatDiagnostic (unDiagnostic d) (fromIntegral i) >>= peek\n\nformatDiagnostic :: ClangBase m => Diagnostic s' -> Int -> ClangT s m (ClangString s)\nformatDiagnostic = (registerClangString .) . unsafe_formatDiagnostic\n\n-- unsigned clang_defaultDiagnosticDisplayOptions(void);\n{# fun clang_defaultDiagnosticDisplayOptions { } -> `CUInt' #}\ndefaultDiagnosticDisplayOptions :: IO Int\ndefaultDiagnosticDisplayOptions = clang_defaultDiagnosticDisplayOptions >>= return . fromIntegral\n\n-- clang_getDiagnosticSeverity(CXDiagnostic);\n{# fun clang_getDiagnosticSeverity {id `Ptr ()' } -> `CInt' #}\ngetDiagnosticSeverity :: Diagnostic s -> IO Severity\ngetDiagnosticSeverity d = clang_getDiagnosticSeverity (unDiagnostic d) >>= return . toEnum . fromIntegral\n\n-- CXSourceLocation clang_getDiagnosticLocation(CXDiagnostic);\n{# fun wrapped_clang_getDiagnosticLocation as clang_getDiagnosticLocation {id `Ptr ()' } -> `Ptr (SourceLocation s)' castPtr #}\ngetDiagnosticLocation :: Proxy s -> Diagnostic s' -> IO (SourceLocation s)\ngetDiagnosticLocation _ d = clang_getDiagnosticLocation (unDiagnostic d) >>= peek\n\n-- CXString clang_getDiagnosticSpelling(CXDiagnostic);\n{# fun wrapped_clang_getDiagnosticSpelling as clang_getDiagnosticSpelling { id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getDiagnosticSpelling :: Diagnostic s -> IO (ClangString ())\nunsafe_getDiagnosticSpelling d = clang_getDiagnosticSpelling (unDiagnostic d) >>= peek\n\ngetDiagnosticSpelling :: ClangBase m => Diagnostic s' -> ClangT s m (ClangString s)\ngetDiagnosticSpelling = registerClangString . unsafe_getDiagnosticSpelling\n\n-- CXString clang_getDiagnosticOption(CXDiagnostic Diag,\n-- CXString *Disable);\n{# fun wrapped_clang_getDiagnosticOption as clang_getDiagnosticOption { id `Ptr ()', id `Ptr ()' } -> `Ptr ()' id #}\nunsafe_getDiagnosticOption :: Diagnostic s -> IO (ClangString (), ClangString ())\nunsafe_getDiagnosticOption d =\n alloca (\\(disableCXStringPtr :: (Ptr (ClangString ()))) -> do\n diagnosticOptionPtr <- clang_getDiagnosticOption (unDiagnostic d) (castPtr disableCXStringPtr)\n disableCXString <- peek disableCXStringPtr\n diagnosticOption <- peek (castPtr diagnosticOptionPtr)\n return (diagnosticOption, disableCXString))\n\ngetDiagnosticOption :: ClangBase m => Diagnostic s' -> ClangT s m (ClangString s, ClangString s)\ngetDiagnosticOption d = do\n (a, b) <- liftIO $ unsafe_getDiagnosticOption d\n (,) <$> registerClangString (return a) <*> registerClangString (return b)\n\n-- unsigned clang_getDiagnosticCategory(CXDiagnostic);\n{# fun clang_getDiagnosticCategory { id `Ptr ()' } -> `Int' #}\ngetDiagnosticCategory :: Diagnostic s -> IO Int\ngetDiagnosticCategory d = clang_getDiagnosticCategory (unDiagnostic d)\n\n-- CXString clang_getDiagnosticCategoryText(CXDiagnostic);\n{# fun wrapped_clang_getDiagnosticCategoryText as clang_getDiagnosticCategoryText { id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getDiagnosticCategoryText :: Diagnostic s -> IO (ClangString ())\nunsafe_getDiagnosticCategoryText d = clang_getDiagnosticCategoryText (unDiagnostic d) >>= peek\n\ngetDiagnosticCategoryText :: ClangBase m => Diagnostic s' -> ClangT s m (ClangString s)\ngetDiagnosticCategoryText = registerClangString . unsafe_getDiagnosticCategoryText\n\n-- unsigned clang_getDiagnosticNumRanges(CXDiagnostic);\n{# fun clang_getDiagnosticNumRanges { id `Ptr ()' } -> `Int' #}\ngetDiagnosticNumRanges :: Diagnostic s -> IO Int\ngetDiagnosticNumRanges d = clang_getDiagnosticNumRanges (unDiagnostic d)\n\n-- CXSourceRange clang_getDiagnosticRange(CXDiagnostic Diagnostic,\n-- unsigned Range);\n{# fun wrapped_clang_getDiagnosticRange as clang_getDiagnosticRange { id `Ptr ()', `Int' } -> `Ptr (SourceRange s)' castPtr #}\ngetDiagnosticRange :: Diagnostic s' -> Int -> IO (SourceRange s)\ngetDiagnosticRange d i = clang_getDiagnosticRange (unDiagnostic d) i >>= peek\n\n-- unsigned clang_getDiagnosticNumFixIts(CXDiagnostic Diagnostic);\n{# fun clang_getDiagnosticNumFixIts { id `Ptr ()' } -> `Int' #}\ngetDiagnosticNumFixIts :: Diagnostic s -> IO Int\ngetDiagnosticNumFixIts d = clang_getDiagnosticNumFixIts (unDiagnostic d)\n\n-- CXString clang_getDiagnosticFixIt(CXDiagnostic Diagnostic,\n-- unsigned FixIt,\n-- CXSourceRange *ReplacementRange);\n{# fun wrapped_clang_getDiagnosticFixIt as clang_getDiagnosticFixIt { id `Ptr ()', `Int', id `Ptr ()' } -> `Ptr (ClangString())' castPtr #}\nunsafe_getDiagnosticFixIt :: Diagnostic s' -> Int -> IO (SourceRange s, ClangString ())\nunsafe_getDiagnosticFixIt d i =\n alloca (\\(replacementRangePtr :: (Ptr (SourceRange s))) -> do\n clangStringPtr <- clang_getDiagnosticFixIt (unDiagnostic d) i (castPtr replacementRangePtr)\n clangString <- peek clangStringPtr\n replacementRange <- peek replacementRangePtr\n return (replacementRange, clangString))\n\ngetDiagnosticFixIt :: ClangBase m => Diagnostic s' -> Int\n -> ClangT s m (SourceRange s, ClangString s)\ngetDiagnosticFixIt d i = do\n (r, s) <- liftIO $ unsafe_getDiagnosticFixIt d i\n (r,) <$> registerClangString (return s)\n\n-- CXString\n-- clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit);\n{# fun wrapped_clang_getTranslationUnitSpelling as clang_getTranslationUnitSpelling { id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getTranslationUnitSpelling :: TranslationUnit s -> IO (ClangString ())\nunsafe_getTranslationUnitSpelling t = clang_getTranslationUnitSpelling (unTranslationUnit t) >>= peek\n\ngetTranslationUnitSpelling :: ClangBase m => TranslationUnit s' -> ClangT s m (ClangString s)\ngetTranslationUnitSpelling = registerClangString . unsafe_getTranslationUnitSpelling\n\n-- CXTranslationUnit clang_createTranslationUnitFromSourceFile(\n-- CXIndex CIdx,\n-- const char *source_filename,\n-- int num_clang_command_line_args,\n-- const char * const *clang_command_line_args,\n-- unsigned num_unsaved_files,\n-- struct CXUnsavedFile *unsaved_files);\n{# fun clang_createTranslationUnitFromSourceFile { id `Ptr ()' , `CString' , `Int' , id `Ptr CString' , `Int' , id `Ptr ()' } -> `Ptr ()' id #}\nunsafe_createTranslationUnitFromSourceFile :: Index s -> String -> Int -> Ptr CString -> Int -> Ptr CUnsavedFile -> IO (TranslationUnit ())\nunsafe_createTranslationUnitFromSourceFile i s nas as nufs ufs =\n withCString s (\\sPtr -> do\n rPtr <- clang_createTranslationUnitFromSourceFile (unIndex i) sPtr nas as nufs (castPtr ufs)\n return (mkTranslationUnit rPtr))\n\ncreateTranslationUnitFromSourceFile :: ClangBase m => Index s' -> String -> [String]\n -> DV.Vector UnsavedFile -> ClangT s m (TranslationUnit s)\ncreateTranslationUnitFromSourceFile idx sf as ufs =\n registerTranslationUnit $\n withStringList as $ \\asPtr asLen ->\n withUnsavedFiles ufs $ \\ufsPtr ufsLen ->\n unsafe_createTranslationUnitFromSourceFile idx sf asLen asPtr ufsLen ufsPtr\n\n-- CXTranslationUnit clang_createTranslationUnit(CXIndex,\n-- const char *ast_filename);\n{# fun clang_createTranslationUnit { id `Ptr ()', `CString' } -> `Ptr ()' #}\nunsafe_createTranslationUnit :: Index s -> String -> IO (TranslationUnit ())\nunsafe_createTranslationUnit i s =\n withCString s (\\strPtr -> do\n trPtr <- clang_createTranslationUnit (unIndex i) strPtr\n return (mkTranslationUnit trPtr))\n\ncreateTranslationUnit :: ClangBase m => Index s' -> String -> ClangT s m (TranslationUnit s)\ncreateTranslationUnit = (registerTranslationUnit .) . unsafe_createTranslationUnit\n\n-- enum CXTranslationUnit_Flags {\n-- CXTranslationUnit_None = 0x0,\n-- CXTranslationUnit_DetailedPreprocessingRecord = 0x01,\n-- CXTranslationUnit_Incomplete = 0x02,\n-- CXTranslationUnit_PrecompiledPreamble = 0x04,\n-- CXTranslationUnit_CacheCompletionResults = 0x08,\n-- CXTranslationUnit_ForSerialization = 0x10,\n-- CXTranslationUnit_CXXChainedPCH = 0x20,\n-- CXTranslationUnit_SkipFunctionBodies = 0x40,\n-- CXTranslationUnit_IncludeBriefCommentsInCodeCompletion = 0x80\n-- };\n\n-- | Flags that control how a translation unit is parsed.\n--\n-- * 'DetailedPreprocessingRecordFlag': Used to indicate that the parser should construct a\n-- \"detailed\" preprocessing record, including all macro definitions and instantiations.\n-- Constructing a detailed preprocessing record requires more memory and time to parse,\n-- since the information contained in the record is usually not retained. However, it can be\n-- useful for applications that require more detailed information about the behavior of the\n-- preprocessor.\n--\n-- * 'IncompleteFlag': Used to indicate that the translation unit is incomplete.\n-- When a translation unit is considered \"incomplete\", semantic analysis that is typically\n-- performed at the end of the translation unit will be suppressed. For example, this\n-- suppresses the completion of tentative declarations in C and of instantiation of\n-- implicitly-instantiation function templates in C++. This option is typically used when\n-- parsing a header with the intent of producing a precompiled header.\n--\n-- * 'PrecompiledPreambleFlag': Used to indicate that the translation unit should be built\n-- with an implicit precompiled header for the preamble. An implicit precompiled header is\n-- used as an optimization when a particular translation unit is likely to be reparsed many\n-- times when the sources aren't changing that often. In this case, an implicit precompiled\n-- header will be built containing all of the initial includes at the top of the main file\n-- (what we refer to as the \"preamble\" of the file). In subsequent parses, if the preamble\n-- or the files in it have not changed, 'Clang.TranslationUnit.reparse' will re-use the\n-- implicit precompiled header to improve parsing performance.\n--\n-- * 'CacheCompletionResultsFlag': Used to indicate that the translation unit should cache\n-- some code-completion results with each reparse of the source file.\n-- Caching of code-completion results is a performance optimization that introduces some\n-- overhead to reparsing but improves the performance of code-completion operations.\n--\n-- * 'ForSerializationFlag': Used to indicate that the translation unit will be serialized\n-- 'Clang.TranslationUnit.save'. This option is typically used when parsing a header with\n-- the intent of producing a precompiled header.\n--\n-- * 'CXXChainedPCHFlag': DEPRECATED: Enabled chained precompiled preambles in C++. Note:\n-- this is a *temporary* option that is available only while we are testing C++ precompiled\n-- preamble support. It is deprecated.\n--\n-- * 'SkipFunctionBodiesFlag': Used to indicate that function\/method bodies should be skipped\n-- while parsing. This option can be used to search for declarations\/definitions while\n-- ignoring the usages.\n--\n-- * 'IncludeBriefCommentsInCodeCompletionFlag': Used to indicate that brief documentation\n-- comments should be included into the set of code completions returned from this\n-- translation unit.\n#c\nenum TranslationUnitFlags\n { DefaultTranslationUnitFlags = CXTranslationUnit_None\n , DetailedPreprocessingRecordFlag = CXTranslationUnit_DetailedPreprocessingRecord\n , IncompleteFlag = CXTranslationUnit_Incomplete\n , PrecompiledPreambleFlag = CXTranslationUnit_PrecompiledPreamble\n , CacheCompletionResultsFlag = CXTranslationUnit_CacheCompletionResults\n , ForSerializationFlag = CXTranslationUnit_ForSerialization\n , ChainedPCHFlag = CXTranslationUnit_CXXChainedPCH\n , SkipFunctionBodiesFlag = CXTranslationUnit_SkipFunctionBodies\n , IncludeBriefCommentsInCodeCompletionFlag = CXTranslationUnit_IncludeBriefCommentsInCodeCompletion\n };\n#endc\n{# enum TranslationUnitFlags {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags TranslationUnitFlags where\n toBit DefaultTranslationUnitFlags = 0x0\n toBit DetailedPreprocessingRecordFlag = 0x01\n toBit IncompleteFlag = 0x02\n toBit PrecompiledPreambleFlag = 0x04\n toBit CacheCompletionResultsFlag = 0x08\n toBit ForSerializationFlag = 0x10\n toBit ChainedPCHFlag = 0x20\n toBit SkipFunctionBodiesFlag = 0x40\n toBit IncludeBriefCommentsInCodeCompletionFlag = 0x80\n\n-- unsigned clang_defaultEditingTranslationUnitOptions(void);\n{# fun clang_defaultEditingTranslationUnitOptions as defaultEditingTranslationUnitOptions {} -> `Int' #}\n\nmaybeTranslationUnit :: TranslationUnit s' -> Maybe (TranslationUnit s)\nmaybeTranslationUnit (TranslationUnit p) | p == nullPtr = Nothing\nmaybeTranslationUnit f = Just (unsafeCoerce f)\n\n-- CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,\n-- const char *source_filename,\n-- const char * const *command_line_args,\n-- int num_command_line_args,\n-- struct CXUnsavedFile *unsaved_files,\n-- unsigned num_unsaved_files,\n-- unsigned options);\n{# fun clang_parseTranslationUnit { id `Ptr ()', `CString' , id `Ptr CString', `Int', id `Ptr ()', `Int', `Int'} -> `Ptr ()' id #}\nunsafe_parseTranslationUnit :: Index s -> CString -> Ptr CString -> Int -> Ptr CUnsavedFile -> Int -> Int -> IO (Maybe (TranslationUnit ()))\nunsafe_parseTranslationUnit i s as nas ufs nufs o =\n clang_parseTranslationUnit (unIndex i) s as nas (castPtr ufs) nufs o >>= return . maybeTranslationUnit . mkTranslationUnit\n\nparseTranslationUnit :: ClangBase m => Index s' -> Maybe String -> [String]\n -> DV.Vector UnsavedFile -> Int -> ClangT s m (Maybe (TranslationUnit s))\nparseTranslationUnit idx maySF as ufs opts = do\n mayTU <- liftIO $\n withMaybeCString maySF $ \\cSF ->\n withStringList as $ \\asPtr asLen ->\n withUnsavedFiles ufs $ \\ufsPtr ufsLen ->\n unsafe_parseTranslationUnit idx cSF asPtr asLen ufsPtr ufsLen opts\n case mayTU of\n Just tu -> Just <$> registerTranslationUnit (return tu)\n Nothing -> return Nothing\n\nwithMaybeCString :: Maybe String -> (CString -> IO a) -> IO a\nwithMaybeCString (Just s) f = withCString s f\nwithMaybeCString Nothing f = f nullPtr\n\nwithStringList :: [String] -> (Ptr CString -> Int -> IO a) -> IO a\nwithStringList [] f = f nullPtr 0\nwithStringList strs f = do\n let len = length strs\n allocaArray len $ \\arr -> go arr len arr strs\n where\n go arr len _ [] = f arr len\n go arr len ptr (s : ss) = withCString s $ \\cs -> do\n poke ptr cs\n go arr len (advancePtr ptr 1) ss\n\n-- enum CXSaveTranslationUnit_Flags {\n-- CXSaveTranslationUnit_None = 0x0\n-- };\n\n-- | Flags that control how a translation unit is saved.\n#c\nenum SaveTranslationUnitFlags\n {DefaultSaveTranslationUnitFlags = CXSaveTranslationUnit_None};\n#endc\n{# enum SaveTranslationUnitFlags {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\ninstance BitFlags SaveTranslationUnitFlags where\n toBit DefaultSaveTranslationUnitFlags = 0x0\n\n-- unsigned clang_defaultSaveOptions(CXTranslationUnit TU);\n{# fun clang_defaultSaveOptions { id `Ptr ()' } -> `Int' #}\ndefaultSaveOptions :: TranslationUnit s -> IO Int\ndefaultSaveOptions t = clang_defaultSaveOptions (unTranslationUnit t)\n\n\n-- int clang_saveTranslationUnit(CXTranslationUnit TU,\n-- const char *FileName,\n-- unsigned options);\n{# fun clang_saveTranslationUnit { id `Ptr ()' , `CString', `Int' } -> `Int' #}\nsaveTranslationUnit :: TranslationUnit s -> String -> Int -> IO Bool\nsaveTranslationUnit t s i =\n withCString s (\\sPtr -> do\n r <- clang_saveTranslationUnit (unTranslationUnit t) sPtr i\n return (toBool ((if (r \/= 0) then 0 else 1) :: Int)))\n\n-- enum CXReparse_Flags {\n-- CXReparse_None = 0x0\n-- };\n\n-- | Flags that control how a translation unit is reparsed.\n#c\nenum ReparseFlags {\n DefaultReparseFlags = CXReparse_None\n};\n#endc\n{# enum ReparseFlags {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags ReparseFlags where\n toBit DefaultReparseFlags = 0x0\n\n-- unsigned clang_defaultReparseOptions(CXTranslationUnit TU);\n{# fun clang_defaultReparseOptions { id `Ptr ()' } -> `CUInt' #}\ndefaultReparseOptions :: TranslationUnit s -> IO Int\ndefaultReparseOptions t = clang_defaultReparseOptions (unTranslationUnit t) >>= return . fromIntegral\n\n-- int clang_reparseTranslationUnit(CXTranslationUnit TU,\n-- unsigned num_unsaved_files,\n-- struct CXUnsavedFile *unsaved_files,\n-- unsigned options);\n{# fun clang_reparseTranslationUnit { id `Ptr ()', `Int' , id `Ptr ()' , `Int' } -> `Bool' toBool #}\nunsafe_reparseTranslationUnit :: TranslationUnit s -> Ptr CUnsavedFile -> Int -> Int -> IO Bool\nunsafe_reparseTranslationUnit t ufs nufs i =\n clang_reparseTranslationUnit (unTranslationUnit t) nufs (castPtr ufs) i\n\nreparseTranslationUnit :: ClangBase m => TranslationUnit s' -> DV.Vector UnsavedFile -> Int\n -> ClangT s m Bool\nreparseTranslationUnit tu ufs opts = liftIO $\n withUnsavedFiles ufs $ \\ufsPtr ufsLen ->\n unsafe_reparseTranslationUnit tu ufsPtr ufsLen opts\n\n\n-- enum CXCursorKind {\n-- \/* Declarations *\/\n-- \/**\n-- * \\brief A declaration whose specific kind is not exposed via this\n-- * interface.\n-- *\n-- * Unexposed declarations have the same operations as any other kind\n-- * of declaration; one can extract their location information,\n-- * spelling, find their definitions, etc. However, the specific kind\n-- * of the declaration is not reported.\n-- *\/\n-- CXCursor_UnexposedDecl = 1,\n-- \/** \\brief A C or C++ struct. *\/\n-- CXCursor_StructDecl = 2,\n-- \/** \\brief A C or C++ union. *\/\n-- CXCursor_UnionDecl = 3,\n-- \/** \\brief A C++ class. *\/\n-- CXCursor_ClassDecl = 4,\n-- \/** \\brief An enumeration. *\/\n-- CXCursor_EnumDecl = 5,\n-- \/**\n-- * \\brief A field (in C) or non-static data member (in C++) in a\n-- * struct, union, or C++ class.\n-- *\/\n-- CXCursor_FieldDecl = 6,\n-- \/** \\brief An enumerator constant. *\/\n-- CXCursor_EnumConstantDecl = 7,\n-- \/** \\brief A function. *\/\n-- CXCursor_FunctionDecl = 8,\n-- \/** \\brief A variable. *\/\n-- CXCursor_VarDecl = 9,\n-- \/** \\brief A function or method parameter. *\/\n-- CXCursor_ParmDecl = 10,\n-- \/** \\brief An Objective-C @interface. *\/\n-- CXCursor_ObjCInterfaceDecl = 11,\n-- \/** \\brief An Objective-C @interface for a category. *\/\n-- CXCursor_ObjCCategoryDecl = 12,\n-- \/** \\brief An Objective-C @protocol declaration. *\/\n-- CXCursor_ObjCProtocolDecl = 13,\n-- \/** \\brief An Objective-C @property declaration. *\/\n-- CXCursor_ObjCPropertyDecl = 14,\n-- \/** \\brief An Objective-C instance variable. *\/\n-- CXCursor_ObjCIvarDecl = 15,\n-- \/** \\brief An Objective-C instance method. *\/\n-- CXCursor_ObjCInstanceMethodDecl = 16,\n-- \/** \\brief An Objective-C class method. *\/\n-- CXCursor_ObjCClassMethodDecl = 17,\n-- \/** \\brief An Objective-C @implementation. *\/\n-- CXCursor_ObjCImplementationDecl = 18,\n-- \/** \\brief An Objective-C @implementation for a category. *\/\n-- CXCursor_ObjCCategoryImplDecl = 19,\n-- \/** \\brief A typedef *\/\n-- CXCursor_TypedefDecl = 20,\n-- \/** \\brief A C++ class method. *\/\n-- CXCursor_CXXMethod = 21,\n-- \/** \\brief A C++ namespace. *\/\n-- CXCursor_Namespace = 22,\n-- \/** \\brief A linkage specification, e.g. 'extern \"C\"'. *\/\n-- CXCursor_LinkageSpec = 23,\n-- \/** \\brief A C++ constructor. *\/\n-- CXCursor_Constructor = 24,\n-- \/** \\brief A C++ destructor. *\/\n-- CXCursor_Destructor = 25,\n-- \/** \\brief A C++ conversion function. *\/\n-- CXCursor_ConversionFunction = 26,\n-- \/** \\brief A C++ template type parameter. *\/\n-- CXCursor_TemplateTypeParameter = 27,\n-- \/** \\brief A C++ non-type template parameter. *\/\n-- CXCursor_NonTypeTemplateParameter = 28,\n-- \/** \\brief A C++ template template parameter. *\/\n-- CXCursor_TemplateTemplateParameter = 29,\n-- \/** \\brief A C++ function template. *\/\n-- CXCursor_FunctionTemplate = 30,\n-- \/** \\brief A C++ class template. *\/\n-- CXCursor_ClassTemplate = 31,\n-- \/** \\brief A C++ class template partial specialization. *\/\n-- CXCursor_ClassTemplatePartialSpecialization = 32,\n-- \/** \\brief A C++ namespace alias declaration. *\/\n-- CXCursor_NamespaceAlias = 33,\n-- \/** \\brief A C++ using directive. *\/\n-- CXCursor_UsingDirective = 34,\n-- \/** \\brief A C++ using declaration. *\/\n-- CXCursor_UsingDeclaration = 35,\n-- \/** \\brief A C++ alias declaration *\/\n-- CXCursor_TypeAliasDecl = 36,\n-- \/** \\brief An Objective-C @synthesize definition. *\/\n-- CXCursor_ObjCSynthesizeDecl = 37,\n-- \/** \\brief An Objective-C @dynamic definition. *\/\n-- CXCursor_ObjCDynamicDecl = 38,\n-- \/** \\brief An access specifier. *\/\n-- CXCursor_CXXAccessSpecifier = 39,\n\n-- CXCursor_FirstDecl = CXCursor_UnexposedDecl,\n-- CXCursor_LastDecl = CXCursor_CXXAccessSpecifier,\n\n-- \/* References *\/\n-- CXCursor_FirstRef = 40, \/* Decl references *\/\n-- CXCursor_ObjCSuperClassRef = 40,\n-- CXCursor_ObjCProtocolRef = 41,\n-- CXCursor_ObjCClassRef = 42,\n-- \/**\n-- * \\brief A reference to a type declaration.\n-- *\n-- * A type reference occurs anywhere where a type is named but not\n-- * declared. For example, given:\n-- *\n-- * \\code\n-- * typedef unsigned size_type;\n-- * size_type size;\n-- * \\endcode\n-- *\n-- * The typedef is a declaration of size_type (CXCursor_TypedefDecl),\n-- * while the type of the variable \"size\" is referenced. The cursor\n-- * referenced by the type of size is the typedef for size_type.\n-- *\/\n-- CXCursor_TypeRef = 43,\n-- CXCursor_CXXBaseSpecifier = 44,\n-- \/**\n-- * \\brief A reference to a class template, function template, template\n-- * template parameter, or class template partial specialization.\n-- *\/\n-- CXCursor_TemplateRef = 45,\n-- \/**\n-- * \\brief A reference to a namespace or namespace alias.\n-- *\/\n-- CXCursor_NamespaceRef = 46,\n-- \/**\n-- * \\brief A reference to a member of a struct, union, or class that occurs in\n-- * some non-expression context, e.g., a designated initializer.\n-- *\/\n-- CXCursor_MemberRef = 47,\n-- \/**\n-- * \\brief A reference to a labeled statement.\n-- *\n-- * This cursor kind is used to describe the jump to \"start_over\" in the\n-- * goto statement in the following example:\n-- *\n-- * \\code\n-- * start_over:\n-- * ++counter;\n-- *\n-- * goto start_over;\n-- * \\endcode\n-- *\n-- * A label reference cursor refers to a label statement.\n-- *\/\n-- CXCursor_LabelRef = 48,\n\n-- \/**\n-- * \\brief A reference to a set of overloaded functions or function templates\n-- * that has not yet been resolved to a specific function or function template.\n-- *\n-- * An overloaded declaration reference cursor occurs in C++ templates where\n-- * a dependent name refers to a function. For example:\n-- *\n-- * \\code\n-- * template void swap(T&, T&);\n-- *\n-- * struct X { ... };\n-- * void swap(X&, X&);\n-- *\n-- * template\n-- * void reverse(T* first, T* last) {\n-- * while (first < last - 1) {\n-- * swap(*first, *--last);\n-- * ++first;\n-- * }\n-- * }\n-- *\n-- * struct Y { };\n-- * void swap(Y&, Y&);\n-- * \\endcode\n-- *\n-- * Here, the identifier \"swap\" is associated with an overloaded declaration\n-- * reference. In the template definition, \"swap\" refers to either of the two\n-- * \"swap\" functions declared above, so both results will be available. At\n-- * instantiation time, \"swap\" may also refer to other functions found via\n-- * argument-dependent lookup (e.g., the \"swap\" function at the end of the\n-- * example).\n-- *\n-- * The functions \\c clang_getNumOverloadedDecls() and\n-- * \\c clang_getOverloadedDecl() can be used to retrieve the definitions\n-- * referenced by this cursor.\n-- *\/\n-- CXCursor_OverloadedDeclRef = 49,\n\n-- \/*\n-- * \\brief A reference to a variable that occurs in some non-expression\n-- * context, e.g., a C++ lambda capture list.\n-- *\/\n-- CXCursor_VariableRef = 50,\n\n-- CXCursor_LastRef = CXCursor_VariableRef,\n\n-- \/* Error conditions *\/\n-- CXCursor_FirstInvalid = 70,\n-- CXCursor_InvalidFile = 70,\n-- CXCursor_NoDeclFound = 71,\n-- CXCursor_NotImplemented = 72,\n-- CXCursor_InvalidCode = 73,\n-- CXCursor_LastInvalid = CXCursor_InvalidCode,\n\n-- \/* Expressions *\/\n-- CXCursor_FirstExpr = 100,\n\n-- \/**\n-- * \\brief An expression whose specific kind is not exposed via this\n-- * interface.\n-- *\n-- * Unexposed expressions have the same operations as any other kind\n-- * of expression; one can extract their location information,\n-- * spelling, children, etc. However, the specific kind of the\n-- * expression is not reported.\n-- *\/\n-- CXCursor_UnexposedExpr = 100,\n\n-- \/**\n-- * \\brief An expression that refers to some value declaration, such\n-- * as a function, varible, or enumerator.\n-- *\/\n-- CXCursor_DeclRefExpr = 101,\n\n-- \/**\n-- * \\brief An expression that refers to a member of a struct, union,\n-- * class, Objective-C class, etc.\n-- *\/\n-- CXCursor_MemberRefExpr = 102,\n\n-- \/** \\brief An expression that calls a function. *\/\n-- CXCursor_CallExpr = 103,\n\n-- \/** \\brief An expression that sends a message to an Objective-C\n-- object or class. *\/\n-- CXCursor_ObjCMessageExpr = 104,\n\n-- \/** \\brief An expression that represents a block literal. *\/\n-- CXCursor_BlockExpr = 105,\n\n-- \/** \\brief An integer literal.\n-- *\/\n-- CXCursor_IntegerLiteral = 106,\n\n-- \/** \\brief A floating point number literal.\n-- *\/\n-- CXCursor_FloatingLiteral = 107,\n\n-- \/** \\brief An imaginary number literal.\n-- *\/\n-- CXCursor_ImaginaryLiteral = 108,\n\n-- \/** \\brief A string literal.\n-- *\/\n-- CXCursor_StringLiteral = 109,\n\n-- \/** \\brief A character literal.\n-- *\/\n-- CXCursor_CharacterLiteral = 110,\n\n-- \/** \\brief A parenthesized expression, e.g. \"(1)\".\n-- *\n-- * This AST node is only formed if full location information is requested.\n-- *\/\n-- CXCursor_ParenExpr = 111,\n\n-- \/** \\brief This represents the unary-expression's (except sizeof and\n-- * alignof).\n-- *\/\n-- CXCursor_UnaryOperator = 112,\n\n-- \/** \\brief [C99 6.5.2.1] Array Subscripting.\n-- *\/\n-- CXCursor_ArraySubscriptExpr = 113,\n\n-- \/** \\brief A builtin binary operation expression such as \"x + y\" or\n-- * \"x <= y\".\n-- *\/\n-- CXCursor_BinaryOperator = 114,\n\n-- \/** \\brief Compound assignment such as \"+=\".\n-- *\/\n-- CXCursor_CompoundAssignOperator = 115,\n\n-- \/** \\brief The ?: ternary operator.\n-- *\/\n-- CXCursor_ConditionalOperator = 116,\n\n-- \/** \\brief An explicit cast in C (C99 6.5.4) or a C-style cast in C++\n-- * (C++ [expr.cast]), which uses the syntax (Type)expr.\n-- *\n-- * For example: (int)f.\n-- *\/\n-- CXCursor_CStyleCastExpr = 117,\n\n-- \/** \\brief [C99 6.5.2.5]\n-- *\/\n-- CXCursor_CompoundLiteralExpr = 118,\n\n-- \/** \\brief Describes an C or C++ initializer list.\n-- *\/\n-- CXCursor_InitListExpr = 119,\n\n-- \/** \\brief The GNU address of label extension, representing &&label.\n-- *\/\n-- CXCursor_AddrLabelExpr = 120,\n\n-- \/** \\brief This is the GNU Statement Expression extension: ({int X=4; X;})\n-- *\/\n-- CXCursor_StmtExpr = 121,\n\n-- \/** \\brief Represents a C1X generic selection.\n-- *\/\n-- CXCursor_GenericSelectionExpr = 122,\n\n-- \/** \\brief Implements the GNU __null extension, which is a name for a null\n-- * pointer constant that has integral type (e.g., int or long) and is the same\n-- * size and alignment as a pointer.\n-- *\n-- * The __null extension is typically only used by system headers, which define\n-- * NULL as __null in C++ rather than using 0 (which is an integer that may not\n-- * match the size of a pointer).\n-- *\/\n-- CXCursor_GNUNullExpr = 123,\n\n-- \/** \\brief C++'s static_cast<> expression.\n-- *\/\n-- CXCursor_CXXStaticCastExpr = 124,\n\n-- \/** \\brief C++'s dynamic_cast<> expression.\n-- *\/\n-- CXCursor_CXXDynamicCastExpr = 125,\n\n-- \/** \\brief C++'s reinterpret_cast<> expression.\n-- *\/\n-- CXCursor_CXXReinterpretCastExpr = 126,\n\n-- \/** \\brief C++'s const_cast<> expression.\n-- *\/\n-- CXCursor_CXXConstCastExpr = 127,\n\n-- \/** \\brief Represents an explicit C++ type conversion that uses \"functional\"\n-- * notion (C++ [expr.type.conv]).\n-- *\n-- * Example:\n-- * \\code\n-- * x = int(0.5);\n-- * \\endcode\n-- *\/\n-- CXCursor_CXXFunctionalCastExpr = 128,\n\n-- \/** \\brief A C++ typeid expression (C++ [expr.typeid]).\n-- *\/\n-- CXCursor_CXXTypeidExpr = 129,\n\n-- \/** \\brief [C++ 2.13.5] C++ Boolean Literal.\n-- *\/\n-- CXCursor_CXXBoolLiteralExpr = 130,\n\n-- \/** \\brief [C++0x 2.14.7] C++ Pointer Literal.\n-- *\/\n-- CXCursor_CXXNullPtrLiteralExpr = 131,\n\n-- \/** \\brief Represents the \"this\" expression in C++\n-- *\/\n-- CXCursor_CXXThisExpr = 132,\n\n-- \/** \\brief [C++ 15] C++ Throw Expression.\n-- *\n-- * This handles 'throw' and 'throw' assignment-expression. When\n-- * assignment-expression isn't present, Op will be null.\n-- *\/\n-- CXCursor_CXXThrowExpr = 133,\n\n-- \/** \\brief A new expression for memory allocation and constructor calls, e.g:\n-- * \"new CXXNewExpr(foo)\".\n-- *\/\n-- CXCursor_CXXNewExpr = 134,\n\n-- \/** \\brief A delete expression for memory deallocation and destructor calls,\n-- * e.g. \"delete[] pArray\".\n-- *\/\n-- CXCursor_CXXDeleteExpr = 135,\n\n-- \/** \\brief A unary expression.\n-- *\/\n-- CXCursor_UnaryExpr = 136,\n\n-- \/** \\brief ObjCStringLiteral, used for Objective-C string literals i.e. \"foo\".\n-- *\/\n-- CXCursor_ObjCStringLiteral = 137,\n\n-- \/** \\brief ObjCEncodeExpr, used for in Objective-C.\n-- *\/\n-- CXCursor_ObjCEncodeExpr = 138,\n\n-- \/** \\brief ObjCSelectorExpr used for in Objective-C.\n-- *\/\n-- CXCursor_ObjCSelectorExpr = 139,\n\n-- \/** \\brief Objective-C's protocol expression.\n-- *\/\n-- CXCursor_ObjCProtocolExpr = 140,\n\n-- \/** \\brief An Objective-C \"bridged\" cast expression, which casts between\n-- * Objective-C pointers and C pointers, transferring ownership in the process.\n-- *\n-- * \\code\n-- * NSString *str = (__bridge_transfer NSString *)CFCreateString();\n-- * \\endcode\n-- *\/\n-- CXCursor_ObjCBridgedCastExpr = 141,\n\n-- \/** \\brief Represents a C++0x pack expansion that produces a sequence of\n-- * expressions.\n-- *\n-- * A pack expansion expression contains a pattern (which itself is an\n-- * expression) followed by an ellipsis. For example:\n-- *\n-- * \\code\n-- * template\n-- * void forward(F f, Types &&...args) {\n-- * f(static_cast(args)...);\n-- * }\n-- * \\endcode\n-- *\/\n-- CXCursor_PackExpansionExpr = 142,\n\n-- \/** \\brief Represents an expression that computes the length of a parameter\n-- * pack.\n-- *\n-- * \\code\n-- * template\n-- * struct count {\n-- * static const unsigned value = sizeof...(Types);\n-- * };\n-- * \\endcode\n-- *\/\n-- CXCursor_SizeOfPackExpr = 143,\n\n-- \/* \\brief Represents a C++ lambda expression that produces a local function\n-- * object.\n-- *\n-- * \\code\n-- * void abssort(float *x, unsigned N) {\n-- * std::sort(x, x + N,\n-- * [](float a, float b) {\n-- * return std::abs(a) < std::abs(b);\n-- * });\n-- * }\n-- * \\endcode\n-- *\/\n-- CXCursor_LambdaExpr = 144,\n\n-- \/** \\brief Objective-c Boolean Literal.\n-- *\/\n-- CXCursor_ObjCBoolLiteralExpr = 145,\n\n-- \/** \\brief Represents the \"self\" expression in a ObjC method.\n-- *\/\n-- CXCursor_ObjCSelfExpr = 146,\n\n-- CXCursor_LastExpr = CXCursor_ObjCSelfExpr,\n\n-- \/* Statements *\/\n-- CXCursor_FirstStmt = 200,\n-- \/**\n-- * \\brief A statement whose specific kind is not exposed via this\n-- * interface.\n-- *\n-- * Unexposed statements have the same operations as any other kind of\n-- * statement; one can extract their location information, spelling,\n-- * children, etc. However, the specific kind of the statement is not\n-- * reported.\n-- *\/\n-- CXCursor_UnexposedStmt = 200,\n\n-- \/** \\brief A labelled statement in a function.\n-- *\n-- * This cursor kind is used to describe the \"start_over:\" label statement in\n-- * the following example:\n-- *\n-- * \\code\n-- * start_over:\n-- * ++counter;\n-- * \\endcode\n-- *\n-- *\/\n-- CXCursor_LabelStmt = 201,\n\n-- \/** \\brief A group of statements like { stmt stmt }.\n-- *\n-- * This cursor kind is used to describe compound statements, e.g. function\n-- * bodies.\n-- *\/\n-- CXCursor_CompoundStmt = 202,\n\n-- \/** \\brief A case statment.\n-- *\/\n-- CXCursor_CaseStmt = 203,\n\n-- \/** \\brief A default statement.\n-- *\/\n-- CXCursor_DefaultStmt = 204,\n\n-- \/** \\brief An if statement\n-- *\/\n-- CXCursor_IfStmt = 205,\n\n-- \/** \\brief A switch statement.\n-- *\/\n-- CXCursor_SwitchStmt = 206,\n\n-- \/** \\brief A while statement.\n-- *\/\n-- CXCursor_WhileStmt = 207,\n\n-- \/** \\brief A do statement.\n-- *\/\n-- CXCursor_DoStmt = 208,\n\n-- \/** \\brief A for statement.\n-- *\/\n-- CXCursor_ForStmt = 209,\n\n-- \/** \\brief A goto statement.\n-- *\/\n-- CXCursor_GotoStmt = 210,\n\n-- \/** \\brief An indirect goto statement.\n-- *\/\n-- CXCursor_IndirectGotoStmt = 211,\n\n-- \/** \\brief A continue statement.\n-- *\/\n-- CXCursor_ContinueStmt = 212,\n\n-- \/** \\brief A break statement.\n-- *\/\n-- CXCursor_BreakStmt = 213,\n\n-- \/** \\brief A return statement.\n-- *\/\n-- CXCursor_ReturnStmt = 214,\n\n-- \/** \\brief A GNU inline assembly statement extension.\n-- *\/\n-- CXCursor_GCCAsmStmt = 215,\n-- CXCursor_AsmStmt = CXCursor_GCCAsmStmt,\n\n-- \/** \\brief Objective-C's overall @try-@catc-@finall statement.\n-- *\/\n-- CXCursor_ObjCAtTryStmt = 216,\n\n-- \/** \\brief Objective-C's @catch statement.\n-- *\/\n-- CXCursor_ObjCAtCatchStmt = 217,\n\n-- \/** \\brief Objective-C's @finally statement.\n-- *\/\n-- CXCursor_ObjCAtFinallyStmt = 218,\n\n-- \/** \\brief Objective-C's @throw statement.\n-- *\/\n-- CXCursor_ObjCAtThrowStmt = 219,\n\n-- \/** \\brief Objective-C's @synchronized statement.\n-- *\/\n-- CXCursor_ObjCAtSynchronizedStmt = 220,\n\n-- \/** \\brief Objective-C's autorelease pool statement.\n-- *\/\n-- CXCursor_ObjCAutoreleasePoolStmt = 221,\n\n-- \/** \\brief Objective-C's collection statement.\n-- *\/\n-- CXCursor_ObjCForCollectionStmt = 222,\n\n-- \/** \\brief C++'s catch statement.\n-- *\/\n-- CXCursor_CXXCatchStmt = 223,\n\n-- \/** \\brief C++'s try statement.\n-- *\/\n-- CXCursor_CXXTryStmt = 224,\n\n-- \/** \\brief C++'s for (* : *) statement.\n-- *\/\n-- CXCursor_CXXForRangeStmt = 225,\n\n-- \/** \\brief Windows Structured Exception Handling's try statement.\n-- *\/\n-- CXCursor_SEHTryStmt = 226,\n\n-- \/** \\brief Windows Structured Exception Handling's except statement.\n-- *\/\n-- CXCursor_SEHExceptStmt = 227,\n\n-- \/** \\brief Windows Structured Exception Handling's finally statement.\n-- *\/\n-- CXCursor_SEHFinallyStmt = 228,\n\n-- \/** \\brief A MS inline assembly statement extension.\n-- *\/\n-- CXCursor_MSAsmStmt = 229,\n\n-- \/** \\brief The null satement \";\": C99 6.8.3p3.\n-- *\n-- * This cursor kind is used to describe the null statement.\n-- *\/\n-- CXCursor_NullStmt = 230,\n\n-- \/** \\brief Adaptor class for mixing declarations with statements and\n-- * expressions.\n-- *\/\n-- CXCursor_DeclStmt = 231,\n\n-- \/** \\brief OpenMP parallel directive.\n-- *\/\n-- CXCursor_OMPParallelDirective = 232,\n\n-- CXCursor_LastStmt = CXCursor_OMPParallelDirective,\n\n-- \/**\n-- * \\brief Cursor that represents the translation unit itself.\n-- *\n-- * The translation unit cursor exists primarily to act as the root\n-- * cursor for traversing the contents of a translation unit.\n-- *\/\n-- CXCursor_TranslationUnit = 300,\n\n-- \/* Attributes *\/\n-- CXCursor_FirstAttr = 400,\n-- \/**\n-- * \\brief An attribute whose specific kind is not exposed via this\n-- * interface.\n-- *\/\n-- CXCursor_UnexposedAttr = 400,\n\n-- CXCursor_IBActionAttr = 401,\n-- CXCursor_IBOutletAttr = 402,\n-- CXCursor_IBOutletCollectionAttr = 403,\n-- CXCursor_CXXFinalAttr = 404,\n-- CXCursor_CXXOverrideAttr = 405,\n-- CXCursor_AnnotateAttr = 406,\n-- CXCursor_AsmLabelAttr = 407,\n-- CXCursor_PackedAttr = 408,\n-- CXCursor_LastAttr = CXCursor_PackedAttr,\n\n-- \/* Preprocessing *\/\n-- CXCursor_PreprocessingDirective = 500,\n-- CXCursor_MacroDefinition = 501,\n-- CXCursor_MacroExpansion = 502,\n-- CXCursor_MacroInstantiation = CXCursor_MacroExpansion,\n-- CXCursor_InclusionDirective = 503,\n-- CXCursor_FirstPreprocessing = CXCursor_PreprocessingDirective,\n-- CXCursor_LastPreprocessing = CXCursor_InclusionDirective\n\n-- \/* Extra Declarations *\/\n-- \/**\n-- * \\brief A module import declaration.\n-- *\/\n-- CXCursor_ModuleImportDecl = 600,\n-- CXCursor_FirstExtraDecl = CXCursor_ModuleImportDecl,\n-- CXCursor_LastExtraDecl = CXCursor_ModuleImportDecl\n-- };\n#c\nenum CursorKind\n { UnexposedDeclCursor = CXCursor_UnexposedDecl\n , StructDeclCursor = CXCursor_StructDecl\n , UnionDeclCursor = CXCursor_UnionDecl\n , ClassDeclCursor = CXCursor_ClassDecl\n , EnumDeclCursor = CXCursor_EnumDecl\n , FieldDeclCursor = CXCursor_FieldDecl\n , EnumConstantDeclCursor = CXCursor_EnumConstantDecl\n , FunctionDeclCursor = CXCursor_FunctionDecl\n , VarDeclCursor = CXCursor_VarDecl\n , ParmDeclCursor = CXCursor_ParmDecl\n , ObjCInterfaceDeclCursor = CXCursor_ObjCInterfaceDecl\n , ObjCCategoryDeclCursor = CXCursor_ObjCCategoryDecl\n , ObjCProtocolDeclCursor = CXCursor_ObjCProtocolDecl\n , ObjCPropertyDeclCursor = CXCursor_ObjCPropertyDecl\n , ObjCIvarDeclCursor = CXCursor_ObjCIvarDecl\n , ObjCInstanceMethodDeclCursor = CXCursor_ObjCInstanceMethodDecl\n , ObjCClassMethodDeclCursor = CXCursor_ObjCClassMethodDecl\n , ObjCImplementationDeclCursor = CXCursor_ObjCImplementationDecl\n , ObjCCategoryImplDeclCursor = CXCursor_ObjCCategoryImplDecl\n , TypedefDeclCursor = CXCursor_TypedefDecl\n , CXXMethodCursor = CXCursor_CXXMethod\n , NamespaceCursor = CXCursor_Namespace\n , LinkageSpecCursor = CXCursor_LinkageSpec\n , ConstructorCursor = CXCursor_Constructor\n , DestructorCursor = CXCursor_Destructor\n , ConversionFunctionCursor = CXCursor_ConversionFunction\n , TemplateTypeParameterCursor = CXCursor_TemplateTypeParameter\n , NonTypeTemplateParameterCursor = CXCursor_NonTypeTemplateParameter\n , TemplateTemplateParameterCursor = CXCursor_TemplateTemplateParameter\n , FunctionTemplateCursor = CXCursor_FunctionTemplate\n , ClassTemplateCursor = CXCursor_ClassTemplate\n , ClassTemplatePartialSpecializationCursor = CXCursor_ClassTemplatePartialSpecialization\n , NamespaceAliasCursor = CXCursor_NamespaceAlias\n , UsingDirectiveCursor = CXCursor_UsingDirective\n , UsingDeclarationCursor = CXCursor_UsingDeclaration\n , TypeAliasDeclCursor = CXCursor_TypeAliasDecl\n , ObjCSynthesizeDeclCursor = CXCursor_ObjCSynthesizeDecl\n , ObjCDynamicDeclCursor = CXCursor_ObjCDynamicDecl\n , CXXAccessSpecifierCursor = CXCursor_CXXAccessSpecifier\n , ObjCSuperClassRefCursor = CXCursor_ObjCSuperClassRef\n , ObjCProtocolRefCursor = CXCursor_ObjCProtocolRef\n , ObjCClassRefCursor = CXCursor_ObjCClassRef\n , TypeRefCursor = CXCursor_TypeRef\n , CXXBaseSpecifierCursor = CXCursor_CXXBaseSpecifier\n , TemplateRefCursor = CXCursor_TemplateRef\n , NamespaceRefCursor = CXCursor_NamespaceRef\n , MemberRefCursor = CXCursor_MemberRef\n , LabelRefCursor = CXCursor_LabelRef\n , OverloadedDeclRefCursor = CXCursor_OverloadedDeclRef\n , VariableRefCursor = CXCursor_VariableRef\n , InvalidFileCursor = CXCursor_InvalidFile\n , NoDeclFoundCursor = CXCursor_NoDeclFound\n , NotImplementedCursor = CXCursor_NotImplemented\n , InvalidCodeCursor = CXCursor_InvalidCode\n , UnexposedExprCursor = CXCursor_UnexposedExpr\n , DeclRefExprCursor = CXCursor_DeclRefExpr\n , MemberRefExprCursor = CXCursor_MemberRefExpr\n , CallExprCursor = CXCursor_CallExpr\n , ObjCMessageExprCursor = CXCursor_ObjCMessageExpr\n , BlockExprCursor = CXCursor_BlockExpr\n , IntegerLiteralCursor = CXCursor_IntegerLiteral\n , FloatingLiteralCursor = CXCursor_FloatingLiteral\n , ImaginaryLiteralCursor = CXCursor_ImaginaryLiteral\n , StringLiteralCursor = CXCursor_StringLiteral\n , CharacterLiteralCursor = CXCursor_CharacterLiteral\n , ParenExprCursor = CXCursor_ParenExpr\n , UnaryOperatorCursor = CXCursor_UnaryOperator\n , ArraySubscriptExprCursor = CXCursor_ArraySubscriptExpr\n , BinaryOperatorCursor = CXCursor_BinaryOperator\n , CompoundAssignOperatorCursor = CXCursor_CompoundAssignOperator\n , ConditionalOperatorCursor = CXCursor_ConditionalOperator\n , CStyleCastExprCursor = CXCursor_CStyleCastExpr\n , CompoundLiteralExprCursor = CXCursor_CompoundLiteralExpr\n , InitListExprCursor = CXCursor_InitListExpr\n , AddrLabelExprCursor = CXCursor_AddrLabelExpr\n , StmtExprCursor = CXCursor_StmtExpr\n , GenericSelectionExprCursor = CXCursor_GenericSelectionExpr\n , GNUNullExprCursor = CXCursor_GNUNullExpr\n , CXXStaticCastExprCursor = CXCursor_CXXStaticCastExpr\n , CXXDynamicCastExprCursor = CXCursor_CXXDynamicCastExpr\n , CXXReinterpretCastExprCursor = CXCursor_CXXReinterpretCastExpr\n , CXXConstCastExprCursor = CXCursor_CXXConstCastExpr\n , CXXFunctionalCastExprCursor = CXCursor_CXXFunctionalCastExpr\n , CXXTypeidExprCursor = CXCursor_CXXTypeidExpr\n , CXXBoolLiteralExprCursor = CXCursor_CXXBoolLiteralExpr\n , CXXNullPtrLiteralExprCursor = CXCursor_CXXNullPtrLiteralExpr\n , CXXThisExprCursor = CXCursor_CXXThisExpr\n , CXXThrowExprCursor = CXCursor_CXXThrowExpr\n , CXXNewExprCursor = CXCursor_CXXNewExpr\n , CXXDeleteExprCursor = CXCursor_CXXDeleteExpr\n , UnaryExprCursor = CXCursor_UnaryExpr\n , ObjCStringLiteralCursor = CXCursor_ObjCStringLiteral\n , ObjCEncodeExprCursor = CXCursor_ObjCEncodeExpr\n , ObjCSelectorExprCursor = CXCursor_ObjCSelectorExpr\n , ObjCProtocolExprCursor = CXCursor_ObjCProtocolExpr\n , ObjCBridgedCastExprCursor = CXCursor_ObjCBridgedCastExpr\n , PackExpansionExprCursor = CXCursor_PackExpansionExpr\n , SizeOfPackExprCursor = CXCursor_SizeOfPackExpr\n , LambdaExprCursor = CXCursor_LambdaExpr\n , ObjCBoolLiteralExprCursor = CXCursor_ObjCBoolLiteralExpr\n , ObjCSelfExprCursor = CXCursor_ObjCSelfExpr\n , UnexposedStmtCursor = CXCursor_UnexposedStmt\n , LabelStmtCursor = CXCursor_LabelStmt\n , CompoundStmtCursor = CXCursor_CompoundStmt\n , CaseStmtCursor = CXCursor_CaseStmt\n , DefaultStmtCursor = CXCursor_DefaultStmt\n , IfStmtCursor = CXCursor_IfStmt\n , SwitchStmtCursor = CXCursor_SwitchStmt\n , WhileStmtCursor = CXCursor_WhileStmt\n , DoStmtCursor = CXCursor_DoStmt\n , ForStmtCursor = CXCursor_ForStmt\n , GotoStmtCursor = CXCursor_GotoStmt\n , IndirectGotoStmtCursor = CXCursor_IndirectGotoStmt\n , ContinueStmtCursor = CXCursor_ContinueStmt\n , BreakStmtCursor = CXCursor_BreakStmt\n , ReturnStmtCursor = CXCursor_ReturnStmt\n , AsmStmtCursor = CXCursor_AsmStmt\n , ObjCAtTryStmtCursor = CXCursor_ObjCAtTryStmt\n , ObjCAtCatchStmtCursor = CXCursor_ObjCAtCatchStmt\n , ObjCAtFinallyStmtCursor = CXCursor_ObjCAtFinallyStmt\n , ObjCAtThrowStmtCursor = CXCursor_ObjCAtThrowStmt\n , ObjCAtSynchronizedStmtCursor = CXCursor_ObjCAtSynchronizedStmt\n , ObjCAutoreleasePoolStmtCursor = CXCursor_ObjCAutoreleasePoolStmt\n , ObjCForCollectionStmtCursor = CXCursor_ObjCForCollectionStmt\n , CXXCatchStmtCursor = CXCursor_CXXCatchStmt\n , CXXTryStmtCursor = CXCursor_CXXTryStmt\n , CXXForRangeStmtCursor = CXCursor_CXXForRangeStmt\n , SEHTryStmtCursor = CXCursor_SEHTryStmt\n , SEHExceptStmtCursor = CXCursor_SEHExceptStmt\n , SEHFinallyStmtCursor = CXCursor_SEHFinallyStmt\n , MSAsmStmtCursor = CXCursor_MSAsmStmt\n , NullStmtCursor = CXCursor_NullStmt\n , DeclStmtCursor = CXCursor_DeclStmt\n , OMPParallelDirectiveCursor = CXCursor_OMPParallelDirective\n , TranslationUnitCursor = CXCursor_TranslationUnit\n , UnexposedAttrCursor = CXCursor_UnexposedAttr\n , IBActionAttrCursor = CXCursor_IBActionAttr\n , IBOutletAttrCursor = CXCursor_IBOutletAttr\n , IBOutletCollectionAttrCursor = CXCursor_IBOutletCollectionAttr\n , CXXFinalAttrCursor = CXCursor_CXXFinalAttr\n , CXXOverrideAttrCursor = CXCursor_CXXOverrideAttr\n , AnnotateAttrCursor = CXCursor_AnnotateAttr\n , AsmLabelAttrCursor = CXCursor_AsmLabelAttr\n , PackedAttrCursor = CXCursor_PackedAttr\n , PreprocessingDirectiveCursor = CXCursor_PreprocessingDirective\n , MacroDefinitionCursor = CXCursor_MacroDefinition\n , MacroExpansionCursor = CXCursor_MacroExpansion\n , InclusionDirectiveCursor = CXCursor_InclusionDirective\n , ModuleImportDeclCursor = CXCursor_ModuleImportDecl\n };\n#endc\n{#enum CursorKind{} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- CursorKind ranges.\nfirstDeclCursor, lastDeclCursor, firstRefCursor, lastRefCursor :: CursorKind\nfirstInvalidCursor, lastInvalidCursor, firstExprCursor, lastExprCursor :: CursorKind\nfirstStmtCursor, lastStmtCursor, firstAttrCursor, lastAttrCursor :: CursorKind\nfirstPreprocessingCursor, lastPreprocessingCursor :: CursorKind\nfirstExtraDeclCursor, lastExtraDeclCursor :: CursorKind\n\nfirstDeclCursor = UnexposedDeclCursor\nlastDeclCursor = CXXAccessSpecifierCursor\nfirstRefCursor = ObjCSuperClassRefCursor\nlastRefCursor = VariableRefCursor\nfirstInvalidCursor = InvalidFileCursor\nlastInvalidCursor = InvalidCodeCursor\nfirstExprCursor = UnexposedExprCursor\nlastExprCursor = ObjCSelfExprCursor\nfirstStmtCursor = UnexposedStmtCursor\nlastStmtCursor = OMPParallelDirectiveCursor\nfirstAttrCursor = UnexposedAttrCursor\nlastAttrCursor = PackedAttrCursor\nfirstPreprocessingCursor = PreprocessingDirectiveCursor\nlastPreprocessingCursor = InclusionDirectiveCursor\nfirstExtraDeclCursor = ModuleImportDeclCursor\nlastExtraDeclCursor = ModuleImportDeclCursor\n\n-- CursorKind aliases.\ngccAsmStmtCursor, macroInstantiationCursor :: CursorKind\ngccAsmStmtCursor = AsmStmtCursor\nmacroInstantiationCursor = MacroExpansionCursor\n\n-- typedef struct {\n-- const void *ASTNode;\n-- CXTranslationUnit TranslationUnit;\n-- } CXComment;\ndata Comment s = Comment !(Ptr ()) !(Ptr ())\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue Comment\n\ninstance Storable (Comment s) where\n sizeOf _ = sizeOfCXComment\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfCXComment\n {-# INLINE alignment #-}\n\n peek p = do\n astNode <- {#get CXComment->ASTNode #} p\n tu <- {#get CXComment->TranslationUnit #} p\n return $! Comment astNode tu\n {-# INLINE peek #-}\n\n poke p (Comment astNode tu)= do\n {#set CXComment->ASTNode #} p astNode\n {#set CXComment->TranslationUnit #} p tu\n {-# INLINE poke #-}\n\n-- typedef struct {\n-- enum CXCursorKind kind;\n-- int xdata;\n-- const void* data[3];\n-- } CXCursor;\ndata Cursor s = Cursor !CursorKind !Int !(Ptr ()) !(Ptr ()) !(Ptr ())\n deriving (Ord, Typeable)\n\ninstance ClangValue Cursor\n\ninstance Storable (Cursor s) where\n sizeOf _ = sizeOfCXCursor\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfCXCursor\n {-# INLINE alignment #-}\n\n peek p = do\n cursorKind <- {#get CXCursor->kind #} p\n xdata <- {#get CXCursor->xdata #} p\n cursorData <- {#get CXCursor->data #} p >>= peekArray 3\n return $! Cursor (toEnum (fromIntegral cursorKind)) (fromIntegral xdata) (cursorData !! 0) (cursorData !! 1) (cursorData !! 2)\n {-# INLINE peek #-}\n\n poke p (Cursor kind xdata p0 p1 p2)= do\n ptrsArray <- mallocArray 3\n pokeArray ptrsArray [p0,p1,p2]\n {#set CXCursor->kind #} p (fromIntegral (fromEnum kind))\n {#set CXCursor->xdata #} p (fromIntegral xdata)\n {#set CXCursor->data #} p (castPtr ptrsArray)\n {-# INLINE poke #-}\n\ninstance Eq (Cursor s) where\n (Cursor aK aXdata aP1 aP2 aP3) == (Cursor bK bXdata bP1 bP2 bP3) =\n (aK == bK) &&\n (aXdata == bXdata) &&\n (aP1 == bP1) &&\n (aP2' == bP2') &&\n (aP3 == bP3)\n where\n aP2' = if isDeclaration aK then intPtrToPtr 0 else aP2\n bP2' = if isDeclaration bK then intPtrToPtr 0 else bP2\n {-# INLINE (==) #-}\n\ninstance Hashable (Cursor s) where\n hashWithSalt salt (Cursor k _ p1 p2 _) =\n let p = if isExpression k || isStatement k then p2 else p1\n kindHash = hashWithSalt salt (fromEnum k)\n pAsInt = fromIntegral (ptrToIntPtr p) :: Int\n in hashWithSalt kindHash pAsInt\n {-# INLINE hash #-}\n\n-- CXCursor clang_getNullCursor(void);\ngetNullCursor :: ClangBase m => ClangT s m (Cursor s)\ngetNullCursor =\n return $ Cursor InvalidFileCursor 0 (intPtrToPtr 0) (intPtrToPtr 0) (intPtrToPtr 0)\n{-# INLINE getNullCursor #-}\n\n-- CXCursor clang_getTranslationUnitCursor(CXTranslationUnit);\n{# fun wrapped_clang_getTranslationUnitCursor as clang_getTranslationUnitCursor { id `Ptr ()' } -> `Ptr (Cursor s)' castPtr #}\ngetTranslationUnitCursor :: Proxy s -> TranslationUnit s' -> IO (Cursor s)\ngetTranslationUnitCursor _ (TranslationUnit tPtr) = clang_getTranslationUnitCursor tPtr >>= peek\n\n-- int clang_Cursor_isNull(CXCursor);\ncursor_isNull :: Cursor s -> Bool\ncursor_isNull (Cursor k xdata p1 p2 p3)\n | k == InvalidFileCursor &&\n xdata == 0 &&\n p1 == intPtrToPtr 0 &&\n p2 == intPtrToPtr 0 &&\n p3 == intPtrToPtr 0\n = True\n | otherwise\n = False\n{-# INLINE cursor_isNull #-}\n\n-- unsigned clang_hashCursor(CXCursor);\n{# fun clang_hashCursor {withVoided* %`Cursor a' } -> `Word32' #}\nhashCursor :: Cursor s -> IO Word32\nhashCursor c = clang_hashCursor c\n{-# INLINEABLE hashCursor #-}\n\ngetCursorKind :: Cursor s -> CursorKind\ngetCursorKind (Cursor k _ _ _ _) = k\n{-# INLINE getCursorKind #-}\n\n-- unsigned clang_isDeclaration(enum CursorKind);\nisDeclaration :: CursorKind -> Bool\nisDeclaration k =\n (k >= firstDeclCursor && k <= lastDeclCursor) ||\n (k >= firstExtraDeclCursor && k <= lastExtraDeclCursor)\n{-# INLINE isDeclaration #-}\n\n-- unsigned clang_isReference(enum CursorKind);\nisReference :: CursorKind -> Bool\nisReference k =\n (k >= firstRefCursor && k <= lastRefCursor)\n{-# INLINE isReference #-}\n\n-- unsigned clang_isExpression(enum CursorKind);\nisExpression :: CursorKind -> Bool\nisExpression k =\n (k >= firstExprCursor && k <= lastExprCursor)\n{-# INLINE isExpression #-}\n\n-- unsigned clang_isStatement(enum CursorKind);\nisStatement :: CursorKind -> Bool\nisStatement k =\n (k >= firstStmtCursor && k <= lastStmtCursor)\n{-# INLINE isStatement #-}\n\nisAttribute :: CursorKind -> Bool\nisAttribute k =\n (k >= firstAttrCursor && k <= lastAttrCursor)\n{-# INLINE isAttribute #-}\n\n-- unsigned clang_isInvalid(enum CursorKind);\nisInvalid :: CursorKind -> Bool\nisInvalid k =\n (k >= firstInvalidCursor && k <= lastInvalidCursor)\n{-# INLINE isInvalid #-}\n\n-- unsigned clang_isTranslationUnit(enum CursorKind);\nisTranslationUnit :: CursorKind -> Bool\nisTranslationUnit TranslationUnitCursor = True\nisTranslationUnit _ = False\n{-# INLINE isTranslationUnit #-}\n\n-- unsigned clang_isPreprocessing(enum CursorKind);\nisPreprocessing :: CursorKind -> Bool\nisPreprocessing k =\n (k >= firstPreprocessingCursor && k <= lastPreprocessingCursor)\n{-# INLINE isPreprocessing #-}\n\n-- unsigned clang_isUnexposed(enum CursorKind);\nisUnexposed :: CursorKind -> Bool\nisUnexposed k =\n (k >= firstPreprocessingCursor && k <= lastPreprocessingCursor)\n{-# INLINE isUnexposed #-}\n\n-- enum CXLinkageKind {\n-- CXLinkage_Invalid,\n-- CXLinkage_NoLinkage,\n-- CXLinkage_Internal,\n-- CXLinkage_UniqueExternal,\n-- CXLinkage_External\n-- };\n#c\nenum LinkageKind\n { Linkage_Invalid = CXLinkage_Invalid\n , Linkage_NoLinkage = CXLinkage_NoLinkage\n , Linkage_Internal = CXLinkage_Internal\n , Linkage_UniqueExternal = CXLinkage_UniqueExternal\n , Linkage_External = CXLinkage_External\n };\n#endc\n{#enum LinkageKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- enum CXLinkageKind clang_getCursorLinkage(CXCursor cursor);\n{# fun clang_getCursorLinkage {withVoided* %`Cursor a' } -> `Int' #}\ngetCursorLinkage :: Cursor s -> IO LinkageKind\ngetCursorLinkage c = clang_getCursorLinkage c >>= return . toEnum\n\n-- enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor);\n{# fun clang_getCursorAvailability {withVoided* %`Cursor a' } -> `Int' #}\ngetCursorAvailability :: Cursor s -> IO AvailabilityKind\ngetCursorAvailability c = clang_getCursorAvailability c >>= return . toEnum\n\ndata PlatformAvailability = PlatformAvailability\n { availabilityPlatform :: !B.ByteString\n , availabilityIntroduced :: !Version\n , availabilityDeprecated :: !Version\n , availabilityObsoleted :: !Version\n , availabilityIsUnavailable :: !Bool\n , availabilityMessage :: !B.ByteString\n } deriving (Eq, Ord, Typeable)\n\ninstance Storable PlatformAvailability where\n sizeOf _ = sizeOfCXPlatformAvailability\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfCXPlatformAvailability\n {-# INLINE alignment #-}\n\n peek p = do\n (ClangString platD platF) <- peekByteOff p offsetCXPlatformAvailabilityPlatform\n platform <- B.packCString =<< getCStringPtr platD platF\n\n introduced <- peekByteOff p offsetCXPlatformAvailabilityIntroduced\n deprecated <- peekByteOff p offsetCXPlatformAvailabilityDeprecated\n obsoleted <- peekByteOff p offsetCXPlatformAvailabilityObsoleted\n intUnavailable :: Int <- fromCInt <$> peekByteOff p offsetCXPlatformAvailabilityUnavailable\n\n (ClangString msgD msgF) <- peekByteOff p offsetCXPlatformAvailabilityMessage\n message <- B.packCString =<< getCStringPtr msgD msgF\n\n return $! PlatformAvailability platform introduced deprecated obsoleted\n (if intUnavailable == 0 then False else True)\n message\n {-# INLINE peek #-}\n\n -- Since we can't construct ClangStrings, we can't really poke these.\n poke _ _ = undefined\n {-# INLINE poke #-}\n\n-- void clang_disposeCXPlatformAvailability(CXPlatformAvailability);\n{# fun clang_disposeCXPlatformAvailability { id `Ptr ()' } -> `()' #}\ndisposeCXPlatformAvailability :: Ptr PlatformAvailability -> IO ()\ndisposeCXPlatformAvailability p = clang_disposeCXPlatformAvailability (castPtr p)\n\n-- int clang_getCursorPlatformAvailability(CXCursor cursor,\n-- int *always_deprecated,\n-- CXString *deprecated_message,\n-- int *always_unavailable,\n-- CXString *unavailable_message,\n-- CXPlatformAvailability *availability,\n-- int availability_size);\n{# fun clang_getCursorPlatformAvailability {withVoided* %`Cursor a', alloca- `CInt' peek*, id `Ptr ()', alloca- `CInt' peek*, id `Ptr ()', id `Ptr ()', `Int' } -> `Int' #}\nunsafe_getCursorPlatformAvailability :: Cursor s' -> Ptr PlatformAvailability -> Int -> IO (Bool, ClangString (), Bool, ClangString (), Int)\nunsafe_getCursorPlatformAvailability c dest destLen =\n alloca (\\(dMsgPtr :: (Ptr (ClangString ()))) ->\n alloca (\\(uMsgPtr :: (Ptr (ClangString ()))) -> do\n (size, ad, au) <- clang_getCursorPlatformAvailability\n c\n (castPtr dMsgPtr)\n (castPtr uMsgPtr)\n (castPtr dest)\n destLen\n dm <- peek dMsgPtr\n um <- peek uMsgPtr\n return (toBool ad, dm, toBool au, um, size)))\n\ndata PlatformAvailabilityInfo s = PlatformAvailabilityInfo\n { availabilityAlwaysDeprecated :: !Bool\n , availabilityDeprecatedMessage :: !(ClangString s)\n , availabilityAlwaysUnavailable :: !Bool\n , availabilityUnavailableMessage :: !(ClangString s)\n , availabilityInfo :: ![PlatformAvailability]\n } deriving (Eq, Ord, Typeable)\n\ninstance ClangValue PlatformAvailabilityInfo\n\ngetCursorPlatformAvailability :: ClangBase m => Cursor s'\n -> ClangT s m (PlatformAvailabilityInfo s)\ngetCursorPlatformAvailability c = do\n (ad, dMsg, au, uMsg, infos) <-\n liftIO $ allocaArray maxPlatformAvailability $ \\p -> do\n (ad, dMsg, au, uMsg, outSize) <-\n unsafe_getCursorPlatformAvailability c p maxPlatformAvailability\n let count = min outSize maxPlatformAvailability\n infos <- peekArray count p\n forM_ [0..(count - 1)] $ \\idx -> do\n disposeCXPlatformAvailability (advancePtr p idx)\n return (ad, dMsg, au, uMsg, infos)\n dMsg' <- registerClangString $ return dMsg\n uMsg' <- registerClangString $ return uMsg\n return $ PlatformAvailabilityInfo ad dMsg' au uMsg' infos\n where\n maxPlatformAvailability = 32\n\n-- enum CXLanguageKind {\n-- CXLanguage_Invalid = 0,\n-- CXLanguage_C,\n-- CXLanguage_ObjC,\n-- CXLanguage_CPlusPlus\n-- };\n#c\nenum LanguageKind {\n Language_Invalid = CXLanguage_Invalid\n , Language_C = CXLanguage_C\n , Language_ObjC = CXLanguage_ObjC\n , Language_CPlusPlus = CXLanguage_CPlusPlus\n };\n#endc\n\n{#enum LanguageKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- enum CXLanguageKind clang_getCursorLanguage(CXCursor cursor);\n{# fun clang_getCursorLanguage {withVoided* %`Cursor a' } -> `Int' #}\ngetCursorLanguage :: Cursor s -> IO LanguageKind\ngetCursorLanguage c = clang_getCursorLanguage c >>= return . toEnum\n\n-- CXTranslationUnit clang_Cursor_getTranslationUnit(CXCursor);\n{# fun clang_Cursor_getTranslationUnit {withVoided* %`Cursor a' } -> `Ptr ()' id #}\nunsafe_Cursor_getTranslationUnit :: Cursor s -> IO (TranslationUnit ())\nunsafe_Cursor_getTranslationUnit c =\n clang_Cursor_getTranslationUnit c >>= return . mkTranslationUnit\n\n-- Note that we do not register the translation unit! This function\n-- never creates a 'new' translation unit, so we don't need to dispose\n-- it. Moreover, since translation units aren't reference counted doing\n-- so will lead to crashes.\ncursor_getTranslationUnit :: ClangBase m => Cursor s' -> ClangT s m (TranslationUnit s)\ncursor_getTranslationUnit c = liftIO $ unsafeCoerce <$> unsafe_Cursor_getTranslationUnit c\n\n-- typedef struct CXCursorSetImpl *CXCursorSet;\nnewtype CursorSet s = CursorSet { unCursorSet :: Ptr () }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue CursorSet\n\n-- void clang_disposeCXCursorSet(CXCursorSet cset);\n{# fun clang_disposeCXCursorSet { id `Ptr ()' } -> `()' #}\ndisposeCXCursorSet :: CursorSet s -> IO ()\ndisposeCXCursorSet cs = clang_disposeCXCursorSet (unCursorSet cs)\n\nregisterCursorSet :: ClangBase m => IO (CursorSet ()) -> ClangT s m (CursorSet s)\nregisterCursorSet action = do\n (_, idx) <- clangAllocate (action >>= return . unsafeCoerce)\n (\\i -> disposeCXCursorSet i)\n return idx\n{-# INLINEABLE registerCursorSet #-}\n\n-- CXCursorSet clang_createCXCursorSet();\n{# fun clang_createCXCursorSet as clang_createCXCursorSet {} -> `Ptr ()' id #}\nunsafe_createCXCursorSet :: IO (CursorSet ())\nunsafe_createCXCursorSet = clang_createCXCursorSet >>= return . CursorSet\n\ncreateCXCursorSet :: ClangBase m => ClangT s m (CursorSet s)\ncreateCXCursorSet = registerCursorSet unsafe_createCXCursorSet\n\n-- unsigned clang_CXCursorSet_contains(CXCursorSet cset, CXCursor cursor);\n{# fun clang_CXCursorSet_contains {id `Ptr ()' ,withVoided* %`Cursor a' } -> `Bool' toBool #}\ncXCursorSet_contains :: CursorSet s -> Cursor s' -> IO Bool\ncXCursorSet_contains cs c =\n clang_CXCursorSet_contains (unCursorSet cs) c\n\n-- unsigned clang_CXCursorSet_insert(CXCursorSet cset, CXCursor cursor);\n{# fun clang_CXCursorSet_insert {id `Ptr ()', withVoided* %`Cursor a' } -> `Bool' toBool #}\ncXCursorSet_insert :: CursorSet s -> Cursor s' -> IO Bool\ncXCursorSet_insert cs c =\n clang_CXCursorSet_insert (unCursorSet cs) c\n\n-- CXCursor clang_getCursorSemanticParent(CXCursor cursor);\n{# fun wrapped_clang_getCursorSemanticParent as clang_getCursorSemanticParent {withVoided* %`Cursor a' } -> `Ptr (Cursor s)' castPtr #}\ngetCursorSemanticParent :: Proxy s -> Cursor s' -> IO (Cursor s)\ngetCursorSemanticParent _ c =\n clang_getCursorSemanticParent c >>= peek\n\n-- CXCursor clang_getCursorLexicalParent(CXCursor cursor);\n{# fun wrapped_clang_getCursorLexicalParent as clang_getCursorLexicalParent {withVoided* %`Cursor a' } -> `Ptr (Cursor s)' castPtr #}\ngetCursorLexicalParent :: Proxy s -> Cursor s' -> IO (Cursor s)\ngetCursorLexicalParent _ c =\n clang_getCursorLexicalParent c >>= peek\n\n-- void clang_disposeOverriddenCursors(CXCursor *overridden);\n{# fun clang_disposeOverriddenCursors { id `Ptr ()' } -> `()' #}\ndisposeOverridden :: CursorList s -> IO ()\ndisposeOverridden cl =\n let (csPtr, _) = fromCursorList cl in\n clang_disposeOverriddenCursors csPtr\n\nregisterOverriddenList :: ClangBase m => IO UnsafeCursorList -> ClangT s m (CursorList s)\nregisterOverriddenList action = do\n (_, cursorList) <- clangAllocate (action >>= cursorListToVector) disposeOverridden\n return cursorList\n{-# INLINEABLE registerOverriddenList #-}\n\n-- void clang_getOverriddenCursors(CXCursor cursor, CXCursor **overridden, unsigned *num_overridden);\n{# fun clang_getOverriddenCursors {withVoided* %`Cursor a', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getOverriddenCursors :: Cursor s -> IO UnsafeCursorList\nunsafe_getOverriddenCursors c = do\n cxListPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr (Cursor s)))))\n n <- clang_getOverriddenCursors c (castPtr cxListPtr)\n free cxListPtr\n return (toCursorList (cxListPtr, (fromIntegral n)))\n\ngetOverriddenCursors :: ClangBase m => Cursor s' -> ClangT s m (CursorList s)\ngetOverriddenCursors = registerOverriddenList . unsafe_getOverriddenCursors\n\n-- CXFile clang_getIncludedFile(CXCursor cursor);\n{# fun clang_getIncludedFile {withVoided* %`Cursor a' } -> `Ptr ()' id #}\ngetIncludedFile :: Proxy s -> Cursor s' -> IO (Maybe (File s))\ngetIncludedFile _ c =\n clang_getIncludedFile c >>= return . maybeFile . File . castPtr\n\n-- CXCursor clang_getCursor(CXTranslationUnit, CXSourceLocation);\n{# fun wrapped_clang_getCursor as clang_getCursor { id `Ptr ()' , withVoided* `SourceLocation a' } -> `Ptr (Cursor s)' castPtr #}\ngetCursor :: Proxy s -> TranslationUnit s' -> SourceLocation s'' -> IO (Cursor s)\ngetCursor _ t s = clang_getCursor (unTranslationUnit t) s >>= peek\n\n-- CXSourceLocation clang_getCursorLocation(CXCursor);\n{# fun wrapped_clang_getCursorLocation as clang_getCursorLocation {withVoided* %`Cursor a' } -> `Ptr (SourceLocation s)' castPtr #}\ngetCursorLocation :: Proxy s -> Cursor s' -> IO (SourceLocation s)\ngetCursorLocation _ c =\n clang_getCursorLocation c>>= peek\n{-# INLINEABLE getCursorLocation #-}\n\n-- Variant of clang_getCursorLocation that fuses a call to clang_getSpellingLocation.\ngetCursorSpellingLocation :: Proxy s -> Cursor s' -> IO (Maybe (File s), Int, Int, Int)\ngetCursorSpellingLocation _ c =\n allocaBytes {#sizeof PtrPtrCXFile #} (\\ptrToFilePtr ->\n alloca (\\(linePtr :: (Ptr CUInt)) ->\n alloca (\\(columnPtr :: (Ptr CUInt)) ->\n alloca (\\(offsetPtr :: (Ptr CUInt)) -> do\n slPtr <- clang_getCursorLocation c\n peek slPtr >>= \\sl -> clang_getSpellingLocation sl ptrToFilePtr linePtr columnPtr offsetPtr\n filePtr <- {#get *CXFile #} ptrToFilePtr\n let _maybeFile = maybeFile (File filePtr)\n line <- peek linePtr\n column <- peek columnPtr\n offset <- peek offsetPtr\n return (_maybeFile, fromIntegral line, fromIntegral column, fromIntegral offset)))))\n{-# INLINEABLE getCursorSpellingLocation #-}\n\n-- CXSourceRange clang_getCursorExtent(CXCursor);\n{# fun wrapped_clang_getCursorExtent as clang_getCursorExtent {withVoided* %`Cursor a' } -> `Ptr (SourceRange s)' castPtr #}\ngetCursorExtent :: Proxy s -> Cursor s' -> IO (SourceRange s)\ngetCursorExtent _ c =\n clang_getCursorExtent c >>= peek\n{-# INLINEABLE getCursorExtent #-}\n\n-- enum CXTypeKind {\n-- CXType_Invalid = 0,\n-- CXType_Unexposed = 1,\n-- CXType_Void = 2,\n-- CXType_Bool = 3,\n-- CXType_Char_U = 4,\n-- CXType_UChar = 5,\n-- CXType_Char16 = 6,\n-- CXType_Char32 = 7,\n-- CXType_UShort = 8,\n-- CXType_UInt = 9,\n-- CXType_ULong = 10,\n-- CXType_ULongLong = 11,\n-- CXType_UInt128 = 12,\n-- CXType_Char_S = 13,\n-- CXType_SChar = 14,\n-- CXType_WChar = 15,\n-- CXType_Short = 16,\n-- CXType_Int = 17,\n-- CXType_Long = 18,\n-- CXType_LongLong = 19,\n-- CXType_Int128 = 20,\n-- CXType_Float = 21,\n-- CXType_Double = 22,\n-- CXType_LongDouble = 23,\n-- CXType_NullPtr = 24,\n-- CXType_Overload = 25,\n-- CXType_Dependent = 26,\n-- CXType_ObjCId = 27,\n-- CXType_ObjCClass = 28,\n-- CXType_ObjCSel = 29,\n-- CXType_FirstBuiltin = CXType_Void,\n-- CXType_LastBuiltin = CXType_ObjCSel,\n-- CXType_Complex = 100,\n-- CXType_Pointer = 101,\n-- CXType_BlockPointer = 102,\n-- CXType_LValueReference = 103,\n-- CXType_RValueReference = 104,\n-- CXType_Record = 105,\n-- CXType_Enum = 106,\n-- CXType_Typedef = 107,\n-- CXType_ObjCInterface = 108,\n-- CXType_ObjCObjectPointer = 109,\n-- CXType_FunctionNoProto = 110,\n-- CXType_FunctionProto = 111\n-- CXType_ConstantArray = 112\n-- CXType_Vector = 113,\n-- CXType_IncompleteArray = 114,\n-- CXType_VariableArray = 115,\n-- CXType_DependentSizedArray = 116,\n-- CXType_MemberPointer = 117\n-- };\n\n#c\nenum TypeKind\n { Type_Invalid = CXType_Invalid\n , Type_Unexposed = CXType_Unexposed\n , Type_Void = CXType_Void\n , Type_Bool = CXType_Bool\n , Type_Char_U = CXType_Char_U\n , Type_UChar = CXType_UChar\n , Type_Char16 = CXType_Char16\n , Type_Char32 = CXType_Char32\n , Type_UShort = CXType_UShort\n , Type_UInt = CXType_UInt\n , Type_ULong = CXType_ULong\n , Type_ULongLong = CXType_ULongLong\n , Type_UInt128 = CXType_UInt128\n , Type_Char_S = CXType_Char_S\n , Type_SChar = CXType_SChar\n , Type_WChar = CXType_WChar\n , Type_Short = CXType_Short\n , Type_Int = CXType_Int\n , Type_Long = CXType_Long\n , Type_LongLong = CXType_LongLong\n , Type_Int128 = CXType_Int128\n , Type_Float = CXType_Float\n , Type_Double = CXType_Double\n , Type_LongDouble = CXType_LongDouble\n , Type_NullPtr = CXType_NullPtr\n , Type_Overload = CXType_Overload\n , Type_Dependent = CXType_Dependent\n , Type_ObjCId = CXType_ObjCId\n , Type_ObjCClass = CXType_ObjCClass\n , Type_ObjCSel = CXType_ObjCSel\n , Type_Complex = CXType_Complex\n , Type_Pointer = CXType_Pointer\n , Type_BlockPointer = CXType_BlockPointer\n , Type_LValueReference = CXType_LValueReference\n , Type_RValueReference = CXType_RValueReference\n , Type_Record = CXType_Record\n , Type_Enum = CXType_Enum\n , Type_Typedef = CXType_Typedef\n , Type_ObjCInterface = CXType_ObjCInterface\n , Type_ObjCObjectPointer = CXType_ObjCObjectPointer\n , Type_FunctionNoProto = CXType_FunctionNoProto\n , Type_FunctionProto = CXType_FunctionProto\n , Type_ConstantArray = CXType_ConstantArray\n , Type_Vector = CXType_Vector\n , Type_IncompleteArray = CXType_IncompleteArray\n , Type_VariableArray = CXType_VariableArray\n , Type_DependentSizedArray = CXType_DependentSizedArray\n , Type_MemberPointer = CXType_MemberPointer\n };\n#endc\n{# enum TypeKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ntype_FirstBuiltin, type_LastBuiltin :: TypeKind\ntype_FirstBuiltin = Type_Void\ntype_LastBuiltin = Type_ObjCSel\n\n-- enum CXCallingConv {\n-- CXCallingConv_Default = 0,\n-- CXCallingConv_C = 1,\n-- CXCallingConv_X86StdCall = 2,\n-- CXCallingConv_X86FastCall = 3,\n-- CXCallingConv_X86ThisCall = 4,\n-- CXCallingConv_X86Pascal = 5,\n-- CXCallingConv_AAPCS = 6,\n-- CXCallingConv_AAPCS_VFP = 7,\n-- CXCallingConv_IntelOclBicc = 9,\n-- CXCallingConv_X86_64Win64 = 10,\n-- CXCallingConv_X86_64SysV = 11,\n-- CXCallingConv_Invalid = 100,\n-- CXCallingConv_Unexposed = 200\n-- };\n#c\nenum CallingConv\n { CallingConv_Default = CXCallingConv_Default\n , CallingConv_C = CXCallingConv_C\n , CallingConv_X86StdCall = CXCallingConv_X86StdCall\n , CallingConv_X86FastCall = CXCallingConv_X86FastCall\n , CallingConv_X86ThisCall = CXCallingConv_X86ThisCall\n , CallingConv_X86Pascal = CXCallingConv_X86Pascal\n , CallingConv_AAPCS = CXCallingConv_AAPCS\n , CallingConv_AAPCS_VFP = CXCallingConv_AAPCS_VFP\n , CallingConv_IntelOclBic = CXCallingConv_IntelOclBicc\n , CallingConv_X86_64Win64 = CXCallingConv_X86_64Win64\n , CallingConv_X86_64SysV = CXCallingConv_X86_64SysV\n , CallingConv_Invalid = CXCallingConv_Invalid\n , CallingConv_Unexposed = CXCallingConv_Unexposed\n };\n#endc\n{# enum CallingConv {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- typedef struct {\n-- enum CXTypeKind kind;\n-- void *data[2];\n-- } CXType;\ndata Type s = Type !TypeKind !(Ptr ()) !(Ptr ())\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue Type\n\ninstance Storable (Type s) where\n sizeOf _ = {#sizeof CXType #}\n {-# INLINE sizeOf #-}\n\n alignment _ = {#alignof CXType #}\n {-# INLINE alignment #-}\n\n peek p = do\n kindCInt <- {#get CXType->kind #} p\n ptrsArray <- {#get CXType->data #} p >>= peekArray 2\n return $! Type (toEnum (fromIntegral kindCInt)) (ptrsArray !! 0) (ptrsArray !! 1)\n {-# INLINE peek #-}\n\n poke p (Type kind p0 p1)= do\n ptrsArray <- mallocArray 2\n pokeArray ptrsArray [p0,p1]\n {#set CXType->kind #} p (fromIntegral (fromEnum kind))\n {#set CXType->data #} p (castPtr ptrsArray)\n {-# INLINE poke #-}\n\ngetTypeKind :: Type s -> TypeKind\ngetTypeKind (Type k _ _) = k\n\n-- CXType clang_getCursorType(CXCursor C);\n{# fun wrapped_clang_getCursorType as clang_getCursorType {withVoided* %`Cursor a' } -> `Ptr (Type s)' castPtr #}\ngetCursorType :: Proxy s -> Cursor s' -> IO (Type s)\ngetCursorType proxy c =\n clang_getCursorType c >>= peek\n\n-- CXString clang_getTypeSpelling(CXType CT);\n{# fun wrapped_clang_getTypeSpelling as clang_getTypeSpelling {withVoided* %`Type a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getTypeSpelling :: (Type s) -> IO (ClangString ())\nunsafe_getTypeSpelling t = do\n cxString <- clang_getTypeSpelling t\n peek cxString\n\ngetTypeSpelling :: ClangBase m => (Type s') -> ClangT s m (ClangString s)\ngetTypeSpelling = registerClangString . unsafe_getTypeSpelling\n\n-- CXType clang_getTypedefDeclUnderlyingType(CXCursor C);\n{# fun wrapped_clang_getTypedefDeclUnderlyingType as clang_getTypedefDeclUnderlyingType {withVoided* %`Cursor a' } -> `Ptr (Type s)' castPtr #}\ngetTypedefDeclUnderlyingType :: Proxy s -> Cursor s' -> IO (Type s)\ngetTypedefDeclUnderlyingType proxy c =\n clang_getTypedefDeclUnderlyingType c >>= peek\n\n-- CXType clang_getEnumDeclIntegerType(CXCursor C);\n{# fun wrapped_clang_getEnumDeclIntegerType as clang_getEnumDeclIntegerType {withVoided* %`Cursor a' } -> `Ptr (Type s)' castPtr #}\ngetEnumDeclIntegerType :: Proxy s -> Cursor s' -> IO (Type s)\ngetEnumDeclIntegerType proxy c =\n clang_getEnumDeclIntegerType c >>= peek\n\n-- long long clang_getEnumConstantDeclValue(CXCursor);\n{# fun clang_getEnumConstantDeclValue {withVoided* %`Cursor a' } -> `Int64' #}\ngetEnumConstantDeclValue :: Cursor s -> IO Int64\ngetEnumConstantDeclValue c = clang_getEnumConstantDeclValue c\n\n-- unsigned long long clang_getEnumConstantDeclUnsignedValue(CXCursor);\n{# fun clang_getEnumConstantDeclUnsignedValue {withVoided* %`Cursor a' } -> `Word64' #}\ngetEnumConstantDeclUnsignedValue :: Cursor s -> IO Word64\ngetEnumConstantDeclUnsignedValue c = clang_getEnumConstantDeclUnsignedValue c\n\n-- int clang_getFieldDeclBitWidth(CXCursor C);\n-- %fun clang_getFieldDeclBitWidth :: Cursor s -> IO Int\n{# fun clang_getFieldDeclBitWidth {withVoided* %`Cursor a' } -> `Int' #}\ngetFieldDeclBitWidth :: Cursor s -> IO Int\ngetFieldDeclBitWidth c = clang_getFieldDeclBitWidth c\n\n-- int clang_Cursor_getNumArguments(CXCursor C);\n{# fun clang_Cursor_getNumArguments {withVoided* %`Cursor a' } -> `Int' #}\ncursor_getNumArguments :: Cursor s -> IO Int\ncursor_getNumArguments c = clang_Cursor_getNumArguments c\n\n-- CXCursor clang_Cursor_getArgument(CXCursor C, unsigned i);\n{# fun wrapped_clang_Cursor_getArgument as clang_Cursor_getArgument {withVoided* %`Cursor a', `Int' } -> `Ptr (Cursor s)' castPtr #}\ncursor_getArgument :: Proxy s -> Cursor s' -> Int -> IO (Cursor s)\ncursor_getArgument _ c i = clang_Cursor_getArgument c i >>= peek\n\n-- unsigned clang_equalTypes(CXType A, CXType B);\n{# fun clang_equalTypes {withVoided* %`Type a',withVoided* %`Type b' } -> `Bool' toBool #}\nequalTypes :: Type s -> Type s' -> IO Bool\nequalTypes t1 t2 = clang_equalTypes t1 t2\n\n-- CXType clang_getCanonicalType(CXType T);\n{# fun wrapped_clang_getCanonicalType as clang_getCanonicalType {withVoided* %`Type a' } -> `Ptr (Type s)' castPtr #}\ngetCanonicalType :: Proxy s -> Type s' -> IO (Type s)\ngetCanonicalType proxy t = do\n cPtr <- clang_getCanonicalType t\n peek cPtr\n\n-- unsigned clang_isConstQualifiedType(CXType T);\n{# fun clang_isConstQualifiedType {withVoided* %`Type a' } -> `Bool' toBool #}\nisConstQualifiedType :: Type s -> IO Bool\nisConstQualifiedType t = clang_isConstQualifiedType t\n\n-- unsigned clang_isVolatileQualifiedType(CXType T);\n{# fun clang_isVolatileQualifiedType {withVoided* %`Type a' } -> `Bool' toBool #}\nisVolatileQualifiedType :: Type s -> IO Bool\nisVolatileQualifiedType t = clang_isVolatileQualifiedType t\n\n-- unsigned clang_isRestrictQualifiedType(CXType T);\n{# fun clang_isRestrictQualifiedType {withVoided* %`Type a' } -> `Bool' toBool #}\nisRestrictQualifiedType :: Type s -> IO Bool\nisRestrictQualifiedType t = clang_isRestrictQualifiedType t\n\n-- CXType clang_getPointeeType(CXType T);\n{# fun wrapped_clang_getPointeeType as clang_getPointeeType { withVoided* %`Type a' } -> `Ptr (Type s)' castPtr #}\ngetPointeeType :: Proxy s -> Type s' -> IO (Type s)\ngetPointeeType proxy t = do\n cPtr <- clang_getPointeeType t\n peek cPtr\n\n-- CXCursor clang_getTypeDeclaration(CXType T);\n{# fun wrapped_clang_getTypeDeclaration as clang_getTypeDeclaration { withVoided* %`Type a' } -> `Ptr (Cursor s)' castPtr #}\ngetTypeDeclaration :: Proxy s -> Type s' -> IO (Cursor s)\ngetTypeDeclaration _ t = do\n cPtr <- clang_getTypeDeclaration t\n peek cPtr\n\n-- CXString clang_getDeclObjCTypeEncoding(CXCursor C);\n{# fun wrapped_clang_getDeclObjCTypeEncoding as clang_getDeclObjCTypeEncoding {withVoided* %`Cursor a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getDeclObjCTypeEncoding :: Cursor s -> IO (ClangString ())\nunsafe_getDeclObjCTypeEncoding c = clang_getDeclObjCTypeEncoding c >>= peek\n\ngetDeclObjCTypeEncoding :: ClangBase m => Cursor s' -> ClangT s m (ClangString s)\ngetDeclObjCTypeEncoding = registerClangString . unsafe_getDeclObjCTypeEncoding\n\n-- CXString clang_getTypeKindSpelling(enum CXTypeKind K);\n{# fun wrapped_clang_getTypeKindSpelling as clang_getTypeKindSpelling { `CInt' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getTypeKindSpelling :: TypeKind -> IO (ClangString ())\nunsafe_getTypeKindSpelling tk = clang_getTypeKindSpelling (fromIntegral (fromEnum tk)) >>= peek\n\ngetTypeKindSpelling :: ClangBase m => TypeKind -> ClangT s m (ClangString s)\ngetTypeKindSpelling = registerClangString . unsafe_getTypeKindSpelling\n\n-- enum CXCallingConv clang_getFunctionTypeCallingConv(CXType T);\n{# fun clang_getFunctionTypeCallingConv { withVoided* %`Type a' } -> `CInt' id #}\ngetFunctionTypeCallingConv :: Type s' -> IO CallingConv\ngetFunctionTypeCallingConv t = clang_getFunctionTypeCallingConv t >>= return . toEnum . fromIntegral\n\n-- CXType clang_getResultType(CXType T);\n{# fun wrapped_clang_getResultType as clang_getResultType { withVoided* %`Type a' } -> `Ptr (Type s)' castPtr #}\ngetResultType :: Proxy s -> Type s' -> IO (Type s)\ngetResultType proxy t = clang_getResultType t >>= peek\n\n-- CXType clang_getNumArgTypes(CXType T);\n{# fun clang_getNumArgTypes { withVoided* %`Type a' } -> `Int' #}\ngetNumArgTypes :: Type s -> IO Int\ngetNumArgTypes t = clang_getNumArgTypes t\n\n-- CXType clang_getArgType(CXType T, int i);\n{# fun wrapped_clang_getArgType as clang_getArgType { withVoided* %`Type a', `Int' } -> `Ptr (Type s)' castPtr #}\ngetArgType :: Proxy s -> Type s' -> Int -> IO (Type s)\ngetArgType proxy t i = clang_getArgType t i >>= peek\n\n-- unsigned clang_isFunctionTypeVariadic(CXType T);\n{# fun clang_isFunctionTypeVariadic { withVoided* %`Type a' } -> `CUInt' id #}\nisFunctionTypeVariadic :: Type s -> IO Bool\nisFunctionTypeVariadic t = clang_isFunctionTypeVariadic t >>= return . (toBool :: Int -> Bool) . fromIntegral\n\n-- CXType clang_getCursorResultType(CXCursor C);\n{# fun wrapped_clang_getCursorResultType as clang_getCursorResultType {withVoided* %`Cursor a' } -> `Ptr (Type s)' castPtr #}\ngetCursorResultType :: Proxy s -> Cursor s' -> IO (Type s)\ngetCursorResultType p c = clang_getCursorResultType c >>= peek\n\n-- unsigned clang_isPODType(CXType T);\n{# fun clang_isPODType {withVoided* %`Type a' } -> `Bool' toBool #}\nisPODType :: Type s -> IO Bool\nisPODType t = clang_isPODType t\n\n-- CXType clang_getElementType(CXType T);\n{# fun wrapped_clang_getElementType as clang_getElementType { withVoided* %`Type a' } -> `Ptr (Type s)' castPtr #}\ngetElementType :: Proxy s -> Type s' -> IO (Type s)\ngetElementType proxy t = clang_getElementType t >>= peek\n\n-- long long clang_getNumElements(CXType T);\n{# fun clang_getNumElements { withVoided* %`Type a' } -> `Int64' #}\ngetNumElements :: Type s -> IO Int64\ngetNumElements t = clang_getNumElements t\n\n-- CXType clang_getArrayElementType(CXType T);\n{# fun wrapped_clang_getArrayElementType as clang_getArrayElementType { withVoided* %`Type a' } -> `Ptr (Type s)' castPtr #}\ngetArrayElementType :: Proxy s -> Type s' -> IO (Type s)\ngetArrayElementType proxy t = clang_getArrayElementType t >>= peek\n\n-- long long clang_getArraySize(CXType T);\n{# fun clang_getArraySize { withVoided* %`Type a' } -> `Int64' #}\ngetArraySize :: Type s -> IO Int64\ngetArraySize t = clang_getArraySize t\n\n-- enum CXTypeLayoutError {\n-- CXTypeLayoutError_Invalid = -1,\n-- CXTypeLayoutError_Incomplete = -2,\n-- CXTypeLayoutError_Dependent = -3,\n-- CXTypeLayoutError_NotConstantSize = -4,\n-- CXTypeLayoutError_InvalidFieldName = -5\n-- };\n#c\nenum TypeLayoutError\n { TypeLayoutError_Invalid = CXTypeLayoutError_Invalid\n , TypeLayoutError_Incomplete = CXTypeLayoutError_Incomplete\n , TypeLayoutError_Dependent = CXTypeLayoutError_Dependent\n , TypeLayoutError_NotConstantSize = CXTypeLayoutError_NotConstantSize\n , TypeLayoutError_InvalidFieldName = CXTypeLayoutError_InvalidFieldName\n };\n#endc\n{# enum TypeLayoutError {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\nint64OrLayoutError :: Int64 -> Either TypeLayoutError Int64\nint64OrLayoutError v | v == -1 = Left TypeLayoutError_Invalid\n | v == -2 = Left TypeLayoutError_Incomplete\n | v == -3 = Left TypeLayoutError_Dependent\n | v == -4 = Left TypeLayoutError_NotConstantSize\n | v == -5 = Left TypeLayoutError_InvalidFieldName\n | otherwise = Right v\n\n-- long long clang_Type_getAlignOf(CXType T);\n{# fun clang_Type_getAlignOf { withVoided* %`Type a' } -> `Int64' #}\ntype_getAlignOf :: Type s -> IO (Either TypeLayoutError Int64)\ntype_getAlignOf t = clang_Type_getAlignOf t >>= return . int64OrLayoutError\n\n-- CXType clang_Type_getClassType(CXType T);\n{# fun wrapped_clang_Type_getClassType as clang_Type_getClassType { withVoided* %`Type a' } -> `Ptr (Type s)' castPtr #}\ntype_getClassType :: Proxy s -> Type s' -> IO (Type s)\ntype_getClassType proxy t = clang_getElementType t >>= peek\n\n-- long long clang_Type_getSizeOf(CXType T);\n{# fun clang_Type_getSizeOf { withVoided* %`Type a' } -> `Int64' #}\ntype_getSizeOf :: Type s -> IO (Either TypeLayoutError Int64)\ntype_getSizeOf t = clang_Type_getSizeOf t >>= return . int64OrLayoutError\n\n-- long long clang_Type_getOffsetOf(CXType T, const char *S);\n{# fun clang_Type_getOffsetOf { withVoided* %`Type a' , `CString' } -> `Int64' #}\nunsafe_Type_getOffsetOf :: Type s -> CString -> IO (Either TypeLayoutError Int64)\nunsafe_Type_getOffsetOf t s = clang_Type_getOffsetOf t s >>= return . int64OrLayoutError\n\ntype_getOffsetOf :: ClangBase m => Type s' -> B.ByteString\n -> ClangT s m (Either TypeLayoutError Int64)\ntype_getOffsetOf t field = liftIO $ B.useAsCString field $ \\cField ->\n unsafe_Type_getOffsetOf t cField\n\n-- enum CXRefQualifierKind {\n-- CXRefQualifier_None = 0,\n-- CXRefQualifier_LValue,\n-- CXRefQualifier_RValue\n-- };\n#c\nenum RefQualifierKind\n { RefQualifier_None = CXRefQualifier_None\n , RefQualifier_LValue = CXRefQualifier_LValue\n , RefQualifier_RValue = CXRefQualifier_RValue\n };\n#endc\n{# enum RefQualifierKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- enum CXRefQualifierKind clang_Type_getCXXRefQualifier(CXType T);\n{# fun clang_Type_getCXXRefQualifier { withVoided* %`Type a' } -> `Int' #}\ntype_getCXXRefQualifier :: Type s -> IO RefQualifierKind\ntype_getCXXRefQualifier t = clang_Type_getCXXRefQualifier t >>= return . toEnum\n\n\n-- unsigned clang_Cursor_isBitField(CXCursor C);\n{# fun clang_Cursor_isBitField {withVoided* %`Cursor a' } -> `Bool' toBool #}\nisBitField :: Cursor s -> IO Bool\nisBitField c = clang_Cursor_isBitField c\n\n-- unsigned clang_isVirtualBase(CXCursor);\n{# fun clang_isVirtualBase {withVoided* %`Cursor a' } -> `Bool' toBool #}\nisVirtualBase :: Cursor s -> IO Bool\nisVirtualBase c = clang_Cursor_isBitField c\n\n-- enum CX_CXXAccessSpecifier {\n-- CX_CXXInvalidAccessSpecifier,\n-- CX_CXXPublic,\n-- CX_CXXProtected,\n-- CX_CXXPrivate\n-- };\n#c\nenum CXXAccessSpecifier\n { CXXInvalidAccessSpecifier = CX_CXXInvalidAccessSpecifier\n , CXXPublic = CX_CXXPublic\n , CXXProtected = CX_CXXProtected\n , CXXPrivate = CX_CXXPrivate\n };\n#endc\n\n{# enum CXXAccessSpecifier {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- enum CX_CXXAccessSpecifier clang_getCXXAccessSpecifier(CXCursor);\n{# fun clang_getCXXAccessSpecifier {withVoided* %`Cursor a' } -> `Int' #}\ngetCXXAccessSpecifier :: Cursor s -> IO CXXAccessSpecifier\ngetCXXAccessSpecifier c = clang_getCXXAccessSpecifier c >>= return . toEnum\n\n-- unsigned clang_getNumOverloadedDecls(CXCursor cursor);\n{# fun clang_getNumOverloadedDecls {withVoided* %`Cursor a' } -> `CUInt' #}\ngetNumOverloadedDecls :: Cursor s -> IO Int\ngetNumOverloadedDecls c = clang_getNumOverloadedDecls c >>= return . fromIntegral\n\n-- CXCursor clang_getOverloadedDecl(CXCursor cursor,\n-- unsigned index);\n{# fun wrapped_clang_getOverloadedDecl as clang_getOverloadedDecl {withVoided* %`Cursor a', `Int' } -> `Ptr (Cursor s)' castPtr #}\ngetOverloadedDecl :: Proxy s -> Cursor s' -> Int -> IO (Cursor s)\ngetOverloadedDecl _ c i = clang_getOverloadedDecl c i >>= peek\n\n-- CXType clang_getIBOutletCollectionType(CXCursor);\n{# fun wrapped_clang_getIBOutletCollectionType as clang_getIBOutletCollectionType {withVoided* %`Cursor a' } -> `Ptr (Type s)' castPtr #}\ngetIBOutletCollectionType :: Proxy s -> Cursor s' -> IO (Type s)\ngetIBOutletCollectionType proxy c = clang_getIBOutletCollectionType c >>= peek\n\n\n-- We deliberately don't export the constructor for UnsafeCursorList.\n-- The only way to unwrap it is registerCursorList.\ntype CursorList s = DVS.Vector (Cursor s)\ninstance ClangValueList Cursor\ndata UnsafeCursorList = UnsafeCursorList !(Ptr ()) !Int\n\n-- void freeCursorList(CXCursor* cursors);\n{# fun freeCursorList as freeCursorList' { id `Ptr ()' } -> `()' #}\nfreeCursorList :: CursorList s -> IO ()\nfreeCursorList cl = let (ptr, _) = fromCursorList cl in freeCursorList' ptr\n\nregisterCursorList :: ClangBase m => IO UnsafeCursorList -> ClangT s m (CursorList s)\nregisterCursorList action = do\n (_, cursorList) <- clangAllocate (action >>= cursorListToVector) freeCursorList\n return cursorList\n{-# INLINEABLE registerCursorList #-}\n\ncursorListToVector :: Storable a => UnsafeCursorList -> IO (DVS.Vector a)\ncursorListToVector (UnsafeCursorList cs n) = do\n fptr <- newForeignPtr_ (castPtr cs)\n return $ DVS.unsafeFromForeignPtr fptr 0 n\n{-# INLINE cursorListToVector #-}\n\nfromCursorList :: CursorList s -> (Ptr (), Int)\nfromCursorList cs = let (p, _, _) = DVS.unsafeToForeignPtr cs in\n (castPtr $ Foreign.ForeignPtr.Unsafe.unsafeForeignPtrToPtr p, DVS.length cs)\n\ntoCursorList :: (Ptr (), Int) -> UnsafeCursorList\ntoCursorList (cs, n) = UnsafeCursorList cs n\n\n-- A more efficient alternative to clang_visitChildren.\n-- void getChildren(CXCursor parent, CXCursor** childrenOut, unsigned* countOut)\n{# fun getChildren as getChildren' {withVoided* %`Cursor a', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getChildren :: Cursor s -> IO UnsafeCursorList\nunsafe_getChildren c =\n do\n cxListPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr ()))))\n n <- getChildren' c cxListPtr\n cxList <- peek cxListPtr\n free cxListPtr\n return (toCursorList (cxList, fromIntegral n))\n\ngetChildren :: ClangBase m => Cursor s' -> ClangT s m (CursorList s)\ngetChildren = registerCursorList . unsafe_getChildren\n\n-- Like getChildren, but gets all transitive descendants.\n-- void getDescendants(CXCursor parent, CXCursor** childrenOut, unsigned* countOut)\n{# fun getDescendants as getDescendants' {withVoided* %`Cursor a', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getDescendants :: Cursor s -> IO UnsafeCursorList\nunsafe_getDescendants c =\n do\n cxListPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Cursor s))))\n n <- getDescendants' c cxListPtr\n cxList <- peek cxListPtr\n free cxListPtr\n return (toCursorList (cxList, fromIntegral n))\n\ngetDescendants :: ClangBase m => Cursor s' -> ClangT s m (CursorList s)\ngetDescendants = registerCursorList . unsafe_getDescendants\n\n-- void getDeclarations(CXTranslationUnit tu, CXCursor** declsOut, unsigned* declCountOut);\n{# fun getDeclarations as getDeclarations' { id `Ptr ()', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getDeclarations :: TranslationUnit s -> IO UnsafeCursorList\nunsafe_getDeclarations t = do\n cxListPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr (Cursor ())))))\n n <- getDeclarations' (unTranslationUnit t) cxListPtr\n cxList <- peek cxListPtr\n free cxListPtr\n return (toCursorList (cxList, fromIntegral n))\n\ngetDeclarations :: ClangBase m => TranslationUnit s' -> ClangT s m (CursorList s)\ngetDeclarations = registerCursorList . unsafe_getDeclarations\n\n-- void getReferences(CXTranslationUnit tu, CXCursor** declsOut, unsigned* declCountOut);\n{# fun getReferences as getReferences' { id `Ptr ()', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getReferences :: TranslationUnit s -> IO UnsafeCursorList\nunsafe_getReferences t = do\n cxListPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr ()))))\n n <- getReferences' (unTranslationUnit t) cxListPtr\n cxList <- peek cxListPtr\n free cxListPtr\n return (toCursorList (cxList, fromIntegral n))\n\ngetReferences :: ClangBase m => TranslationUnit s' -> ClangT s m (CursorList s)\ngetReferences = registerCursorList . unsafe_getReferences\n\n-- void getDeclarationsAndReferences(CXTranslationUnit tu,\n-- CXCursor** declsOut, unsigned* declCountOut,\n-- CXCursor** refsOut, unsigned* refCountOut);\n{# fun getDeclarationsAndReferences as getDeclarationsAndReferences'\n { id `Ptr ()', id `Ptr (Ptr ())', alloca- `CUInt' peek*, id `Ptr (Ptr ())' , alloca- `CUInt' peek* } -> `()' #}\nunsafe_getDeclarationsAndReferences :: TranslationUnit s -> IO (UnsafeCursorList, UnsafeCursorList)\nunsafe_getDeclarationsAndReferences t =\n alloca (\\(declsPtr :: Ptr (Ptr ())) ->\n alloca (\\(refsPtr :: Ptr (Ptr ())) -> do\n (nDecls, nRefs) <- getDeclarationsAndReferences' (unTranslationUnit t) (castPtr declsPtr) (castPtr refsPtr)\n decls <- peek declsPtr\n refs <- peek refsPtr\n return ((toCursorList (decls, fromIntegral nDecls)), (toCursorList (refs, fromIntegral nRefs)))))\n\n-- %fun unsafe_getDeclarationsAndReferences :: TranslationUnit s -> IO (UnsafeCursorList, UnsafeCursorList)\n-- %call (translationUnit t)\n-- %code CXCursor* decls; unsigned declCount;\n-- % CXCursor* refs; unsigned refCount;\n-- % getDeclarationsAndReferences(t, &decls, &declCount, &refs, &refCount);\n-- %result (cursorList decls declCount, cursorList refs refCount)\n\ngetDeclarationsAndReferences :: ClangBase m => TranslationUnit s'\n -> ClangT s m (CursorList s, CursorList s)\ngetDeclarationsAndReferences tu = do\n (ds, rs) <- liftIO $ unsafe_getDeclarationsAndReferences tu\n (,) <$> registerCursorList (return ds) <*> registerCursorList (return rs)\n\ndata ParentedCursor s = ParentedCursor\n { parentCursor :: !(Cursor s)\n , childCursor :: !(Cursor s)\n } deriving (Eq, Ord, Typeable)\n\ninstance ClangValue ParentedCursor\n\ninstance Storable (ParentedCursor s) where\n sizeOf _ = sizeOfParentedCursor\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfParentedCursor\n {-# INLINE alignment #-}\n\n peek p = do\n parent <- peekByteOff p offsetParentedCursorParent\n child <- peekByteOff p offsetParentedCursorCursor\n return $! ParentedCursor parent child\n {-# INLINE peek #-}\n\n poke p (ParentedCursor parent child) = do\n pokeByteOff p offsetParentedCursorParent parent\n pokeByteOff p offsetParentedCursorCursor child\n {-# INLINE poke #-}\n\n-- We deliberately don't export the constructor for UnsafeParentedCursorList.\n-- The only way to unwrap it is registerParentedCursorList.\ntype ParentedCursorList s = DVS.Vector (ParentedCursor s)\ninstance ClangValueList ParentedCursor\ndata UnsafeParentedCursorList = UnsafeParentedCursorList !(Ptr ()) !Int\n\n-- void freeParentedCursorList(struct ParentedCursor* parentedCursors);\n{# fun freeParentedCursorList as freeParentedCursorList' { id `Ptr ()' } -> `()' #}\nfreeParentedCursorList :: ParentedCursorList s -> IO ()\nfreeParentedCursorList pcl = let (pclPtr, _ ) = fromParentedCursorList pcl in freeParentedCursorList' pclPtr\n\nregisterParentedCursorList :: ClangBase m => IO UnsafeParentedCursorList\n -> ClangT s m (ParentedCursorList s)\nregisterParentedCursorList action = do\n (_, pcList) <- clangAllocate (action >>= mkSafe) freeParentedCursorList\n return pcList\n where\n mkSafe (UnsafeParentedCursorList cs n) = do\n fptr <- newForeignPtr_ (castPtr cs)\n return $ DVS.unsafeFromForeignPtr fptr 0 n\n{-# INLINEABLE registerParentedCursorList #-}\n\nfromParentedCursorList :: ParentedCursorList s -> (Ptr (), Int)\nfromParentedCursorList cs =\n let (p, _, _) = DVS.unsafeToForeignPtr cs in\n (castPtr $ Foreign.ForeignPtr.Unsafe.unsafeForeignPtrToPtr p, DVS.length cs)\n\ntoParentedCursorList :: (Ptr (), Int) -> UnsafeParentedCursorList\ntoParentedCursorList (cs, n) = UnsafeParentedCursorList cs n\n\n-- %dis parentedCursorList cs n = (ptr cs) (int n)\n\n-- Like getParentedDescendants, but pairs each descendant with its parent.\n-- void getParentedDescendants(CXCursor parent, struct ParentedCursor** descendantsOut,\n-- unsigned* countOut)\n{# fun getParentedDescendants as getParentedDescendants' {withVoided* %`Cursor a', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getParentedDescendants :: Cursor s -> IO UnsafeParentedCursorList\nunsafe_getParentedDescendants c =\n do\n cxListPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr ()))))\n n <- getParentedDescendants' c cxListPtr\n cxList <- peek cxListPtr\n free cxListPtr\n return (toParentedCursorList (cxList, fromIntegral n))\n\ngetParentedDescendants :: ClangBase m => Cursor s' -> ClangT s m (ParentedCursorList s)\ngetParentedDescendants = registerParentedCursorList . unsafe_getParentedDescendants\n\n-- void getParentedDeclarations(CXTranslationUnit tu, CXCursor** declsOut, unsigned* declCountOut);\n{# fun getParentedDeclarations as getParentedDeclarations' { id `Ptr ()', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getParentedDeclarations :: TranslationUnit s -> IO UnsafeParentedCursorList\nunsafe_getParentedDeclarations t = do\n cxListPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr (Cursor ())))))\n n <- getParentedDeclarations' (unTranslationUnit t) (castPtr cxListPtr)\n cxList <- peek cxListPtr\n free cxListPtr\n return (toParentedCursorList (cxList, fromIntegral n))\n\ngetParentedDeclarations :: ClangBase m => TranslationUnit s' -> ClangT s m (ParentedCursorList s)\ngetParentedDeclarations = registerParentedCursorList . unsafe_getParentedDeclarations\n\n-- void getParentedReferences(CXTranslationUnit tu, CXCursor** declsOut, unsigned* declCountOut);\n{# fun getParentedReferences as getParentedReferences' { id `Ptr ()', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getParentedReferences :: TranslationUnit s -> IO UnsafeParentedCursorList\nunsafe_getParentedReferences t = do\n cxListPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr ()))))\n n <- getParentedReferences' (unTranslationUnit t) cxListPtr\n cxList <- peek cxListPtr\n free cxListPtr\n return (toParentedCursorList (cxList, fromIntegral n))\n\ngetParentedReferences :: ClangBase m => TranslationUnit s' -> ClangT s m (ParentedCursorList s)\ngetParentedReferences = registerParentedCursorList . unsafe_getParentedReferences\n\n-- void getParentedDeclarationsAndReferences(CXTranslationUnit tu,\n-- ParentedCursor** declsOut,\n-- unsigned* declCountOut,\n-- ParentedCursor** refsOut,\n-- unsigned* refCountOut);\n{# fun getParentedDeclarationsAndReferences as getParentedDeclarationsAndReferences'\n { id `Ptr ()', id `Ptr (Ptr ())', alloca- `CUInt' peek*, id `Ptr (Ptr ())' , alloca- `CUInt' peek* } -> `()' #}\nunsafe_getParentedDeclarationsAndReferences :: TranslationUnit s -> IO (UnsafeParentedCursorList, UnsafeParentedCursorList)\nunsafe_getParentedDeclarationsAndReferences t = do\n declsPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr ()))))\n refsPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr ()))))\n (nDecls, nRefs) <- getParentedDeclarationsAndReferences' (unTranslationUnit t) declsPtr refsPtr\n decls <- peek declsPtr\n refs <- peek refsPtr\n free declsPtr\n free refsPtr\n return ((toParentedCursorList (decls, fromIntegral nDecls)), (toParentedCursorList (refs, fromIntegral nRefs)))\n\ngetParentedDeclarationsAndReferences :: ClangBase m => TranslationUnit s'\n -> ClangT s m (ParentedCursorList s, ParentedCursorList s)\ngetParentedDeclarationsAndReferences tu = do\n (ds, rs) <- liftIO $ unsafe_getParentedDeclarationsAndReferences tu\n (,) <$> registerParentedCursorList (return ds) <*> registerParentedCursorList (return rs)\n\n-- CXString clang_getCursorUSR(CXCursor);\n{# fun wrapped_clang_getCursorUSR as clang_getCursorUSR {withVoided* %`Cursor a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCursorUSR :: Cursor s -> IO (ClangString ())\nunsafe_getCursorUSR c =\n clang_getCursorUSR c >>= peek\n\ngetCursorUSR :: ClangBase m => Cursor s' -> ClangT s m (ClangString s)\ngetCursorUSR = registerClangString . unsafe_getCursorUSR\n\n-- CXString clang_constructUSR_ObjCClass(const char *class_name);\n{# fun wrapped_clang_constructUSR_ObjCClass as clang_constructUSR_ObjCClass { `CString' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_constructUSR_ObjCClass :: String -> IO (ClangString ())\nunsafe_constructUSR_ObjCClass s = withCString s (\\sPtr -> clang_constructUSR_ObjCClass sPtr >>= peek)\n\nconstructUSR_ObjCClass :: ClangBase m => String -> ClangT s m (ClangString s)\nconstructUSR_ObjCClass = registerClangString . unsafe_constructUSR_ObjCClass\n\n-- CXString\n-- clang_constructUSR_ObjCCategory(const char *class_name,\n-- const char *category_name);\n{# fun wrapped_clang_constructUSR_ObjCCategory as clang_constructUSR_ObjCCategory { `CString', `CString' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_constructUSR_ObjCCategory :: String -> String -> IO (ClangString ())\nunsafe_constructUSR_ObjCCategory s p =\n withCString s (\\sPtr ->\n withCString p (\\pPtr ->\n clang_constructUSR_ObjCCategory sPtr pPtr >>= peek))\n\nconstructUSR_ObjCCategory :: ClangBase m => String -> String -> ClangT s m (ClangString s)\nconstructUSR_ObjCCategory = (registerClangString .) . unsafe_constructUSR_ObjCCategory\n\n-- CXString\n-- clang_constructUSR_ObjCProtocol(const char *protocol_name);\n{# fun wrapped_clang_constructUSR_ObjCProtocol as clang_constructUSR_ObjCProtocol { `CString' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_constructUSR_ObjCProtocol :: String -> IO (ClangString ())\nunsafe_constructUSR_ObjCProtocol s = withCString s (\\sPtr -> clang_constructUSR_ObjCProtocol sPtr >>= peek)\n\nconstructUSR_ObjCProtocol :: ClangBase m => String -> ClangT s m (ClangString s)\nconstructUSR_ObjCProtocol = registerClangString . unsafe_constructUSR_ObjCProtocol\n\n-- CXString clang_constructUSR_ObjCIvar(const char *name,\n-- CXString classUSR);\n{# fun wrapped_clang_constructUSR_ObjCIvar as clang_constructUSR_ObjCIvar { `CString' , id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_constructUSR_ObjCIvar :: String -> Ptr () -> Word32 -> IO (ClangString ())\nunsafe_constructUSR_ObjCIvar s d f =\n let clangString = ClangString d f in\n withCString s (\\sPtr -> new clangString >>= \\cs -> clang_constructUSR_ObjCIvar sPtr (castPtr cs) >>= peek)\n\nconstructUSR_ObjCIvar :: ClangBase m => String -> ClangString s' -> ClangT s m (ClangString s)\nconstructUSR_ObjCIvar s (ClangString d f) = registerClangString $ unsafe_constructUSR_ObjCIvar s d f\n\n-- CXString clang_constructUSR_ObjCMethod(const char *name,\n-- unsigned isInstanceMethod,\n-- CXString classUSR);\n{# fun wrapped_clang_constructUSR_ObjCMethod as clang_constructUSR_ObjCMethod { `CString' , `CUInt' , id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_constructUSR_ObjCMethod :: String -> Bool -> Ptr () -> Word32 -> IO (ClangString ())\nunsafe_constructUSR_ObjCMethod s b d f =\n let clangString = ClangString d f in\n withCString s (\\sPtr -> (new clangString >>= \\cs -> clang_constructUSR_ObjCMethod sPtr (fromIntegral ((fromBool b) :: Int)) (castPtr cs) >>= peek))\n\nconstructUSR_ObjCMethod :: ClangBase m => String -> Bool -> ClangString s' -> ClangT s m (ClangString s)\nconstructUSR_ObjCMethod s b (ClangString d f) =\n registerClangString $ unsafe_constructUSR_ObjCMethod s b d f\n\n-- CXString clang_constructUSR_ObjCProperty(const char *property,\n-- CXString classUSR);\n{# fun wrapped_clang_constructUSR_ObjCProperty as clang_constructUSR_ObjCProperty { `CString' , id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_constructUSR_ObjCProperty :: String -> Ptr () -> Word32 -> IO (ClangString ())\nunsafe_constructUSR_ObjCProperty s d f =\n let clangString = ClangString d f in\n withCString s (\\sPtr -> (new clangString >>= \\cs -> clang_constructUSR_ObjCProperty sPtr (castPtr cs) >>= peek))\n\nconstructUSR_ObjCProperty :: ClangBase m => String -> ClangString s' -> ClangT s m (ClangString s)\nconstructUSR_ObjCProperty s (ClangString d f) =\n registerClangString $ unsafe_constructUSR_ObjCProperty s d f\n\n-- CXString clang_getCursorSpelling(CXCursor);\n{# fun wrapped_clang_getCursorSpelling as clang_getCursorSpelling {withVoided* %`Cursor a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCursorSpelling :: Cursor s -> IO (ClangString ())\nunsafe_getCursorSpelling c =\n clang_getCursorSpelling c >>= peek\n\ngetCursorSpelling :: ClangBase m => Cursor s' -> ClangT s m (ClangString s)\ngetCursorSpelling = registerClangString . unsafe_getCursorSpelling\n\n-- CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor,\n-- unsigned pieceIndex,\n-- unsigned options);\n{# fun wrapped_clang_Cursor_getSpellingNameRange as clang_Cursor_getSpellingNameRange {withVoided* %`Cursor a', `Int', `Int' } -> `Ptr (SourceRange s)' castPtr #}\ncursor_getSpellingNameRange :: Proxy s -> Cursor s' -> Int -> IO (SourceRange s)\ncursor_getSpellingNameRange _ c i = clang_Cursor_getSpellingNameRange c i 0 >>= peek\n\n-- CXString clang_getCursorDisplayName(CXCursor);\n{# fun wrapped_clang_getCursorDisplayName as clang_getCursorDisplayName {withVoided* %`Cursor a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCursorDisplayName :: Cursor s -> IO (ClangString ())\nunsafe_getCursorDisplayName c =\n clang_getCursorDisplayName c >>= peek\n\ngetCursorDisplayName :: ClangBase m => Cursor s' -> ClangT s m (ClangString s)\ngetCursorDisplayName = registerClangString . unsafe_getCursorDisplayName\n\n-- CXCursor clang_getCursorReferenced(CXCursor);\n{# fun wrapped_clang_getCursorReferenced as clang_getCursorReferenced {withVoided* %`Cursor a' } -> `Ptr (Cursor s)' castPtr #}\ngetCursorReferenced :: Proxy s -> Cursor s' -> IO (Cursor s)\ngetCursorReferenced _ c =\n clang_getCursorReferenced c >>= peek\n\n-- CXCursor clang_getCursorDefinition(CXCursor);\n{# fun wrapped_clang_getCursorDefinition as clang_getCursorDefinition {withVoided* %`Cursor a' } -> `Ptr (Cursor s)' castPtr #}\ngetCursorDefinition :: Proxy s -> Cursor s' -> IO (Cursor s)\ngetCursorDefinition _ c = clang_getCursorDefinition c >>= peek\n\n-- unsigned clang_isCursorDefinition(CXCursor);\n{# fun clang_isCursorDefinition {withVoided* %`Cursor a' } -> `Bool' toBool #}\nisCursorDefinition :: Cursor s -> IO Bool\nisCursorDefinition c = clang_isCursorDefinition c\n\n-- unsigned clang_Cursor_isDynamicCall(CXCursor);\n{# fun clang_Cursor_isDynamicCall {withVoided* %`Cursor a' } -> `Bool' toBool #}\ncursor_isDynamicCall :: Cursor s -> IO Bool\ncursor_isDynamicCall c = clang_Cursor_isDynamicCall c\n\n-- CXCursor clang_getCanonicalCursor(CXCursor);\n{# fun wrapped_clang_getCanonicalCursor as clang_getCanonicalCursor {withVoided* %`Cursor a' } -> `Ptr (Cursor s)' castPtr #}\ngetCanonicalCursor :: Proxy s -> Cursor s' -> IO (Cursor s)\ngetCanonicalCursor _ c =\n clang_getCanonicalCursor c >>= peek\n\n-- int clang_Cursor_getObjCSelectorIndex(CXCursor);\n{# fun clang_Cursor_getObjCSelectorIndex {withVoided* %`Cursor a' } -> `Int' #}\ncursor_getObjCSelectorIndex :: Cursor s -> IO Int\ncursor_getObjCSelectorIndex c = clang_Cursor_getObjCSelectorIndex c\n\n-- CXType clang_Cursor_getReceiverType(CXCursor C);\n{# fun wrapped_clang_Cursor_getReceiverType as clang_Cursor_getReceiverType {withVoided* %`Cursor a' } -> `Ptr (Type s)' castPtr #}\ncursor_getReceiverType :: Proxy s -> Cursor s' -> IO (Type s)\ncursor_getReceiverType proxy c =\n clang_Cursor_getReceiverType c >>= peek\n\n-- typedef enum {\n-- CXObjCPropertyAttr_noattr = 0x00,\n-- CXObjCPropertyAttr_readonly = 0x01,\n-- CXObjCPropertyAttr_getter = 0x02,\n-- CXObjCPropertyAttr_assign = 0x04,\n-- CXObjCPropertyAttr_readwrite = 0x08,\n-- CXObjCPropertyAttr_retain = 0x10,\n-- CXObjCPropertyAttr_copy = 0x20,\n-- CXObjCPropertyAttr_nonatomic = 0x40,\n-- CXObjCPropertyAttr_setter = 0x80,\n-- CXObjCPropertyAttr_atomic = 0x100,\n-- CXObjCPropertyAttr_weak = 0x200,\n-- CXObjCPropertyAttr_strong = 0x400,\n-- CXObjCPropertyAttr_unsafe_unretained = 0x800\n-- } CXObjCPropertyAttrKind;\n\n#c\nenum ObjCPropertyAttrKind\n { ObjCPropertyAttr_noattr = CXObjCPropertyAttr_noattr\n , ObjCPropertyAttr_readonly = CXObjCPropertyAttr_readonly\n , ObjCPropertyAttr_getter = CXObjCPropertyAttr_getter\n , ObjCPropertyAttr_assign = CXObjCPropertyAttr_assign\n , ObjCPropertyAttr_readwrite = CXObjCPropertyAttr_readwrite\n , ObjCPropertyAttr_retain = CXObjCPropertyAttr_retain\n , ObjCPropertyAttr_copy = CXObjCPropertyAttr_copy\n , ObjCPropertyAttr_nonatomic = CXObjCPropertyAttr_nonatomic\n , ObjCPropertyAttr_setter = CXObjCPropertyAttr_setter\n , ObjCPropertyAttr_atomic = CXObjCPropertyAttr_atomic\n , ObjCPropertyAttr_weak = CXObjCPropertyAttr_weak\n , ObjCPropertyAttr_strong = CXObjCPropertyAttr_strong\n , ObjCPropertyAttr_unsafe_unretained= CXObjCPropertyAttr_unsafe_unretained\n };\n#endc\n{# enum ObjCPropertyAttrKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags ObjCPropertyAttrKind where\n toBit ObjCPropertyAttr_noattr = 0x0\n toBit ObjCPropertyAttr_readonly = 0x1\n toBit ObjCPropertyAttr_getter = 0x2\n toBit ObjCPropertyAttr_assign = 0x4\n toBit ObjCPropertyAttr_readwrite = 0x8\n toBit ObjCPropertyAttr_retain = 0x10\n toBit ObjCPropertyAttr_copy = 0x20\n toBit ObjCPropertyAttr_nonatomic = 0x40\n toBit ObjCPropertyAttr_setter = 0x80\n toBit ObjCPropertyAttr_atomic = 0x100\n toBit ObjCPropertyAttr_weak = 0x200\n toBit ObjCPropertyAttr_strong = 0x400\n toBit ObjCPropertyAttr_unsafe_unretained = 0x800\n\n-- unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved);\n{# fun clang_Cursor_getObjCPropertyAttributes {withVoided* %`Cursor a', `Int' } -> `CUInt' #}\ncursor_getObjCPropertyAttributes :: Cursor s -> IO Int\ncursor_getObjCPropertyAttributes c = clang_Cursor_getObjCPropertyAttributes c 0 >>= return . fromIntegral\n\n-- typedef enum {\n-- CXObjCDeclQualifier_None = 0x0,\n-- CXObjCDeclQualifier_In = 0x1,\n-- CXObjCDeclQualifier_Inout = 0x2,\n-- CXObjCDeclQualifier_Out = 0x4,\n-- CXObjCDeclQualifier_Bycopy = 0x8,\n-- CXObjCDeclQualifier_Byref = 0x10,\n-- CXObjCDeclQualifier_Oneway = 0x20\n-- } CXObjCDeclQualifierKind;\n\n#c\nenum ObjCDeclQualifierKind\n { ObjCDeclQualifier_None = CXObjCDeclQualifier_None\n , ObjCDeclQualifier_In = CXObjCDeclQualifier_In\n , ObjCDeclQualifier_Inout = CXObjCDeclQualifier_Inout\n , ObjCDeclQualifier_Out = CXObjCDeclQualifier_Out\n , ObjCDeclQualifier_Bycopy = CXObjCDeclQualifier_Bycopy\n , ObjCDeclQualifier_Byref = CXObjCDeclQualifier_Byref\n , ObjCDeclQualifier_Oneway = CXObjCDeclQualifier_Oneway\n };\n#endc\n{# enum ObjCDeclQualifierKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags ObjCDeclQualifierKind where\n toBit ObjCDeclQualifier_None = 0x0\n toBit ObjCDeclQualifier_In = 0x1\n toBit ObjCDeclQualifier_Inout = 0x2\n toBit ObjCDeclQualifier_Out = 0x4\n toBit ObjCDeclQualifier_Bycopy = 0x8\n toBit ObjCDeclQualifier_Byref = 0x10\n toBit ObjCDeclQualifier_Oneway = 0x20\n\n-- unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C);\n{# fun clang_Cursor_getObjCDeclQualifiers {withVoided* %`Cursor a' } -> `CUInt' #}\ncursor_getObjCDeclQualifiers :: Cursor s -> IO Int\ncursor_getObjCDeclQualifiers c =\n clang_Cursor_getObjCDeclQualifiers c >>= return . fromIntegral\n\n-- unsigned clang_Cursor_isObjCOptional(CXCursor);\n{# fun clang_Cursor_isObjCOptional {withVoided* %`Cursor a' } -> `Bool' toBool #}\ncursor_isObjCOptional :: Cursor s -> IO Bool\ncursor_isObjCOptional c = clang_Cursor_isObjCOptional c\n\n-- unsigned clang_Cursor_isVariadic(CXCursor);\n{# fun clang_Cursor_isVariadic {withVoided* %`Cursor a' } -> `Bool' toBool #}\ncursor_isVariadic :: Cursor s -> IO Bool\ncursor_isVariadic c = clang_Cursor_isVariadic c\n\n-- CXSourceRange clang_Cursor_getCommentRange(CXCursor C);\n{# fun wrapped_clang_Cursor_getCommentRange as clang_Cursor_getCommentRange {withVoided* %`Cursor a' } -> `Ptr (SourceRange s)' castPtr #}\ncursor_getCommentRange :: Proxy s -> Cursor s' -> IO (SourceRange s)\ncursor_getCommentRange _ c = clang_Cursor_getCommentRange c >>= peek\n\n-- CXString clang_Cursor_getRawCommentText(CXCursor C);\n{# fun wrapped_clang_Cursor_getRawCommentText as clang_Cursor_getRawCommentText {withVoided* %`Cursor a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_Cursor_getRawCommentText :: Cursor s -> IO (ClangString ())\nunsafe_Cursor_getRawCommentText c =\n clang_Cursor_getRawCommentText c >>= peek\n\ncursor_getRawCommentText :: ClangBase m => Cursor s' -> ClangT s m (ClangString s)\ncursor_getRawCommentText = registerClangString . unsafe_Cursor_getRawCommentText\n\n-- CXString clang_Cursor_getBriefCommentText(CXCursor C);\n{# fun wrapped_clang_Cursor_getBriefCommentText as clang_Cursor_getBriefCommentText {withVoided* %`Cursor a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_Cursor_getBriefCommentText :: Cursor s -> IO (ClangString ())\nunsafe_Cursor_getBriefCommentText c =\n clang_Cursor_getBriefCommentText c >>= peek\n\ncursor_getBriefCommentText :: ClangBase m => Cursor s' -> ClangT s m (ClangString s)\ncursor_getBriefCommentText = registerClangString . unsafe_Cursor_getBriefCommentText\n\n-- CXComment clang_Cursor_getParsedComment(CXCursor C);\n\n{# fun wrapped_clang_Cursor_getParsedComment as clang_Cursor_getParsedComment {withVoided* %`Cursor a' } -> `Ptr (Comment s)' castPtr #}\ncursor_getParsedComment :: Proxy s -> Cursor s' -> IO (Comment s)\ncursor_getParsedComment _ c =\n clang_Cursor_getParsedComment c >>= peek\n\n-- typedef void *CXModule;\nnewtype Module s = Module { unModule :: Ptr () }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue Module\n\n-- %dis cxmodule p = (ptr p)\n\nmaybeModule :: Module s' -> Maybe (Module s)\nmaybeModule (Module p) | p == nullPtr = Nothing\nmaybeModule f = Just (unsafeCoerce f)\n\nunMaybeModule :: Maybe (Module s') -> Module s\nunMaybeModule (Just f) = unsafeCoerce f\nunMaybeModule Nothing = Module nullPtr\n\n-- CXModule clang_Cursor_getModule(CXCursor C);\n{# fun clang_Cursor_getModule {withVoided* %`Cursor a' } -> `Ptr ()' id #}\ncursor_getModule :: Proxy s -> Cursor s' -> IO (Module s)\ncursor_getModule _ c =\n clang_Cursor_getModule c >>= return . Module\n\n-- CXFile clang_Module_getASTFile(CXModule Module);\n{# fun clang_Module_getASTFile { id `Ptr ()' } -> `Ptr ()' id #}\nmodule_getASTFile :: Proxy s -> Module s' -> IO (File s)\nmodule_getASTFile _ m = clang_Module_getASTFile (unModule m) >>= return . File\n\n-- CXModule clang_Module_getParent(CXModule Module);\n{# fun clang_Module_getParent { id `Ptr ()' } -> `Ptr ()' id #}\nmodule_getParent :: Proxy s -> Module s' -> IO (Maybe (Module s))\nmodule_getParent _ m = clang_Module_getParent (unModule m) >>= return . maybeModule . Module\n\n-- CXString clang_Module_getName(CXModule Module);\n{# fun wrapped_clang_Module_getName as clang_Module_getName { id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_Module_getName :: Module s -> IO (ClangString ())\nunsafe_Module_getName m = clang_Module_getName (unModule m) >>= peek\n\nmodule_getName :: ClangBase m => Module s' -> ClangT s m (ClangString s)\nmodule_getName = registerClangString . unsafe_Module_getName\n\n-- CXString clang_Module_getFullName(CXModule Module);\n{# fun wrapped_clang_Module_getFullName as clang_Module_getFullName { id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_Module_getFullName :: Module s -> IO (ClangString ())\nunsafe_Module_getFullName m = clang_Module_getFullName (unModule m) >>= peek\n\nmodule_getFullName :: ClangBase m => Module s' -> ClangT s m (ClangString s)\nmodule_getFullName = registerClangString . unsafe_Module_getFullName\n\n-- unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit, CXModule Module);\n{# fun clang_Module_getNumTopLevelHeaders { id `Ptr ()', id `Ptr ()' } -> `Int' #}\nmodule_getNumTopLevelHeaders :: TranslationUnit s -> Module s' -> IO Int\nmodule_getNumTopLevelHeaders t m = clang_Module_getNumTopLevelHeaders (unTranslationUnit t) (unModule m)\n\n-- CXFile clang_Module_getTopLevelHeader(CXTranslationUnit, CXModule Module, unsigned Index);\n{# fun clang_Module_getTopLevelHeader { id `Ptr ()', id `Ptr ()', `Int' } -> `Ptr ()' id #}\nmodule_getTopLevelHeader :: Proxy s -> TranslationUnit s' -> Module s'' -> Int -> IO (File s)\nmodule_getTopLevelHeader _ t m i = clang_Module_getTopLevelHeader (unTranslationUnit t) (unModule m) i >>= return . File\n\n-- unsigned clang_CXXMethod_isPureVirtual(CXCursor C);\n{# fun clang_CXXMethod_isPureVirtual {withVoided* %`Cursor a' } -> `Bool' toBool #}\ncXXMethod_isPureVirtual :: Cursor s -> IO Bool\ncXXMethod_isPureVirtual c = clang_Cursor_isBitField c\n\n-- unsigned clang_CXXMethod_isStatic(CXCursor C);\n{# fun clang_CXXMethod_isStatic {withVoided* %`Cursor a' } -> `Bool' toBool #}\ncXXMethod_isStatic :: Cursor s -> IO Bool\ncXXMethod_isStatic c = clang_Cursor_isBitField c\n\n-- unsigned clang_CXXMethod_isVirtual(CXCursor C);\n{# fun clang_CXXMethod_isVirtual {withVoided* %`Cursor a' } -> `Bool' toBool #}\ncXXMethod_isVirtual :: Cursor s -> IO Bool\ncXXMethod_isVirtual c = clang_Cursor_isBitField c\n\n-- enum CXCursorKind clang_getTemplateCursorKind(CXCursor C);\n{# fun clang_getTemplateCursorKind {withVoided* %`Cursor a' } -> `Int' #}\ngetTemplateCursorKind :: Cursor s -> IO CursorKind\ngetTemplateCursorKind c =\n clang_getTemplateCursorKind c >>= return . toEnum\n\n-- CXCursor clang_getSpecializedCursorTemplate(CXCursor C);\n{# fun wrapped_clang_getSpecializedCursorTemplate as clang_getSpecializedCursorTemplate {withVoided* %`Cursor a' } -> `Ptr (Cursor s)' castPtr #}\ngetSpecializedCursorTemplate :: Proxy s -> Cursor s' -> IO (Cursor s)\ngetSpecializedCursorTemplate _ c =\n clang_getSpecializedCursorTemplate c >>= peek\n\n-- CXSourceRange clang_getCursorReferenceNameRange(CXCursor C,\n-- unsigned NameFlags,\n-- unsigned PieceIndex);\n{# fun wrapped_clang_getCursorReferenceNameRange as clang_getCursorReferenceNameRange {withVoided* %`Cursor a', `Int' , `Int' } -> `Ptr (SourceRange s)' castPtr #}\ngetCursorReferenceNameRange :: Proxy s -> Cursor s' -> Int -> Int -> IO (SourceRange s)\ngetCursorReferenceNameRange _ c fs idx = clang_getCursorReferenceNameRange c fs idx >>= peek\n\n-- enum CXNameRefFlags {\n-- CXNameRange_WantQualifier = 0x1,\n-- CXNameRange_WantTemplateArgs = 0x2,\n-- CXNameRange_WantSinglePiece = 0x4\n-- };\n#c\nenum NameRefFlags\n { NameRange_WantQualifier = CXNameRange_WantQualifier\n , NameRange_WantTemplateArgs = CXNameRange_WantTemplateArgs\n , NameRange_WantSinglePiece = CXNameRange_WantSinglePiece\n };\n#endc\n{# enum NameRefFlags {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags NameRefFlags where\n toBit NameRange_WantQualifier = 0x01\n toBit NameRange_WantTemplateArgs = 0x02\n toBit NameRange_WantSinglePiece = 0x04\n\n-- enum CXCommentKind {\n-- CXComment_Null = 0,\n-- CXComment_Text = 1,\n-- CXComment_InlineCommand = 2,\n-- CXComment_HTMLStartTag = 3,\n-- CXComment_HTMLEndTag = 4,\n-- CXComment_Paragraph = 5,\n-- CXComment_BlockCommand = 6,\n-- CXComment_ParamCommand = 7,\n-- CXComment_TParamCommand = 8,\n-- CXComment_VerbatimBlockCommand = 9,\n-- CXComment_VerbatimBlockLine = 10,\n-- CXComment_VerbatimLine = 11,\n-- CXComment_FullComment = 12\n-- };\n#c\nenum CommentKind\n { NullComment = CXComment_Null\n , TextComment = CXComment_Text\n , InlineCommandComment = CXComment_InlineCommand\n , HTMLStartTagComment = CXComment_HTMLStartTag\n , HTMLEndTagComment = CXComment_HTMLEndTag\n , ParagraphComment = CXComment_Paragraph\n , BlockCommandComment = CXComment_BlockCommand\n , ParamCommandComment = CXComment_ParamCommand\n , TParamCommandComment = CXComment_TParamCommand\n , VerbatimBlockCommandComment = CXComment_VerbatimBlockCommand\n , VerbatimBlockLineComment = CXComment_VerbatimBlockLine\n , VerbatimLineComment = CXComment_VerbatimLine\n , FullComment = CXComment_FullComment\n };\n#endc\n{# enum CommentKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- enum CXCommentInlineCommandRenderKind {\n-- CXCommentInlineCommandRenderKind_Normal,\n-- CXCommentInlineCommandRenderKind_Bold,\n-- CXCommentInlineCommandRenderKind_Monospaced,\n-- CXCommentInlineCommandRenderKind_Emphasized\n-- };\n\n-- | A rendering style which should be used for the associated inline command in the comment AST.\n#c\nenum InlineCommandRenderStyle\n { NormalInlineCommandRenderStyle = CXCommentInlineCommandRenderKind_Normal\n , BoldInlineCommandRenderStyle = CXCommentInlineCommandRenderKind_Bold\n , MonospacedInlineCommandRenderStyle = CXCommentInlineCommandRenderKind_Monospaced\n , EmphasizedInlineCommandRenderStyle = CXCommentInlineCommandRenderKind_Emphasized\n };\n#endc\n{# enum InlineCommandRenderStyle {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n-- enum CXCommentParamPassDirection {\n-- CXCommentParamPassDirection_In,\n-- CXCommentParamPassDirection_Out,\n-- CXCommentParamPassDirection_InOut\n-- };\n\n-- | A parameter passing direction.\n#c\nenum ParamPassDirectionKind\n { InParamPassDirection = CXCommentParamPassDirection_In\n , OutParamPassDirection = CXCommentParamPassDirection_Out\n , InOutParamPassDirection = CXCommentParamPassDirection_InOut\n };\n#endc\n{#enum ParamPassDirectionKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- enum CXCommentKind clang_Comment_getKind(CXComment Comment);\n{# fun clang_Comment_getKind {withVoided* %`Comment a' } -> `Int' #}\ncomment_getKind :: Comment s -> IO CommentKind\ncomment_getKind c =\n clang_Comment_getKind c >>= return . toEnum\n\n-- unsigned clang_Comment_getNumChildren(CXComment Comment);\n{# fun clang_Comment_getNumChildren {withVoided* %`Comment a' } -> `Int' #}\ncomment_getNumChildren :: Comment s -> IO Int\ncomment_getNumChildren c =\n clang_Comment_getNumChildren c\n\n-- CXComment clang_Comment_getChild(CXComment Comment, unsigned ChildIdx);\n{# fun clang_Comment_getChild {withVoided* %`Comment a', `Int' } -> `Ptr (Comment s)' castPtr #}\ncomment_getChild :: Proxy s -> Comment s' -> Int -> IO (Comment s)\ncomment_getChild _ c i = clang_Comment_getChild c i >>= peek\n\n-- unsigned clang_Comment_isWhitespace(CXComment Comment);\n{# fun clang_Comment_isWhitespace {withVoided* %`Comment a' } -> `Bool' toBool #}\ncomment_isWhitespace :: Comment s -> IO Bool\ncomment_isWhitespace c = clang_Comment_isWhitespace c\n\n-- unsigned clang_InlineContentComment_hasTrailingNewline(CXComment Comment);\n{# fun clang_InlineContentComment_hasTrailingNewline {withVoided* %`Comment a' } -> `Bool' toBool #}\ninlineContentComment_hasTrailingNewline :: Comment s -> IO Bool\ninlineContentComment_hasTrailingNewline c = clang_InlineContentComment_hasTrailingNewline c\n\n-- CXString clang_TextComment_getText(CXComment Comment);\n{# fun wrapped_clang_TextComment_getText as clang_TextComment_getText {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_TextComment_getText :: Comment s -> IO (ClangString ())\nunsafe_TextComment_getText c =\n clang_TextComment_getText c >>= peek\n\ntextComment_getText :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\ntextComment_getText = registerClangString . unsafe_TextComment_getText\n\n-- CXString clang_InlineCommandComment_getCommandName(CXComment Comment);\n{# fun clang_InlineCommandComment_getCommandName {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_InlineCommandComment_getCommandName :: Comment s -> IO (ClangString ())\nunsafe_InlineCommandComment_getCommandName c =\n clang_InlineCommandComment_getCommandName c >>= peek\n\ninlineCommandComment_getCommandName :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\ninlineCommandComment_getCommandName = registerClangString . unsafe_InlineCommandComment_getCommandName\n\n-- enum CXCommentInlineCommandRenderKind clang_InlineCommandComment_getRenderKind(CXComment Comment);\n{# fun clang_InlineCommandComment_getRenderKind {withVoided* %`Comment a' } -> `Int' #}\ninlineCommandComment_getRenderKind :: Comment s -> IO InlineCommandRenderStyle\ninlineCommandComment_getRenderKind c =\n clang_InlineCommandComment_getRenderKind c >>= return . toEnum\n\n-- unsigned clang_InlineCommandComment_getNumArgs(CXComment Comment);\n{# fun clang_InlineCommandComment_getNumArgs {withVoided* %`Comment a' } -> `Int' #}\ninlineCommandComment_getNumArgs :: Comment s -> IO Int\ninlineCommandComment_getNumArgs c =\n clang_InlineCommandComment_getNumArgs c\n\n-- CXString clang_InlineCommandComment_getArgText(CXComment Comment, unsigned ArgIdx);\n{# fun clang_InlineCommandComment_getArgText {withVoided* %`Comment a', `Int' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_InlineCommandComment_getArgText :: Comment s -> Int -> IO (ClangString ())\nunsafe_InlineCommandComment_getArgText c idx =\n clang_InlineCommandComment_getArgText c idx >>= peek\n\ninlineCommandComment_getArgText :: ClangBase m => Comment s' -> Int -> ClangT s m (ClangString s)\ninlineCommandComment_getArgText = (registerClangString .) . unsafe_InlineCommandComment_getArgText\n\n-- CXString clang_HTMLTagComment_getTagName(CXComment Comment);\n{# fun wrapped_clang_HTMLTagComment_getTagName as clang_HTMLTagComment_getTagName {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_HTMLTagComment_getTagName :: Comment s -> IO (ClangString ())\nunsafe_HTMLTagComment_getTagName c =\n clang_HTMLTagComment_getTagName c >>= peek\n\nhTMLTagComment_getTagName :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\nhTMLTagComment_getTagName = registerClangString . unsafe_HTMLTagComment_getTagName\n\n-- unsigned clang_HTMLStartTagComment_isSelfClosing(CXComment Comment);\n{# fun clang_HTMLStartTagComment_isSelfClosing {withVoided* %`Comment a' } -> `Bool' toBool #}\nhTMLStartTagComment_isSelfClosing :: Comment s -> IO Bool\nhTMLStartTagComment_isSelfClosing c = clang_HTMLStartTagComment_isSelfClosing c\n\n-- unsigned clang_HTMLStartTag_getNumAttrs(CXComment Comment);\n{# fun clang_HTMLStartTag_getNumAttrs {withVoided* %`Comment a' } -> `Int' #}\nhTMLStartTag_getNumAttrs :: Comment s -> IO Int\nhTMLStartTag_getNumAttrs c =\n clang_HTMLStartTag_getNumAttrs c\n\n-- CXString clang_HTMLStartTag_getAttrName(CXComment Comment, unsigned AttrIdx);\n{# fun clang_HTMLStartTag_getAttrName {withVoided* %`Comment a', `Int' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_HTMLStartTag_getAttrName :: Comment s -> Int -> IO (ClangString ())\nunsafe_HTMLStartTag_getAttrName c idx =\n clang_HTMLStartTag_getAttrName c idx >>= peek\n\nhTMLStartTag_getAttrName :: ClangBase m => Comment s' -> Int -> ClangT s m (ClangString s)\nhTMLStartTag_getAttrName = (registerClangString .) . unsafe_HTMLStartTag_getAttrName\n\n-- CXString clang_HTMLStartTag_getAttrValue(CXComment Comment, unsigned AttrIdx);\n{# fun clang_HTMLStartTag_getAttrValue {withVoided* %`Comment a', `Int' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_HTMLStartTag_getAttrValue :: Comment s -> Int -> IO (ClangString ())\nunsafe_HTMLStartTag_getAttrValue c idx =\n clang_HTMLStartTag_getAttrValue c idx >>= peek\n\nhTMLStartTag_getAttrValue :: ClangBase m => Comment s' -> Int -> ClangT s m (ClangString s)\nhTMLStartTag_getAttrValue = (registerClangString .) . unsafe_HTMLStartTag_getAttrValue\n\n-- CXString clang_BlockCommandComment_getCommandName(CXComment Comment);\n{# fun clang_BlockCommandComment_getCommandName {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_BlockCommandComment_getCommandName :: Comment s -> IO (ClangString ())\nunsafe_BlockCommandComment_getCommandName c =\n clang_BlockCommandComment_getCommandName c >>= peek\n\nblockCommandComment_getCommandName :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\nblockCommandComment_getCommandName = registerClangString . unsafe_BlockCommandComment_getCommandName\n\n-- unsigned clang_BlockCommandComment_getNumArgs(CXComment Comment);\n{# fun clang_BlockCommandComment_getNumArgs {withVoided* %`Comment a' } -> `Int' #}\nblockCommandComment_getNumArgs :: Comment s -> IO Int\nblockCommandComment_getNumArgs c =\n clang_BlockCommandComment_getNumArgs c\n\n-- CXString clang_BlockCommandComment_getArgText(CXComment Comment, unsigned ArgIdx);\n{# fun clang_BlockCommandComment_getArgText {withVoided* %`Comment a', `Int' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_BlockCommandComment_getArgText :: Comment s -> Int -> IO (ClangString ())\nunsafe_BlockCommandComment_getArgText c idx =\n clang_BlockCommandComment_getArgText c idx >>= peek\n\nblockCommandComment_getArgText :: ClangBase m => Comment s' -> Int -> ClangT s m (ClangString s)\nblockCommandComment_getArgText = (registerClangString .) . unsafe_BlockCommandComment_getArgText\n\n-- CXComment clang_BlockCommandComment_getParagraph(CXComment Comment);\n{# fun clang_BlockCommandComment_getParagraph {withVoided* %`Comment a' } -> `Ptr (Comment s)' castPtr #}\nblockCommandComment_getParagraph :: Proxy s -> Comment s' -> IO (Comment s)\nblockCommandComment_getParagraph _ c =\n clang_BlockCommandComment_getParagraph c >>= peek\n\n-- CXString clang_ParamCommandComment_getParamName(CXComment Comment);\n{# fun clang_ParamCommandComment_getParamName {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_ParamCommandComment_getParamName :: Comment s -> IO (ClangString ())\nunsafe_ParamCommandComment_getParamName c =\n clang_ParamCommandComment_getParamName c >>= peek\n\nparamCommandComment_getParamName :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\nparamCommandComment_getParamName = registerClangString . unsafe_ParamCommandComment_getParamName\n\n-- unsigned clang_ParamCommandComment_isParamIndexValid(CXComment Comment);\n{# fun clang_ParamCommandComment_isParamIndexValid {withVoided* %`Comment a' } -> `Bool' toBool #}\nparamCommandComment_isParamIndexValid :: Comment s -> IO Bool\nparamCommandComment_isParamIndexValid c =\n clang_ParamCommandComment_isParamIndexValid c\n\n-- unsigned clang_ParamCommandComment_getParamIndex(CXComment Comment);\n{# fun clang_ParamCommandComment_getParamIndex {withVoided* %`Comment a' } -> `Int' #}\nparamCommandComment_getParamIndex :: Comment s -> IO Int\nparamCommandComment_getParamIndex c =\n clang_ParamCommandComment_getParamIndex c\n\n-- unsigned clang_ParamCommandComment_isDirectionExplicit(CXComment Comment);\n{# fun clang_ParamCommandComment_isDirectionExplicit {withVoided* %`Comment a' } -> `Bool' toBool #}\nparamCommandComment_isDirectionExplicit :: Comment s -> IO Bool\nparamCommandComment_isDirectionExplicit c =\n clang_ParamCommandComment_isDirectionExplicit c\n\n-- enum CXCommentParamPassDirection clang_ParamCommandComment_getDirection(CXComment Comment);\n{# fun clang_ParamCommandComment_getDirection {withVoided* %`Comment a' } -> `Int' #}\nparamCommandComment_getDirection :: Comment s -> IO ParamPassDirectionKind\nparamCommandComment_getDirection c =\n clang_ParamCommandComment_getDirection c >>= return . toEnum\n\n-- CXString clang_TParamCommandComment_getParamName(CXComment Comment);\n{# fun clang_TParamCommandComment_getParamName {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_TParamCommandComment_getParamName :: Comment s -> IO (ClangString ())\nunsafe_TParamCommandComment_getParamName c =\n clang_TParamCommandComment_getParamName c >>= peek\n\ntParamCommandComment_getParamName :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\ntParamCommandComment_getParamName = registerClangString . unsafe_TParamCommandComment_getParamName\n\n-- unsigned clang_TParamCommandComment_isParamPositionValid(CXComment Comment);\n{# fun clang_TParamCommandComment_isParamPositionValid {withVoided* %`Comment a' } -> `Bool' toBool #}\ntParamCommandComment_isParamPositionValid :: Comment s -> IO Bool\ntParamCommandComment_isParamPositionValid c =\n clang_TParamCommandComment_isParamPositionValid c\n\n-- unsigned clang_TParamCommandComment_getDepth(CXComment Comment);\n{# fun clang_TParamCommandComment_getDepth { withVoided* %`Comment a' } -> `Int' #}\ntParamCommandComment_getDepth :: Comment s -> IO Int\ntParamCommandComment_getDepth c =\n clang_TParamCommandComment_getDepth c\n\n-- unsigned clang_TParamCommandComment_getIndex(CXComment Comment, unsigned Depth);\n{# fun clang_TParamCommandComment_getIndex {withVoided* %`Comment a', `Int' } -> `Int' #}\ntParamCommandComment_getIndex :: Comment s -> Int -> IO Int\ntParamCommandComment_getIndex c idx =\n clang_TParamCommandComment_getIndex c idx\n\n-- CXString clang_VerbatimBlockLineComment_getText(CXComment Comment);\n{# fun clang_VerbatimBlockLineComment_getText {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_VerbatimBlockLineComment_getText :: Comment s -> IO (ClangString ())\nunsafe_VerbatimBlockLineComment_getText c =\n clang_VerbatimBlockLineComment_getText c >>= peek\n\nverbatimBlockLineComment_getText :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\nverbatimBlockLineComment_getText = registerClangString . unsafe_VerbatimBlockLineComment_getText\n\n-- CXString clang_VerbatimLineComment_getText(CXComment Comment);\n{# fun wrapped_clang_VerbatimLineComment_getText as clang_VerbatimLineComment_getText {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_VerbatimLineComment_getText :: Comment s -> IO (ClangString ())\nunsafe_VerbatimLineComment_getText c =\n clang_VerbatimLineComment_getText c >>= peek\n\nverbatimLineComment_getText :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\nverbatimLineComment_getText = registerClangString . unsafe_VerbatimLineComment_getText\n\n-- CXString clang_HTMLTagComment_getAsString(CXComment Comment);\n{# fun wrapped_clang_HTMLTagComment_getAsString as clang_HTMLTagComment_getAsString {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_HTMLTagComment_getAsString :: Comment s -> IO (ClangString ())\nunsafe_HTMLTagComment_getAsString c =\n clang_HTMLTagComment_getAsString c >>= peek\n\nhTMLTagComment_getAsString :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\nhTMLTagComment_getAsString = registerClangString . unsafe_HTMLTagComment_getAsString\n\n-- CXString clang_FullComment_getAsHTML(CXComment Comment);\n{# fun wrapped_clang_FullComment_getAsHTML as clang_FullComment_getAsHTML {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_FullComment_getAsHTML :: Comment s -> IO (ClangString ())\nunsafe_FullComment_getAsHTML c =\n clang_FullComment_getAsHTML c >>= peek\n\nfullComment_getAsHTML :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\nfullComment_getAsHTML = registerClangString . unsafe_FullComment_getAsHTML\n\n-- CXString clang_FullComment_getAsXML(CXComment Comment);\n{# fun wrapped_clang_FullComment_getAsXML as clang_FullComment_getAsXML {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_FullComment_getAsXML :: Comment s -> IO (ClangString ())\nunsafe_FullComment_getAsXML c =\n clang_FullComment_getAsXML c >>= peek\n\nfullComment_getAsXML :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\nfullComment_getAsXML = registerClangString . unsafe_FullComment_getAsXML\n\n-- typedef enum CXTokenKind {\n-- CXToken_Punctuation,\n-- CXToken_Keyword,\n-- CXToken_Identifier,\n-- CXToken_Literal,\n-- CXToken_Comment\n-- } CXTokenKind;\n#c\nenum TokenKind\n { PunctuationToken = CXToken_Punctuation\n , KeywordToken = CXToken_Keyword\n , IdentifierToken = CXToken_Identifier\n , LiteralToken = CXToken_Literal\n , CommentToken = CXToken_Comment\n };\n#endc\n{# enum TokenKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- typedef struct {\n-- unsigned int_data[4];\n-- void *ptr_data;\n-- } CXToken;\ndata Token s = Token !Int !Int !Int !Int !(Ptr ())\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue Token\n\ninstance Storable (Token s) where\n sizeOf _ = sizeOfCXToken\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfCXToken\n {-# INLINE alignment #-}\n\n peek p = do\n int_data <- {#get CXToken->int_data #} p >>= peekArray 4\n ptr_data <- {#get CXToken->ptr_data #} p\n return $! Token (fromIntegral (int_data !! 0)) (fromIntegral (int_data !! 1)) (fromIntegral (int_data !! 2)) (fromIntegral (int_data !! 3)) ptr_data\n {-# INLINE peek #-}\n\n poke p (Token i0 i1 i2 i3 ptr_data) = do\n intsArray <- mallocArray 4\n pokeArray intsArray (map fromIntegral [i0,i1,i2,i3])\n {#set CXToken->int_data #} p intsArray\n {#set CXToken->ptr_data #} p ptr_data\n {-# INLINE poke #-}\n\n-- CXTokenKind clang_getTokenKind(CXToken);\n{# fun clang_getTokenKind { withVoided* %`Token s' } -> `Int' #}\ngetTokenKind :: Token s -> IO TokenKind\ngetTokenKind t =\n clang_getTokenKind t >>= return . toEnum\n\n-- CXString clang_getTokenSpelling(CXTranslationUnit, CXToken);\n{# fun wrapped_clang_getTokenSpelling as clang_getTokenSpelling { id `Ptr ()', withVoided* %`Token s' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getTokenSpelling :: TranslationUnit s -> Token s' -> IO (ClangString ())\nunsafe_getTokenSpelling tu t =\n clang_getTokenSpelling (unTranslationUnit tu) t >>= peek\n\ngetTokenSpelling :: ClangBase m => TranslationUnit s' -> Token s'' -> ClangT s m (ClangString s)\ngetTokenSpelling = (registerClangString .) . unsafe_getTokenSpelling\n\n-- CXSourceLocation clang_getTokenLocation(CXTranslationUnit,\n-- CXToken);\n{# fun wrapped_clang_getTokenLocation as clang_getTokenLocation { id `Ptr ()', withVoided* %`Token a' } -> `Ptr (SourceLocation s)' castPtr #}\ngetTokenLocation :: Proxy s -> TranslationUnit t -> Token s' -> IO (SourceLocation s)\ngetTokenLocation _ tu t =\n clang_getTokenLocation (unTranslationUnit tu) t >>= peek\n\n-- CXSourceRange clang_getTokenExtent(CXTranslationUnit, CXToken);\n{# fun wrapped_clang_getTokenExtent as clang_getTokenExtent { id `Ptr ()', withVoided* %`Token a' } -> `Ptr (SourceRange s)' castPtr #}\ngetTokenExtent :: Proxy s -> TranslationUnit t -> Token s' -> IO (SourceRange s)\ngetTokenExtent _ tu t =\n clang_getTokenExtent (unTranslationUnit tu) t >>= peek\n\n-- We deliberately don't export the constructor for UnsafeTokenList.\n-- The only way to unwrap it is registerTokenList.\ntype TokenList s = DVS.Vector (Token s)\ninstance ClangValueList Token\ndata UnsafeTokenList = UnsafeTokenList !(Ptr ()) !Int\n\nforeign import ccall unsafe \"FFI_stub_ffi.h clang_disposeTokens\" clang_disposeTokens :: Ptr () -> Ptr () -> CUInt -> IO ()\n\ndisposeTokens :: TranslationUnit s -> TokenList s' -> IO ()\ndisposeTokens tu tl =\n let (tPtr, n) = fromTokenList tl in\n clang_disposeTokens (unTranslationUnit tu) tPtr (fromIntegral n)\n\nregisterTokenList :: ClangBase m => TranslationUnit s' -> IO UnsafeTokenList\n -> ClangT s m (TokenList s)\nregisterTokenList tu action = do\n (_, tokenList) <- clangAllocate (action >>= tokenListToVector) (disposeTokens tu)\n return tokenList\n{-# INLINEABLE registerTokenList #-}\n\ntokenListToVector :: Storable a => UnsafeTokenList -> IO (DVS.Vector a)\ntokenListToVector (UnsafeTokenList ts n) = do\n fptr <- newForeignPtr_ (castPtr ts)\n return $ DVS.unsafeFromForeignPtr fptr 0 n\n{-# INLINE tokenListToVector #-}\n\nfromTokenList :: TokenList s -> (Ptr (), Int)\nfromTokenList ts = let (p, _, _) = DVS.unsafeToForeignPtr ts in\n (castPtr $ Foreign.ForeignPtr.Unsafe.unsafeForeignPtrToPtr p, DVS.length ts)\n\ntoTokenList :: (Ptr (), Int) -> UnsafeTokenList\ntoTokenList (ts, n) = UnsafeTokenList ts n\n\n-- void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,\n-- CXToken **Tokens, unsigned *NumTokens);\n{# fun clang_tokenize { id `Ptr ()',withVoided* %`SourceRange a', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()'#}\nunsafe_tokenize :: TranslationUnit s -> SourceRange s' -> IO UnsafeTokenList\nunsafe_tokenize tu sr = do\n tokensPtrArray <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr (Token ())))))\n numTokens <- clang_tokenize (unTranslationUnit tu) sr (castPtr tokensPtrArray)\n tokensPtr <- peek tokensPtrArray\n return (toTokenList (tokensPtr, fromIntegral numTokens))\n\ntokenize :: ClangBase m => TranslationUnit s' -> SourceRange s'' -> ClangT s m (TokenList s)\ntokenize tu = registerTokenList tu . unsafe_tokenize tu\n\n-- TODO: test me\n-- Note that registerCursorList can be used for the result of this\n-- function because it just calls free() to dispose of the list.\n--\n-- void clang_annotateTokens(CXTranslationUnit TU,\n-- CXToken *Tokens, unsigned NumTokens,\n-- CXCursor *Cursors);\n{# fun clang_annotateTokens { id `Ptr ()', id `Ptr ()', `Int', id `Ptr ()' } -> `()' id#}\nunsafe_annotateTokens :: TranslationUnit s -> TokenList s' -> IO UnsafeCursorList\nunsafe_annotateTokens tu tl =\n let (tPtr, numTokens) = fromTokenList tl in\n do\n cPtr <- mallocBytes ((sizeOf (undefined :: (Ptr (Cursor ())))) * numTokens)\n clang_annotateTokens (unTranslationUnit tu) tPtr numTokens (castPtr cPtr)\n return (toCursorList (cPtr, numTokens))\n\nannotateTokens :: ClangBase m => TranslationUnit s' -> TokenList s'' -> ClangT s m (CursorList s)\nannotateTokens = (registerCursorList .) . unsafe_annotateTokens\n\n-- CXString clang_getCursorKindSpelling(enum CXCursorKind Kind);\n{# fun wrapped_clang_getCursorKindSpelling as clang_getCursorKindSpelling { `CInt' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCursorKindSpelling :: CursorKind -> IO (ClangString ())\nunsafe_getCursorKindSpelling ck = clang_getCursorKindSpelling (fromIntegral (fromEnum ck)) >>= peek\n\ngetCursorKindSpelling :: ClangBase m => CursorKind -> ClangT s m (ClangString s)\ngetCursorKindSpelling = registerClangString . unsafe_getCursorKindSpelling\n\n-- void clang_enableStackTraces(void);\nforeign import ccall unsafe \"clang-c\/Index.h clang_enableStackTraces\" enableStackTraces :: IO ()\n\n-- typedef void *CXCompletionString;\n\n-- | A semantic string that describes a code completion result.\n--\n-- A 'CompletionString' describes the formatting of a code completion\n-- result as a single \\\"template\\\" of text that should be inserted into the\n-- source buffer when a particular code completion result is selected.\n-- Each semantic string is made up of some number of \\\"chunks\\\", each of which\n-- contains some text along with a description of what that text means.\n--\n-- See 'ChunkKind' for more details about the role each kind of chunk plays.\nnewtype CompletionString s = CompletionString (Ptr ())\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue CompletionString\n\n-- typedef struct {\n-- enum CXCursorKind CursorKind;\n-- CXCompletionString CompletionString;\n-- } CXCompletionResult;\ndata CompletionResult s = CompletionResult !CursorKind !(CompletionString s)\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue CompletionResult\n\n-- enum CXCompletionChunkKind {\n-- CXCompletionChunk_Optional,\n-- CXCompletionChunk_TypedText,\n-- CXCompletionChunk_Text,\n-- CXCompletionChunk_Placeholder,\n-- CXCompletionChunk_Informative,\n-- CXCompletionChunk_CurrentParameter,\n-- CXCompletionChunk_LeftParen,\n-- CXCompletionChunk_RightParen,\n-- CXCompletionChunk_LeftBracket,\n-- CXCompletionChunk_RightBracket,\n-- CXCompletionChunk_LeftBrace,\n-- CXCompletionChunk_RightBrace,\n-- CXCompletionChunk_LeftAngle,\n-- CXCompletionChunk_RightAngle,\n-- CXCompletionChunk_Comma,\n-- CXCompletionChunk_ResultType,\n-- CXCompletionChunk_Colon,\n-- CXCompletionChunk_SemiColon,\n-- CXCompletionChunk_Equal,\n-- CXCompletionChunk_HorizontalSpace,\n-- CXCompletionChunk_VerticalSpace\n-- };\n\n-- | Describes a single piece of text within a code completion string.\n--\n-- * 'OptionalChunkKind': A code completion string that describes \"optional\" text that\n-- could be a part of the template (but is not required).\n-- This is the only kind of chunk that has a code completion\n-- string for its representation. The code completion string describes an\n-- describes an additional part of the template that is completely optional.\n-- For example, optional chunks can be used to describe the placeholders for\n-- arguments that match up with defaulted function parameters.\n--\n-- * 'TypedTextChunkKind': Text that a user would be expected to type to get this\n-- code completion result.\n-- There will be exactly one \\\"typed text\\\" chunk in a semantic string, which\n-- will typically provide the spelling of a keyword or the name of a\n-- declaration that could be used at the current code point. Clients are\n-- expected to filter the code completion results based on the text in this\n-- chunk.\n--\n-- * 'TextChunkKind': Text that should be inserted as part of a code completion result.\n-- A \\\"text\\\" chunk represents text that is part of the template to be\n-- inserted into user code should this particular code completion result\n-- be selected.\n--\n-- * 'PlaceholderChunkKind': Placeholder text that should be replaced by the user.\n-- A \\\"placeholder\\\" chunk marks a place where the user should insert text\n-- into the code completion template. For example, placeholders might mark\n-- the function parameters for a function declaration, to indicate that the\n-- user should provide arguments for each of those parameters. The actual\n-- text in a placeholder is a suggestion for the text to display before\n-- the user replaces the placeholder with real code.\n--\n-- * 'InformativeChunkKind': Informative text that should be displayed but never inserted as\n-- part of the template.\n-- An \\\"informative\\\" chunk contains annotations that can be displayed to\n-- help the user decide whether a particular code completion result is the\n-- right option, but which is not part of the actual template to be inserted\n-- by code completion.\n--\n-- * 'CurrentParameterChunkKind': Text that describes the current parameter\n-- when code completion is referring to a function call, message send, or\n-- template specialization.\n-- A \\\"current parameter\\\" chunk occurs when code completion is providing\n-- information about a parameter corresponding to the argument at the\n-- code completion point. For example, given a function \\\"int add(int x, int y);\\\"\n-- and the source code \\\"add(\\\", where the code completion point is after the\n-- \\\"(\\\", the code completion string will contain a \\\"current parameter\\\" chunk\n-- for \\\"int x\\\", indicating that the current argument will initialize that\n-- parameter. After typing further, to \\\"add(17\\\", (where the code completion\n-- point is after the \\\",\\\"), the code completion string will contain a\n-- \\\"current parameter\\\" chunk to \\\"int y\\\".\n--\n-- * 'LeftParenChunkKind': A left parenthesis (\\'(\\'), used to initiate a function call or\n-- signal the beginning of a function parameter list.\n--\n-- * 'RightParenChunkKind': A right parenthesis (\\')\\'), used to finish a function call or\n-- signal the end of a function parameter list.\n--\n-- * 'LeftBracketChunkKind': A left bracket (\\'[\\').\n--\n-- * 'RightBracketChunkKind': A right bracket (\\']\\').\n--\n-- * 'LeftBraceChunkKind': A left brace (\\'{\\').\n--\n-- * 'RightBraceChunkKind': A right brace (\\'}\\').\n--\n-- * 'LeftAngleChunkKind': A left angle bracket (\\'<\\').\n--\n-- * 'RightAngleChunkKind': A right angle bracket (\\'>\\').\n--\n-- * 'CommaChunkKind': A comma separator (\\',\\').\n--\n-- * 'ResultTypeChunkKind': Text that specifies the result type of a given result.\n-- This special kind of informative chunk is not meant to be inserted into\n-- the text buffer. Rather, it is meant to illustrate the type that an\n-- expression using the given completion string would have.\n--\n-- * 'ColonChunkKind': A colon (\\':\\').\n--\n-- * 'SemiColonChunkKind': A semicolon (\\';\\').\n--\n-- * 'EqualChunkKind': An \\'=\\' sign.\n--\n-- * 'HorizontalSpaceChunkKind': Horizontal space (\\' \\').\n--\n-- * 'VerticalSpaceChunkKind': Vertical space (\\'\\\\n\\'), after which it is generally\n-- a good idea to perform indentation.\n#c\nenum ChunkKind\n { OptionalChunkKind = CXCompletionChunk_Optional\n , TypedTextChunkKind = CXCompletionChunk_TypedText\n , TextChunkKind = CXCompletionChunk_Text\n , PlaceholderChunkKind = CXCompletionChunk_Placeholder\n , InformativeChunkKind = CXCompletionChunk_Informative\n , CurrentParameterChunkKind = CXCompletionChunk_CurrentParameter\n , LeftParenChunkKind = CXCompletionChunk_LeftParen\n , RightParenChunkKind = CXCompletionChunk_RightParen\n , LeftBracketChunkKind = CXCompletionChunk_LeftBracket\n , RightBracketChunkKind = CXCompletionChunk_RightBracket\n , LeftBraceChunkKind = CXCompletionChunk_LeftBrace\n , RightBraceChunkKind = CXCompletionChunk_RightBrace\n , LeftAngleChunkKind = CXCompletionChunk_LeftAngle\n , RightAngleChunkKind = CXCompletionChunk_RightAngle\n , CommaChunkKind = CXCompletionChunk_Comma\n , ResultTypeChunkKind = CXCompletionChunk_ResultType\n , ColonChunkKind = CXCompletionChunk_Colon\n , SemiColonChunkKind = CXCompletionChunk_SemiColon\n , EqualChunkKind = CXCompletionChunk_Equal\n , HorizontalSpaceChunkKind = CXCompletionChunk_HorizontalSpace\n , VerticalSpaceChunkKind = CXCompletionChunk_VerticalSpace\n };\n#endc\n{# enum ChunkKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- enum CXCompletionChunkKind\n-- clang_getCompletionChunkKind(CXCompletionString completion_string,\n-- unsigned chunk_number);\n{# fun clang_getCompletionChunkKind { id `Ptr ()', `Int'} -> `Int' #}\ngetCompletionChunkKind :: CompletionString s -> Int -> IO ChunkKind\ngetCompletionChunkKind (CompletionString ptr) i = clang_getCompletionChunkKind ptr i >>= return . toEnum\n\n-- CXString\n-- clang_getCompletionChunkText(CXCompletionString completion_string,\n-- unsigned chunk_number);\n{# fun wrapped_clang_getCompletionChunkText as clang_getCompletionChunkText { id `Ptr ()' , `Int' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCompletionChunkText :: CompletionString s -> Int -> IO (ClangString ())\nunsafe_getCompletionChunkText (CompletionString ptr) i = clang_getCompletionChunkText ptr i >>= peek\n\ngetCompletionChunkText :: ClangBase m => CompletionString s' -> Int -> ClangT s m (ClangString s)\ngetCompletionChunkText = (registerClangString .) . unsafe_getCompletionChunkText\n\n-- CXCompletionString\n-- clang_getCompletionChunkCompletionString(CXCompletionString completion_string,\n-- unsigned chunk_number);\n{# fun clang_getCompletionChunkCompletionString { id `Ptr ()' , `Int' } -> `Ptr ()' id #}\ngetCompletionChunkCompletionString :: CompletionString s -> Int -> IO (CompletionString s')\ngetCompletionChunkCompletionString (CompletionString ptr) i =\n clang_getCompletionChunkCompletionString ptr i >>= return . CompletionString\n\n-- unsigned\n-- clang_getNumCompletionChunks(CXCompletionString completion_string);\n{# fun clang_getNumCompletionChunks { id `Ptr ()' } -> `Int' #}\ngetNumCompletionChunks :: CompletionString s -> IO Int\ngetNumCompletionChunks (CompletionString ptr) = clang_getNumCompletionChunks ptr\n\n-- unsigned\n-- clang_getCompletionPriority(CXCompletionString completion_string);\n{# fun clang_getCompletionPriority { id `Ptr ()' } -> `Int' #}\ngetCompletionPriority :: CompletionString s -> IO Int\ngetCompletionPriority (CompletionString ptr) = clang_getCompletionPriority ptr\n\n-- enum CXAvailabilityKind\n-- clang_getCompletionAvailability(CXCompletionString completion_string);\n{# fun clang_getCompletionAvailability { id `Ptr ()' } -> `Int' #}\ngetCompletionAvailability :: CompletionString s -> IO AvailabilityKind\ngetCompletionAvailability (CompletionString ptr) = clang_getCompletionAvailability ptr >>= return . toEnum\n\n-- unsigned clang_getCompletionNumAnnotations(CXCompletionString completion_string);\n{# fun clang_getCompletionNumAnnotations { id `Ptr ()' } -> `Int' #}\ngetCompletionNumAnnotations :: CompletionString s -> IO Int\ngetCompletionNumAnnotations (CompletionString ptr) = clang_getCompletionNumAnnotations ptr\n\n-- CXString clang_getCompletionAnnotation(CXCompletionString completion_string,\n-- unsigned annotation_number);\n{# fun wrapped_clang_getCompletionAnnotation as clang_getCompletionAnnotation { id `Ptr ()' , `Int' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCompletionAnnotation :: CompletionString s -> Int -> IO (ClangString ())\nunsafe_getCompletionAnnotation (CompletionString ptr) i = clang_getCompletionAnnotation ptr i >>= peek\n\ngetCompletionAnnotation :: ClangBase m => CompletionString s' -> Int -> ClangT s m (ClangString s)\ngetCompletionAnnotation = (registerClangString .) . unsafe_getCompletionAnnotation\n\n-- CXString clang_getCompletionParent(CXCompletionString completion_string,\n-- enum CXCursorKind *kind);\n{# fun wrapped_clang_getCompletionParent as clang_getCompletionParent { id `Ptr ()' , `CInt' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCompletionParent :: CompletionString s -> IO (ClangString ())\nunsafe_getCompletionParent (CompletionString ptr) = clang_getCompletionParent ptr 0 >>= peek\n\ngetCompletionParent :: ClangBase m => CompletionString s' -> ClangT s m (ClangString s)\ngetCompletionParent = registerClangString . unsafe_getCompletionParent\n\n-- CXString clang_getCompletionBriefComment(CXCompletionString completion_string);\n{# fun wrapped_clang_getCompletionBriefComment as clang_getCompletionBriefComment { id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCompletionBriefComment :: CompletionString s -> IO (ClangString ())\nunsafe_getCompletionBriefComment (CompletionString ptr) = clang_getCompletionBriefComment ptr >>= peek\n\ngetCompletionBriefComment :: ClangBase m => CompletionString s' -> ClangT s m (ClangString s)\ngetCompletionBriefComment = registerClangString . unsafe_getCompletionBriefComment\n\n-- CXCompletionString clang_getCursorCompletionString(CXCursor cursor);\n{# fun clang_getCursorCompletionString {withVoided* %`Cursor a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCursorCompletionString :: Cursor s' -> IO (ClangString ())\nunsafe_getCursorCompletionString c =\n clang_getCursorCompletionString c >>= peek\n\ngetCursorCompletionString :: ClangBase m => Cursor s' -> ClangT s m (CompletionString s)\ngetCursorCompletionString c =\n unsafeCoerce <$> (liftIO $ unsafe_getCursorCompletionString c)\n\n-- enum CXCodeComplete_Flags {\n-- CXCodeComplete_IncludeMacros = 0x01,\n-- CXCodeComplete_IncludeCodePatterns = 0x02,\n-- CXCodeComplete_IncludeBriefComments = 0x04\n-- };\n\n-- | Flags that can be used to modify the behavior of 'codeCompleteAt'.\n--\n-- * 'IncludeMacros': Whether to include macros within the set of code\n-- completions returned.\n--\n-- * 'IncludeCodePatterns': Whether to include code patterns for language constructs\n-- within the set of code completions, e.g., 'for' loops.\n--\n-- * 'IncludeBriefComments': Whether to include brief documentation within the set of code\n-- completions returned.\n#c\nenum CodeCompleteFlags\n { IncludeMacros = CXCodeComplete_IncludeMacros\n , IncludeCodePatterns = CXCodeComplete_IncludeCodePatterns\n , IncludeBriefComments = CXCodeComplete_IncludeBriefComments\n };\n#endc\n{# enum CodeCompleteFlags {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags CodeCompleteFlags where\n toBit IncludeMacros = 0x01\n toBit IncludeCodePatterns = 0x02\n toBit IncludeBriefComments = 0x04\n\n-- unsigned clang_defaultCodeCompleteOptions(void);\n{# fun clang_defaultCodeCompleteOptions as defaultCodeCompleteOptions {} -> `Int' #}\n\n-- typedef struct {\n-- CXCompletionResult *Results;\n-- unsigned NumResults;\n-- } CXCodeCompleteResults;\n\n-- | The results of code completion.\nnewtype CodeCompleteResults s = CodeCompleteResults { unCodeCompleteResults :: Ptr () }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue CodeCompleteResults\n\n-- void clang_disposeCodeCompleteResults(CXCodeCompleteResults *Results);\n{# fun clang_disposeCodeCompleteResults { id `Ptr ()' } -> `()' #}\ndisposeCodeCompleteResults :: CodeCompleteResults s -> IO ()\ndisposeCodeCompleteResults rs = clang_disposeCodeCompleteResults (unCodeCompleteResults rs)\n\nregisterCodeCompleteResults :: ClangBase m => IO (CodeCompleteResults ())\n -> ClangT s m (CodeCompleteResults s)\nregisterCodeCompleteResults action = do\n (_, ccrs) <- clangAllocate (action >>= return . unsafeCoerce)\n disposeCodeCompleteResults\n return ccrs\n{-# INLINEABLE registerCodeCompleteResults #-}\n\n-- CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU,\n-- const char *complete_filename,\n-- unsigned complete_line,\n-- unsigned complete_column,\n-- struct CXUnsavedFile *unsaved_files,\n-- unsigned num_unsaved_files,\n-- unsigned options);\n{# fun clang_codeCompleteAt { id `Ptr ()', `CString', `Int', `Int', id `Ptr ()', `Int', `Int' } -> `Ptr ()' id #}\nunsafe_codeCompleteAt :: TranslationUnit s -> String -> Int -> Int -> Ptr CUnsavedFile -> Int -> Int -> IO (CodeCompleteResults ())\nunsafe_codeCompleteAt tu s i1 i2 ufs nufs i3 =\n withCString s (\\sPtr -> clang_codeCompleteAt (unTranslationUnit tu) sPtr i1 i2 (castPtr ufs) nufs i3 >>= return . CodeCompleteResults)\n\ncodeCompleteAt :: ClangBase m => TranslationUnit s' -> String -> Int -> Int\n -> DV.Vector UnsavedFile -> Int -> ClangT s m (CodeCompleteResults s)\ncodeCompleteAt tu f l c ufs os =\n registerCodeCompleteResults $\n withUnsavedFiles ufs $ \\ufsPtr ufsLen ->\n unsafe_codeCompleteAt tu f l c ufsPtr ufsLen os\n\n-- This function, along with codeCompleteGetResult, exist to allow iteration over\n-- the completion strings at the Haskell level. They're (obviously) not real\n-- libclang functions.\n{# fun codeCompleteGetNumResults as codeCompleteGetNumResults' { id `Ptr ()' } -> `Int' #}\ncodeCompleteGetNumResults :: CodeCompleteResults s -> IO Int\ncodeCompleteGetNumResults rs = codeCompleteGetNumResults' (unCodeCompleteResults rs)\n\n-- We don't need to register CompletionStrings; they're always owned by another object.\n-- They still need to be scoped, though.\n{# fun codeCompleteGetResult as codeCompleteGetResult' { id `Ptr ()', `CInt', id `Ptr (Ptr ())' } -> `CInt' id #}\nunsafe_codeCompleteGetResult :: CodeCompleteResults s -> Int -> IO (CompletionString (), CursorKind)\nunsafe_codeCompleteGetResult rs idx = do\n sPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr ()))))\n kind <- codeCompleteGetResult' (unCodeCompleteResults rs) (fromIntegral idx) (castPtr sPtr)\n return ((CompletionString sPtr), toEnum (fromIntegral kind))\n\ncodeCompleteGetResult :: ClangBase m => CodeCompleteResults s' -> Int\n -> ClangT s m (CompletionString s, CursorKind)\ncodeCompleteGetResult rs n = do\n (string, kind) <- liftIO $ unsafe_codeCompleteGetResult rs n\n return (unsafeCoerce string, kind)\n\n-- void clang_sortCodeCompletionResults(CXCompletionResult *Results,\n-- unsigned NumResults);\n{# fun clang_sortCodeCompletionResults { id `Ptr ()', `Int' } -> `()' #}\nsortCodeCompletionResults :: CodeCompleteResults s -> IO ()\nsortCodeCompletionResults rs =\n let results = unCodeCompleteResults rs in\n do\n rPtr <- peek (results `plusPtr` offsetCXCodeCompleteResultsResults)\n numRs <- peek (results `plusPtr` offsetCXCodeCompleteResultsNumResults)\n clang_sortCodeCompletionResults rPtr numRs\n\n-- unsigned clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *Results);\n{# fun clang_codeCompleteGetNumDiagnostics { id `Ptr ()' } -> `Int' #}\ncodeCompleteGetNumDiagnostics :: CodeCompleteResults s -> IO Int\ncodeCompleteGetNumDiagnostics rs = clang_codeCompleteGetNumDiagnostics (unCodeCompleteResults rs)\n\n-- CXDiagnostic clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *Results,\n-- unsigned Index);\n{# fun clang_codeCompleteGetDiagnostic { id `Ptr ()' , `Int' } -> `Ptr ()' id #}\nunsafe_codeCompleteGetDiagnostic :: CodeCompleteResults s -> Int -> IO (Diagnostic ())\nunsafe_codeCompleteGetDiagnostic rs idx =\n clang_codeCompleteGetDiagnostic (unCodeCompleteResults rs) idx >>= return . mkDiagnostic\n\ncodeCompleteGetDiagnostic :: ClangBase m => CodeCompleteResults s' -> Int\n -> ClangT s m (Diagnostic s)\ncodeCompleteGetDiagnostic = (registerDiagnostic .) . unsafe_codeCompleteGetDiagnostic\n\n-- enum CXCompletionContext {\n-- CXCompletionContext_Unexposed = 0,\n-- CXCompletionContext_AnyType = 1 << 0,\n-- CXCompletionContext_AnyValue = 1 << 1,\n-- CXCompletionContext_ObjCObjectValue = 1 << 2,\n-- CXCompletionContext_ObjCSelectorValue = 1 << 3,\n-- CXCompletionContext_CXXClassTypeValue = 1 << 4,\n-- CXCompletionContext_DotMemberAccess = 1 << 5,\n-- CXCompletionContext_ArrowMemberAccess = 1 << 6,\n-- CXCompletionContext_ObjCPropertyAccess = 1 << 7,\n-- CXCompletionContext_EnumTag = 1 << 8,\n-- CXCompletionContext_UnionTag = 1 << 9,\n-- CXCompletionContext_StructTag = 1 << 10,\n-- CXCompletionContext_ClassTag = 1 << 11,\n-- CXCompletionContext_Namespace = 1 << 12,\n-- CXCompletionContext_NestedNameSpecifier = 1 << 13,\n-- CXCompletionContext_ObjCInterface = 1 << 14,\n-- CXCompletionContext_ObjCProtocol = 1 << 15,\n-- CXCompletionContext_ObjCCategory = 1 << 16,\n-- CXCompletionContext_ObjCInstanceMessage = 1 << 17,\n-- CXCompletionContext_ObjCClassMessage = 1 << 18,\n-- CXCompletionContext_ObjCSelectorName = 1 << 19,\n-- CXCompletionContext_MacroName = 1 << 20,\n-- CXCompletionContext_NaturalLanguage = 1 << 21,\n-- CXCompletionContext_Unknown = ((1 << 22) - 1) -- Set all\n -- contexts... Not a real value.\n-- };\n\n-- | Contexts under which completion may occur. Multiple contexts may be\n-- present at the same time.\n--\n-- * 'UnexposedCompletionContext': The context for completions is unexposed,\n-- as only Clang results should be included.\n--\n-- * 'AnyTypeCompletionContext': Completions for any possible type should be\n-- included in the results.\n--\n-- * 'AnyValueCompletionContext': Completions for any possible value (variables,\n-- function calls, etc.) should be included in the results.\n--\n-- * 'ObjCObjectValueCompletionContext': Completions for values that resolve to\n-- an Objective-C object should be included in the results.\n--\n-- * 'ObjCSelectorValueCompletionContext': Completions for values that resolve\n-- to an Objective-C selector should be included in the results.\n--\n-- * 'CXXClassTypeValueCompletionContext': Completions for values that resolve\n-- to a C++ class type should be included in the results.\n--\n-- * 'DotMemberAccessCompletionContext': Completions for fields of the member\n-- being accessed using the dot operator should be included in the results.\n--\n-- * 'ArrowMemberAccessCompletionContext': Completions for fields of the member\n-- being accessed using the arrow operator should be included in the results.\n--\n-- * 'ObjCPropertyAccessCompletionContext': Completions for properties of the\n-- Objective-C object being accessed using the dot operator should be included in the results.\n--\n-- * 'EnumTagCompletionContext': Completions for enum tags should be included in the results.\n--\n-- * 'UnionTagCompletionContext': Completions for union tags should be included in the results.\n--\n-- * 'StructTagCompletionContext': Completions for struct tags should be included in the\n-- results.\n--\n-- * 'ClassTagCompletionContext': Completions for C++ class names should be included in the\n-- results.\n--\n-- * 'NamespaceCompletionContext': Completions for C++ namespaces and namespace aliases should\n-- be included in the results.\n--\n-- * 'NestedNameSpecifierCompletionContext': Completions for C++ nested name specifiers should\n-- be included in the results.\n--\n-- * 'ObjCInterfaceCompletionContext': Completions for Objective-C interfaces (classes) should\n-- be included in the results.\n--\n-- * 'ObjCProtocolCompletionContext': Completions for Objective-C protocols should be included\n-- in the results.\n--\n-- * 'ObjCCategoryCompletionContext': Completions for Objective-C categories should be included\n-- in the results.\n--\n-- * 'ObjCInstanceMessageCompletionContext': Completions for Objective-C instance messages\n-- should be included in the results.\n--\n-- * 'ObjCClassMessageCompletionContext': Completions for Objective-C class messages should be\n-- included in the results.\n--\n-- * 'ObjCSelectorNameCompletionContext': Completions for Objective-C selector names should be\n-- included in the results.\n--\n-- * 'MacroNameCompletionContext': Completions for preprocessor macro names should be included\n-- in the results.\n--\n-- * 'NaturalLanguageCompletionContext': Natural language completions should be included in the\n-- results.\n#c\nenum CompletionContext\n { UnexposedCompletionContext = CXCompletionContext_Unexposed\n , AnyTypeCompletionContext = CXCompletionContext_AnyType\n , AnyValueCompletionContext = CXCompletionContext_AnyValue\n , ObjCObjectValueCompletionContext = CXCompletionContext_ObjCObjectValue\n , ObjCSelectorValueCompletionContext = CXCompletionContext_ObjCSelectorValue\n , CXXClassTypeValueCompletionContext = CXCompletionContext_CXXClassTypeValue\n , DotMemberAccessCompletionContext = CXCompletionContext_DotMemberAccess\n , ArrowMemberAccessCompletionContext = CXCompletionContext_ArrowMemberAccess\n , ObjCPropertyAccessCompletionContext = CXCompletionContext_ObjCPropertyAccess\n , EnumTagCompletionContext = CXCompletionContext_EnumTag\n , UnionTagCompletionContext = CXCompletionContext_UnionTag\n , StructTagCompletionContext = CXCompletionContext_StructTag\n , ClassTagCompletionContext = CXCompletionContext_ClassTag\n , NamespaceCompletionContext = CXCompletionContext_Namespace\n , NestedNameSpecifierCompletionContext = CXCompletionContext_NestedNameSpecifier\n , ObjCInterfaceCompletionContext = CXCompletionContext_ObjCInterface\n , ObjCProtocolCompletionContext = CXCompletionContext_ObjCProtocol\n , ObjCCategoryCompletionContext = CXCompletionContext_ObjCCategory\n , ObjCInstanceMessageCompletionContext = CXCompletionContext_ObjCInstanceMessage\n , ObjCClassMessageCompletionContext = CXCompletionContext_ObjCClassMessage\n , ObjCSelectorNameCompletionContext = CXCompletionContext_ObjCSelectorName\n , MacroNameCompletionContext = CXCompletionContext_MacroName\n , NaturalLanguageCompletionContext = CXCompletionContext_NaturalLanguage\n };\n#endc\n{# enum CompletionContext {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags CompletionContext where\n type FlagInt CompletionContext = Int64\n toBit UnexposedCompletionContext = 0x0\n toBit AnyTypeCompletionContext = 0x1\n toBit AnyValueCompletionContext = 0x2\n toBit ObjCObjectValueCompletionContext = 0x4\n toBit ObjCSelectorValueCompletionContext = 0x8\n toBit CXXClassTypeValueCompletionContext = 0x10\n toBit DotMemberAccessCompletionContext = 0x20\n toBit ArrowMemberAccessCompletionContext = 0x40\n toBit ObjCPropertyAccessCompletionContext = 0x80\n toBit EnumTagCompletionContext = 0x100\n toBit UnionTagCompletionContext = 0x200\n toBit StructTagCompletionContext = 0x400\n toBit ClassTagCompletionContext = 0x800\n toBit NamespaceCompletionContext = 0x1000\n toBit NestedNameSpecifierCompletionContext = 0x2000\n toBit ObjCInterfaceCompletionContext = 0x4000\n toBit ObjCProtocolCompletionContext = 0x8000\n toBit ObjCCategoryCompletionContext = 0x10000\n toBit ObjCInstanceMessageCompletionContext = 0x20000\n toBit ObjCClassMessageCompletionContext = 0x40000\n toBit ObjCSelectorNameCompletionContext = 0x80000\n toBit MacroNameCompletionContext = 0x100000\n toBit NaturalLanguageCompletionContext = 0x200000\n\n-- unsigned long long clang_codeCompleteGetContexts(CXCodeCompleteResults *Results);\n{# fun clang_codeCompleteGetContexts { id `Ptr ()' } -> `Int64' #}\ncodeCompleteGetContexts :: CodeCompleteResults s -> IO Int64\ncodeCompleteGetContexts rs = clang_codeCompleteGetContexts (unCodeCompleteResults rs)\n\n-- enum CXCursorKind clang_codeCompleteGetContainerKind(CXCodeCompleteResults *Results,\n-- unsigned *IsIncomplete);\n{# fun clang_codeCompleteGetContainerKind { id `Ptr ()', id `Ptr CUInt' } -> `Int' #}\ncodeCompleteGetContainerKind :: CodeCompleteResults s -> IO (CursorKind, Bool)\ncodeCompleteGetContainerKind rs =\n alloca (\\(iPtr :: (Ptr CUInt)) -> do\n k <- clang_codeCompleteGetContainerKind (unCodeCompleteResults rs) iPtr\n bool <- peek iPtr\n return (toEnum k, toBool ((fromIntegral bool) :: Int)))\n\n-- CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *Results);\n{# fun clang_codeCompleteGetContainerUSR { id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_codeCompleteGetContainerUSR :: CodeCompleteResults s -> IO (ClangString ())\nunsafe_codeCompleteGetContainerUSR rs = clang_codeCompleteGetContainerUSR (unCodeCompleteResults rs) >>= peek\n\ncodeCompleteGetContainerUSR :: ClangBase m => CodeCompleteResults s' -> ClangT s m (ClangString s)\ncodeCompleteGetContainerUSR = registerClangString . unsafe_codeCompleteGetContainerUSR\n\n-- CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *Results);\n{# fun clang_codeCompleteGetObjCSelector { id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_codeCompleteGetObjCSelector :: CodeCompleteResults s -> IO (ClangString ())\nunsafe_codeCompleteGetObjCSelector rs = clang_codeCompleteGetObjCSelector (unCodeCompleteResults rs) >>= peek\n\ncodeCompleteGetObjCSelector :: ClangBase m => CodeCompleteResults s' -> ClangT s m (ClangString s)\ncodeCompleteGetObjCSelector = registerClangString . unsafe_codeCompleteGetObjCSelector\n\n-- CXString clang_getClangVersion();\n{# fun wrapped_clang_getClangVersion as clang_getClangVersion {} -> `Ptr (ClangString ())' castPtr #}\nunsafe_getClangVersion :: IO (ClangString ())\nunsafe_getClangVersion = clang_getClangVersion >>= peek\n\ngetClangVersion :: ClangBase m => ClangT s m (ClangString s)\ngetClangVersion = registerClangString $ unsafe_getClangVersion\n\n-- -- void clang_toggleCrashRecovery(unsigned isEnabled);\n{# fun clang_toggleCrashRecovery as toggleCrashRecovery' { `Int' } -> `()' #}\ntoggleCrashRecovery :: Bool -> IO ()\ntoggleCrashRecovery b = toggleCrashRecovery' (fromBool b)\n\ndata Inclusion s = Inclusion !(File s) !(SourceLocation s) !Bool\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue Inclusion\n\ninstance Storable (Inclusion s) where\n sizeOf _ = sizeOfInclusion\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfInclusion\n {-# INLINE alignment #-}\n\n peek p = do\n let fromCUChar = fromIntegral :: Num b => CUChar -> b\n file <- File <$> peekByteOff p offsetInclusionInclusion\n sl <- peekByteOff p offsetInclusionLocation\n isDirect :: Int <- fromCUChar <$> peekByteOff p offsetInclusionIsDirect\n return $! Inclusion file sl (if isDirect == 0 then False else True)\n {-# INLINE peek #-}\n\n poke p (Inclusion (File file) sl isDirect) = do\n let toCUChar = fromIntegral :: Integral a => a -> CUChar\n pokeByteOff p offsetInclusionInclusion file\n pokeByteOff p offsetInclusionLocation sl\n pokeByteOff p offsetInclusionIsDirect\n (toCUChar $ if isDirect then 1 :: Int else 0)\n {-# INLINE poke #-}\n\ntype InclusionList s = DVS.Vector (Inclusion s)\ninstance ClangValueList Inclusion\ndata UnsafeInclusionList = UnsafeInclusionList !(Ptr ()) !Int\n\n-- void freeInclusions(struct Inclusion* inclusions);\n{# fun freeInclusionList as freeInclusionList' { id `Ptr ()' } -> `()' #}\nfreeInclusions :: InclusionList s -> IO ()\nfreeInclusions is =\n let (isPtr, n) = fromInclusionList is in\n freeInclusionList' isPtr\n\nregisterInclusionList :: ClangBase m => IO UnsafeInclusionList -> ClangT s m (InclusionList s)\nregisterInclusionList action = do\n (_, inclusionList) <- clangAllocate (action >>= mkSafe) freeInclusions\n return inclusionList\n where\n mkSafe (UnsafeInclusionList is n) = do\n fptr <- newForeignPtr_ (castPtr is)\n return $ DVS.unsafeFromForeignPtr fptr 0 n\n{-# INLINEABLE registerInclusionList #-}\n\nfromInclusionList :: InclusionList s -> (Ptr (), Int)\nfromInclusionList is = let (p, _, _) = DVS.unsafeToForeignPtr is in\n (castPtr $ Foreign.ForeignPtr.Unsafe.unsafeForeignPtrToPtr p, DVS.length is)\n\ntoInclusionList :: (Ptr (), Int) -> UnsafeInclusionList\ntoInclusionList (is, n) = UnsafeInclusionList is n\n\n#c\ntypedef Inclusion** PtrPtrInclusion;\n#endc\n\n-- A more efficient alternative to clang_getInclusions.\n-- void getInclusions(CXTranslationUnit tu, struct Inclusion** inclusionsOut, unsigned* countOut)\n{# fun getInclusions as getInclusions' { id `Ptr ()', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getInclusions :: TranslationUnit s -> IO UnsafeInclusionList\nunsafe_getInclusions tu = do\n iPtrPtr <- mallocBytes {#sizeof PtrPtrInclusion #}\n n <- getInclusions' (unTranslationUnit tu) (castPtr iPtrPtr)\n firstInclusion <- peek (castPtr iPtrPtr :: Ptr (Ptr ()))\n free iPtrPtr\n return (toInclusionList (firstInclusion, fromIntegral n))\n\n\ngetInclusions :: ClangBase m => TranslationUnit s' -> ClangT s m (InclusionList s)\ngetInclusions = registerInclusionList . unsafe_getInclusions\n\n-- typedef void* CXRemapping;\nnewtype Remapping s = Remapping { unRemapping :: Ptr () }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue Remapping\n\nmkRemapping :: Ptr () -> Remapping ()\nmkRemapping = Remapping\n\n-- void clang_remap_dispose(CXRemapping);\n{# fun clang_remap_dispose { id `Ptr ()' } -> `()' #}\nremap_dispose :: Remapping s -> IO ()\nremap_dispose d = clang_remap_dispose (unRemapping d)\n\nregisterRemapping :: ClangBase m => IO (Remapping ()) -> ClangT s m (Remapping s)\nregisterRemapping action = do\n (_, idx) <- clangAllocate (action >>= return . unsafeCoerce)\n (\\i -> remap_dispose i)\n return idx\n{-# INLINEABLE registerRemapping #-}\n\n-- %dis remapping i = (ptr i)\n\nmaybeRemapping :: Remapping s' -> Maybe (Remapping s)\nmaybeRemapping (Remapping p) | p == nullPtr = Nothing\nmaybeRemapping f = Just (unsafeCoerce f)\n\nunMaybeRemapping :: Maybe (Remapping s') -> Remapping s\nunMaybeRemapping (Just f) = unsafeCoerce f\nunMaybeRemapping Nothing = Remapping nullPtr\n\n-- CXRemapping clang_getRemappings(const char *path);\n{# fun clang_getRemappings { `CString' } -> `Ptr ()' id #}\nunsafe_getRemappings :: FilePath -> IO (Maybe (Remapping ()))\nunsafe_getRemappings fp =\n withCString fp (\\sPtr -> clang_getRemappings sPtr >>= return . maybeRemapping . mkRemapping )\n\ngetRemappings :: ClangBase m => FilePath -> ClangT s m (Maybe (Remapping s))\ngetRemappings path = do\n mRemappings <- liftIO $ unsafe_getRemappings path\n case mRemappings of\n Just remappings -> Just <$> registerRemapping (return remappings)\n Nothing -> return Nothing\n\n-- CXRemapping clang_getRemappingsFromFileList(const char **filePaths, unsigned numFiles);\n{# fun clang_getRemappingsFromFileList { id `Ptr CString' , `Int' } -> `Ptr ()' id #}\nunsafe_getRemappingsFromFileList :: Ptr CString -> Int -> IO (Maybe (Remapping ()))\nunsafe_getRemappingsFromFileList paths numPaths =\n clang_getRemappingsFromFileList paths numPaths >>= return . maybeRemapping . mkRemapping\n\ngetRemappingsFromFileList :: ClangBase m => [FilePath] -> ClangT s m (Maybe (Remapping s))\ngetRemappingsFromFileList paths = do\n mRemappings <- liftIO $ withStringList paths unsafe_getRemappingsFromFileList\n case mRemappings of\n Just remappings -> Just <$> registerRemapping (return remappings)\n Nothing -> return Nothing\n\n-- unsigned clang_remap_getNumFiles(CXRemapping);\n{# fun clang_remap_getNumFiles { id `Ptr ()' } -> `Int' #}\nremap_getNumFiles :: Remapping s -> IO Int\nremap_getNumFiles remaps =\n clang_remap_getNumFiles (unRemapping remaps)\n\n-- void clang_remap_getFilenames(CXRemapping, unsigned index,\n-- CXString *original, CXString *transformed);\n{# fun clang_remap_getFilenames { id `Ptr ()', `Int', id `Ptr ()', id `Ptr ()' } -> `()' #}\nunsafe_remap_getFilenames :: Remapping s -> Int -> IO (ClangString (), ClangString ())\nunsafe_remap_getFilenames remaps idx = do\n origPtr <- mallocBytes (sizeOf (undefined :: (Ptr (ClangString ()))))\n txPtr <- mallocBytes (sizeOf (undefined :: (Ptr (ClangString ()))))\n clang_remap_getFilenames (unRemapping remaps) idx origPtr txPtr\n orig <- peek (castPtr origPtr)\n tx <- peek (castPtr txPtr)\n free origPtr\n free txPtr\n return (orig, tx)\n\nremap_getFilenames :: ClangBase m => Remapping s' -> Int -> ClangT s m (ClangString s, ClangString s)\nremap_getFilenames r idx = do\n (orig, tr) <- liftIO $ unsafe_remap_getFilenames r idx\n (,) <$> registerClangString (return orig) <*> registerClangString (return tr)\n","old_contents":"{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-matches #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ConstraintKinds #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE TupleSections #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE CPP #-}\n\nmodule Clang.Internal.FFI\n( versionMajor\n, versionMinor\n, encodedVersion\n, Index\n, createIndex\n, GlobalIndexOptions(..)\n, threadBackgroundPriorityForAll\n, cXIndex_setGlobalOptions\n, cXIndex_getGlobalOptions\n, TranslationUnit\n, UnsavedFile\n, unsavedFilename\n, unsavedContents\n, newUnsavedFile\n, updateUnsavedContents\n, AvailabilityKind(..)\n, Version(..)\n, ClangString\n, getString\n, getByteString\n, unsafeGetByteString\n, File(..)\n, getFileName\n, getFileTime\n, UniqueId(..)\n, getFileUniqueID\n, isFileMultipleIncludeGuarded\n, getFile\n, SourceLocation\n, getNullLocation\n, equalLocations\n, getLocation\n, getLocationForOffset\n, location_isInSystemHeader\n, location_isFromMainFile\n, SourceRange\n, getNullRange\n, getRange\n, equalRanges\n, range_isNull\n, getExpansionLocation\n, getPresumedLocation\n, getSpellingLocation\n, getFileLocation\n, getRangeStart\n, getRangeEnd\n, Severity(..)\n, Diagnostic\n, DiagnosticSet\n, getNumDiagnosticsInSet\n, getDiagnosticInSet\n, LoadError(..)\n, loadDiagnostics\n, getChildDiagnostics\n, getNumDiagnostics\n, getDiagnostic\n, getDiagnosticSetFromTU\n, DisplayOptions(..)\n, formatDiagnostic\n, defaultDiagnosticDisplayOptions\n, getDiagnosticSeverity\n, getDiagnosticLocation\n, getDiagnosticSpelling\n, getDiagnosticOption\n, getDiagnosticCategory\n, getDiagnosticCategoryText\n, getDiagnosticNumRanges\n, getDiagnosticRange\n, getDiagnosticNumFixIts\n, getDiagnosticFixIt\n, getTranslationUnitSpelling\n, createTranslationUnitFromSourceFile\n, createTranslationUnit\n, TranslationUnitFlags(..)\n, defaultEditingTranslationUnitOptions\n, parseTranslationUnit\n, SaveTranslationUnitFlags(..)\n, defaultSaveOptions\n, saveTranslationUnit\n, ReparseFlags(..)\n, defaultReparseOptions\n, reparseTranslationUnit\n, CursorKind(..)\n, firstDeclCursor\n, lastDeclCursor\n, firstRefCursor\n, lastRefCursor\n, firstInvalidCursor\n, lastInvalidCursor\n, firstExprCursor\n, lastExprCursor\n, firstStmtCursor\n, lastStmtCursor\n, firstAttrCursor\n, lastAttrCursor\n, firstPreprocessingCursor\n, lastPreprocessingCursor\n, firstExtraDeclCursor\n, lastExtraDeclCursor\n, gccAsmStmtCursor\n, macroInstantiationCursor\n, Comment(..)\n, Cursor\n, getNullCursor\n, getTranslationUnitCursor\n, cursor_isNull\n, hashCursor\n, getCursorKind\n, isDeclaration\n, isReference\n, isExpression\n, isStatement\n, isAttribute\n, isInvalid\n, isTranslationUnit\n, isPreprocessing\n, isUnexposed\n, LinkageKind(..)\n, getCursorLinkage\n, getCursorAvailability\n, PlatformAvailability(..)\n, PlatformAvailabilityInfo(..)\n, getCursorPlatformAvailability\n, LanguageKind(..)\n, getCursorLanguage\n, cursor_getTranslationUnit\n, CursorSet\n, createCXCursorSet\n, cXCursorSet_contains\n, cXCursorSet_insert\n, getCursorSemanticParent\n, getCursorLexicalParent\n, getOverriddenCursors\n, getIncludedFile\n, getCursor\n, getCursorLocation\n, getCursorSpellingLocation\n, getCursorExtent\n, TypeKind(..)\n, type_FirstBuiltin\n, type_LastBuiltin\n, CallingConv(..)\n, Type\n, getTypeKind\n, getCursorType\n, getTypeSpelling\n, getTypedefDeclUnderlyingType\n, getEnumDeclIntegerType\n, getEnumConstantDeclValue\n, getEnumConstantDeclUnsignedValue\n, getFieldDeclBitWidth\n, cursor_getNumArguments\n, cursor_getArgument\n, equalTypes\n, getCanonicalType\n, isConstQualifiedType\n, isVolatileQualifiedType\n, isRestrictQualifiedType\n, getPointeeType\n, getTypeDeclaration\n, getDeclObjCTypeEncoding\n, getTypeKindSpelling\n, getFunctionTypeCallingConv\n, getResultType\n, getNumArgTypes\n, getArgType\n, isFunctionTypeVariadic\n, getCursorResultType\n, isPODType\n, getElementType\n, getNumElements\n, getArrayElementType\n, getArraySize\n, TypeLayoutError(..)\n, type_getAlignOf\n, type_getClassType\n, type_getSizeOf\n, type_getOffsetOf\n, RefQualifierKind(..)\n, type_getCXXRefQualifier\n, isBitField\n, isVirtualBase\n, CXXAccessSpecifier(..)\n, getCXXAccessSpecifier\n, getNumOverloadedDecls\n, getOverloadedDecl\n, getIBOutletCollectionType\n, CursorList\n, getChildren\n, getDescendants\n, getDeclarations\n, getReferences\n, getDeclarationsAndReferences\n, ParentedCursor(..)\n, ParentedCursorList\n, getParentedDescendants\n, getParentedDeclarations\n, getParentedReferences\n, getParentedDeclarationsAndReferences\n, getCursorUSR\n, constructUSR_ObjCClass\n, constructUSR_ObjCCategory\n, constructUSR_ObjCProtocol\n, constructUSR_ObjCIvar\n, constructUSR_ObjCMethod\n, constructUSR_ObjCProperty\n, getCursorSpelling\n, cursor_getSpellingNameRange\n, getCursorDisplayName\n, getCursorReferenced\n, getCursorDefinition\n, isCursorDefinition\n, cursor_isDynamicCall\n, getCanonicalCursor\n, cursor_getObjCSelectorIndex\n, cursor_getReceiverType\n, ObjCPropertyAttrKind(..)\n, cursor_getObjCPropertyAttributes\n, ObjCDeclQualifierKind(..)\n, cursor_getObjCDeclQualifiers\n, cursor_isObjCOptional\n, cursor_isVariadic\n, cursor_getCommentRange\n, cursor_getRawCommentText\n, cursor_getBriefCommentText\n, cursor_getParsedComment\n, Module(..)\n, cursor_getModule\n, module_getASTFile\n, module_getParent\n, module_getName\n, module_getFullName\n, module_getNumTopLevelHeaders\n, module_getTopLevelHeader\n, cXXMethod_isPureVirtual\n, cXXMethod_isStatic\n, cXXMethod_isVirtual\n, getTemplateCursorKind\n, getSpecializedCursorTemplate\n, getCursorReferenceNameRange\n, NameRefFlags(..)\n, CommentKind(..)\n, InlineCommandRenderStyle(..)\n, ParamPassDirectionKind(..)\n, comment_getKind\n, comment_getNumChildren\n, comment_getChild\n, comment_isWhitespace\n, inlineContentComment_hasTrailingNewline\n, textComment_getText\n, inlineCommandComment_getCommandName\n, inlineCommandComment_getRenderKind\n, inlineCommandComment_getNumArgs\n, inlineCommandComment_getArgText\n, hTMLTagComment_getTagName\n, hTMLStartTagComment_isSelfClosing\n, hTMLStartTag_getNumAttrs\n, hTMLStartTag_getAttrName\n, hTMLStartTag_getAttrValue\n, blockCommandComment_getCommandName\n, blockCommandComment_getNumArgs\n, blockCommandComment_getArgText\n, blockCommandComment_getParagraph\n, paramCommandComment_getParamName\n, paramCommandComment_isParamIndexValid\n, paramCommandComment_getParamIndex\n, paramCommandComment_isDirectionExplicit\n, paramCommandComment_getDirection\n, tParamCommandComment_getParamName\n, tParamCommandComment_isParamPositionValid\n, tParamCommandComment_getDepth\n, tParamCommandComment_getIndex\n, verbatimBlockLineComment_getText\n, verbatimLineComment_getText\n, hTMLTagComment_getAsString\n, fullComment_getAsHTML\n, fullComment_getAsXML\n, TokenKind(..)\n, Token\n, TokenList\n, getTokenKind\n, getTokenSpelling\n, getTokenLocation\n, getTokenExtent\n, tokenize\n, annotateTokens\n, getCursorKindSpelling\n, enableStackTraces\n, CompletionString\n, CompletionResult\n, ChunkKind(..)\n, getCompletionChunkKind\n, getCompletionChunkText\n, getCompletionChunkCompletionString\n, getNumCompletionChunks\n, getCompletionPriority\n, getCompletionAvailability\n, getCompletionNumAnnotations\n, getCompletionAnnotation\n, getCompletionParent\n, getCompletionBriefComment\n, getCursorCompletionString\n, CodeCompleteFlags(..)\n, defaultCodeCompleteOptions\n, CodeCompleteResults\n, codeCompleteAt\n, codeCompleteGetNumResults\n, codeCompleteGetResult\n, sortCodeCompletionResults\n, codeCompleteGetNumDiagnostics\n, codeCompleteGetDiagnostic\n, CompletionContext(..)\n, codeCompleteGetContexts\n, codeCompleteGetContainerKind\n, codeCompleteGetContainerUSR\n, codeCompleteGetObjCSelector\n, getClangVersion\n, toggleCrashRecovery\n, Inclusion(..)\n, InclusionList\n, getInclusions\n, Remapping\n, getRemappings\n, getRemappingsFromFileList\n, remap_getNumFiles\n, remap_getFilenames\n) where\n\nimport Control.Applicative\nimport Control.Monad (forM_)\nimport Control.Monad.Trans\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Unsafe as BU\nimport Data.Hashable\nimport Data.Typeable (Typeable)\nimport qualified Data.Vector as DV\nimport qualified Data.Vector.Storable as DVS\nimport qualified Data.Vector.Storable.Mutable as DVSM\nimport Data.Word\nimport Foreign.C\nimport Foreign\nimport Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)\nimport Unsafe.Coerce (unsafeCoerce) -- With GHC 7.8 we can use the safer 'coerce'.\nimport System.IO.Unsafe(unsafePerformIO)\n\nimport Clang.Internal.BitFlags\nimport Clang.Internal.FFIConstants\nimport Clang.Internal.Monad\n\n#include \n#include \n#include \n#include \n#include \n#include \"utils.h\"\n#include \"visitors.h\"\n#include \"wrappers.h\"\n\n{-\nLibClang uses two strategies to create safe, deterministic\nbindings.\n\nFirst, all types that either represent resources managed on the C side\n(for example, TranslationUnit and ClangString) or contain pointers into\nthose resources (for example, Cursor) are tagged with an ST-like\nuniversally quantified phantom type parameter. This prevents them from\nbeing used outside of the scope in which they were allocated. This is\nparticularly important for libclang, which uses an arena allocator to\nstore much of its data; preventing resources from leaking outside\ntheir proper scope is critical to making this safe.\n\nSecond, all operations that allocate a resource that later\nneeds to be freed are wrapped in a type-specific 'register'\nfunction. An example is registerClangString. This function registers a\ncleanup action with the underlying ClangT monad, which is essentially\njust ResourceT in disguise. This not only provides safety, but it also\nenforces prompt finalization of resources which can significantly\nincrease performance by keeping the working set of user programs down.\n\nThere are a few different patterns for the FFI code, depending on what\nkind of value the libclang function we want to wrap returns.\n\nIf it returns a pure value (say an Int), then we don't need to do\nanything special. The greencard-generated function will have a return\ntype of IO Int, and the user-facing wrapper function will use liftIO\nto call it.\n\nIf it returns a value that doesn't represent a newly allocated\nresource, but does need the phantom type parameter (because it\ncontains a pointer into some other resource, generally), then we\ngenerally pass a Proxy value with a type parameter that we'll use to\ntag the return type. This has no runtime cost. The user-facing wrapper\nfunction still needs to call liftIO.\n\nFor values that DO represent a newly allocated resource, we need to\ncall the appropriate 'register' function. This function will return a\nvalue in the ClangT monad, so user-facing wrapper functions don't need\nto use liftIO or Proxy in this case. It's the convention to use '()' for the\nphantom type parameter returned from the greencard-generated function,\nand allow the 'register' function to coerce the value to the correct\ntype. This way we can distinguish values that need to be registered\nfrom other values: if a value's phantom type parameter is '()', it\nneeds to be registered, and it won't typecheck as the return value of\na user-facing wrapper function.\n\nIt's important to keep in mind that it should be legal to use values\nfrom enclosing scopes in an inner scope created by clangScope. In\npractice, this means that the phantom type parameters used by each\nargument to a function should be distinct, and they should all be\ndistinct from the phantom type parameter used in the return value.\nOf course, this doesn't apply to the Proxy parameter, which must\nalways have the same phantom type parameter as the return value.\n-}\n\n-- Marshalling utility functions.\nfromCInt :: Num b => CInt -> b\nfromCInt = fromIntegral\n\ntoCInt :: Integral a => a -> CInt\ntoCInt = fromIntegral\n\n-- Version information.\nversionMajor :: Int\nversionMajor = {# const CINDEX_VERSION_MAJOR #}\nversionMinor :: Int\nversionMinor = {# const CINDEX_VERSION_MINOR #}\nencodedVersion :: Int\nencodedVersion = {# const CINDEX_VERSION #}\n\n-- typedef void *CXIndex;\nnewtype Index s = Index { unIndex :: Ptr () }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue Index\n\nmkIndex :: Ptr () -> Index ()\nmkIndex = Index\n\n-- CXIndex clang_createIndex(int excludeDeclarationsFromPCH, int displayDiagnostics);\n{# fun clang_createIndex { `CInt', `CInt' } -> `Ptr ()' #}\nunsafe_createIndex :: Bool -> Bool -> IO (Index ())\nunsafe_createIndex a b = clang_createIndex (fromBool a) (fromBool b) >>= return . mkIndex\n\ncreateIndex :: ClangBase m => Bool -> Bool -> ClangT s m (Index s)\ncreateIndex = (registerIndex .) . unsafe_createIndex\n\n\n-- void clang_disposeIndex(CXIndex index);\n{# fun clang_disposeIndex { `Ptr ()' } -> `()' #}\ndisposeIndex :: Index s -> IO ()\ndisposeIndex index = clang_disposeIndex (unIndex index)\n\nregisterIndex :: ClangBase m => IO (Index ()) -> ClangT s m (Index s)\nregisterIndex action = do\n (_, idx) <- clangAllocate (action >>= return . unsafeCoerce)\n (\\i -> disposeIndex i)\n return idx\n{-# INLINEABLE registerIndex #-}\n\n-- typedef enum {\n-- CXGlobalOpt_None = 0x0,\n-- CXGlobalOpt_ThreadBackgroundPriorityForIndexing = 0x1,\n-- CXGlobalOpt_ThreadBackgroundPriorityForEditing = 0x2,\n-- CXGlobalOpt_ThreadBackgroundPriorityForAll =\n-- CXGlobalOpt_ThreadBackgroundPriorityForIndexing |\n-- CXGlobalOpt_ThreadBackgroundPriorityForEditing\n--\n-- } CXGlobalOptFlags;\n\n-- | Options that apply globally to every translation unit within an index.\n#c\nenum GlobalIndexOptions\n { DefaultGlobalIndexOptions = CXGlobalOpt_None\n , ThreadBackgroundPriorityForIndexing = CXGlobalOpt_ThreadBackgroundPriorityForIndexing\n , ThreadBackgroundPriorityForEditing = CXGlobalOpt_ThreadBackgroundPriorityForEditing\n };\n#endc\n{# enum GlobalIndexOptions{} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags GlobalIndexOptions where\n toBit DefaultGlobalIndexOptions = 0x0\n toBit ThreadBackgroundPriorityForIndexing = 0x1\n toBit ThreadBackgroundPriorityForEditing = 0x2\n\n-- | A set of global index options that requests background priority for all threads.\nthreadBackgroundPriorityForAll :: [GlobalIndexOptions]\nthreadBackgroundPriorityForAll = [ThreadBackgroundPriorityForEditing,\n ThreadBackgroundPriorityForIndexing]\n\n-- void clang_CXIndex_setGlobalOptions(CXIndex, unsigned options);\n{# fun clang_CXIndex_setGlobalOptions { `Ptr ()', `Int' } -> `()' #}\ncXIndex_setGlobalOptions :: Index s -> Int -> IO ()\ncXIndex_setGlobalOptions index options = clang_CXIndex_setGlobalOptions (unIndex index) options\n\n-- unsigned clang_CXIndex_getGlobalOptions(CXIndex);\n{# fun clang_CXIndex_getGlobalOptions { `Ptr ()' } -> `Int' #}\ncXIndex_getGlobalOptions :: Index s -> IO Int\ncXIndex_getGlobalOptions index = clang_CXIndex_getGlobalOptions (unIndex index)\n\n-- typedef struct CXTranslationUnitImpl *CXTranslationUnit;\nnewtype TranslationUnit s = TranslationUnit { unTranslationUnit :: (Ptr ()) }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue TranslationUnit\n\nmkTranslationUnit :: Ptr () -> TranslationUnit ()\nmkTranslationUnit = TranslationUnit\n\n-- void clang_disposeTranslationUnit(CXTranslationUnit);\n{# fun clang_disposeTranslationUnit { `Ptr ()' } -> `()' #}\ndisposeTranslationUnit :: TranslationUnit s -> IO ()\ndisposeTranslationUnit t = clang_disposeTranslationUnit (unTranslationUnit t)\n\nregisterTranslationUnit :: ClangBase m => IO (TranslationUnit ())\n -> ClangT s m (TranslationUnit s)\nregisterTranslationUnit action = do\n (_, tu) <- clangAllocate (action >>= return . unsafeCoerce)\n (\\t -> disposeTranslationUnit t)\n return tu\n{-# INLINEABLE registerTranslationUnit #-}\n\n-- struct CXUnsavedFile {\n-- const char* Filename;\n-- const char* Contents;\n-- unsigned long Length;\n-- };\n\n-- | A representation of an unsaved file and its contents.\ndata UnsavedFile = UnsavedFile\n { _unsavedFilename :: !B.ByteString\n , _unsavedContents :: !B.ByteString\n } deriving (Eq, Show, Typeable)\n\n-- We maintain the invariant that _unsavedFilename is always\n-- null-terminated. That's why we don't directly expose the record fields.\nunsavedFilename :: UnsavedFile -> B.ByteString\nunsavedFilename = _unsavedFilename\n\nunsavedContents :: UnsavedFile -> B.ByteString\nunsavedContents = _unsavedContents\n\nnewUnsavedFile :: B.ByteString -> B.ByteString -> UnsavedFile\nnewUnsavedFile f c = UnsavedFile (nullTerminate f) c\n\nupdateUnsavedContents :: UnsavedFile -> B.ByteString -> UnsavedFile\nupdateUnsavedContents uf c = UnsavedFile (unsavedFilename uf) c\n\n-- TODO: Use BU.unsafeLast when we can use newer B.ByteString.\nnullTerminate :: B.ByteString -> B.ByteString\nnullTerminate bs\n | B.null bs = B.singleton 0\n | B.last bs == 0 = bs\n | otherwise = B.snoc bs 0\n\n-- Functions which take a Vector UnsavedFile argument are implemented\n-- internally in terms of this function, which temporarily allocates a\n-- Vector CUnsavedFile holding the same data. (But does not copy the\n-- string data itself.)\nwithUnsavedFiles :: DV.Vector UnsavedFile -> (Ptr CUnsavedFile -> Int -> IO a) -> IO a\nwithUnsavedFiles ufs f =\n withCUnsavedFiles ufs $ \\cufs ->\n DVS.unsafeWith cufs $ \\ptr ->\n f ptr (DVS.length cufs)\n\ndata CUnsavedFile = CUnsavedFile\n { cUnsavedFilename :: CString\n , cUnsavedContents :: CString\n , cUnsavedContentsLen :: CULong\n }\n\ninstance Storable CUnsavedFile where\n sizeOf _ = sizeOfCXUnsavedFile\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfCXUnsavedFile\n {-# INLINE alignment #-}\n\n peek p = do\n filename <- peekByteOff p offsetCXUnsavedFileFilename\n contents <- peekByteOff p offsetCXUnsavedFileContents\n contentsLen <- peekByteOff p offsetCXUnsavedFileContentsLen\n return $! CUnsavedFile filename contents contentsLen\n {-# INLINE peek #-}\n\n poke p (CUnsavedFile filename contents contentsLen) = do\n pokeByteOff p offsetCXUnsavedFileFilename filename\n pokeByteOff p offsetCXUnsavedFileContents contents\n pokeByteOff p offsetCXUnsavedFileContentsLen contentsLen\n {-# INLINE poke #-}\n\n\nwithCUnsavedFiles :: DV.Vector UnsavedFile -> (DVS.Vector CUnsavedFile -> IO a) -> IO a\nwithCUnsavedFiles ufs f = do\n let len = DV.length ufs\n v <- DVSM.new len\n go v 0 len\n where\n go v i len\n | i == len = f =<< DVS.unsafeFreeze v\n | otherwise = do let uf = DV.unsafeIndex ufs i\n ufFilename = unsavedFilename uf\n ufContents = unsavedContents uf\n BU.unsafeUseAsCString ufFilename $ \\cufFilename ->\n BU.unsafeUseAsCString ufContents $ \\cufContents -> do\n let contentsLen = fromIntegral $ B.length ufContents\n cuf = CUnsavedFile cufFilename cufContents contentsLen\n DVSM.write v i cuf\n go v (i + 1) len\n\n#c\nenum AvailabilityKind {\n Availability_Available = CXAvailability_Available,\n Availability_Deprecated = CXAvailability_Deprecated,\n Availability_NotAvailable = CXAvailability_NotAvailable,\n Availability_NotAccessible = CXAvailability_NotAccessible\n};\n#endc\n{# enum AvailabilityKind{} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ndata Version = Version\n { majorVersion :: !Int\n , minorVersion :: !Int\n , subminorVersion :: !Int\n } deriving (Eq, Ord, Show, Typeable)\n\ninstance Storable Version where\n sizeOf _ = sizeOfCXVersion\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfCXVersion\n {-# INLINE alignment #-}\n\n peek p = do\n major <- fromCInt <$> peekByteOff p offsetCXVersionMajor\n minor <- fromCInt <$> peekByteOff p offsetCXVersionMinor\n subminor <- fromCInt <$> peekByteOff p offsetCXVersionSubminor\n return $! Version major minor subminor\n {-# INLINE peek #-}\n\n poke p (Version major minor subminor) = do\n pokeByteOff p offsetCXVersionMajor major\n pokeByteOff p offsetCXVersionMinor minor\n pokeByteOff p offsetCXVersionSubminor subminor\n {-# INLINE poke #-}\n\n-- typedef struct {\n-- const void *data;\n-- unsigned private_flags;\n-- } CXString;\ndata ClangString s = ClangString !(Ptr ()) !Word32\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue ClangString\n\ninstance Storable (ClangString s) where\n sizeOf _ = {# sizeof CXString #} -- sizeOfCXString\n {-# INLINE sizeOf #-}\n\n alignment _ = {# alignof CXString #} -- alignOfCXString\n {-# INLINE alignment #-}\n\n peek p = do\n strData <- {#get CXString->data #} p\n strFlags <- {#get CXString->private_flags #} p\n return $! ClangString strData (fromIntegral strFlags)\n {-# INLINE peek #-}\n\n poke p (ClangString d f) = do\n {#set CXString->data #} p d\n {#set CXString->private_flags #} p (fromIntegral f)\n {-# INLINE poke #-}\n\ninstance Hashable (ClangString s) where\n hashWithSalt salt (ClangString p f) = (`hashWithSalt` f)\n . (`hashWithSalt` pInt)\n $ salt\n where\n pInt = (fromIntegral $ ptrToWordPtr p) :: Int\n\nregisterClangString :: ClangBase m => IO (ClangString ()) -> ClangT s m (ClangString s)\nregisterClangString action = do\n (_, str) <- clangAllocate (action >>= return . unsafeCoerce)\n (\\(ClangString d f) -> freeClangString d f)\n return str\n{-# INLINEABLE registerClangString #-}\n\n{#fun freeClangString { id `Ptr ()', `Word32' } -> `()' #}\n\nunmarshall_clangString :: Ptr () -> Word32 -> IO (ClangString ())\nunmarshall_clangString d f = return $ ClangString d f\n\ngetString :: ClangBase m => ClangString s' -> ClangT s m String\ngetString (ClangString d f) = liftIO $ getCStringPtr d f >>= peekCString\n\ngetByteString :: ClangBase m => ClangString s' -> ClangT s m B.ByteString\ngetByteString (ClangString d f) = liftIO $ getCStringPtr d f >>= B.packCString\n\nunsafeGetByteString :: ClangBase m => ClangString s' -> ClangT s m B.ByteString\nunsafeGetByteString (ClangString d f) = liftIO $ getCStringPtr d f >>= BU.unsafePackCString\n\n-- const char *clang_getCString(ClangString string);\n{# fun clang_getCString {withVoided* %`ClangString a' } -> `CString' id #}\ngetCStringPtr :: Ptr () -> Word32 -> IO CString\ngetCStringPtr d f = clang_getCString (ClangString d f)\n\n-- typedef void *CXFile;\nnewtype File s = File { unFile :: Ptr () }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue File\n\ninstance Hashable (File s) where\n hashWithSalt salt (File p) = let !pInt = (fromIntegral $ ptrToWordPtr p) :: Int\n in hashWithSalt salt pInt\n\nmaybeFile :: File s' -> Maybe (File s)\nmaybeFile (File p) | p == nullPtr = Nothing\nmaybeFile f = Just (unsafeCoerce f)\n\nunMaybeFile :: Maybe (File s') -> File s\nunMaybeFile (Just f) = unsafeCoerce f\nunMaybeFile Nothing = File nullPtr\n\n\n-- CXString clang_getFileName(CXFile SFile);\n{# fun wrapped_clang_getFileName as clang_getFileName { `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getFileName :: File s -> IO (ClangString ())\nunsafe_getFileName x = clang_getFileName (unFile x) >>= peek\n\ngetFileName :: ClangBase m => File s' -> ClangT s m (ClangString s)\ngetFileName = registerClangString . unsafe_getFileName\n\n-- time_t clang_getFileTime(CXFile SFile);\nforeign import ccall unsafe \"clang-c\/Index.h clang_getFileTime\" clang_getFileTime :: Ptr () -> IO CTime\n\ngetFileTime :: File s -> IO CTime\ngetFileTime (File ptr) = clang_getFileTime ptr\n\n-- | A unique identifier that can be used to distinguish 'File's.\ndata UniqueId = UniqueId !Word64 !Word64 !Word64\n deriving (Eq, Ord, Show, Typeable)\n\ninstance Hashable UniqueId where\n hashWithSalt salt (UniqueId a b c) = (`hashWithSalt` a)\n . (`hashWithSalt` b)\n . (`hashWithSalt` c)\n $ salt\n {-# INLINE hashWithSalt #-}\n\nmaybeFileUniqueID :: (Int, Word64, Word64, Word64) -> Maybe UniqueId\nmaybeFileUniqueID (v, d1, d2, d3) | v \/= 0 = Nothing\n | otherwise = Just $ UniqueId d1 d2 d3\n\n-- int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID);\n{# fun clang_getFileUniqueID { `Ptr ()', `Ptr ()' } -> `CInt' id #}\ngetFileUniqueID :: File s -> IO (Maybe UniqueId)\ngetFileUniqueID f =\n allocaArray 3 (ptrToFileUniqueId f)\n where\n ptrToFileUniqueId :: File s -> Ptr Word64 -> IO (Maybe UniqueId)\n ptrToFileUniqueId f' ptr = do\n res' <- clang_getFileUniqueID (unFile f') (castPtr ptr)\n ds' <- peekArray 3 ptr\n return (maybeFileUniqueID (fromIntegral res', ds' !! 0, ds' !! 1, ds' !! 2))\n\n-- -- unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit tu, CXFile file);\n{# fun clang_isFileMultipleIncludeGuarded { `Ptr ()', `Ptr ()' } -> `CInt' #}\nisFileMultipleIncludeGuarded :: TranslationUnit s -> File s' -> IO Bool\nisFileMultipleIncludeGuarded t f = clang_isFileMultipleIncludeGuarded (unTranslationUnit t) (unFile f) >>= return . (toBool :: Int -> Bool) . fromIntegral\n\n-- CXFile clang_getFile(CXTranslationUnit tu, const char *file_name);\n{# fun clang_getFile { `Ptr ()', `CString' } -> `Ptr ()' #}\ngetFile:: Proxy s -> TranslationUnit s' -> String -> IO (File s)\ngetFile _ t s = withCString s (\\cs -> clang_getFile (unTranslationUnit t) cs >>= return . File)\n\n-- typedef struct {\n-- void *ptr_data[2];\n-- unsigned int_data;\n-- } CXSourceLocation;\n\ndata SourceLocation s = SourceLocation !(Ptr ()) !(Ptr ()) !Int\n deriving (Ord, Typeable)\n\ninstance ClangValue SourceLocation\n\ninstance Eq (SourceLocation s) where\n a == b = unsafePerformIO $ equalLocations a b\n\ninstance Storable (SourceLocation s) where\n sizeOf _ = sizeOfCXSourceLocation\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfCXSourceLocation\n {-# INLINE alignment #-}\n\n peek p = do\n ptrArray <- {#get CXSourceLocation->ptr_data #} p >>= peekArray 2\n intData <- {#get CXSourceLocation->int_data #} p\n return $! SourceLocation (ptrArray !! 0) (ptrArray !! 1) (fromIntegral intData)\n {-# INLINE peek #-}\n\n poke p (SourceLocation p0 p1 i )= do\n ptrsArray <- mallocArray 2\n pokeArray ptrsArray [p0,p1]\n {#set CXSourceLocation->ptr_data #} p (castPtr ptrsArray)\n {#set CXSourceLocation->int_data #} p (fromIntegral i)\n {-# INLINE poke #-}\n\n-- typedef struct {\n-- void *ptr_data[2];\n-- unsigned begin_int_data;\n-- unsigned end_int_data;\n-- } CXSourceRange;\ndata SourceRange s = SourceRange !(Ptr ()) !(Ptr ()) !Int !Int\n deriving (Ord, Typeable)\n\ninstance ClangValue SourceRange\n\ninstance Eq (SourceRange s) where\n a == b = unsafePerformIO $ equalRanges a b\n\ninstance Storable (SourceRange s) where\n sizeOf _ = sizeOfCXSourceRange\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfCXSourceRange\n {-# INLINE alignment #-}\n\n peek p = do\n ptrArray <- {#get CXSourceRange->ptr_data #} p >>= peekArray 2\n beginIntData <- {#get CXSourceRange->begin_int_data #} p\n endIntData <- {#get CXSourceRange->end_int_data #} p\n return $! SourceRange (ptrArray !! 0) (ptrArray !! 1) (fromIntegral beginIntData) (fromIntegral endIntData)\n {-# INLINE peek #-}\n\n poke p (SourceRange p0 p1 begin end)= do\n ptrsArray <- mallocArray 2\n pokeArray ptrsArray [p0,p1]\n {#set CXSourceRange->ptr_data #} p (castPtr ptrsArray)\n {#set CXSourceRange->begin_int_data #} p (fromIntegral begin)\n {#set CXSourceRange->end_int_data #} p (fromIntegral end)\n {-# INLINE poke #-}\n\n-- CXSourceLocation wrapped_clang_getNullLocation();\n{# fun wrapped_clang_getNullLocation as clang_getNullLocation { } -> `Ptr (SourceLocation s)' castPtr #}\ngetNullLocation :: Proxy s -> IO (SourceLocation s)\ngetNullLocation _ = clang_getNullLocation >>= peek\n\nwithVoided :: Storable a => a -> (Ptr () -> IO c) -> IO c\nwithVoided a f= with a (\\aPtr -> f (castPtr aPtr))\n\n-- unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2);\n{# fun clang_equalLocations {withVoided* %`SourceLocation a' , withVoided* %`SourceLocation b' } -> `Bool' toBool #}\nequalLocations :: SourceLocation s -> SourceLocation s' -> IO Bool\nequalLocations s1 s2 = clang_equalLocations s1 s2\n\n-- CXSourceLocation clang_getLocation(CXTranslationUnit tu,\n-- CXFile file,\n-- unsigned line,\n-- unsigned column);\n{# fun wrapped_clang_getLocation as clang_getLocation { `Ptr ()' , `Ptr ()', `Int', `Int' } -> `Ptr (SourceLocation s)' castPtr #}\ngetLocation :: Proxy s -> TranslationUnit s' -> File s'' -> Int -> Int -> IO (SourceLocation s)\ngetLocation _ t f i j = clang_getLocation (unTranslationUnit t) (unFile f) i j >>= peek\n\n-- CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,\n-- CXFile file,\n-- unsigned offset);\n{# fun wrapped_clang_getLocationForOffset as clang_getLocationForOffset { `Ptr ()', `Ptr ()', `Int' } -> `Ptr (SourceLocation s)' castPtr #}\ngetLocationForOffset :: Proxy s -> TranslationUnit s' -> File s'' -> Int -> IO (SourceLocation s)\ngetLocationForOffset _ t f i = clang_getLocationForOffset (unTranslationUnit t) (unFile f) i >>= peek\n\n-- int clang_Location_isInSystemHeader(CXSourceLocation location);\n{# fun clang_Location_isInSystemHeader { withVoided* %`SourceLocation a' } -> `Bool' toBool #}\nlocation_isInSystemHeader :: SourceLocation s -> IO Bool\nlocation_isInSystemHeader s = clang_Location_isInSystemHeader s\n\n-- int clang_Location_isFromMainFile(CXSourceLocation location);\n{# fun clang_Location_isFromMainFile { withVoided* %`SourceLocation a' } -> `Bool' toBool #}\nlocation_isFromMainFile :: SourceLocation s -> IO Bool\nlocation_isFromMainFile s = clang_Location_isFromMainFile s\n\n-- CXSourceRange clang_getNullRange();\n{# fun wrapped_clang_getNullRange as clang_getNullRange { } -> `Ptr (SourceRange s)' castPtr #}\ngetNullRange :: Proxy s -> IO (SourceRange s)\ngetNullRange _ = clang_getNullRange >>= peek\n\n-- CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end);\n{# fun wrapped_clang_getRange as clang_getRange { withVoided* %`SourceLocation a', withVoided* %`SourceLocation b' } -> `Ptr (SourceRange s)' castPtr #}\ngetRange :: Proxy s -> SourceLocation s' -> SourceLocation s'' -> IO (SourceRange s)\ngetRange _ sl1 sl2 = clang_getRange sl1 sl2 >>= peek\n\n-- unsigned clang_equalRanges(CXSourceRange range1, CXSourceRange range2);\n{# fun clang_equalRanges {withVoided* %`SourceRange a', withVoided* %`SourceRange b' } -> `Bool' toBool #}\nequalRanges :: SourceRange s' -> SourceRange s'' -> IO Bool\nequalRanges sr1 sr2 = clang_equalRanges sr1 sr2\n\n-- int clang_Range_isNull(CXSourceRange range);\n{# fun clang_Range_isNull {withVoided* %`SourceRange a ' } -> `Bool' toBool #}\nrange_isNull :: SourceRange s -> IO Bool\nrange_isNull s = clang_Range_isNull s\n\n#c\ntypedef CXFile** PtrPtrCXFile;\n#endc\n\n-- void clang_getExpansionLocation(CXSourceLocation location,\n-- CXFile *file,\n-- unsigned *line,\n-- unsigned *column,\n-- unsigned *offset);\n{# fun clang_getExpansionLocation { withVoided* %`SourceLocation a', id `Ptr (Ptr ())', id `Ptr CUInt', id `Ptr CUInt', id `Ptr CUInt' } -> `()' #}\ngetExpansionLocation :: Proxy s -> SourceLocation s' -> IO (Maybe (File s), Int, Int, Int)\ngetExpansionLocation _ s =\n allocaBytes {#sizeof PtrPtrCXFile #} (\\ptrToFilePtr ->\n alloca (\\(linePtr :: (Ptr CUInt)) ->\n alloca (\\(columnPtr :: (Ptr CUInt)) ->\n alloca (\\(offsetPtr :: (Ptr CUInt)) -> do\n clang_getExpansionLocation s (castPtr ptrToFilePtr) (castPtr linePtr) (castPtr columnPtr) (castPtr offsetPtr)\n filePtr <- {#get *CXFile #} ptrToFilePtr\n let _maybeFile = maybeFile (File filePtr)\n line <- peek linePtr\n column <- peek columnPtr\n offset <- peek offsetPtr\n return (_maybeFile, fromIntegral line, fromIntegral column, fromIntegral offset)))))\n\n-- void clang_getPresumedLocation(CXSourceLocation location,\n-- CXString *filename,\n-- unsigned *line,\n-- unsigned *column);\n\n{# fun clang_getPresumedLocation { withVoided* %`SourceLocation a', id `Ptr ()', alloca- `CUInt' peek*, alloca- `CUInt' peek* } -> `()' #}\nunsafe_getPresumedLocation :: SourceLocation s' -> IO (ClangString (), Int, Int)\nunsafe_getPresumedLocation s =\n alloca (\\(stringPtr :: (Ptr (ClangString ()))) -> do\n (line, column) <- clang_getPresumedLocation s (castPtr stringPtr)\n clangString <- peek stringPtr\n return (clangString, fromIntegral line, fromIntegral column))\n\ngetPresumedLocation :: ClangBase m => SourceLocation s' -> ClangT s m (ClangString s, Int, Int)\ngetPresumedLocation l = do\n (f, ln, c) <- liftIO $ unsafe_getPresumedLocation l\n (,,) <$> registerClangString (return f) <*> return ln <*> return c\n\n-- void clang_getSpellingLocation(CXSourceLocation location,\n-- CXFile *file,\n-- unsigned *line,\n-- unsigned *column,\n-- unsigned *offset);\n{# fun clang_getSpellingLocation { withVoided* %`SourceLocation a', id `Ptr (Ptr ())', id `Ptr CUInt', id `Ptr CUInt', id `Ptr CUInt' } -> `()' #}\ngetSpellingLocation :: Proxy s -> SourceLocation s' -> IO (Maybe (File s), Int, Int, Int)\ngetSpellingLocation _ s =\n allocaBytes {# sizeof PtrPtrCXFile #} (\\ptrToFilePtr ->\n alloca (\\(linePtr :: (Ptr CUInt)) ->\n alloca (\\(columnPtr :: (Ptr CUInt)) ->\n alloca (\\(offsetPtr :: (Ptr CUInt)) -> do\n clang_getSpellingLocation s (castPtr ptrToFilePtr) linePtr columnPtr offsetPtr\n filePtr <- {#get *CXFile #} ptrToFilePtr\n let _maybeFile = maybeFile (File filePtr)\n line <- peek linePtr\n column <- peek columnPtr\n offset <- peek offsetPtr\n return (_maybeFile, fromIntegral line, fromIntegral column, fromIntegral offset)))))\n\n-- void clang_getFileLocation(CXSourceLocation location,\n-- CXFile *file,\n-- unsigned *line,\n-- unsigned *column,\n-- unsigned *offset);\n{# fun clang_getFileLocation { withVoided* %`SourceLocation a', id `Ptr (Ptr ())', id `Ptr CUInt', id `Ptr CUInt', id `Ptr CUInt' } -> `()' #}\ngetFileLocation :: Proxy s -> SourceLocation s' -> IO (Maybe (File s), Int, Int, Int)\ngetFileLocation _ s =\n allocaBytes {#sizeof PtrPtrCXFile #} (\\ptrToFilePtr ->\n alloca (\\(linePtr :: (Ptr CUInt)) ->\n alloca (\\(columnPtr :: (Ptr CUInt)) ->\n alloca (\\(offsetPtr :: (Ptr CUInt)) -> do\n clang_getFileLocation s ptrToFilePtr (castPtr linePtr) (castPtr columnPtr) (castPtr offsetPtr)\n filePtr <- {#get *CXFile #} ptrToFilePtr\n let _maybeFile = maybeFile (File filePtr)\n line <- peek linePtr\n column <- peek columnPtr\n offset <- peek offsetPtr\n return (_maybeFile, fromIntegral line, fromIntegral column, fromIntegral offset)))))\n\n-- CXSourceLocation clang_getRangeStart(CXSourceRange range);\n{# fun wrapped_clang_getRangeStart as clang_getRangeStart {withVoided* %`SourceRange a' } -> `Ptr (SourceLocation s)' castPtr #}\ngetRangeStart :: Proxy s -> SourceRange s' -> IO (SourceLocation s)\ngetRangeStart _ sr = clang_getRangeStart sr >>= peek\n\n-- CXSourceLocation clang_getRangeEnd(CXSourceRange range);\n{# fun wrapped_clang_getRangeEnd as clang_getRangeEnd {withVoided* %`SourceRange a' } -> `Ptr (SourceLocation s)' castPtr #}\ngetRangeEnd :: Proxy s -> SourceRange s' -> IO (SourceLocation s)\ngetRangeEnd _ sr = clang_getRangeEnd sr >>= peek\n\n-- enum CXDiagnosticSeverity {\n-- CXDiagnostic_Ignored = 0,\n-- CXDiagnostic_Note = 1,\n-- CXDiagnostic_Warning = 2,\n-- CXDiagnostic_Error = 3,\n-- CXDiagnostic_Fatal = 4\n-- };\n\n-- | The severity of a diagnostic.\n#c\nenum Severity\n { SeverityIgnored = CXDiagnostic_Ignored\n , SeverityNote = CXDiagnostic_Note\n , SeverityWarning = CXDiagnostic_Warning\n , SeverityError = CXDiagnostic_Error\n , SeverityFatal = CXDiagnostic_Fatal\n };\n#endc\n{# enum Severity {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- typedef void* CXDiagnostic;\nnewtype Diagnostic s = Diagnostic { unDiagnostic :: Ptr () }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue Diagnostic\n\nmkDiagnostic :: Ptr () -> Diagnostic ()\nmkDiagnostic = Diagnostic\n\n-- void clang_disposeDiagnostic(CXDiagnostic);\n{# fun clang_disposeDiagnostic { id `Ptr ()' } -> `()' #}\ndisposeDiagnostic:: Diagnostic s -> IO ()\ndisposeDiagnostic d = clang_disposeDiagnostic (unDiagnostic d)\n\nregisterDiagnostic :: ClangBase m => IO (Diagnostic ()) -> ClangT s m (Diagnostic s)\nregisterDiagnostic action = do\n (_, idx) <- clangAllocate (action >>= return . unsafeCoerce)\n (\\i -> disposeDiagnostic i)\n return idx\n{-# INLINEABLE registerDiagnostic #-}\n\n-- typedef void* CXDiagnosticSet;\nnewtype DiagnosticSet s = DiagnosticSet { unDiagnosticSet :: Ptr () }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue DiagnosticSet\n\nmkDiagnosticSet :: Ptr () -> DiagnosticSet ()\nmkDiagnosticSet = DiagnosticSet\n\n-- void clang_disposeDiagnosticSet(CXDiagnosticSet);\n{# fun clang_disposeDiagnosticSet { id `Ptr ()' } -> `()' #}\ndisposeDiagnosticSet :: DiagnosticSet s -> IO ()\ndisposeDiagnosticSet s = clang_disposeDiagnosticSet (unDiagnosticSet s)\n\nregisterDiagnosticSet :: ClangBase m => IO (DiagnosticSet ()) -> ClangT s m (DiagnosticSet s)\nregisterDiagnosticSet action = do\n (_, idx) <- clangAllocate (action >>= return . unsafeCoerce)\n (\\i -> disposeDiagnosticSet i)\n return idx\n{-# INLINEABLE registerDiagnosticSet #-}\n\n-- unsigned clang_getNumDiagnosticsInSet(CXDiagnosticSet Diags);\n{# fun clang_getNumDiagnosticsInSet { id `Ptr ()' } -> `Int' #}\ngetNumDiagnosticsInSet :: DiagnosticSet s -> IO Int\ngetNumDiagnosticsInSet s = clang_getNumDiagnosticsInSet (unDiagnosticSet s)\n\n-- CXDiagnostic clang_getDiagnosticInSet(CXDiagnosticSet Diags, unsigned Index);\n{# fun clang_getDiagnosticInSet { id `Ptr ()', `Int' } -> `Ptr ()' id #}\nunsafe_getDiagnosticInSet :: DiagnosticSet s -> Int -> IO (Diagnostic ())\nunsafe_getDiagnosticInSet s i = clang_getDiagnosticInSet (unDiagnosticSet s) i >>= return . mkDiagnostic\n\ngetDiagnosticInSet :: ClangBase m => DiagnosticSet s' -> Int -> ClangT s m (Diagnostic s)\ngetDiagnosticInSet = (registerDiagnostic .) . unsafe_getDiagnosticInSet\n\n-- enum CXLoadDiag_Error {\n-- CXLoadDiag_None = 0,\n-- CXLoadDiag_Unknown = 1,\n-- CXLoadDiag_CannotLoad = 2,\n-- CXLoadDiag_InvalidFile = 3\n-- };\n\n-- | An error encountered while loading a serialized diagnostics bitcode file.\n#c\nenum LoadError\n { LoadSuccessful = CXLoadDiag_None\n , LoadUnknownError = CXLoadDiag_Unknown\n , LoadCannotOpen = CXLoadDiag_CannotLoad\n , LoadInvalidFile = CXLoadDiag_InvalidFile\n };\n#endc\n{# enum LoadError {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ndata LoadDiagsResult =\n LoadDiagsResult LoadError (ClangString ()) (DiagnosticSet ())\n\n-- CXDiagnosticSet clang_loadDiagnostics(const char *file,\n-- enum CXLoadDiag_Error *error,\n-- CXString *errorString);\n{# fun clang_loadDiagnostics {`CString', alloca- `CInt' peek*, `Ptr ()' } -> `Ptr ()' id #}\nunsafe_loadDiagnostics :: FilePath -> IO LoadDiagsResult\nunsafe_loadDiagnostics file = withCString file (\\cString -> alloca (go cString))\n where\n go :: CString -> Ptr (ClangString ()) -> IO LoadDiagsResult\n go str ptr = do\n (diagnosticSetPtr, err) <- clang_loadDiagnostics str (castPtr ptr)\n errString <- peek (castPtr ptr)\n return (LoadDiagsResult (toEnum (fromIntegral err)) errString (DiagnosticSet diagnosticSetPtr))\n\nloadDiagnostics :: ClangBase m => FilePath\n -> ClangT s m (Either (LoadError, ClangString s) (DiagnosticSet s))\nloadDiagnostics path = do\n result <- liftIO $ unsafe_loadDiagnostics path\n case result of\n (LoadDiagsResult err errStr ds@(DiagnosticSet p))\n | p == nullPtr -> Left . (err,) <$> registerClangString (return errStr)\n | otherwise -> Right <$> registerDiagnosticSet (return ds)\n\n-- CXDiagnosticSet clang_getChildDiagnostics(CXDiagnostic D);\n{# fun clang_getChildDiagnostics { `Ptr ()' } -> `Ptr ()' id #}\nunsafe_getChildDiagnostics :: Diagnostic s' -> IO (DiagnosticSet ())\nunsafe_getChildDiagnostics d = clang_getChildDiagnostics (unDiagnostic d) >>= return . mkDiagnosticSet\n\n-- Note that as a special case, the DiagnosticSet returned by this\n-- function does not need to be freed, so we intentionally don't\n-- register it.\ngetChildDiagnostics :: ClangBase m => Diagnostic s' -> ClangT s m (DiagnosticSet s)\ngetChildDiagnostics = unsafeCoerce <$> unsafe_getChildDiagnostics\n\n-- unsigned clang_getNumDiagnostics(CXTranslationUnit Unit);\n{# fun clang_getNumDiagnostics { `Ptr ()' } -> `CUInt' id#}\ngetNumDiagnostics :: TranslationUnit s -> IO Int\ngetNumDiagnostics t = clang_getNumDiagnostics (unTranslationUnit t) >>= return . fromIntegral\n\n-- CXDiagnostic clang_getDiagnostic(CXTranslationUnit Unit, unsigned Index);\n{# fun clang_getDiagnostic { `Ptr ()', `CUInt' } -> `Ptr ()' id #}\nunsafe_getDiagnostic :: TranslationUnit s -> Int -> IO (Diagnostic ())\nunsafe_getDiagnostic t i = clang_getDiagnostic (unTranslationUnit t) (fromIntegral i) >>= return . mkDiagnostic\n\ngetDiagnostic :: ClangBase m => TranslationUnit s' -> Int -> ClangT s m (Diagnostic s)\ngetDiagnostic = (registerDiagnostic .) . unsafe_getDiagnostic\n\n-- CXDiagnosticSet clang_getDiagnosticSetFromTU(CXTranslationUnit Unit);\n{# fun clang_getDiagnosticSetFromTU { `Ptr ()' } -> `Ptr ()' id #}\nunsafe_getDiagnosticSetFromTU :: TranslationUnit s -> IO (DiagnosticSet ())\nunsafe_getDiagnosticSetFromTU t = do\n set <- clang_getDiagnosticSetFromTU (unTranslationUnit t)\n return (mkDiagnosticSet set)\n\ngetDiagnosticSetFromTU :: ClangBase m => TranslationUnit s' -> ClangT s m (DiagnosticSet s)\ngetDiagnosticSetFromTU = registerDiagnosticSet . unsafe_getDiagnosticSetFromTU\n\n-- enum CXDiagnosticDisplayOptions {\n-- CXDiagnostic_DisplaySourceLocation = 0x01,\n-- CXDiagnostic_DisplayColumn = 0x02,\n-- CXDiagnostic_DisplaySourceRanges = 0x04,\n-- CXDiagnostic_DisplayOption = 0x08,\n-- CXDiagnostic_DisplayCategoryId = 0x10,\n-- CXDiagnostic_DisplayCategoryName = 0x20\n-- };\n\n-- | Options for rendering of 'Diagnostic' values.\n#c\nenum DisplayOptions\n { DisplaySourceLocation = CXDiagnostic_DisplaySourceLocation\n , DisplayColumn = CXDiagnostic_DisplayColumn\n , DisplaySourceRanges = CXDiagnostic_DisplaySourceRanges\n , DisplayOption = CXDiagnostic_DisplayOption\n , DisplayCategoryId = CXDiagnostic_DisplayCategoryId\n , DisplayCategoryName = CXDiagnostic_DisplayCategoryName\n };\n#endc\n{#enum DisplayOptions {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags DisplayOptions where\n toBit DisplaySourceLocation = 0x1\n toBit DisplayColumn = 0x2\n toBit DisplaySourceRanges = 0x4\n toBit DisplayOption = 0x8\n toBit DisplayCategoryId = 0x10\n toBit DisplayCategoryName = 0x20\n\n-- CXString clang_formatDiagnostic(CXDiagnostic Diagnostic, unsigned Options);\n{# fun wrapped_clang_formatDiagnostic as clang_formatDiagnostic { `Ptr ()' , `Int' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_formatDiagnostic :: Diagnostic s -> Int -> IO (ClangString ())\nunsafe_formatDiagnostic d i = clang_formatDiagnostic (unDiagnostic d) (fromIntegral i) >>= peek\n\nformatDiagnostic :: ClangBase m => Diagnostic s' -> Int -> ClangT s m (ClangString s)\nformatDiagnostic = (registerClangString .) . unsafe_formatDiagnostic\n\n-- unsigned clang_defaultDiagnosticDisplayOptions(void);\n{# fun clang_defaultDiagnosticDisplayOptions { } -> `CUInt' #}\ndefaultDiagnosticDisplayOptions :: IO Int\ndefaultDiagnosticDisplayOptions = clang_defaultDiagnosticDisplayOptions >>= return . fromIntegral\n\n-- clang_getDiagnosticSeverity(CXDiagnostic);\n{# fun clang_getDiagnosticSeverity {id `Ptr ()' } -> `CInt' #}\ngetDiagnosticSeverity :: Diagnostic s -> IO Severity\ngetDiagnosticSeverity d = clang_getDiagnosticSeverity (unDiagnostic d) >>= return . toEnum . fromIntegral\n\n-- CXSourceLocation clang_getDiagnosticLocation(CXDiagnostic);\n{# fun wrapped_clang_getDiagnosticLocation as clang_getDiagnosticLocation {id `Ptr ()' } -> `Ptr (SourceLocation s)' castPtr #}\ngetDiagnosticLocation :: Proxy s -> Diagnostic s' -> IO (SourceLocation s)\ngetDiagnosticLocation _ d = clang_getDiagnosticLocation (unDiagnostic d) >>= peek\n\n-- CXString clang_getDiagnosticSpelling(CXDiagnostic);\n{# fun wrapped_clang_getDiagnosticSpelling as clang_getDiagnosticSpelling { id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getDiagnosticSpelling :: Diagnostic s -> IO (ClangString ())\nunsafe_getDiagnosticSpelling d = clang_getDiagnosticSpelling (unDiagnostic d) >>= peek\n\ngetDiagnosticSpelling :: ClangBase m => Diagnostic s' -> ClangT s m (ClangString s)\ngetDiagnosticSpelling = registerClangString . unsafe_getDiagnosticSpelling\n\n-- CXString clang_getDiagnosticOption(CXDiagnostic Diag,\n-- CXString *Disable);\n{# fun wrapped_clang_getDiagnosticOption as clang_getDiagnosticOption { id `Ptr ()', id `Ptr ()' } -> `Ptr ()' id #}\nunsafe_getDiagnosticOption :: Diagnostic s -> IO (ClangString (), ClangString ())\nunsafe_getDiagnosticOption d =\n alloca (\\(disableCXStringPtr :: (Ptr (ClangString ()))) -> do\n diagnosticOptionPtr <- clang_getDiagnosticOption (unDiagnostic d) (castPtr disableCXStringPtr)\n disableCXString <- peek disableCXStringPtr\n diagnosticOption <- peek (castPtr diagnosticOptionPtr)\n return (diagnosticOption, disableCXString))\n\ngetDiagnosticOption :: ClangBase m => Diagnostic s' -> ClangT s m (ClangString s, ClangString s)\ngetDiagnosticOption d = do\n (a, b) <- liftIO $ unsafe_getDiagnosticOption d\n (,) <$> registerClangString (return a) <*> registerClangString (return b)\n\n-- unsigned clang_getDiagnosticCategory(CXDiagnostic);\n{# fun clang_getDiagnosticCategory { id `Ptr ()' } -> `Int' #}\ngetDiagnosticCategory :: Diagnostic s -> IO Int\ngetDiagnosticCategory d = clang_getDiagnosticCategory (unDiagnostic d)\n\n-- CXString clang_getDiagnosticCategoryText(CXDiagnostic);\n{# fun wrapped_clang_getDiagnosticCategoryText as clang_getDiagnosticCategoryText { id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getDiagnosticCategoryText :: Diagnostic s -> IO (ClangString ())\nunsafe_getDiagnosticCategoryText d = clang_getDiagnosticCategoryText (unDiagnostic d) >>= peek\n\ngetDiagnosticCategoryText :: ClangBase m => Diagnostic s' -> ClangT s m (ClangString s)\ngetDiagnosticCategoryText = registerClangString . unsafe_getDiagnosticCategoryText\n\n-- unsigned clang_getDiagnosticNumRanges(CXDiagnostic);\n{# fun clang_getDiagnosticNumRanges { id `Ptr ()' } -> `Int' #}\ngetDiagnosticNumRanges :: Diagnostic s -> IO Int\ngetDiagnosticNumRanges d = clang_getDiagnosticNumRanges (unDiagnostic d)\n\n-- CXSourceRange clang_getDiagnosticRange(CXDiagnostic Diagnostic,\n-- unsigned Range);\n{# fun wrapped_clang_getDiagnosticRange as clang_getDiagnosticRange { id `Ptr ()', `Int' } -> `Ptr (SourceRange s)' castPtr #}\ngetDiagnosticRange :: Diagnostic s' -> Int -> IO (SourceRange s)\ngetDiagnosticRange d i = clang_getDiagnosticRange (unDiagnostic d) i >>= peek\n\n-- unsigned clang_getDiagnosticNumFixIts(CXDiagnostic Diagnostic);\n{# fun clang_getDiagnosticNumFixIts { id `Ptr ()' } -> `Int' #}\ngetDiagnosticNumFixIts :: Diagnostic s -> IO Int\ngetDiagnosticNumFixIts d = clang_getDiagnosticNumFixIts (unDiagnostic d)\n\n-- CXString clang_getDiagnosticFixIt(CXDiagnostic Diagnostic,\n-- unsigned FixIt,\n-- CXSourceRange *ReplacementRange);\n{# fun wrapped_clang_getDiagnosticFixIt as clang_getDiagnosticFixIt { id `Ptr ()', `Int', id `Ptr ()' } -> `Ptr (ClangString())' castPtr #}\nunsafe_getDiagnosticFixIt :: Diagnostic s' -> Int -> IO (SourceRange s, ClangString ())\nunsafe_getDiagnosticFixIt d i =\n alloca (\\(replacementRangePtr :: (Ptr (SourceRange s))) -> do\n clangStringPtr <- clang_getDiagnosticFixIt (unDiagnostic d) i (castPtr replacementRangePtr)\n clangString <- peek clangStringPtr\n replacementRange <- peek replacementRangePtr\n return (replacementRange, clangString))\n\ngetDiagnosticFixIt :: ClangBase m => Diagnostic s' -> Int\n -> ClangT s m (SourceRange s, ClangString s)\ngetDiagnosticFixIt d i = do\n (r, s) <- liftIO $ unsafe_getDiagnosticFixIt d i\n (r,) <$> registerClangString (return s)\n\n-- CXString\n-- clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit);\n{# fun wrapped_clang_getTranslationUnitSpelling as clang_getTranslationUnitSpelling { id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getTranslationUnitSpelling :: TranslationUnit s -> IO (ClangString ())\nunsafe_getTranslationUnitSpelling t = clang_getTranslationUnitSpelling (unTranslationUnit t) >>= peek\n\ngetTranslationUnitSpelling :: ClangBase m => TranslationUnit s' -> ClangT s m (ClangString s)\ngetTranslationUnitSpelling = registerClangString . unsafe_getTranslationUnitSpelling\n\n-- CXTranslationUnit clang_createTranslationUnitFromSourceFile(\n-- CXIndex CIdx,\n-- const char *source_filename,\n-- int num_clang_command_line_args,\n-- const char * const *clang_command_line_args,\n-- unsigned num_unsaved_files,\n-- struct CXUnsavedFile *unsaved_files);\n{# fun clang_createTranslationUnitFromSourceFile { id `Ptr ()' , `CString' , `Int' , id `Ptr CString' , `Int' , id `Ptr ()' } -> `Ptr ()' id #}\nunsafe_createTranslationUnitFromSourceFile :: Index s -> String -> Int -> Ptr CString -> Int -> Ptr CUnsavedFile -> IO (TranslationUnit ())\nunsafe_createTranslationUnitFromSourceFile i s nas as nufs ufs =\n withCString s (\\sPtr -> do\n rPtr <- clang_createTranslationUnitFromSourceFile (unIndex i) sPtr nas as nufs (castPtr ufs)\n return (mkTranslationUnit rPtr))\n\ncreateTranslationUnitFromSourceFile :: ClangBase m => Index s' -> String -> [String]\n -> DV.Vector UnsavedFile -> ClangT s m (TranslationUnit s)\ncreateTranslationUnitFromSourceFile idx sf as ufs =\n registerTranslationUnit $\n withStringList as $ \\asPtr asLen ->\n withUnsavedFiles ufs $ \\ufsPtr ufsLen ->\n unsafe_createTranslationUnitFromSourceFile idx sf asLen asPtr ufsLen ufsPtr\n\n-- CXTranslationUnit clang_createTranslationUnit(CXIndex,\n-- const char *ast_filename);\n{# fun clang_createTranslationUnit { id `Ptr ()', `CString' } -> `Ptr ()' #}\nunsafe_createTranslationUnit :: Index s -> String -> IO (TranslationUnit ())\nunsafe_createTranslationUnit i s =\n withCString s (\\strPtr -> do\n trPtr <- clang_createTranslationUnit (unIndex i) strPtr\n return (mkTranslationUnit trPtr))\n\ncreateTranslationUnit :: ClangBase m => Index s' -> String -> ClangT s m (TranslationUnit s)\ncreateTranslationUnit = (registerTranslationUnit .) . unsafe_createTranslationUnit\n\n-- enum CXTranslationUnit_Flags {\n-- CXTranslationUnit_None = 0x0,\n-- CXTranslationUnit_DetailedPreprocessingRecord = 0x01,\n-- CXTranslationUnit_Incomplete = 0x02,\n-- CXTranslationUnit_PrecompiledPreamble = 0x04,\n-- CXTranslationUnit_CacheCompletionResults = 0x08,\n-- CXTranslationUnit_ForSerialization = 0x10,\n-- CXTranslationUnit_CXXChainedPCH = 0x20,\n-- CXTranslationUnit_SkipFunctionBodies = 0x40,\n-- CXTranslationUnit_IncludeBriefCommentsInCodeCompletion = 0x80\n-- };\n\n-- | Flags that control how a translation unit is parsed.\n--\n-- * 'DetailedPreprocessingRecordFlag': Used to indicate that the parser should construct a\n-- \"detailed\" preprocessing record, including all macro definitions and instantiations.\n-- Constructing a detailed preprocessing record requires more memory and time to parse,\n-- since the information contained in the record is usually not retained. However, it can be\n-- useful for applications that require more detailed information about the behavior of the\n-- preprocessor.\n--\n-- * 'IncompleteFlag': Used to indicate that the translation unit is incomplete.\n-- When a translation unit is considered \"incomplete\", semantic analysis that is typically\n-- performed at the end of the translation unit will be suppressed. For example, this\n-- suppresses the completion of tentative declarations in C and of instantiation of\n-- implicitly-instantiation function templates in C++. This option is typically used when\n-- parsing a header with the intent of producing a precompiled header.\n--\n-- * 'PrecompiledPreambleFlag': Used to indicate that the translation unit should be built\n-- with an implicit precompiled header for the preamble. An implicit precompiled header is\n-- used as an optimization when a particular translation unit is likely to be reparsed many\n-- times when the sources aren't changing that often. In this case, an implicit precompiled\n-- header will be built containing all of the initial includes at the top of the main file\n-- (what we refer to as the \"preamble\" of the file). In subsequent parses, if the preamble\n-- or the files in it have not changed, 'Clang.TranslationUnit.reparse' will re-use the\n-- implicit precompiled header to improve parsing performance.\n--\n-- * 'CacheCompletionResultsFlag': Used to indicate that the translation unit should cache\n-- some code-completion results with each reparse of the source file.\n-- Caching of code-completion results is a performance optimization that introduces some\n-- overhead to reparsing but improves the performance of code-completion operations.\n--\n-- * 'ForSerializationFlag': Used to indicate that the translation unit will be serialized\n-- 'Clang.TranslationUnit.save'. This option is typically used when parsing a header with\n-- the intent of producing a precompiled header.\n--\n-- * 'CXXChainedPCHFlag': DEPRECATED: Enabled chained precompiled preambles in C++. Note:\n-- this is a *temporary* option that is available only while we are testing C++ precompiled\n-- preamble support. It is deprecated.\n--\n-- * 'SkipFunctionBodiesFlag': Used to indicate that function\/method bodies should be skipped\n-- while parsing. This option can be used to search for declarations\/definitions while\n-- ignoring the usages.\n--\n-- * 'IncludeBriefCommentsInCodeCompletionFlag': Used to indicate that brief documentation\n-- comments should be included into the set of code completions returned from this\n-- translation unit.\n#c\nenum TranslationUnitFlags\n { DefaultTranslationUnitFlags = CXTranslationUnit_None\n , DetailedPreprocessingRecordFlag = CXTranslationUnit_DetailedPreprocessingRecord\n , IncompleteFlag = CXTranslationUnit_Incomplete\n , PrecompiledPreambleFlag = CXTranslationUnit_PrecompiledPreamble\n , CacheCompletionResultsFlag = CXTranslationUnit_CacheCompletionResults\n , ForSerializationFlag = CXTranslationUnit_ForSerialization\n , ChainedPCHFlag = CXTranslationUnit_CXXChainedPCH\n , SkipFunctionBodiesFlag = CXTranslationUnit_SkipFunctionBodies\n , IncludeBriefCommentsInCodeCompletionFlag = CXTranslationUnit_IncludeBriefCommentsInCodeCompletion\n };\n#endc\n{# enum TranslationUnitFlags {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags TranslationUnitFlags where\n toBit DefaultTranslationUnitFlags = 0x0\n toBit DetailedPreprocessingRecordFlag = 0x01\n toBit IncompleteFlag = 0x02\n toBit PrecompiledPreambleFlag = 0x04\n toBit CacheCompletionResultsFlag = 0x08\n toBit ForSerializationFlag = 0x10\n toBit ChainedPCHFlag = 0x20\n toBit SkipFunctionBodiesFlag = 0x40\n toBit IncludeBriefCommentsInCodeCompletionFlag = 0x80\n\n-- unsigned clang_defaultEditingTranslationUnitOptions(void);\n{# fun clang_defaultEditingTranslationUnitOptions as defaultEditingTranslationUnitOptions {} -> `Int' #}\n\nmaybeTranslationUnit :: TranslationUnit s' -> Maybe (TranslationUnit s)\nmaybeTranslationUnit (TranslationUnit p) | p == nullPtr = Nothing\nmaybeTranslationUnit f = Just (unsafeCoerce f)\n\n-- CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,\n-- const char *source_filename,\n-- const char * const *command_line_args,\n-- int num_command_line_args,\n-- struct CXUnsavedFile *unsaved_files,\n-- unsigned num_unsaved_files,\n-- unsigned options);\n{# fun clang_parseTranslationUnit { id `Ptr ()', `CString' , id `Ptr CString', `Int', id `Ptr ()', `Int', `Int'} -> `Ptr ()' id #}\nunsafe_parseTranslationUnit :: Index s -> CString -> Ptr CString -> Int -> Ptr CUnsavedFile -> Int -> Int -> IO (Maybe (TranslationUnit ()))\nunsafe_parseTranslationUnit i s as nas ufs nufs o =\n clang_parseTranslationUnit (unIndex i) s as nas (castPtr ufs) nufs o >>= return . maybeTranslationUnit . mkTranslationUnit\n\nparseTranslationUnit :: ClangBase m => Index s' -> Maybe String -> [String]\n -> DV.Vector UnsavedFile -> Int -> ClangT s m (Maybe (TranslationUnit s))\nparseTranslationUnit idx maySF as ufs opts = do\n mayTU <- liftIO $\n withMaybeCString maySF $ \\cSF ->\n withStringList as $ \\asPtr asLen ->\n withUnsavedFiles ufs $ \\ufsPtr ufsLen ->\n unsafe_parseTranslationUnit idx cSF asPtr asLen ufsPtr ufsLen opts\n case mayTU of\n Just tu -> Just <$> registerTranslationUnit (return tu)\n Nothing -> return Nothing\n\nwithMaybeCString :: Maybe String -> (CString -> IO a) -> IO a\nwithMaybeCString (Just s) f = withCString s f\nwithMaybeCString Nothing f = f nullPtr\n\nwithStringList :: [String] -> (Ptr CString -> Int -> IO a) -> IO a\nwithStringList [] f = f nullPtr 0\nwithStringList strs f = do\n let len = length strs\n allocaArray len $ \\arr -> go arr len arr strs\n where\n go arr len _ [] = f arr len\n go arr len ptr (s : ss) = withCString s $ \\cs -> do\n poke ptr cs\n go arr len (advancePtr ptr 1) ss\n\n-- enum CXSaveTranslationUnit_Flags {\n-- CXSaveTranslationUnit_None = 0x0\n-- };\n\n-- | Flags that control how a translation unit is saved.\n#c\nenum SaveTranslationUnitFlags\n {DefaultSaveTranslationUnitFlags = CXSaveTranslationUnit_None};\n#endc\n{# enum SaveTranslationUnitFlags {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\ninstance BitFlags SaveTranslationUnitFlags where\n toBit DefaultSaveTranslationUnitFlags = 0x0\n\n-- unsigned clang_defaultSaveOptions(CXTranslationUnit TU);\n{# fun clang_defaultSaveOptions { id `Ptr ()' } -> `Int' #}\ndefaultSaveOptions :: TranslationUnit s -> IO Int\ndefaultSaveOptions t = clang_defaultSaveOptions (unTranslationUnit t)\n\n\n-- int clang_saveTranslationUnit(CXTranslationUnit TU,\n-- const char *FileName,\n-- unsigned options);\n{# fun clang_saveTranslationUnit { id `Ptr ()' , `CString', `Int' } -> `Int' #}\nsaveTranslationUnit :: TranslationUnit s -> String -> Int -> IO Bool\nsaveTranslationUnit t s i =\n withCString s (\\sPtr -> do\n r <- clang_saveTranslationUnit (unTranslationUnit t) sPtr i\n return (toBool ((if (r \/= 0) then 0 else 1) :: Int)))\n\n-- enum CXReparse_Flags {\n-- CXReparse_None = 0x0\n-- };\n\n-- | Flags that control how a translation unit is reparsed.\n#c\nenum ReparseFlags {\n DefaultReparseFlags = CXReparse_None\n};\n#endc\n{# enum ReparseFlags {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags ReparseFlags where\n toBit DefaultReparseFlags = 0x0\n\n-- unsigned clang_defaultReparseOptions(CXTranslationUnit TU);\n{# fun clang_defaultReparseOptions { id `Ptr ()' } -> `CUInt' #}\ndefaultReparseOptions :: TranslationUnit s -> IO Int\ndefaultReparseOptions t = clang_defaultReparseOptions (unTranslationUnit t) >>= return . fromIntegral\n\n-- int clang_reparseTranslationUnit(CXTranslationUnit TU,\n-- unsigned num_unsaved_files,\n-- struct CXUnsavedFile *unsaved_files,\n-- unsigned options);\n{# fun clang_reparseTranslationUnit { id `Ptr ()', `Int' , id `Ptr ()' , `Int' } -> `Bool' toBool #}\nunsafe_reparseTranslationUnit :: TranslationUnit s -> Ptr CUnsavedFile -> Int -> Int -> IO Bool\nunsafe_reparseTranslationUnit t ufs nufs i =\n clang_reparseTranslationUnit (unTranslationUnit t) nufs (castPtr ufs) i\n\nreparseTranslationUnit :: ClangBase m => TranslationUnit s' -> DV.Vector UnsavedFile -> Int\n -> ClangT s m Bool\nreparseTranslationUnit tu ufs opts = liftIO $\n withUnsavedFiles ufs $ \\ufsPtr ufsLen ->\n unsafe_reparseTranslationUnit tu ufsPtr ufsLen opts\n\n\n-- enum CXCursorKind {\n-- \/* Declarations *\/\n-- \/**\n-- * \\brief A declaration whose specific kind is not exposed via this\n-- * interface.\n-- *\n-- * Unexposed declarations have the same operations as any other kind\n-- * of declaration; one can extract their location information,\n-- * spelling, find their definitions, etc. However, the specific kind\n-- * of the declaration is not reported.\n-- *\/\n-- CXCursor_UnexposedDecl = 1,\n-- \/** \\brief A C or C++ struct. *\/\n-- CXCursor_StructDecl = 2,\n-- \/** \\brief A C or C++ union. *\/\n-- CXCursor_UnionDecl = 3,\n-- \/** \\brief A C++ class. *\/\n-- CXCursor_ClassDecl = 4,\n-- \/** \\brief An enumeration. *\/\n-- CXCursor_EnumDecl = 5,\n-- \/**\n-- * \\brief A field (in C) or non-static data member (in C++) in a\n-- * struct, union, or C++ class.\n-- *\/\n-- CXCursor_FieldDecl = 6,\n-- \/** \\brief An enumerator constant. *\/\n-- CXCursor_EnumConstantDecl = 7,\n-- \/** \\brief A function. *\/\n-- CXCursor_FunctionDecl = 8,\n-- \/** \\brief A variable. *\/\n-- CXCursor_VarDecl = 9,\n-- \/** \\brief A function or method parameter. *\/\n-- CXCursor_ParmDecl = 10,\n-- \/** \\brief An Objective-C @interface. *\/\n-- CXCursor_ObjCInterfaceDecl = 11,\n-- \/** \\brief An Objective-C @interface for a category. *\/\n-- CXCursor_ObjCCategoryDecl = 12,\n-- \/** \\brief An Objective-C @protocol declaration. *\/\n-- CXCursor_ObjCProtocolDecl = 13,\n-- \/** \\brief An Objective-C @property declaration. *\/\n-- CXCursor_ObjCPropertyDecl = 14,\n-- \/** \\brief An Objective-C instance variable. *\/\n-- CXCursor_ObjCIvarDecl = 15,\n-- \/** \\brief An Objective-C instance method. *\/\n-- CXCursor_ObjCInstanceMethodDecl = 16,\n-- \/** \\brief An Objective-C class method. *\/\n-- CXCursor_ObjCClassMethodDecl = 17,\n-- \/** \\brief An Objective-C @implementation. *\/\n-- CXCursor_ObjCImplementationDecl = 18,\n-- \/** \\brief An Objective-C @implementation for a category. *\/\n-- CXCursor_ObjCCategoryImplDecl = 19,\n-- \/** \\brief A typedef *\/\n-- CXCursor_TypedefDecl = 20,\n-- \/** \\brief A C++ class method. *\/\n-- CXCursor_CXXMethod = 21,\n-- \/** \\brief A C++ namespace. *\/\n-- CXCursor_Namespace = 22,\n-- \/** \\brief A linkage specification, e.g. 'extern \"C\"'. *\/\n-- CXCursor_LinkageSpec = 23,\n-- \/** \\brief A C++ constructor. *\/\n-- CXCursor_Constructor = 24,\n-- \/** \\brief A C++ destructor. *\/\n-- CXCursor_Destructor = 25,\n-- \/** \\brief A C++ conversion function. *\/\n-- CXCursor_ConversionFunction = 26,\n-- \/** \\brief A C++ template type parameter. *\/\n-- CXCursor_TemplateTypeParameter = 27,\n-- \/** \\brief A C++ non-type template parameter. *\/\n-- CXCursor_NonTypeTemplateParameter = 28,\n-- \/** \\brief A C++ template template parameter. *\/\n-- CXCursor_TemplateTemplateParameter = 29,\n-- \/** \\brief A C++ function template. *\/\n-- CXCursor_FunctionTemplate = 30,\n-- \/** \\brief A C++ class template. *\/\n-- CXCursor_ClassTemplate = 31,\n-- \/** \\brief A C++ class template partial specialization. *\/\n-- CXCursor_ClassTemplatePartialSpecialization = 32,\n-- \/** \\brief A C++ namespace alias declaration. *\/\n-- CXCursor_NamespaceAlias = 33,\n-- \/** \\brief A C++ using directive. *\/\n-- CXCursor_UsingDirective = 34,\n-- \/** \\brief A C++ using declaration. *\/\n-- CXCursor_UsingDeclaration = 35,\n-- \/** \\brief A C++ alias declaration *\/\n-- CXCursor_TypeAliasDecl = 36,\n-- \/** \\brief An Objective-C @synthesize definition. *\/\n-- CXCursor_ObjCSynthesizeDecl = 37,\n-- \/** \\brief An Objective-C @dynamic definition. *\/\n-- CXCursor_ObjCDynamicDecl = 38,\n-- \/** \\brief An access specifier. *\/\n-- CXCursor_CXXAccessSpecifier = 39,\n\n-- CXCursor_FirstDecl = CXCursor_UnexposedDecl,\n-- CXCursor_LastDecl = CXCursor_CXXAccessSpecifier,\n\n-- \/* References *\/\n-- CXCursor_FirstRef = 40, \/* Decl references *\/\n-- CXCursor_ObjCSuperClassRef = 40,\n-- CXCursor_ObjCProtocolRef = 41,\n-- CXCursor_ObjCClassRef = 42,\n-- \/**\n-- * \\brief A reference to a type declaration.\n-- *\n-- * A type reference occurs anywhere where a type is named but not\n-- * declared. For example, given:\n-- *\n-- * \\code\n-- * typedef unsigned size_type;\n-- * size_type size;\n-- * \\endcode\n-- *\n-- * The typedef is a declaration of size_type (CXCursor_TypedefDecl),\n-- * while the type of the variable \"size\" is referenced. The cursor\n-- * referenced by the type of size is the typedef for size_type.\n-- *\/\n-- CXCursor_TypeRef = 43,\n-- CXCursor_CXXBaseSpecifier = 44,\n-- \/**\n-- * \\brief A reference to a class template, function template, template\n-- * template parameter, or class template partial specialization.\n-- *\/\n-- CXCursor_TemplateRef = 45,\n-- \/**\n-- * \\brief A reference to a namespace or namespace alias.\n-- *\/\n-- CXCursor_NamespaceRef = 46,\n-- \/**\n-- * \\brief A reference to a member of a struct, union, or class that occurs in\n-- * some non-expression context, e.g., a designated initializer.\n-- *\/\n-- CXCursor_MemberRef = 47,\n-- \/**\n-- * \\brief A reference to a labeled statement.\n-- *\n-- * This cursor kind is used to describe the jump to \"start_over\" in the\n-- * goto statement in the following example:\n-- *\n-- * \\code\n-- * start_over:\n-- * ++counter;\n-- *\n-- * goto start_over;\n-- * \\endcode\n-- *\n-- * A label reference cursor refers to a label statement.\n-- *\/\n-- CXCursor_LabelRef = 48,\n\n-- \/**\n-- * \\brief A reference to a set of overloaded functions or function templates\n-- * that has not yet been resolved to a specific function or function template.\n-- *\n-- * An overloaded declaration reference cursor occurs in C++ templates where\n-- * a dependent name refers to a function. For example:\n-- *\n-- * \\code\n-- * template void swap(T&, T&);\n-- *\n-- * struct X { ... };\n-- * void swap(X&, X&);\n-- *\n-- * template\n-- * void reverse(T* first, T* last) {\n-- * while (first < last - 1) {\n-- * swap(*first, *--last);\n-- * ++first;\n-- * }\n-- * }\n-- *\n-- * struct Y { };\n-- * void swap(Y&, Y&);\n-- * \\endcode\n-- *\n-- * Here, the identifier \"swap\" is associated with an overloaded declaration\n-- * reference. In the template definition, \"swap\" refers to either of the two\n-- * \"swap\" functions declared above, so both results will be available. At\n-- * instantiation time, \"swap\" may also refer to other functions found via\n-- * argument-dependent lookup (e.g., the \"swap\" function at the end of the\n-- * example).\n-- *\n-- * The functions \\c clang_getNumOverloadedDecls() and\n-- * \\c clang_getOverloadedDecl() can be used to retrieve the definitions\n-- * referenced by this cursor.\n-- *\/\n-- CXCursor_OverloadedDeclRef = 49,\n\n-- \/*\n-- * \\brief A reference to a variable that occurs in some non-expression\n-- * context, e.g., a C++ lambda capture list.\n-- *\/\n-- CXCursor_VariableRef = 50,\n\n-- CXCursor_LastRef = CXCursor_VariableRef,\n\n-- \/* Error conditions *\/\n-- CXCursor_FirstInvalid = 70,\n-- CXCursor_InvalidFile = 70,\n-- CXCursor_NoDeclFound = 71,\n-- CXCursor_NotImplemented = 72,\n-- CXCursor_InvalidCode = 73,\n-- CXCursor_LastInvalid = CXCursor_InvalidCode,\n\n-- \/* Expressions *\/\n-- CXCursor_FirstExpr = 100,\n\n-- \/**\n-- * \\brief An expression whose specific kind is not exposed via this\n-- * interface.\n-- *\n-- * Unexposed expressions have the same operations as any other kind\n-- * of expression; one can extract their location information,\n-- * spelling, children, etc. However, the specific kind of the\n-- * expression is not reported.\n-- *\/\n-- CXCursor_UnexposedExpr = 100,\n\n-- \/**\n-- * \\brief An expression that refers to some value declaration, such\n-- * as a function, varible, or enumerator.\n-- *\/\n-- CXCursor_DeclRefExpr = 101,\n\n-- \/**\n-- * \\brief An expression that refers to a member of a struct, union,\n-- * class, Objective-C class, etc.\n-- *\/\n-- CXCursor_MemberRefExpr = 102,\n\n-- \/** \\brief An expression that calls a function. *\/\n-- CXCursor_CallExpr = 103,\n\n-- \/** \\brief An expression that sends a message to an Objective-C\n-- object or class. *\/\n-- CXCursor_ObjCMessageExpr = 104,\n\n-- \/** \\brief An expression that represents a block literal. *\/\n-- CXCursor_BlockExpr = 105,\n\n-- \/** \\brief An integer literal.\n-- *\/\n-- CXCursor_IntegerLiteral = 106,\n\n-- \/** \\brief A floating point number literal.\n-- *\/\n-- CXCursor_FloatingLiteral = 107,\n\n-- \/** \\brief An imaginary number literal.\n-- *\/\n-- CXCursor_ImaginaryLiteral = 108,\n\n-- \/** \\brief A string literal.\n-- *\/\n-- CXCursor_StringLiteral = 109,\n\n-- \/** \\brief A character literal.\n-- *\/\n-- CXCursor_CharacterLiteral = 110,\n\n-- \/** \\brief A parenthesized expression, e.g. \"(1)\".\n-- *\n-- * This AST node is only formed if full location information is requested.\n-- *\/\n-- CXCursor_ParenExpr = 111,\n\n-- \/** \\brief This represents the unary-expression's (except sizeof and\n-- * alignof).\n-- *\/\n-- CXCursor_UnaryOperator = 112,\n\n-- \/** \\brief [C99 6.5.2.1] Array Subscripting.\n-- *\/\n-- CXCursor_ArraySubscriptExpr = 113,\n\n-- \/** \\brief A builtin binary operation expression such as \"x + y\" or\n-- * \"x <= y\".\n-- *\/\n-- CXCursor_BinaryOperator = 114,\n\n-- \/** \\brief Compound assignment such as \"+=\".\n-- *\/\n-- CXCursor_CompoundAssignOperator = 115,\n\n-- \/** \\brief The ?: ternary operator.\n-- *\/\n-- CXCursor_ConditionalOperator = 116,\n\n-- \/** \\brief An explicit cast in C (C99 6.5.4) or a C-style cast in C++\n-- * (C++ [expr.cast]), which uses the syntax (Type)expr.\n-- *\n-- * For example: (int)f.\n-- *\/\n-- CXCursor_CStyleCastExpr = 117,\n\n-- \/** \\brief [C99 6.5.2.5]\n-- *\/\n-- CXCursor_CompoundLiteralExpr = 118,\n\n-- \/** \\brief Describes an C or C++ initializer list.\n-- *\/\n-- CXCursor_InitListExpr = 119,\n\n-- \/** \\brief The GNU address of label extension, representing &&label.\n-- *\/\n-- CXCursor_AddrLabelExpr = 120,\n\n-- \/** \\brief This is the GNU Statement Expression extension: ({int X=4; X;})\n-- *\/\n-- CXCursor_StmtExpr = 121,\n\n-- \/** \\brief Represents a C1X generic selection.\n-- *\/\n-- CXCursor_GenericSelectionExpr = 122,\n\n-- \/** \\brief Implements the GNU __null extension, which is a name for a null\n-- * pointer constant that has integral type (e.g., int or long) and is the same\n-- * size and alignment as a pointer.\n-- *\n-- * The __null extension is typically only used by system headers, which define\n-- * NULL as __null in C++ rather than using 0 (which is an integer that may not\n-- * match the size of a pointer).\n-- *\/\n-- CXCursor_GNUNullExpr = 123,\n\n-- \/** \\brief C++'s static_cast<> expression.\n-- *\/\n-- CXCursor_CXXStaticCastExpr = 124,\n\n-- \/** \\brief C++'s dynamic_cast<> expression.\n-- *\/\n-- CXCursor_CXXDynamicCastExpr = 125,\n\n-- \/** \\brief C++'s reinterpret_cast<> expression.\n-- *\/\n-- CXCursor_CXXReinterpretCastExpr = 126,\n\n-- \/** \\brief C++'s const_cast<> expression.\n-- *\/\n-- CXCursor_CXXConstCastExpr = 127,\n\n-- \/** \\brief Represents an explicit C++ type conversion that uses \"functional\"\n-- * notion (C++ [expr.type.conv]).\n-- *\n-- * Example:\n-- * \\code\n-- * x = int(0.5);\n-- * \\endcode\n-- *\/\n-- CXCursor_CXXFunctionalCastExpr = 128,\n\n-- \/** \\brief A C++ typeid expression (C++ [expr.typeid]).\n-- *\/\n-- CXCursor_CXXTypeidExpr = 129,\n\n-- \/** \\brief [C++ 2.13.5] C++ Boolean Literal.\n-- *\/\n-- CXCursor_CXXBoolLiteralExpr = 130,\n\n-- \/** \\brief [C++0x 2.14.7] C++ Pointer Literal.\n-- *\/\n-- CXCursor_CXXNullPtrLiteralExpr = 131,\n\n-- \/** \\brief Represents the \"this\" expression in C++\n-- *\/\n-- CXCursor_CXXThisExpr = 132,\n\n-- \/** \\brief [C++ 15] C++ Throw Expression.\n-- *\n-- * This handles 'throw' and 'throw' assignment-expression. When\n-- * assignment-expression isn't present, Op will be null.\n-- *\/\n-- CXCursor_CXXThrowExpr = 133,\n\n-- \/** \\brief A new expression for memory allocation and constructor calls, e.g:\n-- * \"new CXXNewExpr(foo)\".\n-- *\/\n-- CXCursor_CXXNewExpr = 134,\n\n-- \/** \\brief A delete expression for memory deallocation and destructor calls,\n-- * e.g. \"delete[] pArray\".\n-- *\/\n-- CXCursor_CXXDeleteExpr = 135,\n\n-- \/** \\brief A unary expression.\n-- *\/\n-- CXCursor_UnaryExpr = 136,\n\n-- \/** \\brief ObjCStringLiteral, used for Objective-C string literals i.e. \"foo\".\n-- *\/\n-- CXCursor_ObjCStringLiteral = 137,\n\n-- \/** \\brief ObjCEncodeExpr, used for in Objective-C.\n-- *\/\n-- CXCursor_ObjCEncodeExpr = 138,\n\n-- \/** \\brief ObjCSelectorExpr used for in Objective-C.\n-- *\/\n-- CXCursor_ObjCSelectorExpr = 139,\n\n-- \/** \\brief Objective-C's protocol expression.\n-- *\/\n-- CXCursor_ObjCProtocolExpr = 140,\n\n-- \/** \\brief An Objective-C \"bridged\" cast expression, which casts between\n-- * Objective-C pointers and C pointers, transferring ownership in the process.\n-- *\n-- * \\code\n-- * NSString *str = (__bridge_transfer NSString *)CFCreateString();\n-- * \\endcode\n-- *\/\n-- CXCursor_ObjCBridgedCastExpr = 141,\n\n-- \/** \\brief Represents a C++0x pack expansion that produces a sequence of\n-- * expressions.\n-- *\n-- * A pack expansion expression contains a pattern (which itself is an\n-- * expression) followed by an ellipsis. For example:\n-- *\n-- * \\code\n-- * template\n-- * void forward(F f, Types &&...args) {\n-- * f(static_cast(args)...);\n-- * }\n-- * \\endcode\n-- *\/\n-- CXCursor_PackExpansionExpr = 142,\n\n-- \/** \\brief Represents an expression that computes the length of a parameter\n-- * pack.\n-- *\n-- * \\code\n-- * template\n-- * struct count {\n-- * static const unsigned value = sizeof...(Types);\n-- * };\n-- * \\endcode\n-- *\/\n-- CXCursor_SizeOfPackExpr = 143,\n\n-- \/* \\brief Represents a C++ lambda expression that produces a local function\n-- * object.\n-- *\n-- * \\code\n-- * void abssort(float *x, unsigned N) {\n-- * std::sort(x, x + N,\n-- * [](float a, float b) {\n-- * return std::abs(a) < std::abs(b);\n-- * });\n-- * }\n-- * \\endcode\n-- *\/\n-- CXCursor_LambdaExpr = 144,\n\n-- \/** \\brief Objective-c Boolean Literal.\n-- *\/\n-- CXCursor_ObjCBoolLiteralExpr = 145,\n\n-- \/** \\brief Represents the \"self\" expression in a ObjC method.\n-- *\/\n-- CXCursor_ObjCSelfExpr = 146,\n\n-- CXCursor_LastExpr = CXCursor_ObjCSelfExpr,\n\n-- \/* Statements *\/\n-- CXCursor_FirstStmt = 200,\n-- \/**\n-- * \\brief A statement whose specific kind is not exposed via this\n-- * interface.\n-- *\n-- * Unexposed statements have the same operations as any other kind of\n-- * statement; one can extract their location information, spelling,\n-- * children, etc. However, the specific kind of the statement is not\n-- * reported.\n-- *\/\n-- CXCursor_UnexposedStmt = 200,\n\n-- \/** \\brief A labelled statement in a function.\n-- *\n-- * This cursor kind is used to describe the \"start_over:\" label statement in\n-- * the following example:\n-- *\n-- * \\code\n-- * start_over:\n-- * ++counter;\n-- * \\endcode\n-- *\n-- *\/\n-- CXCursor_LabelStmt = 201,\n\n-- \/** \\brief A group of statements like { stmt stmt }.\n-- *\n-- * This cursor kind is used to describe compound statements, e.g. function\n-- * bodies.\n-- *\/\n-- CXCursor_CompoundStmt = 202,\n\n-- \/** \\brief A case statment.\n-- *\/\n-- CXCursor_CaseStmt = 203,\n\n-- \/** \\brief A default statement.\n-- *\/\n-- CXCursor_DefaultStmt = 204,\n\n-- \/** \\brief An if statement\n-- *\/\n-- CXCursor_IfStmt = 205,\n\n-- \/** \\brief A switch statement.\n-- *\/\n-- CXCursor_SwitchStmt = 206,\n\n-- \/** \\brief A while statement.\n-- *\/\n-- CXCursor_WhileStmt = 207,\n\n-- \/** \\brief A do statement.\n-- *\/\n-- CXCursor_DoStmt = 208,\n\n-- \/** \\brief A for statement.\n-- *\/\n-- CXCursor_ForStmt = 209,\n\n-- \/** \\brief A goto statement.\n-- *\/\n-- CXCursor_GotoStmt = 210,\n\n-- \/** \\brief An indirect goto statement.\n-- *\/\n-- CXCursor_IndirectGotoStmt = 211,\n\n-- \/** \\brief A continue statement.\n-- *\/\n-- CXCursor_ContinueStmt = 212,\n\n-- \/** \\brief A break statement.\n-- *\/\n-- CXCursor_BreakStmt = 213,\n\n-- \/** \\brief A return statement.\n-- *\/\n-- CXCursor_ReturnStmt = 214,\n\n-- \/** \\brief A GNU inline assembly statement extension.\n-- *\/\n-- CXCursor_GCCAsmStmt = 215,\n-- CXCursor_AsmStmt = CXCursor_GCCAsmStmt,\n\n-- \/** \\brief Objective-C's overall @try-@catc-@finall statement.\n-- *\/\n-- CXCursor_ObjCAtTryStmt = 216,\n\n-- \/** \\brief Objective-C's @catch statement.\n-- *\/\n-- CXCursor_ObjCAtCatchStmt = 217,\n\n-- \/** \\brief Objective-C's @finally statement.\n-- *\/\n-- CXCursor_ObjCAtFinallyStmt = 218,\n\n-- \/** \\brief Objective-C's @throw statement.\n-- *\/\n-- CXCursor_ObjCAtThrowStmt = 219,\n\n-- \/** \\brief Objective-C's @synchronized statement.\n-- *\/\n-- CXCursor_ObjCAtSynchronizedStmt = 220,\n\n-- \/** \\brief Objective-C's autorelease pool statement.\n-- *\/\n-- CXCursor_ObjCAutoreleasePoolStmt = 221,\n\n-- \/** \\brief Objective-C's collection statement.\n-- *\/\n-- CXCursor_ObjCForCollectionStmt = 222,\n\n-- \/** \\brief C++'s catch statement.\n-- *\/\n-- CXCursor_CXXCatchStmt = 223,\n\n-- \/** \\brief C++'s try statement.\n-- *\/\n-- CXCursor_CXXTryStmt = 224,\n\n-- \/** \\brief C++'s for (* : *) statement.\n-- *\/\n-- CXCursor_CXXForRangeStmt = 225,\n\n-- \/** \\brief Windows Structured Exception Handling's try statement.\n-- *\/\n-- CXCursor_SEHTryStmt = 226,\n\n-- \/** \\brief Windows Structured Exception Handling's except statement.\n-- *\/\n-- CXCursor_SEHExceptStmt = 227,\n\n-- \/** \\brief Windows Structured Exception Handling's finally statement.\n-- *\/\n-- CXCursor_SEHFinallyStmt = 228,\n\n-- \/** \\brief A MS inline assembly statement extension.\n-- *\/\n-- CXCursor_MSAsmStmt = 229,\n\n-- \/** \\brief The null satement \";\": C99 6.8.3p3.\n-- *\n-- * This cursor kind is used to describe the null statement.\n-- *\/\n-- CXCursor_NullStmt = 230,\n\n-- \/** \\brief Adaptor class for mixing declarations with statements and\n-- * expressions.\n-- *\/\n-- CXCursor_DeclStmt = 231,\n\n-- \/** \\brief OpenMP parallel directive.\n-- *\/\n-- CXCursor_OMPParallelDirective = 232,\n\n-- CXCursor_LastStmt = CXCursor_OMPParallelDirective,\n\n-- \/**\n-- * \\brief Cursor that represents the translation unit itself.\n-- *\n-- * The translation unit cursor exists primarily to act as the root\n-- * cursor for traversing the contents of a translation unit.\n-- *\/\n-- CXCursor_TranslationUnit = 300,\n\n-- \/* Attributes *\/\n-- CXCursor_FirstAttr = 400,\n-- \/**\n-- * \\brief An attribute whose specific kind is not exposed via this\n-- * interface.\n-- *\/\n-- CXCursor_UnexposedAttr = 400,\n\n-- CXCursor_IBActionAttr = 401,\n-- CXCursor_IBOutletAttr = 402,\n-- CXCursor_IBOutletCollectionAttr = 403,\n-- CXCursor_CXXFinalAttr = 404,\n-- CXCursor_CXXOverrideAttr = 405,\n-- CXCursor_AnnotateAttr = 406,\n-- CXCursor_AsmLabelAttr = 407,\n-- CXCursor_PackedAttr = 408,\n-- CXCursor_LastAttr = CXCursor_PackedAttr,\n\n-- \/* Preprocessing *\/\n-- CXCursor_PreprocessingDirective = 500,\n-- CXCursor_MacroDefinition = 501,\n-- CXCursor_MacroExpansion = 502,\n-- CXCursor_MacroInstantiation = CXCursor_MacroExpansion,\n-- CXCursor_InclusionDirective = 503,\n-- CXCursor_FirstPreprocessing = CXCursor_PreprocessingDirective,\n-- CXCursor_LastPreprocessing = CXCursor_InclusionDirective\n\n-- \/* Extra Declarations *\/\n-- \/**\n-- * \\brief A module import declaration.\n-- *\/\n-- CXCursor_ModuleImportDecl = 600,\n-- CXCursor_FirstExtraDecl = CXCursor_ModuleImportDecl,\n-- CXCursor_LastExtraDecl = CXCursor_ModuleImportDecl\n-- };\n#c\nenum CursorKind\n { UnexposedDeclCursor = CXCursor_UnexposedDecl\n , StructDeclCursor = CXCursor_StructDecl\n , UnionDeclCursor = CXCursor_UnionDecl\n , ClassDeclCursor = CXCursor_ClassDecl\n , EnumDeclCursor = CXCursor_EnumDecl\n , FieldDeclCursor = CXCursor_FieldDecl\n , EnumConstantDeclCursor = CXCursor_EnumConstantDecl\n , FunctionDeclCursor = CXCursor_FunctionDecl\n , VarDeclCursor = CXCursor_VarDecl\n , ParmDeclCursor = CXCursor_ParmDecl\n , ObjCInterfaceDeclCursor = CXCursor_ObjCInterfaceDecl\n , ObjCCategoryDeclCursor = CXCursor_ObjCCategoryDecl\n , ObjCProtocolDeclCursor = CXCursor_ObjCProtocolDecl\n , ObjCPropertyDeclCursor = CXCursor_ObjCPropertyDecl\n , ObjCIvarDeclCursor = CXCursor_ObjCIvarDecl\n , ObjCInstanceMethodDeclCursor = CXCursor_ObjCInstanceMethodDecl\n , ObjCClassMethodDeclCursor = CXCursor_ObjCClassMethodDecl\n , ObjCImplementationDeclCursor = CXCursor_ObjCImplementationDecl\n , ObjCCategoryImplDeclCursor = CXCursor_ObjCCategoryImplDecl\n , TypedefDeclCursor = CXCursor_TypedefDecl\n , CXXMethodCursor = CXCursor_CXXMethod\n , NamespaceCursor = CXCursor_Namespace\n , LinkageSpecCursor = CXCursor_LinkageSpec\n , ConstructorCursor = CXCursor_Constructor\n , DestructorCursor = CXCursor_Destructor\n , ConversionFunctionCursor = CXCursor_ConversionFunction\n , TemplateTypeParameterCursor = CXCursor_TemplateTypeParameter\n , NonTypeTemplateParameterCursor = CXCursor_NonTypeTemplateParameter\n , TemplateTemplateParameterCursor = CXCursor_TemplateTemplateParameter\n , FunctionTemplateCursor = CXCursor_FunctionTemplate\n , ClassTemplateCursor = CXCursor_ClassTemplate\n , ClassTemplatePartialSpecializationCursor = CXCursor_ClassTemplatePartialSpecialization\n , NamespaceAliasCursor = CXCursor_NamespaceAlias\n , UsingDirectiveCursor = CXCursor_UsingDirective\n , UsingDeclarationCursor = CXCursor_UsingDeclaration\n , TypeAliasDeclCursor = CXCursor_TypeAliasDecl\n , ObjCSynthesizeDeclCursor = CXCursor_ObjCSynthesizeDecl\n , ObjCDynamicDeclCursor = CXCursor_ObjCDynamicDecl\n , CXXAccessSpecifierCursor = CXCursor_CXXAccessSpecifier\n , ObjCSuperClassRefCursor = CXCursor_ObjCSuperClassRef\n , ObjCProtocolRefCursor = CXCursor_ObjCProtocolRef\n , ObjCClassRefCursor = CXCursor_ObjCClassRef\n , TypeRefCursor = CXCursor_TypeRef\n , CXXBaseSpecifierCursor = CXCursor_CXXBaseSpecifier\n , TemplateRefCursor = CXCursor_TemplateRef\n , NamespaceRefCursor = CXCursor_NamespaceRef\n , MemberRefCursor = CXCursor_MemberRef\n , LabelRefCursor = CXCursor_LabelRef\n , OverloadedDeclRefCursor = CXCursor_OverloadedDeclRef\n , VariableRefCursor = CXCursor_VariableRef\n , InvalidFileCursor = CXCursor_InvalidFile\n , NoDeclFoundCursor = CXCursor_NoDeclFound\n , NotImplementedCursor = CXCursor_NotImplemented\n , InvalidCodeCursor = CXCursor_InvalidCode\n , UnexposedExprCursor = CXCursor_UnexposedExpr\n , DeclRefExprCursor = CXCursor_DeclRefExpr\n , MemberRefExprCursor = CXCursor_MemberRefExpr\n , CallExprCursor = CXCursor_CallExpr\n , ObjCMessageExprCursor = CXCursor_ObjCMessageExpr\n , BlockExprCursor = CXCursor_BlockExpr\n , IntegerLiteralCursor = CXCursor_IntegerLiteral\n , FloatingLiteralCursor = CXCursor_FloatingLiteral\n , ImaginaryLiteralCursor = CXCursor_ImaginaryLiteral\n , StringLiteralCursor = CXCursor_StringLiteral\n , CharacterLiteralCursor = CXCursor_CharacterLiteral\n , ParenExprCursor = CXCursor_ParenExpr\n , UnaryOperatorCursor = CXCursor_UnaryOperator\n , ArraySubscriptExprCursor = CXCursor_ArraySubscriptExpr\n , BinaryOperatorCursor = CXCursor_BinaryOperator\n , CompoundAssignOperatorCursor = CXCursor_CompoundAssignOperator\n , ConditionalOperatorCursor = CXCursor_ConditionalOperator\n , CStyleCastExprCursor = CXCursor_CStyleCastExpr\n , CompoundLiteralExprCursor = CXCursor_CompoundLiteralExpr\n , InitListExprCursor = CXCursor_InitListExpr\n , AddrLabelExprCursor = CXCursor_AddrLabelExpr\n , StmtExprCursor = CXCursor_StmtExpr\n , GenericSelectionExprCursor = CXCursor_GenericSelectionExpr\n , GNUNullExprCursor = CXCursor_GNUNullExpr\n , CXXStaticCastExprCursor = CXCursor_CXXStaticCastExpr\n , CXXDynamicCastExprCursor = CXCursor_CXXDynamicCastExpr\n , CXXReinterpretCastExprCursor = CXCursor_CXXReinterpretCastExpr\n , CXXConstCastExprCursor = CXCursor_CXXConstCastExpr\n , CXXFunctionalCastExprCursor = CXCursor_CXXFunctionalCastExpr\n , CXXTypeidExprCursor = CXCursor_CXXTypeidExpr\n , CXXBoolLiteralExprCursor = CXCursor_CXXBoolLiteralExpr\n , CXXNullPtrLiteralExprCursor = CXCursor_CXXNullPtrLiteralExpr\n , CXXThisExprCursor = CXCursor_CXXThisExpr\n , CXXThrowExprCursor = CXCursor_CXXThrowExpr\n , CXXNewExprCursor = CXCursor_CXXNewExpr\n , CXXDeleteExprCursor = CXCursor_CXXDeleteExpr\n , UnaryExprCursor = CXCursor_UnaryExpr\n , ObjCStringLiteralCursor = CXCursor_ObjCStringLiteral\n , ObjCEncodeExprCursor = CXCursor_ObjCEncodeExpr\n , ObjCSelectorExprCursor = CXCursor_ObjCSelectorExpr\n , ObjCProtocolExprCursor = CXCursor_ObjCProtocolExpr\n , ObjCBridgedCastExprCursor = CXCursor_ObjCBridgedCastExpr\n , PackExpansionExprCursor = CXCursor_PackExpansionExpr\n , SizeOfPackExprCursor = CXCursor_SizeOfPackExpr\n , LambdaExprCursor = CXCursor_LambdaExpr\n , ObjCBoolLiteralExprCursor = CXCursor_ObjCBoolLiteralExpr\n , ObjCSelfExprCursor = CXCursor_ObjCSelfExpr\n , UnexposedStmtCursor = CXCursor_UnexposedStmt\n , LabelStmtCursor = CXCursor_LabelStmt\n , CompoundStmtCursor = CXCursor_CompoundStmt\n , CaseStmtCursor = CXCursor_CaseStmt\n , DefaultStmtCursor = CXCursor_DefaultStmt\n , IfStmtCursor = CXCursor_IfStmt\n , SwitchStmtCursor = CXCursor_SwitchStmt\n , WhileStmtCursor = CXCursor_WhileStmt\n , DoStmtCursor = CXCursor_DoStmt\n , ForStmtCursor = CXCursor_ForStmt\n , GotoStmtCursor = CXCursor_GotoStmt\n , IndirectGotoStmtCursor = CXCursor_IndirectGotoStmt\n , ContinueStmtCursor = CXCursor_ContinueStmt\n , BreakStmtCursor = CXCursor_BreakStmt\n , ReturnStmtCursor = CXCursor_ReturnStmt\n , AsmStmtCursor = CXCursor_AsmStmt\n , ObjCAtTryStmtCursor = CXCursor_ObjCAtTryStmt\n , ObjCAtCatchStmtCursor = CXCursor_ObjCAtCatchStmt\n , ObjCAtFinallyStmtCursor = CXCursor_ObjCAtFinallyStmt\n , ObjCAtThrowStmtCursor = CXCursor_ObjCAtThrowStmt\n , ObjCAtSynchronizedStmtCursor = CXCursor_ObjCAtSynchronizedStmt\n , ObjCAutoreleasePoolStmtCursor = CXCursor_ObjCAutoreleasePoolStmt\n , ObjCForCollectionStmtCursor = CXCursor_ObjCForCollectionStmt\n , CXXCatchStmtCursor = CXCursor_CXXCatchStmt\n , CXXTryStmtCursor = CXCursor_CXXTryStmt\n , CXXForRangeStmtCursor = CXCursor_CXXForRangeStmt\n , SEHTryStmtCursor = CXCursor_SEHTryStmt\n , SEHExceptStmtCursor = CXCursor_SEHExceptStmt\n , SEHFinallyStmtCursor = CXCursor_SEHFinallyStmt\n , MSAsmStmtCursor = CXCursor_MSAsmStmt\n , NullStmtCursor = CXCursor_NullStmt\n , DeclStmtCursor = CXCursor_DeclStmt\n , OMPParallelDirectiveCursor = CXCursor_OMPParallelDirective\n , TranslationUnitCursor = CXCursor_TranslationUnit\n , UnexposedAttrCursor = CXCursor_UnexposedAttr\n , IBActionAttrCursor = CXCursor_IBActionAttr\n , IBOutletAttrCursor = CXCursor_IBOutletAttr\n , IBOutletCollectionAttrCursor = CXCursor_IBOutletCollectionAttr\n , CXXFinalAttrCursor = CXCursor_CXXFinalAttr\n , CXXOverrideAttrCursor = CXCursor_CXXOverrideAttr\n , AnnotateAttrCursor = CXCursor_AnnotateAttr\n , AsmLabelAttrCursor = CXCursor_AsmLabelAttr\n , PackedAttrCursor = CXCursor_PackedAttr\n , PreprocessingDirectiveCursor = CXCursor_PreprocessingDirective\n , MacroDefinitionCursor = CXCursor_MacroDefinition\n , MacroExpansionCursor = CXCursor_MacroExpansion\n , InclusionDirectiveCursor = CXCursor_InclusionDirective\n , ModuleImportDeclCursor = CXCursor_ModuleImportDecl\n };\n#endc\n{#enum CursorKind{} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- CursorKind ranges.\nfirstDeclCursor, lastDeclCursor, firstRefCursor, lastRefCursor :: CursorKind\nfirstInvalidCursor, lastInvalidCursor, firstExprCursor, lastExprCursor :: CursorKind\nfirstStmtCursor, lastStmtCursor, firstAttrCursor, lastAttrCursor :: CursorKind\nfirstPreprocessingCursor, lastPreprocessingCursor :: CursorKind\nfirstExtraDeclCursor, lastExtraDeclCursor :: CursorKind\n\nfirstDeclCursor = UnexposedDeclCursor\nlastDeclCursor = CXXAccessSpecifierCursor\nfirstRefCursor = ObjCSuperClassRefCursor\nlastRefCursor = VariableRefCursor\nfirstInvalidCursor = InvalidFileCursor\nlastInvalidCursor = InvalidCodeCursor\nfirstExprCursor = UnexposedExprCursor\nlastExprCursor = ObjCSelfExprCursor\nfirstStmtCursor = UnexposedStmtCursor\nlastStmtCursor = OMPParallelDirectiveCursor\nfirstAttrCursor = UnexposedAttrCursor\nlastAttrCursor = PackedAttrCursor\nfirstPreprocessingCursor = PreprocessingDirectiveCursor\nlastPreprocessingCursor = InclusionDirectiveCursor\nfirstExtraDeclCursor = ModuleImportDeclCursor\nlastExtraDeclCursor = ModuleImportDeclCursor\n\n-- CursorKind aliases.\ngccAsmStmtCursor, macroInstantiationCursor :: CursorKind\ngccAsmStmtCursor = AsmStmtCursor\nmacroInstantiationCursor = MacroExpansionCursor\n\n-- typedef struct {\n-- const void *ASTNode;\n-- CXTranslationUnit TranslationUnit;\n-- } CXComment;\ndata Comment s = Comment !(Ptr ()) !(Ptr ())\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue Comment\n\ninstance Storable (Comment s) where\n sizeOf _ = sizeOfCXComment\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfCXComment\n {-# INLINE alignment #-}\n\n peek p = do\n astNode <- {#get CXComment->ASTNode #} p\n tu <- {#get CXComment->TranslationUnit #} p\n return $! Comment astNode tu\n {-# INLINE peek #-}\n\n poke p (Comment astNode tu)= do\n {#set CXComment->ASTNode #} p astNode\n {#set CXComment->TranslationUnit #} p tu\n {-# INLINE poke #-}\n\n-- typedef struct {\n-- enum CXCursorKind kind;\n-- int xdata;\n-- const void* data[3];\n-- } CXCursor;\ndata Cursor s = Cursor !CursorKind !Int !(Ptr ()) !(Ptr ()) !(Ptr ())\n deriving (Ord, Typeable)\n\ninstance ClangValue Cursor\n\ninstance Storable (Cursor s) where\n sizeOf _ = sizeOfCXCursor\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfCXCursor\n {-# INLINE alignment #-}\n\n peek p = do\n cursorKind <- {#get CXCursor->kind #} p\n xdata <- {#get CXCursor->xdata #} p\n cursorData <- {#get CXCursor->data #} p >>= peekArray 3\n return $! Cursor (toEnum (fromIntegral cursorKind)) (fromIntegral xdata) (cursorData !! 0) (cursorData !! 1) (cursorData !! 2)\n {-# INLINE peek #-}\n\n poke p (Cursor kind xdata p0 p1 p2)= do\n ptrsArray <- mallocArray 3\n pokeArray ptrsArray [p0,p1,p2]\n {#set CXCursor->kind #} p (fromIntegral (fromEnum kind))\n {#set CXCursor->xdata #} p (fromIntegral xdata)\n {#set CXCursor->data #} p (castPtr ptrsArray)\n {-# INLINE poke #-}\n\ninstance Eq (Cursor s) where\n (Cursor aK aXdata aP1 aP2 aP3) == (Cursor bK bXdata bP1 bP2 bP3) =\n (aK == bK) &&\n (aXdata == bXdata) &&\n (aP1 == bP1) &&\n (aP2' == bP2') &&\n (aP3 == bP3)\n where\n aP2' = if isDeclaration aK then intPtrToPtr 0 else aP2\n bP2' = if isDeclaration bK then intPtrToPtr 0 else bP2\n {-# INLINE (==) #-}\n\ninstance Hashable (Cursor s) where\n hashWithSalt salt (Cursor k _ p1 p2 _) =\n let p = if isExpression k || isStatement k then p2 else p1\n kindHash = hashWithSalt salt (fromEnum k)\n pAsInt = fromIntegral (ptrToIntPtr p) :: Int\n in hashWithSalt kindHash pAsInt\n {-# INLINE hash #-}\n\n-- CXCursor clang_getNullCursor(void);\ngetNullCursor :: ClangBase m => ClangT s m (Cursor s)\ngetNullCursor =\n return $ Cursor InvalidFileCursor 0 (intPtrToPtr 0) (intPtrToPtr 0) (intPtrToPtr 0)\n{-# INLINE getNullCursor #-}\n\n-- CXCursor clang_getTranslationUnitCursor(CXTranslationUnit);\n{# fun wrapped_clang_getTranslationUnitCursor as clang_getTranslationUnitCursor { id `Ptr ()' } -> `Ptr (Cursor s)' castPtr #}\ngetTranslationUnitCursor :: Proxy s -> TranslationUnit s' -> IO (Cursor s)\ngetTranslationUnitCursor _ (TranslationUnit tPtr) = clang_getTranslationUnitCursor tPtr >>= peek\n\n-- int clang_Cursor_isNull(CXCursor);\ncursor_isNull :: Cursor s -> Bool\ncursor_isNull (Cursor k xdata p1 p2 p3)\n | k == InvalidFileCursor &&\n xdata == 0 &&\n p1 == intPtrToPtr 0 &&\n p2 == intPtrToPtr 0 &&\n p3 == intPtrToPtr 0\n = True\n | otherwise\n = False\n{-# INLINE cursor_isNull #-}\n\n-- unsigned clang_hashCursor(CXCursor);\n{# fun clang_hashCursor {withVoided* %`Cursor a' } -> `Word32' #}\nhashCursor :: Cursor s -> IO Word32\nhashCursor c = clang_hashCursor c\n{-# INLINEABLE hashCursor #-}\n\ngetCursorKind :: Cursor s -> CursorKind\ngetCursorKind (Cursor k _ _ _ _) = k\n{-# INLINE getCursorKind #-}\n\n-- unsigned clang_isDeclaration(enum CursorKind);\nisDeclaration :: CursorKind -> Bool\nisDeclaration k =\n (k >= firstDeclCursor && k <= lastDeclCursor) ||\n (k >= firstExtraDeclCursor && k <= lastExtraDeclCursor)\n{-# INLINE isDeclaration #-}\n\n-- unsigned clang_isReference(enum CursorKind);\nisReference :: CursorKind -> Bool\nisReference k =\n (k >= firstRefCursor && k <= lastRefCursor)\n{-# INLINE isReference #-}\n\n-- unsigned clang_isExpression(enum CursorKind);\nisExpression :: CursorKind -> Bool\nisExpression k =\n (k >= firstExprCursor && k <= lastExprCursor)\n{-# INLINE isExpression #-}\n\n-- unsigned clang_isStatement(enum CursorKind);\nisStatement :: CursorKind -> Bool\nisStatement k =\n (k >= firstStmtCursor && k <= lastStmtCursor)\n{-# INLINE isStatement #-}\n\nisAttribute :: CursorKind -> Bool\nisAttribute k =\n (k >= firstAttrCursor && k <= lastAttrCursor)\n{-# INLINE isAttribute #-}\n\n-- unsigned clang_isInvalid(enum CursorKind);\nisInvalid :: CursorKind -> Bool\nisInvalid k =\n (k >= firstInvalidCursor && k <= lastInvalidCursor)\n{-# INLINE isInvalid #-}\n\n-- unsigned clang_isTranslationUnit(enum CursorKind);\nisTranslationUnit :: CursorKind -> Bool\nisTranslationUnit TranslationUnitCursor = True\nisTranslationUnit _ = False\n{-# INLINE isTranslationUnit #-}\n\n-- unsigned clang_isPreprocessing(enum CursorKind);\nisPreprocessing :: CursorKind -> Bool\nisPreprocessing k =\n (k >= firstPreprocessingCursor && k <= lastPreprocessingCursor)\n{-# INLINE isPreprocessing #-}\n\n-- unsigned clang_isUnexposed(enum CursorKind);\nisUnexposed :: CursorKind -> Bool\nisUnexposed k =\n (k >= firstPreprocessingCursor && k <= lastPreprocessingCursor)\n{-# INLINE isUnexposed #-}\n\n-- enum CXLinkageKind {\n-- CXLinkage_Invalid,\n-- CXLinkage_NoLinkage,\n-- CXLinkage_Internal,\n-- CXLinkage_UniqueExternal,\n-- CXLinkage_External\n-- };\n#c\nenum LinkageKind\n { Linkage_Invalid = CXLinkage_Invalid\n , Linkage_NoLinkage = CXLinkage_NoLinkage\n , Linkage_Internal = CXLinkage_Internal\n , Linkage_UniqueExternal = CXLinkage_UniqueExternal\n , Linkage_External = CXLinkage_External\n };\n#endc\n{#enum LinkageKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- enum CXLinkageKind clang_getCursorLinkage(CXCursor cursor);\n{# fun clang_getCursorLinkage {withVoided* %`Cursor a' } -> `Int' #}\ngetCursorLinkage :: Cursor s -> IO LinkageKind\ngetCursorLinkage c = clang_getCursorLinkage c >>= return . toEnum\n\n-- enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor);\n{# fun clang_getCursorAvailability {withVoided* %`Cursor a' } -> `Int' #}\ngetCursorAvailability :: Cursor s -> IO AvailabilityKind\ngetCursorAvailability c = clang_getCursorAvailability c >>= return . toEnum\n\ndata PlatformAvailability = PlatformAvailability\n { availabilityPlatform :: !B.ByteString\n , availabilityIntroduced :: !Version\n , availabilityDeprecated :: !Version\n , availabilityObsoleted :: !Version\n , availabilityIsUnavailable :: !Bool\n , availabilityMessage :: !B.ByteString\n } deriving (Eq, Ord, Typeable)\n\ninstance Storable PlatformAvailability where\n sizeOf _ = sizeOfCXPlatformAvailability\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfCXPlatformAvailability\n {-# INLINE alignment #-}\n\n peek p = do\n (ClangString platD platF) <- peekByteOff p offsetCXPlatformAvailabilityPlatform\n platform <- B.packCString =<< getCStringPtr platD platF\n\n introduced <- peekByteOff p offsetCXPlatformAvailabilityIntroduced\n deprecated <- peekByteOff p offsetCXPlatformAvailabilityDeprecated\n obsoleted <- peekByteOff p offsetCXPlatformAvailabilityObsoleted\n intUnavailable :: Int <- fromCInt <$> peekByteOff p offsetCXPlatformAvailabilityUnavailable\n\n (ClangString msgD msgF) <- peekByteOff p offsetCXPlatformAvailabilityMessage\n message <- B.packCString =<< getCStringPtr msgD msgF\n\n return $! PlatformAvailability platform introduced deprecated obsoleted\n (if intUnavailable == 0 then False else True)\n message\n {-# INLINE peek #-}\n\n -- Since we can't construct ClangStrings, we can't really poke these.\n poke _ _ = undefined\n {-# INLINE poke #-}\n\n-- void clang_disposeCXPlatformAvailability(CXPlatformAvailability);\n{# fun clang_disposeCXPlatformAvailability { id `Ptr ()' } -> `()' #}\ndisposeCXPlatformAvailability :: Ptr PlatformAvailability -> IO ()\ndisposeCXPlatformAvailability p = clang_disposeCXPlatformAvailability (castPtr p)\n\n-- int clang_getCursorPlatformAvailability(CXCursor cursor,\n-- int *always_deprecated,\n-- CXString *deprecated_message,\n-- int *always_unavailable,\n-- CXString *unavailable_message,\n-- CXPlatformAvailability *availability,\n-- int availability_size);\n{# fun clang_getCursorPlatformAvailability {withVoided* %`Cursor a', alloca- `CInt' peek*, id `Ptr ()', alloca- `CInt' peek*, id `Ptr ()', id `Ptr ()', `Int' } -> `Int' #}\nunsafe_getCursorPlatformAvailability :: Cursor s' -> Ptr PlatformAvailability -> Int -> IO (Bool, ClangString (), Bool, ClangString (), Int)\nunsafe_getCursorPlatformAvailability c dest destLen =\n alloca (\\(dMsgPtr :: (Ptr (ClangString ()))) ->\n alloca (\\(uMsgPtr :: (Ptr (ClangString ()))) -> do\n (size, ad, au) <- clang_getCursorPlatformAvailability\n c\n (castPtr dMsgPtr)\n (castPtr uMsgPtr)\n (castPtr dest)\n destLen\n dm <- peek dMsgPtr\n um <- peek uMsgPtr\n return (toBool ad, dm, toBool au, um, size)))\n\ndata PlatformAvailabilityInfo s = PlatformAvailabilityInfo\n { availabilityAlwaysDeprecated :: !Bool\n , availabilityDeprecatedMessage :: !(ClangString s)\n , availabilityAlwaysUnavailable :: !Bool\n , availabilityUnavailableMessage :: !(ClangString s)\n , availabilityInfo :: ![PlatformAvailability]\n } deriving (Eq, Ord, Typeable)\n\ninstance ClangValue PlatformAvailabilityInfo\n\ngetCursorPlatformAvailability :: ClangBase m => Cursor s'\n -> ClangT s m (PlatformAvailabilityInfo s)\ngetCursorPlatformAvailability c = do\n (ad, dMsg, au, uMsg, infos) <-\n liftIO $ allocaArray maxPlatformAvailability $ \\p -> do\n (ad, dMsg, au, uMsg, outSize) <-\n unsafe_getCursorPlatformAvailability c p maxPlatformAvailability\n let count = min outSize maxPlatformAvailability\n infos <- peekArray count p\n forM_ [0..(count - 1)] $ \\idx -> do\n disposeCXPlatformAvailability (advancePtr p idx)\n return (ad, dMsg, au, uMsg, infos)\n dMsg' <- registerClangString $ return dMsg\n uMsg' <- registerClangString $ return uMsg\n return $ PlatformAvailabilityInfo ad dMsg' au uMsg' infos\n where\n maxPlatformAvailability = 32\n\n-- enum CXLanguageKind {\n-- CXLanguage_Invalid = 0,\n-- CXLanguage_C,\n-- CXLanguage_ObjC,\n-- CXLanguage_CPlusPlus\n-- };\n#c\nenum LanguageKind {\n Language_Invalid = CXLanguage_Invalid\n , Language_C = CXLanguage_C\n , Language_ObjC = CXLanguage_ObjC\n , Language_CPlusPlus = CXLanguage_CPlusPlus\n };\n#endc\n\n{#enum LanguageKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- enum CXLanguageKind clang_getCursorLanguage(CXCursor cursor);\n{# fun clang_getCursorLanguage {withVoided* %`Cursor a' } -> `Int' #}\ngetCursorLanguage :: Cursor s -> IO LanguageKind\ngetCursorLanguage c = clang_getCursorLanguage c >>= return . toEnum\n\n-- CXTranslationUnit clang_Cursor_getTranslationUnit(CXCursor);\n{# fun clang_Cursor_getTranslationUnit {withVoided* %`Cursor a' } -> `Ptr ()' id #}\nunsafe_Cursor_getTranslationUnit :: Cursor s -> IO (TranslationUnit ())\nunsafe_Cursor_getTranslationUnit c =\n clang_Cursor_getTranslationUnit c >>= return . mkTranslationUnit\n\n-- Note that we do not register the translation unit! This function\n-- never creates a 'new' translation unit, so we don't need to dispose\n-- it. Moreover, since translation units aren't reference counted doing\n-- so will lead to crashes.\ncursor_getTranslationUnit :: ClangBase m => Cursor s' -> ClangT s m (TranslationUnit s)\ncursor_getTranslationUnit c = liftIO $ unsafeCoerce <$> unsafe_Cursor_getTranslationUnit c\n\n-- typedef struct CXCursorSetImpl *CXCursorSet;\nnewtype CursorSet s = CursorSet { unCursorSet :: Ptr () }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue CursorSet\n\n-- void clang_disposeCXCursorSet(CXCursorSet cset);\n{# fun clang_disposeCXCursorSet { id `Ptr ()' } -> `()' #}\ndisposeCXCursorSet :: CursorSet s -> IO ()\ndisposeCXCursorSet cs = clang_disposeCXCursorSet (unCursorSet cs)\n\nregisterCursorSet :: ClangBase m => IO (CursorSet ()) -> ClangT s m (CursorSet s)\nregisterCursorSet action = do\n (_, idx) <- clangAllocate (action >>= return . unsafeCoerce)\n (\\i -> disposeCXCursorSet i)\n return idx\n{-# INLINEABLE registerCursorSet #-}\n\n-- CXCursorSet clang_createCXCursorSet();\n{# fun clang_createCXCursorSet as clang_createCXCursorSet {} -> `Ptr ()' id #}\nunsafe_createCXCursorSet :: IO (CursorSet ())\nunsafe_createCXCursorSet = clang_createCXCursorSet >>= return . CursorSet\n\ncreateCXCursorSet :: ClangBase m => ClangT s m (CursorSet s)\ncreateCXCursorSet = registerCursorSet unsafe_createCXCursorSet\n\n-- unsigned clang_CXCursorSet_contains(CXCursorSet cset, CXCursor cursor);\n{# fun clang_CXCursorSet_contains {id `Ptr ()' ,withVoided* %`Cursor a' } -> `Bool' toBool #}\ncXCursorSet_contains :: CursorSet s -> Cursor s' -> IO Bool\ncXCursorSet_contains cs c =\n clang_CXCursorSet_contains (unCursorSet cs) c\n\n-- unsigned clang_CXCursorSet_insert(CXCursorSet cset, CXCursor cursor);\n{# fun clang_CXCursorSet_insert {id `Ptr ()', withVoided* %`Cursor a' } -> `Bool' toBool #}\ncXCursorSet_insert :: CursorSet s -> Cursor s' -> IO Bool\ncXCursorSet_insert cs c =\n clang_CXCursorSet_insert (unCursorSet cs) c\n\n-- CXCursor clang_getCursorSemanticParent(CXCursor cursor);\n{# fun wrapped_clang_getCursorSemanticParent as clang_getCursorSemanticParent {withVoided* %`Cursor a' } -> `Ptr (Cursor s)' castPtr #}\ngetCursorSemanticParent :: Proxy s -> Cursor s' -> IO (Cursor s)\ngetCursorSemanticParent _ c =\n clang_getCursorSemanticParent c >>= peek\n\n-- CXCursor clang_getCursorLexicalParent(CXCursor cursor);\n{# fun wrapped_clang_getCursorLexicalParent as clang_getCursorLexicalParent {withVoided* %`Cursor a' } -> `Ptr (Cursor s)' castPtr #}\ngetCursorLexicalParent :: Proxy s -> Cursor s' -> IO (Cursor s)\ngetCursorLexicalParent _ c =\n clang_getCursorLexicalParent c >>= peek\n\n-- void clang_disposeOverriddenCursors(CXCursor *overridden);\n{# fun clang_disposeOverriddenCursors { id `Ptr ()' } -> `()' #}\ndisposeOverridden :: CursorList s -> IO ()\ndisposeOverridden cl =\n let (csPtr, _) = fromCursorList cl in\n clang_disposeOverriddenCursors csPtr\n\nregisterOverriddenList :: ClangBase m => IO UnsafeCursorList -> ClangT s m (CursorList s)\nregisterOverriddenList action = do\n (_, cursorList) <- clangAllocate (action >>= cursorListToVector) disposeOverridden\n return cursorList\n{-# INLINEABLE registerOverriddenList #-}\n\n-- void clang_getOverriddenCursors(CXCursor cursor, CXCursor **overridden, unsigned *num_overridden);\n{# fun clang_getOverriddenCursors {withVoided* %`Cursor a', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getOverriddenCursors :: Cursor s -> IO UnsafeCursorList\nunsafe_getOverriddenCursors c = do\n cxListPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr (Cursor s)))))\n n <- clang_getOverriddenCursors c (castPtr cxListPtr)\n free cxListPtr\n return (toCursorList (cxListPtr, (fromIntegral n)))\n\ngetOverriddenCursors :: ClangBase m => Cursor s' -> ClangT s m (CursorList s)\ngetOverriddenCursors = registerOverriddenList . unsafe_getOverriddenCursors\n\n-- CXFile clang_getIncludedFile(CXCursor cursor);\n{# fun clang_getIncludedFile {withVoided* %`Cursor a' } -> `Ptr ()' id #}\ngetIncludedFile :: Proxy s -> Cursor s' -> IO (Maybe (File s))\ngetIncludedFile _ c =\n clang_getIncludedFile c >>= return . maybeFile . File . castPtr\n\n-- CXCursor clang_getCursor(CXTranslationUnit, CXSourceLocation);\n{# fun wrapped_clang_getCursor as clang_getCursor { id `Ptr ()' , withVoided* `SourceLocation a' } -> `Ptr (Cursor s)' castPtr #}\ngetCursor :: Proxy s -> TranslationUnit s' -> SourceLocation s'' -> IO (Cursor s)\ngetCursor _ t s = clang_getCursor (unTranslationUnit t) s >>= peek\n\n-- CXSourceLocation clang_getCursorLocation(CXCursor);\n{# fun wrapped_clang_getCursorLocation as clang_getCursorLocation {withVoided* %`Cursor a' } -> `Ptr (SourceLocation s)' castPtr #}\ngetCursorLocation :: Proxy s -> Cursor s' -> IO (SourceLocation s)\ngetCursorLocation _ c =\n clang_getCursorLocation c>>= peek\n{-# INLINEABLE getCursorLocation #-}\n\n-- Variant of clang_getCursorLocation that fuses a call to clang_getSpellingLocation.\ngetCursorSpellingLocation :: Proxy s -> Cursor s' -> IO (Maybe (File s), Int, Int, Int)\ngetCursorSpellingLocation _ c =\n allocaBytes {#sizeof PtrPtrCXFile #} (\\ptrToFilePtr ->\n alloca (\\(linePtr :: (Ptr CUInt)) ->\n alloca (\\(columnPtr :: (Ptr CUInt)) ->\n alloca (\\(offsetPtr :: (Ptr CUInt)) -> do\n slPtr <- clang_getCursorLocation c\n peek slPtr >>= \\sl -> clang_getSpellingLocation sl ptrToFilePtr linePtr columnPtr offsetPtr\n filePtr <- {#get *CXFile #} ptrToFilePtr\n let _maybeFile = maybeFile (File filePtr)\n line <- peek linePtr\n column <- peek columnPtr\n offset <- peek offsetPtr\n return (_maybeFile, fromIntegral line, fromIntegral column, fromIntegral offset)))))\n{-# INLINEABLE getCursorSpellingLocation #-}\n\n-- CXSourceRange clang_getCursorExtent(CXCursor);\n{# fun wrapped_clang_getCursorExtent as clang_getCursorExtent {withVoided* %`Cursor a' } -> `Ptr (SourceRange s)' castPtr #}\ngetCursorExtent :: Proxy s -> Cursor s' -> IO (SourceRange s)\ngetCursorExtent _ c =\n clang_getCursorExtent c >>= peek\n{-# INLINEABLE getCursorExtent #-}\n\n-- enum CXTypeKind {\n-- CXType_Invalid = 0,\n-- CXType_Unexposed = 1,\n-- CXType_Void = 2,\n-- CXType_Bool = 3,\n-- CXType_Char_U = 4,\n-- CXType_UChar = 5,\n-- CXType_Char16 = 6,\n-- CXType_Char32 = 7,\n-- CXType_UShort = 8,\n-- CXType_UInt = 9,\n-- CXType_ULong = 10,\n-- CXType_ULongLong = 11,\n-- CXType_UInt128 = 12,\n-- CXType_Char_S = 13,\n-- CXType_SChar = 14,\n-- CXType_WChar = 15,\n-- CXType_Short = 16,\n-- CXType_Int = 17,\n-- CXType_Long = 18,\n-- CXType_LongLong = 19,\n-- CXType_Int128 = 20,\n-- CXType_Float = 21,\n-- CXType_Double = 22,\n-- CXType_LongDouble = 23,\n-- CXType_NullPtr = 24,\n-- CXType_Overload = 25,\n-- CXType_Dependent = 26,\n-- CXType_ObjCId = 27,\n-- CXType_ObjCClass = 28,\n-- CXType_ObjCSel = 29,\n-- CXType_FirstBuiltin = CXType_Void,\n-- CXType_LastBuiltin = CXType_ObjCSel,\n-- CXType_Complex = 100,\n-- CXType_Pointer = 101,\n-- CXType_BlockPointer = 102,\n-- CXType_LValueReference = 103,\n-- CXType_RValueReference = 104,\n-- CXType_Record = 105,\n-- CXType_Enum = 106,\n-- CXType_Typedef = 107,\n-- CXType_ObjCInterface = 108,\n-- CXType_ObjCObjectPointer = 109,\n-- CXType_FunctionNoProto = 110,\n-- CXType_FunctionProto = 111\n-- CXType_ConstantArray = 112\n-- CXType_Vector = 113,\n-- CXType_IncompleteArray = 114,\n-- CXType_VariableArray = 115,\n-- CXType_DependentSizedArray = 116,\n-- CXType_MemberPointer = 117\n-- };\n\n#c\nenum TypeKind\n { Type_Invalid = CXType_Invalid\n , Type_Unexposed = CXType_Unexposed\n , Type_Void = CXType_Void\n , Type_Bool = CXType_Bool\n , Type_Char_U = CXType_Char_U\n , Type_UChar = CXType_UChar\n , Type_Char16 = CXType_Char16\n , Type_Char32 = CXType_Char32\n , Type_UShort = CXType_UShort\n , Type_UInt = CXType_UInt\n , Type_ULong = CXType_ULong\n , Type_ULongLong = CXType_ULongLong\n , Type_UInt128 = CXType_UInt128\n , Type_Char_S = CXType_Char_S\n , Type_SChar = CXType_SChar\n , Type_WChar = CXType_WChar\n , Type_Short = CXType_Short\n , Type_Int = CXType_Int\n , Type_Long = CXType_Long\n , Type_LongLong = CXType_LongLong\n , Type_Int128 = CXType_Int128\n , Type_Float = CXType_Float\n , Type_Double = CXType_Double\n , Type_LongDouble = CXType_LongDouble\n , Type_NullPtr = CXType_NullPtr\n , Type_Overload = CXType_Overload\n , Type_Dependent = CXType_Dependent\n , Type_ObjCId = CXType_ObjCId\n , Type_ObjCClass = CXType_ObjCClass\n , Type_ObjCSel = CXType_ObjCSel\n , Type_Complex = CXType_Complex\n , Type_Pointer = CXType_Pointer\n , Type_BlockPointer = CXType_BlockPointer\n , Type_LValueReference = CXType_LValueReference\n , Type_RValueReference = CXType_RValueReference\n , Type_Record = CXType_Record\n , Type_Enum = CXType_Enum\n , Type_Typedef = CXType_Typedef\n , Type_ObjCInterface = CXType_ObjCInterface\n , Type_ObjCObjectPointer = CXType_ObjCObjectPointer\n , Type_FunctionNoProto = CXType_FunctionNoProto\n , Type_FunctionProto = CXType_FunctionProto\n , Type_ConstantArray = CXType_ConstantArray\n , Type_Vector = CXType_Vector\n , Type_IncompleteArray = CXType_IncompleteArray\n , Type_VariableArray = CXType_VariableArray\n , Type_DependentSizedArray = CXType_DependentSizedArray\n , Type_MemberPointer = CXType_MemberPointer\n };\n#endc\n{# enum TypeKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ntype_FirstBuiltin, type_LastBuiltin :: TypeKind\ntype_FirstBuiltin = Type_Void\ntype_LastBuiltin = Type_ObjCSel\n\n-- enum CXCallingConv {\n-- CXCallingConv_Default = 0,\n-- CXCallingConv_C = 1,\n-- CXCallingConv_X86StdCall = 2,\n-- CXCallingConv_X86FastCall = 3,\n-- CXCallingConv_X86ThisCall = 4,\n-- CXCallingConv_X86Pascal = 5,\n-- CXCallingConv_AAPCS = 6,\n-- CXCallingConv_AAPCS_VFP = 7,\n-- CXCallingConv_IntelOclBicc = 9,\n-- CXCallingConv_X86_64Win64 = 10,\n-- CXCallingConv_X86_64SysV = 11,\n-- CXCallingConv_Invalid = 100,\n-- CXCallingConv_Unexposed = 200\n-- };\n#c\nenum CallingConv\n { CallingConv_Default = CXCallingConv_Default\n , CallingConv_C = CXCallingConv_C\n , CallingConv_X86StdCall = CXCallingConv_X86StdCall\n , CallingConv_X86FastCall = CXCallingConv_X86FastCall\n , CallingConv_X86ThisCall = CXCallingConv_X86ThisCall\n , CallingConv_X86Pascal = CXCallingConv_X86Pascal\n , CallingConv_AAPCS = CXCallingConv_AAPCS\n , CallingConv_AAPCS_VFP = CXCallingConv_AAPCS_VFP\n , CallingConv_IntelOclBic = CXCallingConv_IntelOclBicc\n , CallingConv_X86_64Win64 = CXCallingConv_X86_64Win64\n , CallingConv_X86_64SysV = CXCallingConv_X86_64SysV\n , CallingConv_Invalid = CXCallingConv_Invalid\n , CallingConv_Unexposed = CXCallingConv_Unexposed\n };\n#endc\n{# enum CallingConv {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- typedef struct {\n-- enum CXTypeKind kind;\n-- void *data[2];\n-- } CXType;\ndata Type s = Type !TypeKind !(Ptr ()) !(Ptr ())\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue Type\n\ninstance Storable (Type s) where\n sizeOf _ = {#sizeof CXType #}\n {-# INLINE sizeOf #-}\n\n alignment _ = {#alignof CXType #}\n {-# INLINE alignment #-}\n\n peek p = do\n kindCInt <- {#get CXType->kind #} p\n ptrsArray <- {#get CXType->data #} p >>= peekArray 2\n return $! Type (toEnum (fromIntegral kindCInt)) (ptrsArray !! 0) (ptrsArray !! 1)\n {-# INLINE peek #-}\n\n poke p (Type kind p0 p1)= do\n ptrsArray <- mallocArray 2\n pokeArray ptrsArray [p0,p1]\n {#set CXType->kind #} p (fromIntegral (fromEnum kind))\n {#set CXType->data #} p (castPtr ptrsArray)\n {-# INLINE poke #-}\n\ngetTypeKind :: Type s -> TypeKind\ngetTypeKind (Type k _ _) = k\n\n-- CXType clang_getCursorType(CXCursor C);\n{# fun wrapped_clang_getCursorType as clang_getCursorType {withVoided* %`Cursor a' } -> `Ptr (Type s)' castPtr #}\ngetCursorType :: Proxy s -> Cursor s' -> IO (Type s)\ngetCursorType proxy c =\n clang_getCursorType c >>= peek\n\n-- CXString clang_getTypeSpelling(CXType CT);\n{# fun wrapped_clang_getTypeSpelling as clang_getTypeSpelling {withVoided* %`Type a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getTypeSpelling :: (Type s) -> IO (ClangString ())\nunsafe_getTypeSpelling t = do\n cxString <- clang_getTypeSpelling t\n peek cxString\n\ngetTypeSpelling :: ClangBase m => (Type s') -> ClangT s m (ClangString s)\ngetTypeSpelling = registerClangString . unsafe_getTypeSpelling\n\n-- CXType clang_getTypedefDeclUnderlyingType(CXCursor C);\n{# fun wrapped_clang_getTypedefDeclUnderlyingType as clang_getTypedefDeclUnderlyingType {withVoided* %`Cursor a' } -> `Ptr (Type s)' castPtr #}\ngetTypedefDeclUnderlyingType :: Proxy s -> Cursor s' -> IO (Type s)\ngetTypedefDeclUnderlyingType proxy c =\n clang_getTypedefDeclUnderlyingType c >>= peek\n\n-- CXType clang_getEnumDeclIntegerType(CXCursor C);\n{# fun wrapped_clang_getEnumDeclIntegerType as clang_getEnumDeclIntegerType {withVoided* %`Cursor a' } -> `Ptr (Type s)' castPtr #}\ngetEnumDeclIntegerType :: Proxy s -> Cursor s' -> IO (Type s)\ngetEnumDeclIntegerType proxy c =\n clang_getEnumDeclIntegerType c >>= peek\n\n-- long long clang_getEnumConstantDeclValue(CXCursor);\n{# fun clang_getEnumConstantDeclValue {withVoided* %`Cursor a' } -> `Int64' #}\ngetEnumConstantDeclValue :: Cursor s -> IO Int64\ngetEnumConstantDeclValue c = clang_getEnumConstantDeclValue c\n\n-- unsigned long long clang_getEnumConstantDeclUnsignedValue(CXCursor);\n{# fun clang_getEnumConstantDeclUnsignedValue {withVoided* %`Cursor a' } -> `Word64' #}\ngetEnumConstantDeclUnsignedValue :: Cursor s -> IO Word64\ngetEnumConstantDeclUnsignedValue c = clang_getEnumConstantDeclUnsignedValue c\n\n-- int clang_getFieldDeclBitWidth(CXCursor C);\n-- %fun clang_getFieldDeclBitWidth :: Cursor s -> IO Int\n{# fun clang_getFieldDeclBitWidth {withVoided* %`Cursor a' } -> `Int' #}\ngetFieldDeclBitWidth :: Cursor s -> IO Int\ngetFieldDeclBitWidth c = clang_getFieldDeclBitWidth c\n\n-- int clang_Cursor_getNumArguments(CXCursor C);\n{# fun clang_Cursor_getNumArguments {withVoided* %`Cursor a' } -> `Int' #}\ncursor_getNumArguments :: Cursor s -> IO Int\ncursor_getNumArguments c = clang_Cursor_getNumArguments c\n\n-- CXCursor clang_Cursor_getArgument(CXCursor C, unsigned i);\n{# fun wrapped_clang_Cursor_getArgument as clang_Cursor_getArgument {withVoided* %`Cursor a', `Int' } -> `Ptr (Cursor s)' castPtr #}\ncursor_getArgument :: Proxy s -> Cursor s' -> Int -> IO (Cursor s)\ncursor_getArgument _ c i = clang_Cursor_getArgument c i >>= peek\n\n-- unsigned clang_equalTypes(CXType A, CXType B);\n{# fun clang_equalTypes {withVoided* %`Type a',withVoided* %`Type b' } -> `Bool' toBool #}\nequalTypes :: Type s -> Type s' -> IO Bool\nequalTypes t1 t2 = clang_equalTypes t1 t2\n\n-- CXType clang_getCanonicalType(CXType T);\n{# fun wrapped_clang_getCanonicalType as clang_getCanonicalType {withVoided* %`Type a' } -> `Ptr (Type s)' castPtr #}\ngetCanonicalType :: Proxy s -> Type s' -> IO (Type s)\ngetCanonicalType proxy t = do\n cPtr <- clang_getCanonicalType t\n peek cPtr\n\n-- unsigned clang_isConstQualifiedType(CXType T);\n{# fun clang_isConstQualifiedType {withVoided* %`Type a' } -> `Bool' toBool #}\nisConstQualifiedType :: Type s -> IO Bool\nisConstQualifiedType t = clang_isConstQualifiedType t\n\n-- unsigned clang_isVolatileQualifiedType(CXType T);\n{# fun clang_isVolatileQualifiedType {withVoided* %`Type a' } -> `Bool' toBool #}\nisVolatileQualifiedType :: Type s -> IO Bool\nisVolatileQualifiedType t = clang_isVolatileQualifiedType t\n\n-- unsigned clang_isRestrictQualifiedType(CXType T);\n{# fun clang_isRestrictQualifiedType {withVoided* %`Type a' } -> `Bool' toBool #}\nisRestrictQualifiedType :: Type s -> IO Bool\nisRestrictQualifiedType t = clang_isRestrictQualifiedType t\n\n-- CXType clang_getPointeeType(CXType T);\n{# fun wrapped_clang_getPointeeType as clang_getPointeeType { withVoided* %`Type a' } -> `Ptr (Type s)' castPtr #}\ngetPointeeType :: Proxy s -> Type s' -> IO (Type s)\ngetPointeeType proxy t = do\n cPtr <- clang_getPointeeType t\n peek cPtr\n\n-- CXCursor clang_getTypeDeclaration(CXType T);\n{# fun wrapped_clang_getTypeDeclaration as clang_getTypeDeclaration { withVoided* %`Type a' } -> `Ptr (Cursor s)' castPtr #}\ngetTypeDeclaration :: Proxy s -> Type s' -> IO (Cursor s)\ngetTypeDeclaration _ t = do\n cPtr <- clang_getTypeDeclaration t\n peek cPtr\n\n-- CXString clang_getDeclObjCTypeEncoding(CXCursor C);\n{# fun wrapped_clang_getDeclObjCTypeEncoding as clang_getDeclObjCTypeEncoding {withVoided* %`Cursor a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getDeclObjCTypeEncoding :: Cursor s -> IO (ClangString ())\nunsafe_getDeclObjCTypeEncoding c = clang_getDeclObjCTypeEncoding c >>= peek\n\ngetDeclObjCTypeEncoding :: ClangBase m => Cursor s' -> ClangT s m (ClangString s)\ngetDeclObjCTypeEncoding = registerClangString . unsafe_getDeclObjCTypeEncoding\n\n-- CXString clang_getTypeKindSpelling(enum CXTypeKind K);\n{# fun wrapped_clang_getTypeKindSpelling as clang_getTypeKindSpelling { `CInt' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getTypeKindSpelling :: TypeKind -> IO (ClangString ())\nunsafe_getTypeKindSpelling tk = clang_getTypeKindSpelling (fromIntegral (fromEnum tk)) >>= peek\n\ngetTypeKindSpelling :: ClangBase m => TypeKind -> ClangT s m (ClangString s)\ngetTypeKindSpelling = registerClangString . unsafe_getTypeKindSpelling\n\n-- enum CXCallingConv clang_getFunctionTypeCallingConv(CXType T);\n{# fun clang_getFunctionTypeCallingConv { withVoided* %`Type a' } -> `CInt' id #}\ngetFunctionTypeCallingConv :: Type s' -> IO CallingConv\ngetFunctionTypeCallingConv t = clang_getFunctionTypeCallingConv t >>= return . toEnum . fromIntegral\n\n-- CXType clang_getResultType(CXType T);\n{# fun wrapped_clang_getResultType as clang_getResultType { withVoided* %`Type a' } -> `Ptr (Type s)' castPtr #}\ngetResultType :: Proxy s -> Type s' -> IO (Type s)\ngetResultType proxy t = clang_getResultType t >>= peek\n\n-- CXType clang_getNumArgTypes(CXType T);\n{# fun clang_getNumArgTypes { withVoided* %`Type a' } -> `Int' #}\ngetNumArgTypes :: Type s -> IO Int\ngetNumArgTypes t = clang_getNumArgTypes t\n\n-- CXType clang_getArgType(CXType T, int i);\n{# fun wrapped_clang_getArgType as clang_getArgType { withVoided* %`Type a', `Int' } -> `Ptr (Type s)' castPtr #}\ngetArgType :: Proxy s -> Type s' -> Int -> IO (Type s)\ngetArgType proxy t i = clang_getArgType t i >>= peek\n\n-- unsigned clang_isFunctionTypeVariadic(CXType T);\n{# fun clang_isFunctionTypeVariadic { withVoided* %`Type a' } -> `CUInt' id #}\nisFunctionTypeVariadic :: Type s -> IO Bool\nisFunctionTypeVariadic t = clang_isFunctionTypeVariadic t >>= return . (toBool :: Int -> Bool) . fromIntegral\n\n-- CXType clang_getCursorResultType(CXCursor C);\n{# fun wrapped_clang_getCursorResultType as clang_getCursorResultType {withVoided* %`Cursor a' } -> `Ptr (Type s)' castPtr #}\ngetCursorResultType :: Proxy s -> Cursor s' -> IO (Type s)\ngetCursorResultType p c = clang_getCursorResultType c >>= peek\n\n-- unsigned clang_isPODType(CXType T);\n{# fun clang_isPODType {withVoided* %`Type a' } -> `Bool' toBool #}\nisPODType :: Type s -> IO Bool\nisPODType t = clang_isPODType t\n\n-- CXType clang_getElementType(CXType T);\n{# fun wrapped_clang_getElementType as clang_getElementType { withVoided* %`Type a' } -> `Ptr (Type s)' castPtr #}\ngetElementType :: Proxy s -> Type s' -> IO (Type s)\ngetElementType proxy t = clang_getElementType t >>= peek\n\n-- long long clang_getNumElements(CXType T);\n{# fun clang_getNumElements { withVoided* %`Type a' } -> `Int64' #}\ngetNumElements :: Type s -> IO Int64\ngetNumElements t = clang_getNumElements t\n\n-- CXType clang_getArrayElementType(CXType T);\n{# fun wrapped_clang_getArrayElementType as clang_getArrayElementType { withVoided* %`Type a' } -> `Ptr (Type s)' castPtr #}\ngetArrayElementType :: Proxy s -> Type s' -> IO (Type s)\ngetArrayElementType proxy t = clang_getArrayElementType t >>= peek\n\n-- long long clang_getArraySize(CXType T);\n{# fun clang_getArraySize { withVoided* %`Type a' } -> `Int64' #}\ngetArraySize :: Type s -> IO Int64\ngetArraySize t = clang_getArraySize t\n\n-- enum CXTypeLayoutError {\n-- CXTypeLayoutError_Invalid = -1,\n-- CXTypeLayoutError_Incomplete = -2,\n-- CXTypeLayoutError_Dependent = -3,\n-- CXTypeLayoutError_NotConstantSize = -4,\n-- CXTypeLayoutError_InvalidFieldName = -5\n-- };\n#c\nenum TypeLayoutError\n { TypeLayoutError_Invalid = CXTypeLayoutError_Invalid\n , TypeLayoutError_Incomplete = CXTypeLayoutError_Incomplete\n , TypeLayoutError_Dependent = CXTypeLayoutError_Dependent\n , TypeLayoutError_NotConstantSize = CXTypeLayoutError_NotConstantSize\n , TypeLayoutError_InvalidFieldName = CXTypeLayoutError_InvalidFieldName\n };\n#endc\n{# enum TypeLayoutError {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\nint64OrLayoutError :: Int64 -> Either TypeLayoutError Int64\nint64OrLayoutError v | v == -1 = Left TypeLayoutError_Invalid\n | v == -2 = Left TypeLayoutError_Incomplete\n | v == -3 = Left TypeLayoutError_Dependent\n | v == -4 = Left TypeLayoutError_NotConstantSize\n | v == -5 = Left TypeLayoutError_InvalidFieldName\n | otherwise = Right v\n\n-- long long clang_Type_getAlignOf(CXType T);\n{# fun clang_Type_getAlignOf { withVoided* %`Type a' } -> `Int64' #}\ntype_getAlignOf :: Type s -> IO (Either TypeLayoutError Int64)\ntype_getAlignOf t = clang_Type_getAlignOf t >>= return . int64OrLayoutError\n\n-- CXType clang_Type_getClassType(CXType T);\n{# fun wrapped_clang_Type_getClassType as clang_Type_getClassType { withVoided* %`Type a' } -> `Ptr (Type s)' castPtr #}\ntype_getClassType :: Proxy s -> Type s' -> IO (Type s)\ntype_getClassType proxy t = clang_getElementType t >>= peek\n\n-- long long clang_Type_getSizeOf(CXType T);\n{# fun clang_Type_getSizeOf { withVoided* %`Type a' } -> `Int64' #}\ntype_getSizeOf :: Type s -> IO (Either TypeLayoutError Int64)\ntype_getSizeOf t = clang_Type_getSizeOf t >>= return . int64OrLayoutError\n\n-- long long clang_Type_getOffsetOf(CXType T, const char *S);\n{# fun clang_Type_getOffsetOf { withVoided* %`Type a' , `CString' } -> `Int64' #}\nunsafe_Type_getOffsetOf :: Type s -> CString -> IO (Either TypeLayoutError Int64)\nunsafe_Type_getOffsetOf t s = clang_Type_getOffsetOf t s >>= return . int64OrLayoutError\n\ntype_getOffsetOf :: ClangBase m => Type s' -> B.ByteString\n -> ClangT s m (Either TypeLayoutError Int64)\ntype_getOffsetOf t field = liftIO $ B.useAsCString field $ \\cField ->\n unsafe_Type_getOffsetOf t cField\n\n-- enum CXRefQualifierKind {\n-- CXRefQualifier_None = 0,\n-- CXRefQualifier_LValue,\n-- CXRefQualifier_RValue\n-- };\n#c\nenum RefQualifierKind\n { RefQualifier_None = CXRefQualifier_None\n , RefQualifier_LValue = CXRefQualifier_LValue\n , RefQualifier_RValue = CXRefQualifier_RValue\n };\n#endc\n{# enum RefQualifierKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- enum CXRefQualifierKind clang_Type_getCXXRefQualifier(CXType T);\n{# fun clang_Type_getCXXRefQualifier { withVoided* %`Type a' } -> `Int' #}\ntype_getCXXRefQualifier :: Type s -> IO RefQualifierKind\ntype_getCXXRefQualifier t = clang_Type_getCXXRefQualifier t >>= return . toEnum\n\n\n-- unsigned clang_Cursor_isBitField(CXCursor C);\n{# fun clang_Cursor_isBitField {withVoided* %`Cursor a' } -> `Bool' toBool #}\nisBitField :: Cursor s -> IO Bool\nisBitField c = clang_Cursor_isBitField c\n\n-- unsigned clang_isVirtualBase(CXCursor);\n{# fun clang_isVirtualBase {withVoided* %`Cursor a' } -> `Bool' toBool #}\nisVirtualBase :: Cursor s -> IO Bool\nisVirtualBase c = clang_Cursor_isBitField c\n\n-- enum CX_CXXAccessSpecifier {\n-- CX_CXXInvalidAccessSpecifier,\n-- CX_CXXPublic,\n-- CX_CXXProtected,\n-- CX_CXXPrivate\n-- };\n#c\nenum CXXAccessSpecifier\n { CXXInvalidAccessSpecifier = CX_CXXInvalidAccessSpecifier\n , CXXPublic = CX_CXXPublic\n , CXXProtected = CX_CXXProtected\n , CXXPrivate = CX_CXXPrivate\n };\n#endc\n\n{# enum CXXAccessSpecifier {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- enum CX_CXXAccessSpecifier clang_getCXXAccessSpecifier(CXCursor);\n{# fun clang_getCXXAccessSpecifier {withVoided* %`Cursor a' } -> `Int' #}\ngetCXXAccessSpecifier :: Cursor s -> IO CXXAccessSpecifier\ngetCXXAccessSpecifier c = clang_getCXXAccessSpecifier c >>= return . toEnum\n\n-- unsigned clang_getNumOverloadedDecls(CXCursor cursor);\n{# fun clang_getNumOverloadedDecls {withVoided* %`Cursor a' } -> `CUInt' #}\ngetNumOverloadedDecls :: Cursor s -> IO Int\ngetNumOverloadedDecls c = clang_getNumOverloadedDecls c >>= return . fromIntegral\n\n-- CXCursor clang_getOverloadedDecl(CXCursor cursor,\n-- unsigned index);\n{# fun wrapped_clang_getOverloadedDecl as clang_getOverloadedDecl {withVoided* %`Cursor a', `Int' } -> `Ptr (Cursor s)' castPtr #}\ngetOverloadedDecl :: Proxy s -> Cursor s' -> Int -> IO (Cursor s)\ngetOverloadedDecl _ c i = clang_getOverloadedDecl c i >>= peek\n\n-- CXType clang_getIBOutletCollectionType(CXCursor);\n{# fun wrapped_clang_getIBOutletCollectionType as clang_getIBOutletCollectionType {withVoided* %`Cursor a' } -> `Ptr (Type s)' castPtr #}\ngetIBOutletCollectionType :: Proxy s -> Cursor s' -> IO (Type s)\ngetIBOutletCollectionType proxy c = clang_getIBOutletCollectionType c >>= peek\n\n\n-- We deliberately don't export the constructor for UnsafeCursorList.\n-- The only way to unwrap it is registerCursorList.\ntype CursorList s = DVS.Vector (Cursor s)\ninstance ClangValueList Cursor\ndata UnsafeCursorList = UnsafeCursorList !(Ptr ()) !Int\n\n-- void freeCursorList(CXCursor* cursors);\n{# fun freeCursorList as freeCursorList' { id `Ptr ()' } -> `()' #}\nfreeCursorList :: CursorList s -> IO ()\nfreeCursorList cl = let (ptr, _) = fromCursorList cl in freeCursorList' ptr\n\nregisterCursorList :: ClangBase m => IO UnsafeCursorList -> ClangT s m (CursorList s)\nregisterCursorList action = do\n (_, cursorList) <- clangAllocate (action >>= cursorListToVector) freeCursorList\n return cursorList\n{-# INLINEABLE registerCursorList #-}\n\ncursorListToVector :: Storable a => UnsafeCursorList -> IO (DVS.Vector a)\ncursorListToVector (UnsafeCursorList cs n) = do\n fptr <- newForeignPtr_ (castPtr cs)\n return $ DVS.unsafeFromForeignPtr fptr 0 n\n{-# INLINE cursorListToVector #-}\n\nfromCursorList :: CursorList s -> (Ptr (), Int)\nfromCursorList cs = let (p, _, _) = DVS.unsafeToForeignPtr cs in\n (castPtr $ Foreign.ForeignPtr.Unsafe.unsafeForeignPtrToPtr p, DVS.length cs)\n\ntoCursorList :: (Ptr (), Int) -> UnsafeCursorList\ntoCursorList (cs, n) = UnsafeCursorList cs n\n\n-- A more efficient alternative to clang_visitChildren.\n-- void getChildren(CXCursor parent, CXCursor** childrenOut, unsigned* countOut)\n{# fun getChildren as getChildren' {withVoided* %`Cursor a', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getChildren :: Cursor s -> IO UnsafeCursorList\nunsafe_getChildren c =\n do\n cxListPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr ()))))\n n <- getChildren' c cxListPtr\n cxList <- peek cxListPtr\n free cxListPtr\n return (toCursorList (cxList, fromIntegral n))\n\ngetChildren :: ClangBase m => Cursor s' -> ClangT s m (CursorList s)\ngetChildren = registerCursorList . unsafe_getChildren\n\n-- Like getChildren, but gets all transitive descendants.\n-- void getDescendants(CXCursor parent, CXCursor** childrenOut, unsigned* countOut)\n{# fun getDescendants as getDescendants' {withVoided* %`Cursor a', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getDescendants :: Cursor s -> IO UnsafeCursorList\nunsafe_getDescendants c =\n do\n cxListPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Cursor s))))\n n <- getDescendants' c cxListPtr\n cxList <- peek cxListPtr\n free cxListPtr\n return (toCursorList (cxList, fromIntegral n))\n\ngetDescendants :: ClangBase m => Cursor s' -> ClangT s m (CursorList s)\ngetDescendants = registerCursorList . unsafe_getDescendants\n\n-- void getDeclarations(CXTranslationUnit tu, CXCursor** declsOut, unsigned* declCountOut);\n{# fun getDeclarations as getDeclarations' { id `Ptr ()', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getDeclarations :: TranslationUnit s -> IO UnsafeCursorList\nunsafe_getDeclarations t = do\n cxListPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr (Cursor ())))))\n n <- getDeclarations' (unTranslationUnit t) cxListPtr\n cxList <- peek cxListPtr\n free cxListPtr\n return (toCursorList (cxList, fromIntegral n))\n\ngetDeclarations :: ClangBase m => TranslationUnit s' -> ClangT s m (CursorList s)\ngetDeclarations = registerCursorList . unsafe_getDeclarations\n\n-- void getReferences(CXTranslationUnit tu, CXCursor** declsOut, unsigned* declCountOut);\n{# fun getReferences as getReferences' { id `Ptr ()', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getReferences :: TranslationUnit s -> IO UnsafeCursorList\nunsafe_getReferences t = do\n cxListPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr ()))))\n n <- getReferences' (unTranslationUnit t) cxListPtr\n cxList <- peek cxListPtr\n free cxListPtr\n return (toCursorList (cxList, fromIntegral n))\n\ngetReferences :: ClangBase m => TranslationUnit s' -> ClangT s m (CursorList s)\ngetReferences = registerCursorList . unsafe_getReferences\n\n-- void getDeclarationsAndReferences(CXTranslationUnit tu,\n-- CXCursor** declsOut, unsigned* declCountOut,\n-- CXCursor** refsOut, unsigned* refCountOut);\n{# fun getDeclarationsAndReferences as getDeclarationsAndReferences'\n { id `Ptr ()', id `Ptr (Ptr ())', alloca- `CUInt' peek*, id `Ptr (Ptr ())' , alloca- `CUInt' peek* } -> `()' #}\nunsafe_getDeclarationsAndReferences :: TranslationUnit s -> IO (UnsafeCursorList, UnsafeCursorList)\nunsafe_getDeclarationsAndReferences t =\n alloca (\\(declsPtr :: Ptr (Ptr ())) ->\n alloca (\\(refsPtr :: Ptr (Ptr ())) -> do\n (nDecls, nRefs) <- getDeclarationsAndReferences' (unTranslationUnit t) (castPtr declsPtr) (castPtr refsPtr)\n decls <- peek declsPtr\n refs <- peek refsPtr\n return ((toCursorList (decls, fromIntegral nDecls)), (toCursorList (refs, fromIntegral nRefs)))))\n\n-- %fun unsafe_getDeclarationsAndReferences :: TranslationUnit s -> IO (UnsafeCursorList, UnsafeCursorList)\n-- %call (translationUnit t)\n-- %code CXCursor* decls; unsigned declCount;\n-- % CXCursor* refs; unsigned refCount;\n-- % getDeclarationsAndReferences(t, &decls, &declCount, &refs, &refCount);\n-- %result (cursorList decls declCount, cursorList refs refCount)\n\ngetDeclarationsAndReferences :: ClangBase m => TranslationUnit s'\n -> ClangT s m (CursorList s, CursorList s)\ngetDeclarationsAndReferences tu = do\n (ds, rs) <- liftIO $ unsafe_getDeclarationsAndReferences tu\n (,) <$> registerCursorList (return ds) <*> registerCursorList (return rs)\n\ndata ParentedCursor s = ParentedCursor\n { parentCursor :: !(Cursor s)\n , childCursor :: !(Cursor s)\n } deriving (Eq, Ord, Typeable)\n\ninstance ClangValue ParentedCursor\n\ninstance Storable (ParentedCursor s) where\n sizeOf _ = sizeOfParentedCursor\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfParentedCursor\n {-# INLINE alignment #-}\n\n peek p = do\n parent <- peekByteOff p offsetParentedCursorParent\n child <- peekByteOff p offsetParentedCursorCursor\n return $! ParentedCursor parent child\n {-# INLINE peek #-}\n\n poke p (ParentedCursor parent child) = do\n pokeByteOff p offsetParentedCursorParent parent\n pokeByteOff p offsetParentedCursorCursor child\n {-# INLINE poke #-}\n\n-- We deliberately don't export the constructor for UnsafeParentedCursorList.\n-- The only way to unwrap it is registerParentedCursorList.\ntype ParentedCursorList s = DVS.Vector (ParentedCursor s)\ninstance ClangValueList ParentedCursor\ndata UnsafeParentedCursorList = UnsafeParentedCursorList !(Ptr ()) !Int\n\n-- void freeParentedCursorList(struct ParentedCursor* parentedCursors);\n{# fun freeParentedCursorList as freeParentedCursorList' { id `Ptr ()' } -> `()' #}\nfreeParentedCursorList :: ParentedCursorList s -> IO ()\nfreeParentedCursorList pcl = let (pclPtr, _ ) = fromParentedCursorList pcl in freeParentedCursorList' pclPtr\n\nregisterParentedCursorList :: ClangBase m => IO UnsafeParentedCursorList\n -> ClangT s m (ParentedCursorList s)\nregisterParentedCursorList action = do\n (_, pcList) <- clangAllocate (action >>= mkSafe) freeParentedCursorList\n return pcList\n where\n mkSafe (UnsafeParentedCursorList cs n) = do\n fptr <- newForeignPtr_ (castPtr cs)\n return $ DVS.unsafeFromForeignPtr fptr 0 n\n{-# INLINEABLE registerParentedCursorList #-}\n\nfromParentedCursorList :: ParentedCursorList s -> (Ptr (), Int)\nfromParentedCursorList cs =\n let (p, _, _) = DVS.unsafeToForeignPtr cs in\n (castPtr $ Foreign.ForeignPtr.Unsafe.unsafeForeignPtrToPtr p, DVS.length cs)\n\ntoParentedCursorList :: (Ptr (), Int) -> UnsafeParentedCursorList\ntoParentedCursorList (cs, n) = UnsafeParentedCursorList cs n\n\n-- %dis parentedCursorList cs n = (ptr cs) (int n)\n\n-- Like getParentedDescendants, but pairs each descendant with its parent.\n-- void getParentedDescendants(CXCursor parent, struct ParentedCursor** descendantsOut,\n-- unsigned* countOut)\n{# fun getParentedDescendants as getParentedDescendants' {withVoided* %`Cursor a', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getParentedDescendants :: Cursor s -> IO UnsafeParentedCursorList\nunsafe_getParentedDescendants c =\n do\n cxListPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr ()))))\n n <- getParentedDescendants' c cxListPtr\n cxList <- peek cxListPtr\n free cxListPtr\n return (toParentedCursorList (cxList, fromIntegral n))\n\ngetParentedDescendants :: ClangBase m => Cursor s' -> ClangT s m (ParentedCursorList s)\ngetParentedDescendants = registerParentedCursorList . unsafe_getParentedDescendants\n\n-- void getParentedDeclarations(CXTranslationUnit tu, CXCursor** declsOut, unsigned* declCountOut);\n{# fun getParentedDeclarations as getParentedDeclarations' { id `Ptr ()', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getParentedDeclarations :: TranslationUnit s -> IO UnsafeParentedCursorList\nunsafe_getParentedDeclarations t = do\n cxListPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr (Cursor ())))))\n n <- getParentedDeclarations' (unTranslationUnit t) (castPtr cxListPtr)\n cxList <- peek cxListPtr\n free cxListPtr\n return (toParentedCursorList (cxList, fromIntegral n))\n\ngetParentedDeclarations :: ClangBase m => TranslationUnit s' -> ClangT s m (ParentedCursorList s)\ngetParentedDeclarations = registerParentedCursorList . unsafe_getParentedDeclarations\n\n-- void getParentedReferences(CXTranslationUnit tu, CXCursor** declsOut, unsigned* declCountOut);\n{# fun getParentedReferences as getParentedReferences' { id `Ptr ()', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getParentedReferences :: TranslationUnit s -> IO UnsafeParentedCursorList\nunsafe_getParentedReferences t = do\n cxListPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr ()))))\n n <- getParentedReferences' (unTranslationUnit t) cxListPtr\n cxList <- peek cxListPtr\n free cxListPtr\n return (toParentedCursorList (cxList, fromIntegral n))\n\ngetParentedReferences :: ClangBase m => TranslationUnit s' -> ClangT s m (ParentedCursorList s)\ngetParentedReferences = registerParentedCursorList . unsafe_getParentedReferences\n\n-- void getParentedDeclarationsAndReferences(CXTranslationUnit tu,\n-- ParentedCursor** declsOut,\n-- unsigned* declCountOut,\n-- ParentedCursor** refsOut,\n-- unsigned* refCountOut);\n{# fun getParentedDeclarationsAndReferences as getParentedDeclarationsAndReferences'\n { id `Ptr ()', id `Ptr (Ptr ())', alloca- `CUInt' peek*, id `Ptr (Ptr ())' , alloca- `CUInt' peek* } -> `()' #}\nunsafe_getParentedDeclarationsAndReferences :: TranslationUnit s -> IO (UnsafeParentedCursorList, UnsafeParentedCursorList)\nunsafe_getParentedDeclarationsAndReferences t = do\n declsPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr ()))))\n refsPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr ()))))\n (nDecls, nRefs) <- getParentedDeclarationsAndReferences' (unTranslationUnit t) declsPtr refsPtr\n decls <- peek declsPtr\n refs <- peek refsPtr\n free declsPtr\n free refsPtr\n return ((toParentedCursorList (decls, fromIntegral nDecls)), (toParentedCursorList (refs, fromIntegral nRefs)))\n\ngetParentedDeclarationsAndReferences :: ClangBase m => TranslationUnit s'\n -> ClangT s m (ParentedCursorList s, ParentedCursorList s)\ngetParentedDeclarationsAndReferences tu = do\n (ds, rs) <- liftIO $ unsafe_getParentedDeclarationsAndReferences tu\n (,) <$> registerParentedCursorList (return ds) <*> registerParentedCursorList (return rs)\n\n-- CXString clang_getCursorUSR(CXCursor);\n{# fun wrapped_clang_getCursorUSR as clang_getCursorUSR {withVoided* %`Cursor a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCursorUSR :: Cursor s -> IO (ClangString ())\nunsafe_getCursorUSR c =\n clang_getCursorUSR c >>= peek\n\ngetCursorUSR :: ClangBase m => Cursor s' -> ClangT s m (ClangString s)\ngetCursorUSR = registerClangString . unsafe_getCursorUSR\n\n-- CXString clang_constructUSR_ObjCClass(const char *class_name);\n{# fun wrapped_clang_constructUSR_ObjCClass as clang_constructUSR_ObjCClass { `CString' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_constructUSR_ObjCClass :: String -> IO (ClangString ())\nunsafe_constructUSR_ObjCClass s = withCString s (\\sPtr -> clang_constructUSR_ObjCClass sPtr >>= peek)\n\nconstructUSR_ObjCClass :: ClangBase m => String -> ClangT s m (ClangString s)\nconstructUSR_ObjCClass = registerClangString . unsafe_constructUSR_ObjCClass\n\n-- CXString\n-- clang_constructUSR_ObjCCategory(const char *class_name,\n-- const char *category_name);\n{# fun wrapped_clang_constructUSR_ObjCCategory as clang_constructUSR_ObjCCategory { `CString', `CString' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_constructUSR_ObjCCategory :: String -> String -> IO (ClangString ())\nunsafe_constructUSR_ObjCCategory s p =\n withCString s (\\sPtr ->\n withCString p (\\pPtr ->\n clang_constructUSR_ObjCCategory sPtr pPtr >>= peek))\n\nconstructUSR_ObjCCategory :: ClangBase m => String -> String -> ClangT s m (ClangString s)\nconstructUSR_ObjCCategory = (registerClangString .) . unsafe_constructUSR_ObjCCategory\n\n-- CXString\n-- clang_constructUSR_ObjCProtocol(const char *protocol_name);\n{# fun wrapped_clang_constructUSR_ObjCProtocol as clang_constructUSR_ObjCProtocol { `CString' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_constructUSR_ObjCProtocol :: String -> IO (ClangString ())\nunsafe_constructUSR_ObjCProtocol s = withCString s (\\sPtr -> clang_constructUSR_ObjCProtocol sPtr >>= peek)\n\nconstructUSR_ObjCProtocol :: ClangBase m => String -> ClangT s m (ClangString s)\nconstructUSR_ObjCProtocol = registerClangString . unsafe_constructUSR_ObjCProtocol\n\n-- CXString clang_constructUSR_ObjCIvar(const char *name,\n-- CXString classUSR);\n{# fun wrapped_clang_constructUSR_ObjCIvar as clang_constructUSR_ObjCIvar { `CString' , id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_constructUSR_ObjCIvar :: String -> Ptr () -> Word32 -> IO (ClangString ())\nunsafe_constructUSR_ObjCIvar s d f =\n let clangString = ClangString d f in\n withCString s (\\sPtr -> new clangString >>= \\cs -> clang_constructUSR_ObjCIvar sPtr (castPtr cs) >>= peek)\n\nconstructUSR_ObjCIvar :: ClangBase m => String -> ClangString s' -> ClangT s m (ClangString s)\nconstructUSR_ObjCIvar s (ClangString d f) = registerClangString $ unsafe_constructUSR_ObjCIvar s d f\n\n-- CXString clang_constructUSR_ObjCMethod(const char *name,\n-- unsigned isInstanceMethod,\n-- CXString classUSR);\n{# fun wrapped_clang_constructUSR_ObjCMethod as clang_constructUSR_ObjCMethod { `CString' , `CUInt' , id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_constructUSR_ObjCMethod :: String -> Bool -> Ptr () -> Word32 -> IO (ClangString ())\nunsafe_constructUSR_ObjCMethod s b d f =\n let clangString = ClangString d f in\n withCString s (\\sPtr -> (new clangString >>= \\cs -> clang_constructUSR_ObjCMethod sPtr (fromIntegral ((fromBool b) :: Int)) (castPtr cs) >>= peek))\n\nconstructUSR_ObjCMethod :: ClangBase m => String -> Bool -> ClangString s' -> ClangT s m (ClangString s)\nconstructUSR_ObjCMethod s b (ClangString d f) =\n registerClangString $ unsafe_constructUSR_ObjCMethod s b d f\n\n-- CXString clang_constructUSR_ObjCProperty(const char *property,\n-- CXString classUSR);\n{# fun wrapped_clang_constructUSR_ObjCProperty as clang_constructUSR_ObjCProperty { `CString' , id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_constructUSR_ObjCProperty :: String -> Ptr () -> Word32 -> IO (ClangString ())\nunsafe_constructUSR_ObjCProperty s d f =\n let clangString = ClangString d f in\n withCString s (\\sPtr -> (new clangString >>= \\cs -> clang_constructUSR_ObjCProperty sPtr (castPtr cs) >>= peek))\n\nconstructUSR_ObjCProperty :: ClangBase m => String -> ClangString s' -> ClangT s m (ClangString s)\nconstructUSR_ObjCProperty s (ClangString d f) =\n registerClangString $ unsafe_constructUSR_ObjCProperty s d f\n\n-- CXString clang_getCursorSpelling(CXCursor);\n{# fun wrapped_clang_getCursorSpelling as clang_getCursorSpelling {withVoided* %`Cursor a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCursorSpelling :: Cursor s -> IO (ClangString ())\nunsafe_getCursorSpelling c =\n clang_getCursorSpelling c >>= peek\n\ngetCursorSpelling :: ClangBase m => Cursor s' -> ClangT s m (ClangString s)\ngetCursorSpelling = registerClangString . unsafe_getCursorSpelling\n\n-- CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor,\n-- unsigned pieceIndex,\n-- unsigned options);\n{# fun wrapped_clang_Cursor_getSpellingNameRange as clang_Cursor_getSpellingNameRange {withVoided* %`Cursor a', `Int', `Int' } -> `Ptr (SourceRange s)' castPtr #}\ncursor_getSpellingNameRange :: Proxy s -> Cursor s' -> Int -> IO (SourceRange s)\ncursor_getSpellingNameRange _ c i = clang_Cursor_getSpellingNameRange c i 0 >>= peek\n\n-- CXString clang_getCursorDisplayName(CXCursor);\n{# fun wrapped_clang_getCursorDisplayName as clang_getCursorDisplayName {withVoided* %`Cursor a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCursorDisplayName :: Cursor s -> IO (ClangString ())\nunsafe_getCursorDisplayName c =\n clang_getCursorDisplayName c >>= peek\n\ngetCursorDisplayName :: ClangBase m => Cursor s' -> ClangT s m (ClangString s)\ngetCursorDisplayName = registerClangString . unsafe_getCursorDisplayName\n\n-- CXCursor clang_getCursorReferenced(CXCursor);\n{# fun wrapped_clang_getCursorReferenced as clang_getCursorReferenced {withVoided* %`Cursor a' } -> `Ptr (Cursor s)' castPtr #}\ngetCursorReferenced :: Proxy s -> Cursor s' -> IO (Cursor s)\ngetCursorReferenced _ c =\n clang_getCursorReferenced c >>= peek\n\n-- CXCursor clang_getCursorDefinition(CXCursor);\n{# fun wrapped_clang_getCursorDefinition as clang_getCursorDefinition {withVoided* %`Cursor a' } -> `Ptr (Cursor s)' castPtr #}\ngetCursorDefinition :: Proxy s -> Cursor s' -> IO (Cursor s)\ngetCursorDefinition _ c = clang_getCursorDefinition c >>= peek\n\n-- unsigned clang_isCursorDefinition(CXCursor);\n{# fun clang_isCursorDefinition {withVoided* %`Cursor a' } -> `Bool' toBool #}\nisCursorDefinition :: Cursor s -> IO Bool\nisCursorDefinition c = clang_isCursorDefinition c\n\n-- unsigned clang_Cursor_isDynamicCall(CXCursor);\n{# fun clang_Cursor_isDynamicCall {withVoided* %`Cursor a' } -> `Bool' toBool #}\ncursor_isDynamicCall :: Cursor s -> IO Bool\ncursor_isDynamicCall c = clang_Cursor_isDynamicCall c\n\n-- CXCursor clang_getCanonicalCursor(CXCursor);\n{# fun wrapped_clang_getCanonicalCursor as clang_getCanonicalCursor {withVoided* %`Cursor a' } -> `Ptr (Cursor s)' castPtr #}\ngetCanonicalCursor :: Proxy s -> Cursor s' -> IO (Cursor s)\ngetCanonicalCursor _ c =\n clang_getCanonicalCursor c >>= peek\n\n-- int clang_Cursor_getObjCSelectorIndex(CXCursor);\n{# fun clang_Cursor_getObjCSelectorIndex {withVoided* %`Cursor a' } -> `Int' #}\ncursor_getObjCSelectorIndex :: Cursor s -> IO Int\ncursor_getObjCSelectorIndex c = clang_Cursor_getObjCSelectorIndex c\n\n-- CXType clang_Cursor_getReceiverType(CXCursor C);\n{# fun wrapped_clang_Cursor_getReceiverType as clang_Cursor_getReceiverType {withVoided* %`Cursor a' } -> `Ptr (Type s)' castPtr #}\ncursor_getReceiverType :: Proxy s -> Cursor s' -> IO (Type s)\ncursor_getReceiverType proxy c =\n clang_Cursor_getReceiverType c >>= peek\n\n-- typedef enum {\n-- CXObjCPropertyAttr_noattr = 0x00,\n-- CXObjCPropertyAttr_readonly = 0x01,\n-- CXObjCPropertyAttr_getter = 0x02,\n-- CXObjCPropertyAttr_assign = 0x04,\n-- CXObjCPropertyAttr_readwrite = 0x08,\n-- CXObjCPropertyAttr_retain = 0x10,\n-- CXObjCPropertyAttr_copy = 0x20,\n-- CXObjCPropertyAttr_nonatomic = 0x40,\n-- CXObjCPropertyAttr_setter = 0x80,\n-- CXObjCPropertyAttr_atomic = 0x100,\n-- CXObjCPropertyAttr_weak = 0x200,\n-- CXObjCPropertyAttr_strong = 0x400,\n-- CXObjCPropertyAttr_unsafe_unretained = 0x800\n-- } CXObjCPropertyAttrKind;\n\n#c\nenum ObjCPropertyAttrKind\n { ObjCPropertyAttr_noattr = CXObjCPropertyAttr_noattr\n , ObjCPropertyAttr_readonly = CXObjCPropertyAttr_readonly\n , ObjCPropertyAttr_getter = CXObjCPropertyAttr_getter\n , ObjCPropertyAttr_assign = CXObjCPropertyAttr_assign\n , ObjCPropertyAttr_readwrite = CXObjCPropertyAttr_readwrite\n , ObjCPropertyAttr_retain = CXObjCPropertyAttr_retain\n , ObjCPropertyAttr_copy = CXObjCPropertyAttr_copy\n , ObjCPropertyAttr_nonatomic = CXObjCPropertyAttr_nonatomic\n , ObjCPropertyAttr_setter = CXObjCPropertyAttr_setter\n , ObjCPropertyAttr_atomic = CXObjCPropertyAttr_atomic\n , ObjCPropertyAttr_weak = CXObjCPropertyAttr_weak\n , ObjCPropertyAttr_strong = CXObjCPropertyAttr_strong\n , ObjCPropertyAttr_unsafe_unretained= CXObjCPropertyAttr_unsafe_unretained\n };\n#endc\n{# enum ObjCPropertyAttrKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags ObjCPropertyAttrKind where\n toBit ObjCPropertyAttr_noattr = 0x0\n toBit ObjCPropertyAttr_readonly = 0x1\n toBit ObjCPropertyAttr_getter = 0x2\n toBit ObjCPropertyAttr_assign = 0x4\n toBit ObjCPropertyAttr_readwrite = 0x8\n toBit ObjCPropertyAttr_retain = 0x10\n toBit ObjCPropertyAttr_copy = 0x20\n toBit ObjCPropertyAttr_nonatomic = 0x40\n toBit ObjCPropertyAttr_setter = 0x80\n toBit ObjCPropertyAttr_atomic = 0x100\n toBit ObjCPropertyAttr_weak = 0x200\n toBit ObjCPropertyAttr_strong = 0x400\n toBit ObjCPropertyAttr_unsafe_unretained = 0x800\n\n-- unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved);\n{# fun clang_Cursor_getObjCPropertyAttributes {withVoided* %`Cursor a', `Int' } -> `CUInt' #}\ncursor_getObjCPropertyAttributes :: Cursor s -> IO Int\ncursor_getObjCPropertyAttributes c = clang_Cursor_getObjCPropertyAttributes c 0 >>= return . fromIntegral\n\n-- typedef enum {\n-- CXObjCDeclQualifier_None = 0x0,\n-- CXObjCDeclQualifier_In = 0x1,\n-- CXObjCDeclQualifier_Inout = 0x2,\n-- CXObjCDeclQualifier_Out = 0x4,\n-- CXObjCDeclQualifier_Bycopy = 0x8,\n-- CXObjCDeclQualifier_Byref = 0x10,\n-- CXObjCDeclQualifier_Oneway = 0x20\n-- } CXObjCDeclQualifierKind;\n\n#c\nenum ObjCDeclQualifierKind\n { ObjCDeclQualifier_None = CXObjCDeclQualifier_None\n , ObjCDeclQualifier_In = CXObjCDeclQualifier_In\n , ObjCDeclQualifier_Inout = CXObjCDeclQualifier_Inout\n , ObjCDeclQualifier_Out = CXObjCDeclQualifier_Out\n , ObjCDeclQualifier_Bycopy = CXObjCDeclQualifier_Bycopy\n , ObjCDeclQualifier_Byref = CXObjCDeclQualifier_Byref\n , ObjCDeclQualifier_Oneway = CXObjCDeclQualifier_Oneway\n };\n#endc\n{# enum ObjCDeclQualifierKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags ObjCDeclQualifierKind where\n toBit ObjCDeclQualifier_None = 0x0\n toBit ObjCDeclQualifier_In = 0x1\n toBit ObjCDeclQualifier_Inout = 0x2\n toBit ObjCDeclQualifier_Out = 0x4\n toBit ObjCDeclQualifier_Bycopy = 0x8\n toBit ObjCDeclQualifier_Byref = 0x10\n toBit ObjCDeclQualifier_Oneway = 0x20\n\n-- unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C);\n{# fun clang_Cursor_getObjCDeclQualifiers {withVoided* %`Cursor a' } -> `CUInt' #}\ncursor_getObjCDeclQualifiers :: Cursor s -> IO Int\ncursor_getObjCDeclQualifiers c =\n clang_Cursor_getObjCDeclQualifiers c >>= return . fromIntegral\n\n-- unsigned clang_Cursor_isObjCOptional(CXCursor);\n{# fun clang_Cursor_isObjCOptional {withVoided* %`Cursor a' } -> `Bool' toBool #}\ncursor_isObjCOptional :: Cursor s -> IO Bool\ncursor_isObjCOptional c = clang_Cursor_isObjCOptional c\n\n-- unsigned clang_Cursor_isVariadic(CXCursor);\n{# fun clang_Cursor_isVariadic {withVoided* %`Cursor a' } -> `Bool' toBool #}\ncursor_isVariadic :: Cursor s -> IO Bool\ncursor_isVariadic c = clang_Cursor_isVariadic c\n\n-- CXSourceRange clang_Cursor_getCommentRange(CXCursor C);\n{# fun wrapped_clang_Cursor_getCommentRange as clang_Cursor_getCommentRange {withVoided* %`Cursor a' } -> `Ptr (SourceRange s)' castPtr #}\ncursor_getCommentRange :: Proxy s -> Cursor s' -> IO (SourceRange s)\ncursor_getCommentRange _ c = clang_Cursor_getCommentRange c >>= peek\n\n-- CXString clang_Cursor_getRawCommentText(CXCursor C);\n{# fun wrapped_clang_Cursor_getRawCommentText as clang_Cursor_getRawCommentText {withVoided* %`Cursor a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_Cursor_getRawCommentText :: Cursor s -> IO (ClangString ())\nunsafe_Cursor_getRawCommentText c =\n clang_Cursor_getRawCommentText c >>= peek\n\ncursor_getRawCommentText :: ClangBase m => Cursor s' -> ClangT s m (ClangString s)\ncursor_getRawCommentText = registerClangString . unsafe_Cursor_getRawCommentText\n\n-- CXString clang_Cursor_getBriefCommentText(CXCursor C);\n{# fun wrapped_clang_Cursor_getBriefCommentText as clang_Cursor_getBriefCommentText {withVoided* %`Cursor a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_Cursor_getBriefCommentText :: Cursor s -> IO (ClangString ())\nunsafe_Cursor_getBriefCommentText c =\n clang_Cursor_getBriefCommentText c >>= peek\n\ncursor_getBriefCommentText :: ClangBase m => Cursor s' -> ClangT s m (ClangString s)\ncursor_getBriefCommentText = registerClangString . unsafe_Cursor_getBriefCommentText\n\n-- CXComment clang_Cursor_getParsedComment(CXCursor C);\n\n{# fun wrapped_clang_Cursor_getParsedComment as clang_Cursor_getParsedComment {withVoided* %`Cursor a' } -> `Ptr (Comment s)' castPtr #}\ncursor_getParsedComment :: Proxy s -> Cursor s' -> IO (Comment s)\ncursor_getParsedComment _ c =\n clang_Cursor_getParsedComment c >>= peek\n\n-- typedef void *CXModule;\nnewtype Module s = Module { unModule :: Ptr () }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue Module\n\n-- %dis cxmodule p = (ptr p)\n\nmaybeModule :: Module s' -> Maybe (Module s)\nmaybeModule (Module p) | p == nullPtr = Nothing\nmaybeModule f = Just (unsafeCoerce f)\n\nunMaybeModule :: Maybe (Module s') -> Module s\nunMaybeModule (Just f) = unsafeCoerce f\nunMaybeModule Nothing = Module nullPtr\n\n-- CXModule clang_Cursor_getModule(CXCursor C);\n{# fun clang_Cursor_getModule {withVoided* %`Cursor a' } -> `Ptr ()' id #}\ncursor_getModule :: Proxy s -> Cursor s' -> IO (Module s)\ncursor_getModule _ c =\n clang_Cursor_getModule c >>= return . Module\n\n-- CXFile clang_Module_getASTFile(CXModule Module);\n{# fun clang_Module_getASTFile { id `Ptr ()' } -> `Ptr ()' id #}\nmodule_getASTFile :: Proxy s -> Module s' -> IO (File s)\nmodule_getASTFile _ m = clang_Module_getASTFile (unModule m) >>= return . File\n\n-- CXModule clang_Module_getParent(CXModule Module);\n{# fun clang_Module_getParent { id `Ptr ()' } -> `Ptr ()' id #}\nmodule_getParent :: Proxy s -> Module s' -> IO (Maybe (Module s))\nmodule_getParent _ m = clang_Module_getParent (unModule m) >>= return . maybeModule . Module\n\n-- CXString clang_Module_getName(CXModule Module);\n{# fun wrapped_clang_Module_getName as clang_Module_getName { id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_Module_getName :: Module s -> IO (ClangString ())\nunsafe_Module_getName m = clang_Module_getName (unModule m) >>= peek\n\nmodule_getName :: ClangBase m => Module s' -> ClangT s m (ClangString s)\nmodule_getName = registerClangString . unsafe_Module_getName\n\n-- CXString clang_Module_getFullName(CXModule Module);\n{# fun wrapped_clang_Module_getFullName as clang_Module_getFullName { id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_Module_getFullName :: Module s -> IO (ClangString ())\nunsafe_Module_getFullName m = clang_Module_getFullName (unModule m) >>= peek\n\nmodule_getFullName :: ClangBase m => Module s' -> ClangT s m (ClangString s)\nmodule_getFullName = registerClangString . unsafe_Module_getFullName\n\n-- unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit, CXModule Module);\n{# fun clang_Module_getNumTopLevelHeaders { id `Ptr ()', id `Ptr ()' } -> `Int' #}\nmodule_getNumTopLevelHeaders :: TranslationUnit s -> Module s' -> IO Int\nmodule_getNumTopLevelHeaders t m = clang_Module_getNumTopLevelHeaders (unTranslationUnit t) (unModule m)\n\n-- CXFile clang_Module_getTopLevelHeader(CXTranslationUnit, CXModule Module, unsigned Index);\n{# fun clang_Module_getTopLevelHeader { id `Ptr ()', id `Ptr ()', `Int' } -> `Ptr ()' id #}\nmodule_getTopLevelHeader :: Proxy s -> TranslationUnit s' -> Module s'' -> Int -> IO (File s)\nmodule_getTopLevelHeader _ t m i = clang_Module_getTopLevelHeader (unTranslationUnit t) (unModule m) i >>= return . File\n\n-- unsigned clang_CXXMethod_isPureVirtual(CXCursor C);\n{# fun clang_CXXMethod_isPureVirtual {withVoided* %`Cursor a' } -> `Bool' toBool #}\ncXXMethod_isPureVirtual :: Cursor s -> IO Bool\ncXXMethod_isPureVirtual c = clang_Cursor_isBitField c\n\n-- unsigned clang_CXXMethod_isStatic(CXCursor C);\n{# fun clang_CXXMethod_isStatic {withVoided* %`Cursor a' } -> `Bool' toBool #}\ncXXMethod_isStatic :: Cursor s -> IO Bool\ncXXMethod_isStatic c = clang_Cursor_isBitField c\n\n-- unsigned clang_CXXMethod_isVirtual(CXCursor C);\n{# fun clang_CXXMethod_isVirtual {withVoided* %`Cursor a' } -> `Bool' toBool #}\ncXXMethod_isVirtual :: Cursor s -> IO Bool\ncXXMethod_isVirtual c = clang_Cursor_isBitField c\n\n-- enum CXCursorKind clang_getTemplateCursorKind(CXCursor C);\n{# fun clang_getTemplateCursorKind {withVoided* %`Cursor a' } -> `Int' #}\ngetTemplateCursorKind :: Cursor s -> IO CursorKind\ngetTemplateCursorKind c =\n clang_getTemplateCursorKind c >>= return . toEnum\n\n-- CXCursor clang_getSpecializedCursorTemplate(CXCursor C);\n{# fun wrapped_clang_getSpecializedCursorTemplate as clang_getSpecializedCursorTemplate {withVoided* %`Cursor a' } -> `Ptr (Cursor s)' castPtr #}\ngetSpecializedCursorTemplate :: Proxy s -> Cursor s' -> IO (Cursor s)\ngetSpecializedCursorTemplate _ c =\n clang_getSpecializedCursorTemplate c >>= peek\n\n-- CXSourceRange clang_getCursorReferenceNameRange(CXCursor C,\n-- unsigned NameFlags,\n-- unsigned PieceIndex);\n{# fun wrapped_clang_getCursorReferenceNameRange as clang_getCursorReferenceNameRange {withVoided* %`Cursor a', `Int' , `Int' } -> `Ptr (SourceRange s)' castPtr #}\ngetCursorReferenceNameRange :: Proxy s -> Cursor s' -> Int -> Int -> IO (SourceRange s)\ngetCursorReferenceNameRange _ c fs idx = clang_getCursorReferenceNameRange c fs idx >>= peek\n\n-- enum CXNameRefFlags {\n-- CXNameRange_WantQualifier = 0x1,\n-- CXNameRange_WantTemplateArgs = 0x2,\n-- CXNameRange_WantSinglePiece = 0x4\n-- };\n#c\nenum NameRefFlags\n { NameRange_WantQualifier = CXNameRange_WantQualifier\n , NameRange_WantTemplateArgs = CXNameRange_WantTemplateArgs\n , NameRange_WantSinglePiece = CXNameRange_WantSinglePiece\n };\n#endc\n{# enum NameRefFlags {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags NameRefFlags where\n toBit NameRange_WantQualifier = 0x01\n toBit NameRange_WantTemplateArgs = 0x02\n toBit NameRange_WantSinglePiece = 0x04\n\n-- enum CXCommentKind {\n-- CXComment_Null = 0,\n-- CXComment_Text = 1,\n-- CXComment_InlineCommand = 2,\n-- CXComment_HTMLStartTag = 3,\n-- CXComment_HTMLEndTag = 4,\n-- CXComment_Paragraph = 5,\n-- CXComment_BlockCommand = 6,\n-- CXComment_ParamCommand = 7,\n-- CXComment_TParamCommand = 8,\n-- CXComment_VerbatimBlockCommand = 9,\n-- CXComment_VerbatimBlockLine = 10,\n-- CXComment_VerbatimLine = 11,\n-- CXComment_FullComment = 12\n-- };\n#c\nenum CommentKind\n { NullComment = CXComment_Null\n , TextComment = CXComment_Text\n , InlineCommandComment = CXComment_InlineCommand\n , HTMLStartTagComment = CXComment_HTMLStartTag\n , HTMLEndTagComment = CXComment_HTMLEndTag\n , ParagraphComment = CXComment_Paragraph\n , BlockCommandComment = CXComment_BlockCommand\n , ParamCommandComment = CXComment_ParamCommand\n , TParamCommandComment = CXComment_TParamCommand\n , VerbatimBlockCommandComment = CXComment_VerbatimBlockCommand\n , VerbatimBlockLineComment = CXComment_VerbatimBlockLine\n , VerbatimLineComment = CXComment_VerbatimLine\n , FullComment = CXComment_FullComment\n };\n#endc\n{# enum CommentKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- enum CXCommentInlineCommandRenderKind {\n-- CXCommentInlineCommandRenderKind_Normal,\n-- CXCommentInlineCommandRenderKind_Bold,\n-- CXCommentInlineCommandRenderKind_Monospaced,\n-- CXCommentInlineCommandRenderKind_Emphasized\n-- };\n\n-- | A rendering style which should be used for the associated inline command in the comment AST.\n#c\nenum InlineCommandRenderStyle\n { NormalInlineCommandRenderStyle = CXCommentInlineCommandRenderKind_Normal\n , BoldInlineCommandRenderStyle = CXCommentInlineCommandRenderKind_Bold\n , MonospacedInlineCommandRenderStyle = CXCommentInlineCommandRenderKind_Monospaced\n , EmphasizedInlineCommandRenderStyle = CXCommentInlineCommandRenderKind_Emphasized\n };\n#endc\n{# enum InlineCommandRenderStyle {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n-- enum CXCommentParamPassDirection {\n-- CXCommentParamPassDirection_In,\n-- CXCommentParamPassDirection_Out,\n-- CXCommentParamPassDirection_InOut\n-- };\n\n-- | A parameter passing direction.\n#c\nenum ParamPassDirectionKind\n { InParamPassDirection = CXCommentParamPassDirection_In\n , OutParamPassDirection = CXCommentParamPassDirection_Out\n , InOutParamPassDirection = CXCommentParamPassDirection_InOut\n };\n#endc\n{#enum ParamPassDirectionKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- enum CXCommentKind clang_Comment_getKind(CXComment Comment);\n{# fun clang_Comment_getKind {withVoided* %`Comment a' } -> `Int' #}\ncomment_getKind :: Comment s -> IO CommentKind\ncomment_getKind c =\n clang_Comment_getKind c >>= return . toEnum\n\n-- unsigned clang_Comment_getNumChildren(CXComment Comment);\n{# fun clang_Comment_getNumChildren {withVoided* %`Comment a' } -> `Int' #}\ncomment_getNumChildren :: Comment s -> IO Int\ncomment_getNumChildren c =\n clang_Comment_getNumChildren c\n\n-- CXComment clang_Comment_getChild(CXComment Comment, unsigned ChildIdx);\n{# fun clang_Comment_getChild {withVoided* %`Comment a', `Int' } -> `Ptr (Comment s)' castPtr #}\ncomment_getChild :: Proxy s -> Comment s' -> Int -> IO (Comment s)\ncomment_getChild _ c i = clang_Comment_getChild c i >>= peek\n\n-- unsigned clang_Comment_isWhitespace(CXComment Comment);\n{# fun clang_Comment_isWhitespace {withVoided* %`Comment a' } -> `Bool' toBool #}\ncomment_isWhitespace :: Comment s -> IO Bool\ncomment_isWhitespace c = clang_Comment_isWhitespace c\n\n-- unsigned clang_InlineContentComment_hasTrailingNewline(CXComment Comment);\n{# fun clang_InlineContentComment_hasTrailingNewline {withVoided* %`Comment a' } -> `Bool' toBool #}\ninlineContentComment_hasTrailingNewline :: Comment s -> IO Bool\ninlineContentComment_hasTrailingNewline c = clang_InlineContentComment_hasTrailingNewline c\n\n-- CXString clang_TextComment_getText(CXComment Comment);\n{# fun wrapped_clang_TextComment_getText as clang_TextComment_getText {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_TextComment_getText :: Comment s -> IO (ClangString ())\nunsafe_TextComment_getText c =\n clang_TextComment_getText c >>= peek\n\ntextComment_getText :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\ntextComment_getText = registerClangString . unsafe_TextComment_getText\n\n-- CXString clang_InlineCommandComment_getCommandName(CXComment Comment);\n{# fun clang_InlineCommandComment_getCommandName {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_InlineCommandComment_getCommandName :: Comment s -> IO (ClangString ())\nunsafe_InlineCommandComment_getCommandName c =\n clang_InlineCommandComment_getCommandName c >>= peek\n\ninlineCommandComment_getCommandName :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\ninlineCommandComment_getCommandName = registerClangString . unsafe_InlineCommandComment_getCommandName\n\n-- enum CXCommentInlineCommandRenderKind clang_InlineCommandComment_getRenderKind(CXComment Comment);\n{# fun clang_InlineCommandComment_getRenderKind {withVoided* %`Comment a' } -> `Int' #}\ninlineCommandComment_getRenderKind :: Comment s -> IO InlineCommandRenderStyle\ninlineCommandComment_getRenderKind c =\n clang_InlineCommandComment_getRenderKind c >>= return . toEnum\n\n-- unsigned clang_InlineCommandComment_getNumArgs(CXComment Comment);\n{# fun clang_InlineCommandComment_getNumArgs {withVoided* %`Comment a' } -> `Int' #}\ninlineCommandComment_getNumArgs :: Comment s -> IO Int\ninlineCommandComment_getNumArgs c =\n clang_InlineCommandComment_getNumArgs c\n\n-- CXString clang_InlineCommandComment_getArgText(CXComment Comment, unsigned ArgIdx);\n{# fun clang_InlineCommandComment_getArgText {withVoided* %`Comment a', `Int' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_InlineCommandComment_getArgText :: Comment s -> Int -> IO (ClangString ())\nunsafe_InlineCommandComment_getArgText c idx =\n clang_InlineCommandComment_getArgText c idx >>= peek\n\ninlineCommandComment_getArgText :: ClangBase m => Comment s' -> Int -> ClangT s m (ClangString s)\ninlineCommandComment_getArgText = (registerClangString .) . unsafe_InlineCommandComment_getArgText\n\n-- CXString clang_HTMLTagComment_getTagName(CXComment Comment);\n{# fun wrapped_clang_HTMLTagComment_getTagName as clang_HTMLTagComment_getTagName {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_HTMLTagComment_getTagName :: Comment s -> IO (ClangString ())\nunsafe_HTMLTagComment_getTagName c =\n clang_HTMLTagComment_getTagName c >>= peek\n\nhTMLTagComment_getTagName :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\nhTMLTagComment_getTagName = registerClangString . unsafe_HTMLTagComment_getTagName\n\n-- unsigned clang_HTMLStartTagComment_isSelfClosing(CXComment Comment);\n{# fun clang_HTMLStartTagComment_isSelfClosing {withVoided* %`Comment a' } -> `Bool' toBool #}\nhTMLStartTagComment_isSelfClosing :: Comment s -> IO Bool\nhTMLStartTagComment_isSelfClosing c = clang_HTMLStartTagComment_isSelfClosing c\n\n-- unsigned clang_HTMLStartTag_getNumAttrs(CXComment Comment);\n{# fun clang_HTMLStartTag_getNumAttrs {withVoided* %`Comment a' } -> `Int' #}\nhTMLStartTag_getNumAttrs :: Comment s -> IO Int\nhTMLStartTag_getNumAttrs c =\n clang_HTMLStartTag_getNumAttrs c\n\n-- CXString clang_HTMLStartTag_getAttrName(CXComment Comment, unsigned AttrIdx);\n{# fun clang_HTMLStartTag_getAttrName {withVoided* %`Comment a', `Int' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_HTMLStartTag_getAttrName :: Comment s -> Int -> IO (ClangString ())\nunsafe_HTMLStartTag_getAttrName c idx =\n clang_HTMLStartTag_getAttrName c idx >>= peek\n\nhTMLStartTag_getAttrName :: ClangBase m => Comment s' -> Int -> ClangT s m (ClangString s)\nhTMLStartTag_getAttrName = (registerClangString .) . unsafe_HTMLStartTag_getAttrName\n\n-- CXString clang_HTMLStartTag_getAttrValue(CXComment Comment, unsigned AttrIdx);\n{# fun clang_HTMLStartTag_getAttrValue {withVoided* %`Comment a', `Int' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_HTMLStartTag_getAttrValue :: Comment s -> Int -> IO (ClangString ())\nunsafe_HTMLStartTag_getAttrValue c idx =\n clang_HTMLStartTag_getAttrValue c idx >>= peek\n\nhTMLStartTag_getAttrValue :: ClangBase m => Comment s' -> Int -> ClangT s m (ClangString s)\nhTMLStartTag_getAttrValue = (registerClangString .) . unsafe_HTMLStartTag_getAttrValue\n\n-- CXString clang_BlockCommandComment_getCommandName(CXComment Comment);\n{# fun clang_BlockCommandComment_getCommandName {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_BlockCommandComment_getCommandName :: Comment s -> IO (ClangString ())\nunsafe_BlockCommandComment_getCommandName c =\n clang_BlockCommandComment_getCommandName c >>= peek\n\nblockCommandComment_getCommandName :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\nblockCommandComment_getCommandName = registerClangString . unsafe_BlockCommandComment_getCommandName\n\n-- unsigned clang_BlockCommandComment_getNumArgs(CXComment Comment);\n{# fun clang_BlockCommandComment_getNumArgs {withVoided* %`Comment a' } -> `Int' #}\nblockCommandComment_getNumArgs :: Comment s -> IO Int\nblockCommandComment_getNumArgs c =\n clang_BlockCommandComment_getNumArgs c\n\n-- CXString clang_BlockCommandComment_getArgText(CXComment Comment, unsigned ArgIdx);\n{# fun clang_BlockCommandComment_getArgText {withVoided* %`Comment a', `Int' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_BlockCommandComment_getArgText :: Comment s -> Int -> IO (ClangString ())\nunsafe_BlockCommandComment_getArgText c idx =\n clang_BlockCommandComment_getArgText c idx >>= peek\n\nblockCommandComment_getArgText :: ClangBase m => Comment s' -> Int -> ClangT s m (ClangString s)\nblockCommandComment_getArgText = (registerClangString .) . unsafe_BlockCommandComment_getArgText\n\n-- CXComment clang_BlockCommandComment_getParagraph(CXComment Comment);\n{# fun clang_BlockCommandComment_getParagraph {withVoided* %`Comment a' } -> `Ptr (Comment s)' castPtr #}\nblockCommandComment_getParagraph :: Proxy s -> Comment s' -> IO (Comment s)\nblockCommandComment_getParagraph _ c =\n clang_BlockCommandComment_getParagraph c >>= peek\n\n-- CXString clang_ParamCommandComment_getParamName(CXComment Comment);\n{# fun clang_ParamCommandComment_getParamName {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_ParamCommandComment_getParamName :: Comment s -> IO (ClangString ())\nunsafe_ParamCommandComment_getParamName c =\n clang_ParamCommandComment_getParamName c >>= peek\n\nparamCommandComment_getParamName :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\nparamCommandComment_getParamName = registerClangString . unsafe_ParamCommandComment_getParamName\n\n-- unsigned clang_ParamCommandComment_isParamIndexValid(CXComment Comment);\n{# fun clang_ParamCommandComment_isParamIndexValid {withVoided* %`Comment a' } -> `Bool' toBool #}\nparamCommandComment_isParamIndexValid :: Comment s -> IO Bool\nparamCommandComment_isParamIndexValid c =\n clang_ParamCommandComment_isParamIndexValid c\n\n-- unsigned clang_ParamCommandComment_getParamIndex(CXComment Comment);\n{# fun clang_ParamCommandComment_getParamIndex {withVoided* %`Comment a' } -> `Int' #}\nparamCommandComment_getParamIndex :: Comment s -> IO Int\nparamCommandComment_getParamIndex c =\n clang_ParamCommandComment_getParamIndex c\n\n-- unsigned clang_ParamCommandComment_isDirectionExplicit(CXComment Comment);\n{# fun clang_ParamCommandComment_isDirectionExplicit {withVoided* %`Comment a' } -> `Bool' toBool #}\nparamCommandComment_isDirectionExplicit :: Comment s -> IO Bool\nparamCommandComment_isDirectionExplicit c =\n clang_ParamCommandComment_isDirectionExplicit c\n\n-- enum CXCommentParamPassDirection clang_ParamCommandComment_getDirection(CXComment Comment);\n{# fun clang_ParamCommandComment_getDirection {withVoided* %`Comment a' } -> `Int' #}\nparamCommandComment_getDirection :: Comment s -> IO ParamPassDirectionKind\nparamCommandComment_getDirection c =\n clang_ParamCommandComment_getDirection c >>= return . toEnum\n\n-- CXString clang_TParamCommandComment_getParamName(CXComment Comment);\n{# fun clang_TParamCommandComment_getParamName {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_TParamCommandComment_getParamName :: Comment s -> IO (ClangString ())\nunsafe_TParamCommandComment_getParamName c =\n clang_TParamCommandComment_getParamName c >>= peek\n\ntParamCommandComment_getParamName :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\ntParamCommandComment_getParamName = registerClangString . unsafe_TParamCommandComment_getParamName\n\n-- unsigned clang_TParamCommandComment_isParamPositionValid(CXComment Comment);\n{# fun clang_TParamCommandComment_isParamPositionValid {withVoided* %`Comment a' } -> `Bool' toBool #}\ntParamCommandComment_isParamPositionValid :: Comment s -> IO Bool\ntParamCommandComment_isParamPositionValid c =\n clang_TParamCommandComment_isParamPositionValid c\n\n-- unsigned clang_TParamCommandComment_getDepth(CXComment Comment);\n{# fun clang_TParamCommandComment_getDepth { withVoided* %`Comment a' } -> `Int' #}\ntParamCommandComment_getDepth :: Comment s -> IO Int\ntParamCommandComment_getDepth c =\n clang_TParamCommandComment_getDepth c\n\n-- unsigned clang_TParamCommandComment_getIndex(CXComment Comment, unsigned Depth);\n{# fun clang_TParamCommandComment_getIndex {withVoided* %`Comment a', `Int' } -> `Int' #}\ntParamCommandComment_getIndex :: Comment s -> Int -> IO Int\ntParamCommandComment_getIndex c idx =\n clang_TParamCommandComment_getIndex c idx\n\n-- CXString clang_VerbatimBlockLineComment_getText(CXComment Comment);\n{# fun clang_VerbatimBlockLineComment_getText {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_VerbatimBlockLineComment_getText :: Comment s -> IO (ClangString ())\nunsafe_VerbatimBlockLineComment_getText c =\n clang_VerbatimBlockLineComment_getText c >>= peek\n\nverbatimBlockLineComment_getText :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\nverbatimBlockLineComment_getText = registerClangString . unsafe_VerbatimBlockLineComment_getText\n\n-- CXString clang_VerbatimLineComment_getText(CXComment Comment);\n{# fun wrapped_clang_VerbatimLineComment_getText as clang_VerbatimLineComment_getText {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_VerbatimLineComment_getText :: Comment s -> IO (ClangString ())\nunsafe_VerbatimLineComment_getText c =\n clang_VerbatimLineComment_getText c >>= peek\n\nverbatimLineComment_getText :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\nverbatimLineComment_getText = registerClangString . unsafe_VerbatimLineComment_getText\n\n-- CXString clang_HTMLTagComment_getAsString(CXComment Comment);\n{# fun wrapped_clang_HTMLTagComment_getAsString as clang_HTMLTagComment_getAsString {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_HTMLTagComment_getAsString :: Comment s -> IO (ClangString ())\nunsafe_HTMLTagComment_getAsString c =\n clang_HTMLTagComment_getAsString c >>= peek\n\nhTMLTagComment_getAsString :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\nhTMLTagComment_getAsString = registerClangString . unsafe_HTMLTagComment_getAsString\n\n-- CXString clang_FullComment_getAsHTML(CXComment Comment);\n{# fun wrapped_clang_FullComment_getAsHTML as clang_FullComment_getAsHTML {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_FullComment_getAsHTML :: Comment s -> IO (ClangString ())\nunsafe_FullComment_getAsHTML c =\n clang_FullComment_getAsHTML c >>= peek\n\nfullComment_getAsHTML :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\nfullComment_getAsHTML = registerClangString . unsafe_FullComment_getAsHTML\n\n-- CXString clang_FullComment_getAsXML(CXComment Comment);\n{# fun wrapped_clang_FullComment_getAsXML as clang_FullComment_getAsXML {withVoided* %`Comment a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_FullComment_getAsXML :: Comment s -> IO (ClangString ())\nunsafe_FullComment_getAsXML c =\n clang_FullComment_getAsXML c >>= peek\n\nfullComment_getAsXML :: ClangBase m => Comment s' -> ClangT s m (ClangString s)\nfullComment_getAsXML = registerClangString . unsafe_FullComment_getAsXML\n\n-- typedef enum CXTokenKind {\n-- CXToken_Punctuation,\n-- CXToken_Keyword,\n-- CXToken_Identifier,\n-- CXToken_Literal,\n-- CXToken_Comment\n-- } CXTokenKind;\n#c\nenum TokenKind\n { PunctuationToken = CXToken_Punctuation\n , KeywordToken = CXToken_Keyword\n , IdentifierToken = CXToken_Identifier\n , LiteralToken = CXToken_Literal\n , CommentToken = CXToken_Comment\n };\n#endc\n{# enum TokenKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- typedef struct {\n-- unsigned int_data[4];\n-- void *ptr_data;\n-- } CXToken;\ndata Token s = Token !Int !Int !Int !Int !(Ptr ())\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue Token\n\ninstance Storable (Token s) where\n sizeOf _ = sizeOfCXToken\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfCXToken\n {-# INLINE alignment #-}\n\n peek p = do\n int_data <- {#get CXToken->int_data #} p >>= peekArray 4\n ptr_data <- {#get CXToken->ptr_data #} p\n return $! Token (fromIntegral (int_data !! 0)) (fromIntegral (int_data !! 1)) (fromIntegral (int_data !! 2)) (fromIntegral (int_data !! 3)) ptr_data\n {-# INLINE peek #-}\n\n poke p (Token i0 i1 i2 i3 ptr_data) = do\n intsArray <- mallocArray 4\n pokeArray intsArray (map fromIntegral [i0,i1,i2,i3])\n {#set CXToken->int_data #} p intsArray\n {#set CXToken->ptr_data #} p ptr_data\n {-# INLINE poke #-}\n\n-- CXTokenKind clang_getTokenKind(CXToken);\n{# fun clang_getTokenKind { withVoided* %`Token s' } -> `Int' #}\ngetTokenKind :: Token s -> IO TokenKind\ngetTokenKind t =\n clang_getTokenKind t >>= return . toEnum\n\n-- CXString clang_getTokenSpelling(CXTranslationUnit, CXToken);\n{# fun wrapped_clang_getTokenSpelling as clang_getTokenSpelling { id `Ptr ()', withVoided* %`Token s' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getTokenSpelling :: TranslationUnit s -> Token s' -> IO (ClangString ())\nunsafe_getTokenSpelling tu t =\n clang_getTokenSpelling (unTranslationUnit tu) t >>= peek\n\ngetTokenSpelling :: ClangBase m => TranslationUnit s' -> Token s'' -> ClangT s m (ClangString s)\ngetTokenSpelling = (registerClangString .) . unsafe_getTokenSpelling\n\n-- CXSourceLocation clang_getTokenLocation(CXTranslationUnit,\n-- CXToken);\n{# fun wrapped_clang_getTokenLocation as clang_getTokenLocation { id `Ptr ()', withVoided* %`Token a' } -> `Ptr (SourceLocation s)' castPtr #}\ngetTokenLocation :: Proxy s -> TranslationUnit t -> Token s' -> IO (SourceLocation s)\ngetTokenLocation _ tu t =\n clang_getTokenLocation (unTranslationUnit tu) t >>= peek\n\n-- CXSourceRange clang_getTokenExtent(CXTranslationUnit, CXToken);\n{# fun wrapped_clang_getTokenExtent as clang_getTokenExtent { id `Ptr ()', withVoided* %`Token a' } -> `Ptr (SourceRange s)' castPtr #}\ngetTokenExtent :: Proxy s -> TranslationUnit t -> Token s' -> IO (SourceRange s)\ngetTokenExtent _ tu t =\n clang_getTokenExtent (unTranslationUnit tu) t >>= peek\n\n-- We deliberately don't export the constructor for UnsafeTokenList.\n-- The only way to unwrap it is registerTokenList.\ntype TokenList s = DVS.Vector (Token s)\ninstance ClangValueList Token\ndata UnsafeTokenList = UnsafeTokenList !(Ptr ()) !Int\n\nforeign import ccall unsafe \"FFI_stub_ffi.h clang_disposeTokens\" clang_disposeTokens :: Ptr () -> Ptr () -> CUInt -> IO ()\n\ndisposeTokens :: TranslationUnit s -> TokenList s' -> IO ()\ndisposeTokens tu tl =\n let (tPtr, n) = fromTokenList tl in\n clang_disposeTokens (unTranslationUnit tu) tPtr (fromIntegral n)\n\nregisterTokenList :: ClangBase m => TranslationUnit s' -> IO UnsafeTokenList\n -> ClangT s m (TokenList s)\nregisterTokenList tu action = do\n (_, tokenList) <- clangAllocate (action >>= tokenListToVector) (disposeTokens tu)\n return tokenList\n{-# INLINEABLE registerTokenList #-}\n\ntokenListToVector :: Storable a => UnsafeTokenList -> IO (DVS.Vector a)\ntokenListToVector (UnsafeTokenList ts n) = do\n fptr <- newForeignPtr_ (castPtr ts)\n return $ DVS.unsafeFromForeignPtr fptr 0 n\n{-# INLINE tokenListToVector #-}\n\nfromTokenList :: TokenList s -> (Ptr (), Int)\nfromTokenList ts = let (p, _, _) = DVS.unsafeToForeignPtr ts in\n (castPtr $ Foreign.ForeignPtr.Unsafe.unsafeForeignPtrToPtr p, DVS.length ts)\n\ntoTokenList :: (Ptr (), Int) -> UnsafeTokenList\ntoTokenList (ts, n) = UnsafeTokenList ts n\n\n-- void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,\n-- CXToken **Tokens, unsigned *NumTokens);\n{# fun clang_tokenize { id `Ptr ()',withVoided* %`SourceRange a', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()'#}\nunsafe_tokenize :: TranslationUnit s -> SourceRange s' -> IO UnsafeTokenList\nunsafe_tokenize tu sr = do\n tokensPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr (Token ())))))\n numTokens <- clang_tokenize (unTranslationUnit tu) sr (castPtr tokensPtr)\n return (toTokenList (tokensPtr, fromIntegral numTokens))\n\ntokenize :: ClangBase m => TranslationUnit s' -> SourceRange s'' -> ClangT s m (TokenList s)\ntokenize tu = registerTokenList tu . unsafe_tokenize tu\n\n-- TODO: test me\n-- Note that registerCursorList can be used for the result of this\n-- function because it just calls free() to dispose of the list.\n--\n-- void clang_annotateTokens(CXTranslationUnit TU,\n-- CXToken *Tokens, unsigned NumTokens,\n-- CXCursor *Cursors);\n{# fun clang_annotateTokens { id `Ptr ()', id `Ptr ()', `Int', id `Ptr ()' } -> `()' id#}\nunsafe_annotateTokens :: TranslationUnit s -> TokenList s' -> IO UnsafeCursorList\nunsafe_annotateTokens tu tl =\n let (tPtr, numTokens) = fromTokenList tl in\n do\n cPtr <- mallocBytes ((sizeOf (undefined :: (Ptr (Cursor ())))) * numTokens)\n clang_annotateTokens (unTranslationUnit tu) tPtr numTokens (castPtr cPtr)\n return (toCursorList (cPtr, numTokens))\n\nannotateTokens :: ClangBase m => TranslationUnit s' -> TokenList s'' -> ClangT s m (CursorList s)\nannotateTokens = (registerCursorList .) . unsafe_annotateTokens\n\n-- CXString clang_getCursorKindSpelling(enum CXCursorKind Kind);\n{# fun wrapped_clang_getCursorKindSpelling as clang_getCursorKindSpelling { `CInt' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCursorKindSpelling :: CursorKind -> IO (ClangString ())\nunsafe_getCursorKindSpelling ck = clang_getCursorKindSpelling (fromIntegral (fromEnum ck)) >>= peek\n\ngetCursorKindSpelling :: ClangBase m => CursorKind -> ClangT s m (ClangString s)\ngetCursorKindSpelling = registerClangString . unsafe_getCursorKindSpelling\n\n-- void clang_enableStackTraces(void);\nforeign import ccall unsafe \"clang-c\/Index.h clang_enableStackTraces\" enableStackTraces :: IO ()\n\n-- typedef void *CXCompletionString;\n\n-- | A semantic string that describes a code completion result.\n--\n-- A 'CompletionString' describes the formatting of a code completion\n-- result as a single \\\"template\\\" of text that should be inserted into the\n-- source buffer when a particular code completion result is selected.\n-- Each semantic string is made up of some number of \\\"chunks\\\", each of which\n-- contains some text along with a description of what that text means.\n--\n-- See 'ChunkKind' for more details about the role each kind of chunk plays.\nnewtype CompletionString s = CompletionString (Ptr ())\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue CompletionString\n\n-- typedef struct {\n-- enum CXCursorKind CursorKind;\n-- CXCompletionString CompletionString;\n-- } CXCompletionResult;\ndata CompletionResult s = CompletionResult !CursorKind !(CompletionString s)\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue CompletionResult\n\n-- enum CXCompletionChunkKind {\n-- CXCompletionChunk_Optional,\n-- CXCompletionChunk_TypedText,\n-- CXCompletionChunk_Text,\n-- CXCompletionChunk_Placeholder,\n-- CXCompletionChunk_Informative,\n-- CXCompletionChunk_CurrentParameter,\n-- CXCompletionChunk_LeftParen,\n-- CXCompletionChunk_RightParen,\n-- CXCompletionChunk_LeftBracket,\n-- CXCompletionChunk_RightBracket,\n-- CXCompletionChunk_LeftBrace,\n-- CXCompletionChunk_RightBrace,\n-- CXCompletionChunk_LeftAngle,\n-- CXCompletionChunk_RightAngle,\n-- CXCompletionChunk_Comma,\n-- CXCompletionChunk_ResultType,\n-- CXCompletionChunk_Colon,\n-- CXCompletionChunk_SemiColon,\n-- CXCompletionChunk_Equal,\n-- CXCompletionChunk_HorizontalSpace,\n-- CXCompletionChunk_VerticalSpace\n-- };\n\n-- | Describes a single piece of text within a code completion string.\n--\n-- * 'OptionalChunkKind': A code completion string that describes \"optional\" text that\n-- could be a part of the template (but is not required).\n-- This is the only kind of chunk that has a code completion\n-- string for its representation. The code completion string describes an\n-- describes an additional part of the template that is completely optional.\n-- For example, optional chunks can be used to describe the placeholders for\n-- arguments that match up with defaulted function parameters.\n--\n-- * 'TypedTextChunkKind': Text that a user would be expected to type to get this\n-- code completion result.\n-- There will be exactly one \\\"typed text\\\" chunk in a semantic string, which\n-- will typically provide the spelling of a keyword or the name of a\n-- declaration that could be used at the current code point. Clients are\n-- expected to filter the code completion results based on the text in this\n-- chunk.\n--\n-- * 'TextChunkKind': Text that should be inserted as part of a code completion result.\n-- A \\\"text\\\" chunk represents text that is part of the template to be\n-- inserted into user code should this particular code completion result\n-- be selected.\n--\n-- * 'PlaceholderChunkKind': Placeholder text that should be replaced by the user.\n-- A \\\"placeholder\\\" chunk marks a place where the user should insert text\n-- into the code completion template. For example, placeholders might mark\n-- the function parameters for a function declaration, to indicate that the\n-- user should provide arguments for each of those parameters. The actual\n-- text in a placeholder is a suggestion for the text to display before\n-- the user replaces the placeholder with real code.\n--\n-- * 'InformativeChunkKind': Informative text that should be displayed but never inserted as\n-- part of the template.\n-- An \\\"informative\\\" chunk contains annotations that can be displayed to\n-- help the user decide whether a particular code completion result is the\n-- right option, but which is not part of the actual template to be inserted\n-- by code completion.\n--\n-- * 'CurrentParameterChunkKind': Text that describes the current parameter\n-- when code completion is referring to a function call, message send, or\n-- template specialization.\n-- A \\\"current parameter\\\" chunk occurs when code completion is providing\n-- information about a parameter corresponding to the argument at the\n-- code completion point. For example, given a function \\\"int add(int x, int y);\\\"\n-- and the source code \\\"add(\\\", where the code completion point is after the\n-- \\\"(\\\", the code completion string will contain a \\\"current parameter\\\" chunk\n-- for \\\"int x\\\", indicating that the current argument will initialize that\n-- parameter. After typing further, to \\\"add(17\\\", (where the code completion\n-- point is after the \\\",\\\"), the code completion string will contain a\n-- \\\"current parameter\\\" chunk to \\\"int y\\\".\n--\n-- * 'LeftParenChunkKind': A left parenthesis (\\'(\\'), used to initiate a function call or\n-- signal the beginning of a function parameter list.\n--\n-- * 'RightParenChunkKind': A right parenthesis (\\')\\'), used to finish a function call or\n-- signal the end of a function parameter list.\n--\n-- * 'LeftBracketChunkKind': A left bracket (\\'[\\').\n--\n-- * 'RightBracketChunkKind': A right bracket (\\']\\').\n--\n-- * 'LeftBraceChunkKind': A left brace (\\'{\\').\n--\n-- * 'RightBraceChunkKind': A right brace (\\'}\\').\n--\n-- * 'LeftAngleChunkKind': A left angle bracket (\\'<\\').\n--\n-- * 'RightAngleChunkKind': A right angle bracket (\\'>\\').\n--\n-- * 'CommaChunkKind': A comma separator (\\',\\').\n--\n-- * 'ResultTypeChunkKind': Text that specifies the result type of a given result.\n-- This special kind of informative chunk is not meant to be inserted into\n-- the text buffer. Rather, it is meant to illustrate the type that an\n-- expression using the given completion string would have.\n--\n-- * 'ColonChunkKind': A colon (\\':\\').\n--\n-- * 'SemiColonChunkKind': A semicolon (\\';\\').\n--\n-- * 'EqualChunkKind': An \\'=\\' sign.\n--\n-- * 'HorizontalSpaceChunkKind': Horizontal space (\\' \\').\n--\n-- * 'VerticalSpaceChunkKind': Vertical space (\\'\\\\n\\'), after which it is generally\n-- a good idea to perform indentation.\n#c\nenum ChunkKind\n { OptionalChunkKind = CXCompletionChunk_Optional\n , TypedTextChunkKind = CXCompletionChunk_TypedText\n , TextChunkKind = CXCompletionChunk_Text\n , PlaceholderChunkKind = CXCompletionChunk_Placeholder\n , InformativeChunkKind = CXCompletionChunk_Informative\n , CurrentParameterChunkKind = CXCompletionChunk_CurrentParameter\n , LeftParenChunkKind = CXCompletionChunk_LeftParen\n , RightParenChunkKind = CXCompletionChunk_RightParen\n , LeftBracketChunkKind = CXCompletionChunk_LeftBracket\n , RightBracketChunkKind = CXCompletionChunk_RightBracket\n , LeftBraceChunkKind = CXCompletionChunk_LeftBrace\n , RightBraceChunkKind = CXCompletionChunk_RightBrace\n , LeftAngleChunkKind = CXCompletionChunk_LeftAngle\n , RightAngleChunkKind = CXCompletionChunk_RightAngle\n , CommaChunkKind = CXCompletionChunk_Comma\n , ResultTypeChunkKind = CXCompletionChunk_ResultType\n , ColonChunkKind = CXCompletionChunk_Colon\n , SemiColonChunkKind = CXCompletionChunk_SemiColon\n , EqualChunkKind = CXCompletionChunk_Equal\n , HorizontalSpaceChunkKind = CXCompletionChunk_HorizontalSpace\n , VerticalSpaceChunkKind = CXCompletionChunk_VerticalSpace\n };\n#endc\n{# enum ChunkKind {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\n-- enum CXCompletionChunkKind\n-- clang_getCompletionChunkKind(CXCompletionString completion_string,\n-- unsigned chunk_number);\n{# fun clang_getCompletionChunkKind { id `Ptr ()', `Int'} -> `Int' #}\ngetCompletionChunkKind :: CompletionString s -> Int -> IO ChunkKind\ngetCompletionChunkKind (CompletionString ptr) i = clang_getCompletionChunkKind ptr i >>= return . toEnum\n\n-- CXString\n-- clang_getCompletionChunkText(CXCompletionString completion_string,\n-- unsigned chunk_number);\n{# fun wrapped_clang_getCompletionChunkText as clang_getCompletionChunkText { id `Ptr ()' , `Int' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCompletionChunkText :: CompletionString s -> Int -> IO (ClangString ())\nunsafe_getCompletionChunkText (CompletionString ptr) i = clang_getCompletionChunkText ptr i >>= peek\n\ngetCompletionChunkText :: ClangBase m => CompletionString s' -> Int -> ClangT s m (ClangString s)\ngetCompletionChunkText = (registerClangString .) . unsafe_getCompletionChunkText\n\n-- CXCompletionString\n-- clang_getCompletionChunkCompletionString(CXCompletionString completion_string,\n-- unsigned chunk_number);\n{# fun clang_getCompletionChunkCompletionString { id `Ptr ()' , `Int' } -> `Ptr ()' id #}\ngetCompletionChunkCompletionString :: CompletionString s -> Int -> IO (CompletionString s')\ngetCompletionChunkCompletionString (CompletionString ptr) i =\n clang_getCompletionChunkCompletionString ptr i >>= return . CompletionString\n\n-- unsigned\n-- clang_getNumCompletionChunks(CXCompletionString completion_string);\n{# fun clang_getNumCompletionChunks { id `Ptr ()' } -> `Int' #}\ngetNumCompletionChunks :: CompletionString s -> IO Int\ngetNumCompletionChunks (CompletionString ptr) = clang_getNumCompletionChunks ptr\n\n-- unsigned\n-- clang_getCompletionPriority(CXCompletionString completion_string);\n{# fun clang_getCompletionPriority { id `Ptr ()' } -> `Int' #}\ngetCompletionPriority :: CompletionString s -> IO Int\ngetCompletionPriority (CompletionString ptr) = clang_getCompletionPriority ptr\n\n-- enum CXAvailabilityKind\n-- clang_getCompletionAvailability(CXCompletionString completion_string);\n{# fun clang_getCompletionAvailability { id `Ptr ()' } -> `Int' #}\ngetCompletionAvailability :: CompletionString s -> IO AvailabilityKind\ngetCompletionAvailability (CompletionString ptr) = clang_getCompletionAvailability ptr >>= return . toEnum\n\n-- unsigned clang_getCompletionNumAnnotations(CXCompletionString completion_string);\n{# fun clang_getCompletionNumAnnotations { id `Ptr ()' } -> `Int' #}\ngetCompletionNumAnnotations :: CompletionString s -> IO Int\ngetCompletionNumAnnotations (CompletionString ptr) = clang_getCompletionNumAnnotations ptr\n\n-- CXString clang_getCompletionAnnotation(CXCompletionString completion_string,\n-- unsigned annotation_number);\n{# fun wrapped_clang_getCompletionAnnotation as clang_getCompletionAnnotation { id `Ptr ()' , `Int' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCompletionAnnotation :: CompletionString s -> Int -> IO (ClangString ())\nunsafe_getCompletionAnnotation (CompletionString ptr) i = clang_getCompletionAnnotation ptr i >>= peek\n\ngetCompletionAnnotation :: ClangBase m => CompletionString s' -> Int -> ClangT s m (ClangString s)\ngetCompletionAnnotation = (registerClangString .) . unsafe_getCompletionAnnotation\n\n-- CXString clang_getCompletionParent(CXCompletionString completion_string,\n-- enum CXCursorKind *kind);\n{# fun wrapped_clang_getCompletionParent as clang_getCompletionParent { id `Ptr ()' , `CInt' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCompletionParent :: CompletionString s -> IO (ClangString ())\nunsafe_getCompletionParent (CompletionString ptr) = clang_getCompletionParent ptr 0 >>= peek\n\ngetCompletionParent :: ClangBase m => CompletionString s' -> ClangT s m (ClangString s)\ngetCompletionParent = registerClangString . unsafe_getCompletionParent\n\n-- CXString clang_getCompletionBriefComment(CXCompletionString completion_string);\n{# fun wrapped_clang_getCompletionBriefComment as clang_getCompletionBriefComment { id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCompletionBriefComment :: CompletionString s -> IO (ClangString ())\nunsafe_getCompletionBriefComment (CompletionString ptr) = clang_getCompletionBriefComment ptr >>= peek\n\ngetCompletionBriefComment :: ClangBase m => CompletionString s' -> ClangT s m (ClangString s)\ngetCompletionBriefComment = registerClangString . unsafe_getCompletionBriefComment\n\n-- CXCompletionString clang_getCursorCompletionString(CXCursor cursor);\n{# fun clang_getCursorCompletionString {withVoided* %`Cursor a' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_getCursorCompletionString :: Cursor s' -> IO (ClangString ())\nunsafe_getCursorCompletionString c =\n clang_getCursorCompletionString c >>= peek\n\ngetCursorCompletionString :: ClangBase m => Cursor s' -> ClangT s m (CompletionString s)\ngetCursorCompletionString c =\n unsafeCoerce <$> (liftIO $ unsafe_getCursorCompletionString c)\n\n-- enum CXCodeComplete_Flags {\n-- CXCodeComplete_IncludeMacros = 0x01,\n-- CXCodeComplete_IncludeCodePatterns = 0x02,\n-- CXCodeComplete_IncludeBriefComments = 0x04\n-- };\n\n-- | Flags that can be used to modify the behavior of 'codeCompleteAt'.\n--\n-- * 'IncludeMacros': Whether to include macros within the set of code\n-- completions returned.\n--\n-- * 'IncludeCodePatterns': Whether to include code patterns for language constructs\n-- within the set of code completions, e.g., 'for' loops.\n--\n-- * 'IncludeBriefComments': Whether to include brief documentation within the set of code\n-- completions returned.\n#c\nenum CodeCompleteFlags\n { IncludeMacros = CXCodeComplete_IncludeMacros\n , IncludeCodePatterns = CXCodeComplete_IncludeCodePatterns\n , IncludeBriefComments = CXCodeComplete_IncludeBriefComments\n };\n#endc\n{# enum CodeCompleteFlags {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags CodeCompleteFlags where\n toBit IncludeMacros = 0x01\n toBit IncludeCodePatterns = 0x02\n toBit IncludeBriefComments = 0x04\n\n-- unsigned clang_defaultCodeCompleteOptions(void);\n{# fun clang_defaultCodeCompleteOptions as defaultCodeCompleteOptions {} -> `Int' #}\n\n-- typedef struct {\n-- CXCompletionResult *Results;\n-- unsigned NumResults;\n-- } CXCodeCompleteResults;\n\n-- | The results of code completion.\nnewtype CodeCompleteResults s = CodeCompleteResults { unCodeCompleteResults :: Ptr () }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue CodeCompleteResults\n\n-- void clang_disposeCodeCompleteResults(CXCodeCompleteResults *Results);\n{# fun clang_disposeCodeCompleteResults { id `Ptr ()' } -> `()' #}\ndisposeCodeCompleteResults :: CodeCompleteResults s -> IO ()\ndisposeCodeCompleteResults rs = clang_disposeCodeCompleteResults (unCodeCompleteResults rs)\n\nregisterCodeCompleteResults :: ClangBase m => IO (CodeCompleteResults ())\n -> ClangT s m (CodeCompleteResults s)\nregisterCodeCompleteResults action = do\n (_, ccrs) <- clangAllocate (action >>= return . unsafeCoerce)\n disposeCodeCompleteResults\n return ccrs\n{-# INLINEABLE registerCodeCompleteResults #-}\n\n-- CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU,\n-- const char *complete_filename,\n-- unsigned complete_line,\n-- unsigned complete_column,\n-- struct CXUnsavedFile *unsaved_files,\n-- unsigned num_unsaved_files,\n-- unsigned options);\n{# fun clang_codeCompleteAt { id `Ptr ()', `CString', `Int', `Int', id `Ptr ()', `Int', `Int' } -> `Ptr ()' id #}\nunsafe_codeCompleteAt :: TranslationUnit s -> String -> Int -> Int -> Ptr CUnsavedFile -> Int -> Int -> IO (CodeCompleteResults ())\nunsafe_codeCompleteAt tu s i1 i2 ufs nufs i3 =\n withCString s (\\sPtr -> clang_codeCompleteAt (unTranslationUnit tu) sPtr i1 i2 (castPtr ufs) nufs i3 >>= return . CodeCompleteResults)\n\ncodeCompleteAt :: ClangBase m => TranslationUnit s' -> String -> Int -> Int\n -> DV.Vector UnsavedFile -> Int -> ClangT s m (CodeCompleteResults s)\ncodeCompleteAt tu f l c ufs os =\n registerCodeCompleteResults $\n withUnsavedFiles ufs $ \\ufsPtr ufsLen ->\n unsafe_codeCompleteAt tu f l c ufsPtr ufsLen os\n\n-- This function, along with codeCompleteGetResult, exist to allow iteration over\n-- the completion strings at the Haskell level. They're (obviously) not real\n-- libclang functions.\n{# fun codeCompleteGetNumResults as codeCompleteGetNumResults' { id `Ptr ()' } -> `Int' #}\ncodeCompleteGetNumResults :: CodeCompleteResults s -> IO Int\ncodeCompleteGetNumResults rs = codeCompleteGetNumResults' (unCodeCompleteResults rs)\n\n-- We don't need to register CompletionStrings; they're always owned by another object.\n-- They still need to be scoped, though.\n{# fun codeCompleteGetResult as codeCompleteGetResult' { id `Ptr ()', `CInt', id `Ptr (Ptr ())' } -> `CInt' id #}\nunsafe_codeCompleteGetResult :: CodeCompleteResults s -> Int -> IO (CompletionString (), CursorKind)\nunsafe_codeCompleteGetResult rs idx = do\n sPtr <- mallocBytes (sizeOf (undefined :: (Ptr (Ptr ()))))\n kind <- codeCompleteGetResult' (unCodeCompleteResults rs) (fromIntegral idx) (castPtr sPtr)\n return ((CompletionString sPtr), toEnum (fromIntegral kind))\n\ncodeCompleteGetResult :: ClangBase m => CodeCompleteResults s' -> Int\n -> ClangT s m (CompletionString s, CursorKind)\ncodeCompleteGetResult rs n = do\n (string, kind) <- liftIO $ unsafe_codeCompleteGetResult rs n\n return (unsafeCoerce string, kind)\n\n-- void clang_sortCodeCompletionResults(CXCompletionResult *Results,\n-- unsigned NumResults);\n{# fun clang_sortCodeCompletionResults { id `Ptr ()', `Int' } -> `()' #}\nsortCodeCompletionResults :: CodeCompleteResults s -> IO ()\nsortCodeCompletionResults rs =\n let results = unCodeCompleteResults rs in\n do\n rPtr <- peek (results `plusPtr` offsetCXCodeCompleteResultsResults)\n numRs <- peek (results `plusPtr` offsetCXCodeCompleteResultsNumResults)\n clang_sortCodeCompletionResults rPtr numRs\n\n-- unsigned clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *Results);\n{# fun clang_codeCompleteGetNumDiagnostics { id `Ptr ()' } -> `Int' #}\ncodeCompleteGetNumDiagnostics :: CodeCompleteResults s -> IO Int\ncodeCompleteGetNumDiagnostics rs = clang_codeCompleteGetNumDiagnostics (unCodeCompleteResults rs)\n\n-- CXDiagnostic clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *Results,\n-- unsigned Index);\n{# fun clang_codeCompleteGetDiagnostic { id `Ptr ()' , `Int' } -> `Ptr ()' id #}\nunsafe_codeCompleteGetDiagnostic :: CodeCompleteResults s -> Int -> IO (Diagnostic ())\nunsafe_codeCompleteGetDiagnostic rs idx =\n clang_codeCompleteGetDiagnostic (unCodeCompleteResults rs) idx >>= return . mkDiagnostic\n\ncodeCompleteGetDiagnostic :: ClangBase m => CodeCompleteResults s' -> Int\n -> ClangT s m (Diagnostic s)\ncodeCompleteGetDiagnostic = (registerDiagnostic .) . unsafe_codeCompleteGetDiagnostic\n\n-- enum CXCompletionContext {\n-- CXCompletionContext_Unexposed = 0,\n-- CXCompletionContext_AnyType = 1 << 0,\n-- CXCompletionContext_AnyValue = 1 << 1,\n-- CXCompletionContext_ObjCObjectValue = 1 << 2,\n-- CXCompletionContext_ObjCSelectorValue = 1 << 3,\n-- CXCompletionContext_CXXClassTypeValue = 1 << 4,\n-- CXCompletionContext_DotMemberAccess = 1 << 5,\n-- CXCompletionContext_ArrowMemberAccess = 1 << 6,\n-- CXCompletionContext_ObjCPropertyAccess = 1 << 7,\n-- CXCompletionContext_EnumTag = 1 << 8,\n-- CXCompletionContext_UnionTag = 1 << 9,\n-- CXCompletionContext_StructTag = 1 << 10,\n-- CXCompletionContext_ClassTag = 1 << 11,\n-- CXCompletionContext_Namespace = 1 << 12,\n-- CXCompletionContext_NestedNameSpecifier = 1 << 13,\n-- CXCompletionContext_ObjCInterface = 1 << 14,\n-- CXCompletionContext_ObjCProtocol = 1 << 15,\n-- CXCompletionContext_ObjCCategory = 1 << 16,\n-- CXCompletionContext_ObjCInstanceMessage = 1 << 17,\n-- CXCompletionContext_ObjCClassMessage = 1 << 18,\n-- CXCompletionContext_ObjCSelectorName = 1 << 19,\n-- CXCompletionContext_MacroName = 1 << 20,\n-- CXCompletionContext_NaturalLanguage = 1 << 21,\n-- CXCompletionContext_Unknown = ((1 << 22) - 1) -- Set all\n -- contexts... Not a real value.\n-- };\n\n-- | Contexts under which completion may occur. Multiple contexts may be\n-- present at the same time.\n--\n-- * 'UnexposedCompletionContext': The context for completions is unexposed,\n-- as only Clang results should be included.\n--\n-- * 'AnyTypeCompletionContext': Completions for any possible type should be\n-- included in the results.\n--\n-- * 'AnyValueCompletionContext': Completions for any possible value (variables,\n-- function calls, etc.) should be included in the results.\n--\n-- * 'ObjCObjectValueCompletionContext': Completions for values that resolve to\n-- an Objective-C object should be included in the results.\n--\n-- * 'ObjCSelectorValueCompletionContext': Completions for values that resolve\n-- to an Objective-C selector should be included in the results.\n--\n-- * 'CXXClassTypeValueCompletionContext': Completions for values that resolve\n-- to a C++ class type should be included in the results.\n--\n-- * 'DotMemberAccessCompletionContext': Completions for fields of the member\n-- being accessed using the dot operator should be included in the results.\n--\n-- * 'ArrowMemberAccessCompletionContext': Completions for fields of the member\n-- being accessed using the arrow operator should be included in the results.\n--\n-- * 'ObjCPropertyAccessCompletionContext': Completions for properties of the\n-- Objective-C object being accessed using the dot operator should be included in the results.\n--\n-- * 'EnumTagCompletionContext': Completions for enum tags should be included in the results.\n--\n-- * 'UnionTagCompletionContext': Completions for union tags should be included in the results.\n--\n-- * 'StructTagCompletionContext': Completions for struct tags should be included in the\n-- results.\n--\n-- * 'ClassTagCompletionContext': Completions for C++ class names should be included in the\n-- results.\n--\n-- * 'NamespaceCompletionContext': Completions for C++ namespaces and namespace aliases should\n-- be included in the results.\n--\n-- * 'NestedNameSpecifierCompletionContext': Completions for C++ nested name specifiers should\n-- be included in the results.\n--\n-- * 'ObjCInterfaceCompletionContext': Completions for Objective-C interfaces (classes) should\n-- be included in the results.\n--\n-- * 'ObjCProtocolCompletionContext': Completions for Objective-C protocols should be included\n-- in the results.\n--\n-- * 'ObjCCategoryCompletionContext': Completions for Objective-C categories should be included\n-- in the results.\n--\n-- * 'ObjCInstanceMessageCompletionContext': Completions for Objective-C instance messages\n-- should be included in the results.\n--\n-- * 'ObjCClassMessageCompletionContext': Completions for Objective-C class messages should be\n-- included in the results.\n--\n-- * 'ObjCSelectorNameCompletionContext': Completions for Objective-C selector names should be\n-- included in the results.\n--\n-- * 'MacroNameCompletionContext': Completions for preprocessor macro names should be included\n-- in the results.\n--\n-- * 'NaturalLanguageCompletionContext': Natural language completions should be included in the\n-- results.\n#c\nenum CompletionContext\n { UnexposedCompletionContext = CXCompletionContext_Unexposed\n , AnyTypeCompletionContext = CXCompletionContext_AnyType\n , AnyValueCompletionContext = CXCompletionContext_AnyValue\n , ObjCObjectValueCompletionContext = CXCompletionContext_ObjCObjectValue\n , ObjCSelectorValueCompletionContext = CXCompletionContext_ObjCSelectorValue\n , CXXClassTypeValueCompletionContext = CXCompletionContext_CXXClassTypeValue\n , DotMemberAccessCompletionContext = CXCompletionContext_DotMemberAccess\n , ArrowMemberAccessCompletionContext = CXCompletionContext_ArrowMemberAccess\n , ObjCPropertyAccessCompletionContext = CXCompletionContext_ObjCPropertyAccess\n , EnumTagCompletionContext = CXCompletionContext_EnumTag\n , UnionTagCompletionContext = CXCompletionContext_UnionTag\n , StructTagCompletionContext = CXCompletionContext_StructTag\n , ClassTagCompletionContext = CXCompletionContext_ClassTag\n , NamespaceCompletionContext = CXCompletionContext_Namespace\n , NestedNameSpecifierCompletionContext = CXCompletionContext_NestedNameSpecifier\n , ObjCInterfaceCompletionContext = CXCompletionContext_ObjCInterface\n , ObjCProtocolCompletionContext = CXCompletionContext_ObjCProtocol\n , ObjCCategoryCompletionContext = CXCompletionContext_ObjCCategory\n , ObjCInstanceMessageCompletionContext = CXCompletionContext_ObjCInstanceMessage\n , ObjCClassMessageCompletionContext = CXCompletionContext_ObjCClassMessage\n , ObjCSelectorNameCompletionContext = CXCompletionContext_ObjCSelectorName\n , MacroNameCompletionContext = CXCompletionContext_MacroName\n , NaturalLanguageCompletionContext = CXCompletionContext_NaturalLanguage\n };\n#endc\n{# enum CompletionContext {} deriving (Bounded, Eq, Ord, Read, Show, Typeable) #}\n\ninstance BitFlags CompletionContext where\n type FlagInt CompletionContext = Int64\n toBit UnexposedCompletionContext = 0x0\n toBit AnyTypeCompletionContext = 0x1\n toBit AnyValueCompletionContext = 0x2\n toBit ObjCObjectValueCompletionContext = 0x4\n toBit ObjCSelectorValueCompletionContext = 0x8\n toBit CXXClassTypeValueCompletionContext = 0x10\n toBit DotMemberAccessCompletionContext = 0x20\n toBit ArrowMemberAccessCompletionContext = 0x40\n toBit ObjCPropertyAccessCompletionContext = 0x80\n toBit EnumTagCompletionContext = 0x100\n toBit UnionTagCompletionContext = 0x200\n toBit StructTagCompletionContext = 0x400\n toBit ClassTagCompletionContext = 0x800\n toBit NamespaceCompletionContext = 0x1000\n toBit NestedNameSpecifierCompletionContext = 0x2000\n toBit ObjCInterfaceCompletionContext = 0x4000\n toBit ObjCProtocolCompletionContext = 0x8000\n toBit ObjCCategoryCompletionContext = 0x10000\n toBit ObjCInstanceMessageCompletionContext = 0x20000\n toBit ObjCClassMessageCompletionContext = 0x40000\n toBit ObjCSelectorNameCompletionContext = 0x80000\n toBit MacroNameCompletionContext = 0x100000\n toBit NaturalLanguageCompletionContext = 0x200000\n\n-- unsigned long long clang_codeCompleteGetContexts(CXCodeCompleteResults *Results);\n{# fun clang_codeCompleteGetContexts { id `Ptr ()' } -> `Int64' #}\ncodeCompleteGetContexts :: CodeCompleteResults s -> IO Int64\ncodeCompleteGetContexts rs = clang_codeCompleteGetContexts (unCodeCompleteResults rs)\n\n-- enum CXCursorKind clang_codeCompleteGetContainerKind(CXCodeCompleteResults *Results,\n-- unsigned *IsIncomplete);\n{# fun clang_codeCompleteGetContainerKind { id `Ptr ()', id `Ptr CUInt' } -> `Int' #}\ncodeCompleteGetContainerKind :: CodeCompleteResults s -> IO (CursorKind, Bool)\ncodeCompleteGetContainerKind rs =\n alloca (\\(iPtr :: (Ptr CUInt)) -> do\n k <- clang_codeCompleteGetContainerKind (unCodeCompleteResults rs) iPtr\n bool <- peek iPtr\n return (toEnum k, toBool ((fromIntegral bool) :: Int)))\n\n-- CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *Results);\n{# fun clang_codeCompleteGetContainerUSR { id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_codeCompleteGetContainerUSR :: CodeCompleteResults s -> IO (ClangString ())\nunsafe_codeCompleteGetContainerUSR rs = clang_codeCompleteGetContainerUSR (unCodeCompleteResults rs) >>= peek\n\ncodeCompleteGetContainerUSR :: ClangBase m => CodeCompleteResults s' -> ClangT s m (ClangString s)\ncodeCompleteGetContainerUSR = registerClangString . unsafe_codeCompleteGetContainerUSR\n\n-- CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *Results);\n{# fun clang_codeCompleteGetObjCSelector { id `Ptr ()' } -> `Ptr (ClangString ())' castPtr #}\nunsafe_codeCompleteGetObjCSelector :: CodeCompleteResults s -> IO (ClangString ())\nunsafe_codeCompleteGetObjCSelector rs = clang_codeCompleteGetObjCSelector (unCodeCompleteResults rs) >>= peek\n\ncodeCompleteGetObjCSelector :: ClangBase m => CodeCompleteResults s' -> ClangT s m (ClangString s)\ncodeCompleteGetObjCSelector = registerClangString . unsafe_codeCompleteGetObjCSelector\n\n-- CXString clang_getClangVersion();\n{# fun wrapped_clang_getClangVersion as clang_getClangVersion {} -> `Ptr (ClangString ())' castPtr #}\nunsafe_getClangVersion :: IO (ClangString ())\nunsafe_getClangVersion = clang_getClangVersion >>= peek\n\ngetClangVersion :: ClangBase m => ClangT s m (ClangString s)\ngetClangVersion = registerClangString $ unsafe_getClangVersion\n\n-- -- void clang_toggleCrashRecovery(unsigned isEnabled);\n{# fun clang_toggleCrashRecovery as toggleCrashRecovery' { `Int' } -> `()' #}\ntoggleCrashRecovery :: Bool -> IO ()\ntoggleCrashRecovery b = toggleCrashRecovery' (fromBool b)\n\ndata Inclusion s = Inclusion !(File s) !(SourceLocation s) !Bool\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue Inclusion\n\ninstance Storable (Inclusion s) where\n sizeOf _ = sizeOfInclusion\n {-# INLINE sizeOf #-}\n\n alignment _ = alignOfInclusion\n {-# INLINE alignment #-}\n\n peek p = do\n let fromCUChar = fromIntegral :: Num b => CUChar -> b\n file <- File <$> peekByteOff p offsetInclusionInclusion\n sl <- peekByteOff p offsetInclusionLocation\n isDirect :: Int <- fromCUChar <$> peekByteOff p offsetInclusionIsDirect\n return $! Inclusion file sl (if isDirect == 0 then False else True)\n {-# INLINE peek #-}\n\n poke p (Inclusion (File file) sl isDirect) = do\n let toCUChar = fromIntegral :: Integral a => a -> CUChar\n pokeByteOff p offsetInclusionInclusion file\n pokeByteOff p offsetInclusionLocation sl\n pokeByteOff p offsetInclusionIsDirect\n (toCUChar $ if isDirect then 1 :: Int else 0)\n {-# INLINE poke #-}\n\ntype InclusionList s = DVS.Vector (Inclusion s)\ninstance ClangValueList Inclusion\ndata UnsafeInclusionList = UnsafeInclusionList !(Ptr ()) !Int\n\n-- void freeInclusions(struct Inclusion* inclusions);\n{# fun freeInclusionList as freeInclusionList' { id `Ptr ()' } -> `()' #}\nfreeInclusions :: InclusionList s -> IO ()\nfreeInclusions is =\n let (isPtr, n) = fromInclusionList is in\n freeInclusionList' isPtr\n\nregisterInclusionList :: ClangBase m => IO UnsafeInclusionList -> ClangT s m (InclusionList s)\nregisterInclusionList action = do\n (_, inclusionList) <- clangAllocate (action >>= mkSafe) freeInclusions\n return inclusionList\n where\n mkSafe (UnsafeInclusionList is n) = do\n fptr <- newForeignPtr_ (castPtr is)\n return $ DVS.unsafeFromForeignPtr fptr 0 n\n{-# INLINEABLE registerInclusionList #-}\n\nfromInclusionList :: InclusionList s -> (Ptr (), Int)\nfromInclusionList is = let (p, _, _) = DVS.unsafeToForeignPtr is in\n (castPtr $ Foreign.ForeignPtr.Unsafe.unsafeForeignPtrToPtr p, DVS.length is)\n\ntoInclusionList :: (Ptr (), Int) -> UnsafeInclusionList\ntoInclusionList (is, n) = UnsafeInclusionList is n\n\n#c\ntypedef Inclusion** PtrPtrInclusion;\n#endc\n\n-- A more efficient alternative to clang_getInclusions.\n-- void getInclusions(CXTranslationUnit tu, struct Inclusion** inclusionsOut, unsigned* countOut)\n{# fun getInclusions as getInclusions' { id `Ptr ()', id `Ptr (Ptr ())', alloca- `CUInt' peek* } -> `()' #}\nunsafe_getInclusions :: TranslationUnit s -> IO UnsafeInclusionList\nunsafe_getInclusions tu = do\n iPtrPtr <- mallocBytes {#sizeof PtrPtrInclusion #}\n n <- getInclusions' (unTranslationUnit tu) (castPtr iPtrPtr)\n firstInclusion <- peek (castPtr iPtrPtr :: Ptr (Ptr ()))\n free iPtrPtr\n return (toInclusionList (firstInclusion, fromIntegral n))\n\n\ngetInclusions :: ClangBase m => TranslationUnit s' -> ClangT s m (InclusionList s)\ngetInclusions = registerInclusionList . unsafe_getInclusions\n\n-- typedef void* CXRemapping;\nnewtype Remapping s = Remapping { unRemapping :: Ptr () }\n deriving (Eq, Ord, Typeable)\n\ninstance ClangValue Remapping\n\nmkRemapping :: Ptr () -> Remapping ()\nmkRemapping = Remapping\n\n-- void clang_remap_dispose(CXRemapping);\n{# fun clang_remap_dispose { id `Ptr ()' } -> `()' #}\nremap_dispose :: Remapping s -> IO ()\nremap_dispose d = clang_remap_dispose (unRemapping d)\n\nregisterRemapping :: ClangBase m => IO (Remapping ()) -> ClangT s m (Remapping s)\nregisterRemapping action = do\n (_, idx) <- clangAllocate (action >>= return . unsafeCoerce)\n (\\i -> remap_dispose i)\n return idx\n{-# INLINEABLE registerRemapping #-}\n\n-- %dis remapping i = (ptr i)\n\nmaybeRemapping :: Remapping s' -> Maybe (Remapping s)\nmaybeRemapping (Remapping p) | p == nullPtr = Nothing\nmaybeRemapping f = Just (unsafeCoerce f)\n\nunMaybeRemapping :: Maybe (Remapping s') -> Remapping s\nunMaybeRemapping (Just f) = unsafeCoerce f\nunMaybeRemapping Nothing = Remapping nullPtr\n\n-- CXRemapping clang_getRemappings(const char *path);\n{# fun clang_getRemappings { `CString' } -> `Ptr ()' id #}\nunsafe_getRemappings :: FilePath -> IO (Maybe (Remapping ()))\nunsafe_getRemappings fp =\n withCString fp (\\sPtr -> clang_getRemappings sPtr >>= return . maybeRemapping . mkRemapping )\n\ngetRemappings :: ClangBase m => FilePath -> ClangT s m (Maybe (Remapping s))\ngetRemappings path = do\n mRemappings <- liftIO $ unsafe_getRemappings path\n case mRemappings of\n Just remappings -> Just <$> registerRemapping (return remappings)\n Nothing -> return Nothing\n\n-- CXRemapping clang_getRemappingsFromFileList(const char **filePaths, unsigned numFiles);\n{# fun clang_getRemappingsFromFileList { id `Ptr CString' , `Int' } -> `Ptr ()' id #}\nunsafe_getRemappingsFromFileList :: Ptr CString -> Int -> IO (Maybe (Remapping ()))\nunsafe_getRemappingsFromFileList paths numPaths =\n clang_getRemappingsFromFileList paths numPaths >>= return . maybeRemapping . mkRemapping\n\ngetRemappingsFromFileList :: ClangBase m => [FilePath] -> ClangT s m (Maybe (Remapping s))\ngetRemappingsFromFileList paths = do\n mRemappings <- liftIO $ withStringList paths unsafe_getRemappingsFromFileList\n case mRemappings of\n Just remappings -> Just <$> registerRemapping (return remappings)\n Nothing -> return Nothing\n\n-- unsigned clang_remap_getNumFiles(CXRemapping);\n{# fun clang_remap_getNumFiles { id `Ptr ()' } -> `Int' #}\nremap_getNumFiles :: Remapping s -> IO Int\nremap_getNumFiles remaps =\n clang_remap_getNumFiles (unRemapping remaps)\n\n-- void clang_remap_getFilenames(CXRemapping, unsigned index,\n-- CXString *original, CXString *transformed);\n{# fun clang_remap_getFilenames { id `Ptr ()', `Int', id `Ptr ()', id `Ptr ()' } -> `()' #}\nunsafe_remap_getFilenames :: Remapping s -> Int -> IO (ClangString (), ClangString ())\nunsafe_remap_getFilenames remaps idx = do\n origPtr <- mallocBytes (sizeOf (undefined :: (Ptr (ClangString ()))))\n txPtr <- mallocBytes (sizeOf (undefined :: (Ptr (ClangString ()))))\n clang_remap_getFilenames (unRemapping remaps) idx origPtr txPtr\n orig <- peek (castPtr origPtr)\n tx <- peek (castPtr txPtr)\n free origPtr\n free txPtr\n return (orig, tx)\n\nremap_getFilenames :: ClangBase m => Remapping s' -> Int -> ClangT s m (ClangString s, ClangString s)\nremap_getFilenames r idx = do\n (orig, tr) <- liftIO $ unsafe_remap_getFilenames r idx\n (,) <$> registerClangString (return orig) <*> registerClangString (return tr)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"3d956680b58f93a7e5edcc7f84a9b2dbf35110c8","subject":"Document the Cairo.SVG module.","message":"Document the Cairo.SVG module.\n","repos":"gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/vte,gtk2hs\/gtksourceview","old_file":"svgcairo\/Graphics\/Rendering\/Cairo\/SVG.chs","new_file":"svgcairo\/Graphics\/Rendering\/Cairo\/SVG.chs","new_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.SVG\n-- Copyright : (c) 2005 Duncan Coutts, Paolo Martini \n-- License : BSD-style (see cairo\/COPYRIGHT)\n--\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : experimental\n-- Portability : portable\n--\n-- The SVG extension to the Cairo 2D graphics library.\n--\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.SVG (\n -- * Convenience API\n\n -- | These operations render an SVG image directly in the current 'Render'\n -- contect. Because they operate in the cairo 'Render' monad they are\n -- affected by the current transformation matrix. So it is possible, for\n -- example, to scale or rotate an SVG image.\n --\n -- In the following example we scale an SVG image to a unit square:\n --\n -- > let (width, height) = svgGetSize in\n -- > do scale (1\/width) (1\/height)\n -- > svgRender svg\n\n svgRenderFromFile,\n svgRenderFromHandle,\n svgRenderFromString,\n\n -- * Standard API\n\n -- | With this API there are seperate functions for loading the SVG and\n -- rendering it. This allows us to be more effecient in the case that an SVG\n -- image is used many times - since it can be loaded just once and rendered\n -- many times. With the convenience API above the SVG would be parsed and\n -- processed each time it is drawn.\n\n SVG,\n svgRender,\n svgGetSize,\n\n -- ** Block scoped versions\n\n -- | These versions of the SVG loading operations give temporary access\n -- to the 'SVG' object within the scope of the handler function. These\n -- operations guarantee that the resources for the SVG object are deallocated\n -- at the end of the handler block. If this form of resource allocation is\n -- too restrictive you can use the GC-managed versions below.\n --\n -- These versions are ofen used in the following style:\n --\n -- > withSvgFromFile \"foo.svg\" $ \\svg -> do\n -- > ...\n -- > svgRender svg\n -- > ...\n\n withSvgFromFile,\n withSvgFromHandle,\n withSvgFromString,\n\n -- ** GC-managed versions\n\n -- | These versions of the SVG loading operations use the standard Haskell\n -- garbage collector to manage the resources associated with the 'SVG' object.\n -- As such they are more convenient to use but the GC cannot give\n -- strong guarantees about when the resources associated with the 'SVG' object\n -- will be released. In most circumstances this is not a problem, especially\n -- if the SVG files being used are not very big.\n\n svgNewFromFile,\n svgNewFromHandle,\n svgNewFromString,\n ) where\n\nimport Control.Monad (liftM, when)\nimport Foreign hiding (rotate)\nimport CForeign\nimport Control.Exception (bracket)\nimport Control.Monad.Reader (ReaderT(..), runReaderT, ask, MonadIO, liftIO)\nimport System.IO\n\nimport Graphics.Rendering.Cairo.Internal hiding (Status(..))\n{# import Graphics.Rendering.Cairo.Types #} hiding (Status(..))\n\n{# context lib=\"svg-cairo\" prefix=\"svg_cairo\" #}\n\n---------------------\n-- Types\n-- \n\n{# pointer *svg_cairo_t as SVG foreign newtype #}\n\n{# enum status_t as Status {underscoreToCase} deriving(Eq, Show) #}\n\n---------------------\n-- Basic API\n-- \n\n-- block scoped versions\n\nwithSvgFromFile :: FilePath -> (SVG -> Render a) -> Render a\nwithSvgFromFile file action =\n withSVG $ \\svg -> do \n liftIO $ svgParseFromFile file svg\n action svg\n\nwithSvgFromHandle :: Handle -> (SVG -> Render a) -> Render a\nwithSvgFromHandle hnd action =\n withSVG $ \\svg -> do \n liftIO $ svgParseFromHandle hnd svg\n action svg\n\nwithSvgFromString :: String -> (SVG -> Render a) -> Render a\nwithSvgFromString str action =\n withSVG $ \\svg -> do\n liftIO $ svgParseFromString str svg\n action svg\n\nwithSVG :: (SVG -> Render a) -> Render a\nwithSVG =\n bracketR (alloca $ \\svgPtrPtr -> do\n {# call unsafe create #} (castPtr svgPtrPtr)\n svgPtr <- peek (svgPtrPtr :: Ptr (Ptr SVG))\n svgPtr' <- newForeignPtr_ svgPtr\n return (SVG svgPtr'))\n \n {# call unsafe destroy #}\n\n-- GC managed versions\n\nsvgNewFromFile :: FilePath -> IO SVG\nsvgNewFromFile file = do\n svg <- svgNew\n svgParseFromFile file svg\n return svg\n\nsvgNewFromHandle :: Handle -> IO SVG\nsvgNewFromHandle hnd = do\n svg <- svgNew\n svgParseFromHandle hnd svg\n return svg\n\nsvgNewFromString :: String -> IO SVG\nsvgNewFromString str = do\n svg <- svgNew\n svgParseFromString str svg\n return svg\n\nsvgNew :: IO SVG\nsvgNew =\n alloca $ \\svgPtrPtr -> do\n {# call unsafe create #} (castPtr svgPtrPtr)\n svgPtr <- peek (svgPtrPtr :: Ptr (Ptr SVG))\n svgPtr' <- newForeignPtr svg_cairo_destroy_ptr svgPtr\n return (SVG svgPtr')\n\nforeign import ccall unsafe \"&svg_cairo_destroy\"\n svg_cairo_destroy_ptr :: FinalizerPtr SVG\n\n-- internal implementation\n\nsvgParseFromFile :: FilePath -> SVG -> IO ()\nsvgParseFromFile file svg =\n checkStatus $\n withCString file $ \\filePtr -> \n {# call parse #} svg filePtr\n\nsvgParseFromHandle :: Handle -> SVG -> IO ()\nsvgParseFromHandle hnd svg =\n allocaBytes 4096 $ \\bufferPtr -> do\n checkStatus $ {# call parse_chunk_begin #} svg\n let loop = do\n count <- hGetBuf hnd bufferPtr 4096\n when (count > 0)\n (checkStatus $ {# call parse_chunk #}\n svg bufferPtr (fromIntegral count))\n when (count == 4096) loop\n loop\n checkStatus $ {# call parse_chunk_end #} svg\n\nsvgParseFromString :: String -> SVG -> IO ()\nsvgParseFromString str svg = do\n checkStatus $ {# call parse_chunk_begin #} svg\n let loop \"\" = return ()\n loop str =\n case splitAt 4096 str of\n (chunk, str') -> do\n withCStringLen chunk $ \\(chunkPtr, len) ->\n checkStatus $ {# call parse_chunk #}\n svg chunkPtr (fromIntegral len)\n loop str'\n loop str\n checkStatus $ {# call parse_chunk_end #} svg\n\n-- actually render it\n\nsvgRender :: SVG -> Render ()\nsvgRender svg = do\n cr <- ask\n liftIO $ checkStatus $ {# call render #} svg cr\n\n-- | Get the width and height of the SVG image.\n--\nsvgGetSize :: \n SVG\n -> (Int, Int) -- ^ @(width, height)@\nsvgGetSize svg = unsafePerformIO $\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call unsafe get_size #} svg widthPtr heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n---------------------\n-- Convenience API\n-- \n\nsvgRenderFromFile :: FilePath -> Render ()\nsvgRenderFromFile file = withSvgFromFile file svgRender\n\nsvgRenderFromHandle :: Handle -> Render ()\nsvgRenderFromHandle hnd = withSvgFromHandle hnd svgRender\n\nsvgRenderFromString :: String -> Render ()\nsvgRenderFromString str = withSvgFromString str svgRender\n\n---------------------\n-- Utils\n-- \n\ncheckStatus :: IO CInt -> IO ()\ncheckStatus action = do\n status <- liftM (toEnum . fromIntegral) action\n if status == StatusSuccess\n then return ()\n else fail (\"svg-cairo error: \" ++ show status)\n","old_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.SVG\n-- Copyright : (c) 2005 Duncan Coutts, Paolo Martini \n-- License : BSD-style (see cairo\/COPYRIGHT)\n--\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : experimental\n-- Portability : portable\n--\n-- The SVG extension to the Cairo 2D graphics library.\n--\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.SVG (\n -- * Convenience API\n svgRenderFromFile,\n svgRenderFromHandle,\n svgRenderFromString,\n \n -- * Basic API\n SVG,\n svgRender,\n svgGetSize,\n\n -- ** Block scoped versions\n withSvgFromFile,\n withSvgFromHandle,\n withSvgFromString,\n\n -- ** GC-managed versions\n svgNewFromFile,\n svgNewFromHandle,\n svgNewFromString,\n ) where\n\nimport Control.Monad (liftM, when)\nimport Foreign hiding (rotate)\nimport CForeign\nimport Control.Exception (bracket)\nimport Control.Monad.Reader (ReaderT(..), runReaderT, ask, MonadIO, liftIO)\nimport System.IO\n\nimport Graphics.Rendering.Cairo.Internal hiding (Status(..))\n{# import Graphics.Rendering.Cairo.Types #} hiding (Status(..))\n\n{# context lib=\"svg-cairo\" prefix=\"svg_cairo\" #}\n\n---------------------\n-- Types\n-- \n\n{# pointer *svg_cairo_t as SVG foreign newtype #}\n\n{# enum status_t as Status {underscoreToCase} deriving(Eq, Show) #}\n\n---------------------\n-- Basic API\n-- \n\n-- block scoped versions\n\nwithSvgFromFile :: FilePath -> (SVG -> Render a) -> Render a\nwithSvgFromFile file action =\n withSVG $ \\svg -> do \n liftIO $ svgParseFromFile file svg\n action svg\n\nwithSvgFromHandle :: Handle -> (SVG -> Render a) -> Render a\nwithSvgFromHandle hnd action =\n withSVG $ \\svg -> do \n liftIO $ svgParseFromHandle hnd svg\n action svg\n\nwithSvgFromString :: String -> (SVG -> Render a) -> Render a\nwithSvgFromString str action =\n withSVG $ \\svg -> do\n liftIO $ svgParseFromString str svg\n action svg\n\nwithSVG :: (SVG -> Render a) -> Render a\nwithSVG =\n bracketR (alloca $ \\svgPtrPtr -> do\n {# call unsafe create #} (castPtr svgPtrPtr)\n svgPtr <- peek (svgPtrPtr :: Ptr (Ptr SVG))\n svgPtr' <- newForeignPtr_ svgPtr\n return (SVG svgPtr'))\n \n {# call unsafe destroy #}\n\n-- GC managed versions\n\nsvgNewFromFile :: FilePath -> IO SVG\nsvgNewFromFile file = do\n svg <- svgNew\n svgParseFromFile file svg\n return svg\n\nsvgNewFromHandle :: Handle -> IO SVG\nsvgNewFromHandle hnd = do\n svg <- svgNew\n svgParseFromHandle hnd svg\n return svg\n\nsvgNewFromString :: String -> IO SVG\nsvgNewFromString str = do\n svg <- svgNew\n svgParseFromString str svg\n return svg\n\nsvgNew :: IO SVG\nsvgNew =\n alloca $ \\svgPtrPtr -> do\n {# call unsafe create #} (castPtr svgPtrPtr)\n svgPtr <- peek (svgPtrPtr :: Ptr (Ptr SVG))\n svgPtr' <- newForeignPtr svg_cairo_destroy_ptr svgPtr\n return (SVG svgPtr')\n\nforeign import ccall unsafe \"&svg_cairo_destroy\"\n svg_cairo_destroy_ptr :: FinalizerPtr SVG\n\n-- internal implementation\n\nsvgParseFromFile :: FilePath -> SVG -> IO ()\nsvgParseFromFile file svg =\n checkStatus $\n withCString file $ \\filePtr -> \n {# call parse #} svg filePtr\n\nsvgParseFromHandle :: Handle -> SVG -> IO ()\nsvgParseFromHandle hnd svg =\n allocaBytes 4096 $ \\bufferPtr -> do\n checkStatus $ {# call parse_chunk_begin #} svg\n let loop = do\n count <- hGetBuf hnd bufferPtr 4096\n when (count > 0)\n (checkStatus $ {# call parse_chunk #}\n svg bufferPtr (fromIntegral count))\n when (count == 4096) loop\n loop\n checkStatus $ {# call parse_chunk_end #} svg\n\nsvgParseFromString :: String -> SVG -> IO ()\nsvgParseFromString str svg = do\n checkStatus $ {# call parse_chunk_begin #} svg\n let loop \"\" = return ()\n loop str =\n case splitAt 4096 str of\n (chunk, str') -> do\n withCStringLen chunk $ \\(chunkPtr, len) ->\n checkStatus $ {# call parse_chunk #}\n svg chunkPtr (fromIntegral len)\n loop str'\n loop str\n checkStatus $ {# call parse_chunk_end #} svg\n\n-- actually render it\n\nsvgRender :: SVG -> Render ()\nsvgRender svg = do\n cr <- ask\n liftIO $ checkStatus $ {# call render #} svg cr\n\n-- find out how big the thing is supposed to be.\nsvgGetSize :: SVG -> (Int, Int)\nsvgGetSize svg = unsafePerformIO $\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call unsafe get_size #} svg widthPtr heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n---------------------\n-- Convenience API\n-- \n\nsvgRenderFromFile :: FilePath -> Render ()\nsvgRenderFromFile file = withSvgFromFile file svgRender\n\nsvgRenderFromHandle :: Handle -> Render ()\nsvgRenderFromHandle hnd = withSvgFromHandle hnd svgRender\n\nsvgRenderFromString :: String -> Render ()\nsvgRenderFromString str = withSvgFromString str svgRender\n\n---------------------\n-- Utils\n-- \n\ncheckStatus :: IO CInt -> IO ()\ncheckStatus action = do\n status <- liftM (toEnum . fromIntegral) action\n if status == StatusSuccess\n then return ()\n else fail (\"svg-cairo error: \" ++ show status)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"5732b0484cf1e6fcdacf90b5ccd2e30a2e21dde4","subject":"flushCache only makes sense on RWDatasets and better error reporting","message":"flushCache only makes sense on RWDatasets and better error reporting\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/OSGeo\/GDAL\/Internal.chs","new_file":"src\/OSGeo\/GDAL\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nmodule OSGeo.GDAL.Internal (\n HasDataset\n , HasBand\n , HasWritebaleBand\n , HasDatatype\n , Datatype (..)\n , GDALException\n , isGDALException\n , Geotransform (..)\n , IOVector\n , DriverOptions\n , MajorObject\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Driver\n , DriverName\n , ColorTable\n , RasterAttributeTable\n , GComplex (..)\n\n , setQuietErrorHandler\n , unDataset\n , unBand\n\n , withAllDriversRegistered\n , registerAllDrivers\n , destroyDriverManager\n , driverByName\n , create\n , create'\n , createMem\n , flushCache\n , openReadOnly\n , openReadWrite\n , createCopy\n\n , datatypeSize\n , datatypeByName\n , datatypeUnion\n , datatypeIsComplex\n\n , datasetProjection\n , setDatasetProjection\n , datasetGeotransform\n , setDatasetGeotransform\n , datasetBandCount\n\n , withBand\n , bandDatatype\n , bandBlockSize\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , readBand\n , readBandBlock\n , writeBand\n , writeBand'\n , writeBandBlock\n , fillBand\n\n , toComplex\n , fromComplex\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception (bracket, throw, Exception(..), SomeException,\n finally)\nimport Control.Monad (liftM, foldM)\n\nimport Data.Int (Int16, Int32)\nimport qualified Data.Complex as Complex\nimport Data.Maybe (isJust)\nimport Data.Typeable (Typeable, typeOf)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector, unsafeFromForeignPtr0, unsafeToForeignPtr0)\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (ForeignPtr, withForeignPtr, newForeignPtr\n ,mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport OSGeo.Util\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\ntype DriverName = String\n\n\ndata GDALException = GDALException Error String\n deriving (Show, Typeable)\n\ninstance Exception GDALException\n\nisGDALException :: SomeException -> Bool\nisGDALException e = isJust (fromException e :: Maybe GDALException)\n\n{# enum CPLErr as Error {upcaseFirstLetter} deriving (Eq,Show) #}\n\n\ntype ErrorHandler = CInt -> CInt -> CString -> IO ()\n\nforeign import ccall \"cpl_error.h &CPLQuietErrorHandler\"\n c_quietErrorHandler :: FunPtr ErrorHandler\n\nforeign import ccall \"cpl_error.h CPLSetErrorHandler\"\n c_setErrorHandler :: FunPtr ErrorHandler -> IO (FunPtr ErrorHandler)\n\nsetQuietErrorHandler :: IO ()\nsetQuietErrorHandler = setErrorHandler c_quietErrorHandler\n\nsetErrorHandler :: FunPtr ErrorHandler -> IO ()\nsetErrorHandler h = c_setErrorHandler h >>= (\\_->return ())\n\n\nthrowIfError :: String -> IO CInt -> IO ()\nthrowIfError msg act = do\n e <- liftM toEnumC act\n case e of\n CE_None -> return ()\n e' -> throw $ GDALException e' msg\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\ninstance Show Datatype where\n show = getDatatypeName\n\n{# fun pure unsafe GDALGetDataTypeSize as datatypeSize\n { fromEnumC `Datatype' } -> `Int' #}\n\n{# fun pure unsafe GDALDataTypeIsComplex as datatypeIsComplex\n { fromEnumC `Datatype' } -> `Bool' #}\n\n{# fun pure unsafe GDALGetDataTypeName as getDatatypeName\n { fromEnumC `Datatype' } -> `String' #}\n\n{# fun pure unsafe GDALGetDataTypeByName as datatypeByName\n { `String' } -> `Datatype' toEnumC #}\n\n{# fun pure unsafe GDALDataTypeUnion as datatypeUnion\n { fromEnumC `Datatype', fromEnumC `Datatype' } -> `Datatype' toEnumC #}\n\n\n{# enum GDALAccess as Access {upcaseFirstLetter} deriving (Eq, Show) #}\n\n{# enum GDALRWFlag as RwFlag {upcaseFirstLetter} deriving (Eq, Show) #}\n\n{#pointer GDALMajorObjectH as MajorObject newtype#}\n{#pointer GDALDatasetH as Dataset foreign newtype nocode#}\n\ndata ReadOnly\ndata ReadWrite\nnewtype (Dataset a t) = Dataset (ForeignPtr (Dataset a t), Mutex)\n\nunDataset (Dataset (d, _)) = d\n\ntype RODataset = Dataset ReadOnly\ntype RWDataset = Dataset ReadWrite\nwithDataset, withDataset' :: (Dataset a t) -> (Ptr (Dataset a t) -> IO b) -> IO b\nwithDataset ds@(Dataset (_, m)) fun = withMutex m $ withDataset' ds fun\n\nwithDataset' (Dataset (fptr,_)) = withForeignPtr fptr\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band a t) = Band (Ptr ((Band a t)))\n\nunBand (Band b) = b\n\ntype ROBand = Band ReadOnly\ntype RWBand = Band ReadWrite\n\n\n{#pointer GDALDriverH as Driver newtype#}\n{#pointer GDALColorTableH as ColorTable newtype#}\n{#pointer GDALRasterAttributeTableH as RasterAttributeTable newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\nwithAllDriversRegistered act\n = registerAllDrivers >> finally act destroyDriverManager\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `Driver' id #}\n\ndriverByName :: String -> IO Driver\ndriverByName s = do\n driver@(Driver ptr) <- c_driverByName s\n if ptr==nullPtr\n then throw $ GDALException CE_Failure \"failed to load driver\"\n else return driver\n\ntype DriverOptions = [(String,String)]\n\nclass ( HasDatatype t\n , a ~ ReadWrite\n , d ~ Dataset,\n HasWritebaleBand Band ReadWrite t)\n => HasDataset d a t where\n create :: String -> String -> Int -> Int -> Int -> DriverOptions\n -> IO (d a t)\n create drv path nx ny bands options = do\n d <- driverByName drv\n create' d path nx ny bands (datatype (undefined :: t)) options\n\ncreate' :: Driver -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO (Dataset ReadWrite t)\ncreate' drv path nx ny bands dtype options = withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC dtype\n withOptionList options $ \\opts ->\n create_ drv path' nx' ny' bands' dtype' opts >>= newDatasetHandle\n\nwithOptionList ::\n [(String, String)] -> (Ptr CString -> IO c) -> IO c\nwithOptionList opts = bracket (toOptionList opts) freeOptionList\n where toOptionList = foldM folder nullPtr\n folder acc (k,v) = withCString k $ \\k' -> withCString v $ \\v' ->\n {#call unsafe CSLSetNameValue as ^#} acc k' v'\n freeOptionList = {#call unsafe CSLDestroy as ^#} . castPtr\n\ninstance HasDataset Dataset ReadWrite Word8 where\ninstance HasDataset Dataset ReadWrite Int16 where\ninstance HasDataset Dataset ReadWrite Int32 where\ninstance HasDataset Dataset ReadWrite Word16 where\ninstance HasDataset Dataset ReadWrite Word32 where\ninstance HasDataset Dataset ReadWrite Float where\ninstance HasDataset Dataset ReadWrite Double where\ninstance HasDataset Dataset ReadWrite (GComplex Int16) where\ninstance HasDataset Dataset ReadWrite (GComplex Int32) where\ninstance HasDataset Dataset ReadWrite (GComplex Float) where\ninstance HasDataset Dataset ReadWrite (GComplex Double) where\n\n\nforeign import ccall safe \"gdal.h GDALCreate\" create_\n :: Driver\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset t))\n\nopenReadOnly :: String -> IO (RODataset t)\nopenReadOnly p = withCString p openIt\n where openIt p' = open_ p' (fromEnumC GA_ReadOnly) >>= newDatasetHandle\n\nopenReadWrite :: String -> IO (RWDataset t)\nopenReadWrite p = withCString p openIt\n where openIt p' = open_ p' (fromEnumC GA_Update) >>= newDatasetHandle\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset a t))\n\n\ncreateCopy' ::\n Driver -> String -> (Dataset a t) -> Bool -> DriverOptions\n -> ProgressFun -> IO (RWDataset t)\ncreateCopy' driver path dataset strict options progressFun\n = withCString path $ \\p ->\n withDataset dataset $ \\ds ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n createCopy_ driver p ds s o pFunc (castPtr nullPtr)\n >>= newDatasetHandle\n\n\ncreateCopy ::\n String -> String -> (Dataset a t) -> Bool -> DriverOptions\n -> IO (RWDataset t)\ncreateCopy driver path dataset strict options = do\n d <- driverByName driver\n createCopy' d path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" createCopy_\n :: Driver\n -> Ptr CChar\n -> Ptr (Dataset a t)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset t))\n\n\nwithProgressFun :: forall c.\n ProgressFun -> (FunPtr ProgressFun -> IO c) -> IO c\nwithProgressFun = withCCallback wrapProgressFun\n\nwithCCallback :: forall c t a.\n (t -> IO (FunPtr a)) -> t -> (FunPtr a -> IO c) -> IO c\nwithCCallback w f = bracket (w f) freeHaskellFunPtr\n\ntype ProgressFun = CDouble -> Ptr CChar -> Ptr () -> IO CInt\n\nforeign import ccall \"wrapper\"\n wrapProgressFun :: ProgressFun -> IO (FunPtr ProgressFun)\n\n\nnewDatasetHandle :: Ptr (Dataset a t) -> IO (Dataset a t)\nnewDatasetHandle p =\n if p==nullPtr\n then throw $ GDALException CE_Failure \"Could not create dataset\"\n else do fp <- newForeignPtr closeDataset p\n mutex <- newMutex\n return $ Dataset (fp, mutex)\n\nforeign import ccall \"gdal.h &GDALClose\"\n closeDataset :: FunPtr (Ptr (Dataset a t) -> IO ())\n\ncreateMem:: HasDataset d a t\n => Int -> Int -> Int -> DriverOptions -> IO (d a t)\ncreateMem = create \"MEM\" \"\"\n\nflushCache :: forall t. RWDataset t -> IO ()\nflushCache d = withDataset d flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: Ptr (Dataset a t) -> IO ()\n\n\ndatasetProjection :: Dataset a t -> IO String\ndatasetProjection d = withDataset d $ \\d' -> do\n p <- getProjection_ d'\n peekCString p\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset a t) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset t) -> String -> IO ()\nsetDatasetProjection d p = throwIfError\n \"setDatasetProjection: could not set projection\" f\n where f = withDataset d $ \\d' -> withCString p $ \\p' -> setProjection' d' p'\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset a t) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset a t -> IO Geotransform\ndatasetGeotransform ds = withDataset' ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n throwIfError \"could not get geotransform\" $ getGeoTransform dPtr a\n Geotransform <$> liftM realToFrac (peekElemOff a 0)\n <*> liftM realToFrac (peekElemOff a 1)\n <*> liftM realToFrac (peekElemOff a 2)\n <*> liftM realToFrac (peekElemOff a 3)\n <*> liftM realToFrac (peekElemOff a 4)\n <*> liftM realToFrac (peekElemOff a 5)\n\nforeign import ccall unsafe \"gdal.h GDALGetGeoTransform\" getGeoTransform\n :: Ptr (Dataset a t) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset t) -> Geotransform -> IO ()\nsetDatasetGeotransform ds gt = withDataset ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n let (Geotransform g0 g1 g2 g3 g4 g5) = gt\n pokeElemOff a 0 (realToFrac g0)\n pokeElemOff a 1 (realToFrac g1)\n pokeElemOff a 2 (realToFrac g2)\n pokeElemOff a 3 (realToFrac g3)\n pokeElemOff a 4 (realToFrac g4)\n pokeElemOff a 5 (realToFrac g5)\n throwIfError \"could not set geotransform\" $ setGeoTransform dPtr a\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset a t) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset a t -> IO (Int)\ndatasetBandCount d = liftM fromIntegral $ withDataset d bandCount_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset a t) -> IO CInt\n\nwithBand :: Dataset a t -> Int -> (Band a t -> IO b) -> IO b\nwithBand ds band f = withDataset ds $ \\dPtr -> do\n rBand@(Band p) <- getRasterBand dPtr (fromIntegral band)\n if p == nullPtr\n then throw $\n GDALException CE_Failure (\"could not get band #\" ++ show band)\n else f rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset a t) -> CInt -> IO ((Band a t))\n\n\nbandDatatype :: (Band a t) -> Datatype\nbandDatatype band = toEnumC . getDatatype_ $ band\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band a t) -> CInt\n\n\nbandBlockSize :: (Band a t) -> (Int,Int)\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n -- unsafePerformIO is safe here since the block size cant change once\n -- a dataset is created\n getBlockSize_ band xPtr yPtr\n liftA2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nforeign import ccall unsafe \"gdal.h GDALGetBlockSize\" getBlockSize_\n :: (Band a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band a t) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band a t) -> (Int, Int)\nbandSize band\n = (fromIntegral . getXSize_ $ band, fromIntegral . getYSize_ $ band)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getXSize_\n :: (Band a t) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getYSize_\n :: (Band a t) -> CInt\n\n\nbandNodataValue :: (Band a t) -> IO (Maybe Double)\nbandNodataValue b = alloca $ \\p -> do\n value <- liftM realToFrac $ getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: (Band a t) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: (RWBand t) -> Double -> IO ()\nsetBandNodataValue b v = throwIfError \"could not set nodata\" $\n setNodata_ b (realToFrac v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand t) -> CDouble -> IO CInt\n\n\nfillBand :: (RWBand t) -> Double -> Double -> IO ()\nfillBand b r i = throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand t) -> CDouble -> CDouble -> IO CInt\n\n\n\n\ndata GComplex a = (:+) !a !a deriving (Eq, Typeable)\ninfix 6 :+\ninstance Show a => Show (GComplex a) where\n show (r :+ i) = show r ++ \" :+ \" ++ show i\n\nclass IsGComplex a where\n type ComplexType a :: *\n toComplex :: GComplex a -> Complex.Complex (ComplexType a)\n fromComplex :: Complex.Complex (ComplexType a) -> GComplex a\n\n toComplex (r :+ i) = (toUnit r) Complex.:+ (toUnit i)\n fromComplex (r Complex.:+ i) = (fromUnit r) :+ (fromUnit i)\n\n toUnit :: a -> ComplexType a\n fromUnit :: ComplexType a -> a\n\ninstance IsGComplex Int16 where\n type ComplexType Int16 = Float\n toUnit = fromIntegral\n fromUnit = round\n\ninstance IsGComplex Int32 where\n type ComplexType Int32 = Double\n toUnit = fromIntegral\n fromUnit = round\n\ninstance IsGComplex Float where\n type ComplexType Float = Float\n toUnit = id\n fromUnit = id\n\ninstance IsGComplex Double where\n type ComplexType Double = Double\n toUnit = id\n fromUnit = id\n\n\ninstance Storable a => Storable (GComplex a) where\n sizeOf _ = sizeOf (undefined :: a) * 2\n alignment _ = alignment (undefined :: a)\n \n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Double) -> IO (GComplex Double) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Float) -> IO (GComplex Float) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Int16) -> IO (GComplex Int16) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Int32) -> IO (GComplex Int32) #-}\n peek p = (:+) <$> peekElemOff (castPtr p) 0 <*> peekElemOff (castPtr p) 1\n\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Float) -> GComplex Float -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Double) -> GComplex Double -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Int16) -> GComplex Int16 -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Int32) -> GComplex Int32 -> IO () #-}\n poke p (r :+ i)\n = pokeElemOff (castPtr p) 0 r >> pokeElemOff (castPtr p) 1 i\n\n\n\nreadBand :: forall a b t. HasDatatype a\n => (Band b t)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector a)\nreadBand band xoff yoff sx sy bx by pxs lns = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (undefined :: a))\n withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\n adviseRead_\n band\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (fromIntegral bx)\n (fromIntegral by)\n dtype\n (castPtr nullPtr)\n throwIfError \"could not read band\" $\n rasterIO_\n band\n (fromEnumC GF_Read) \n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n dtype\n (fromIntegral pxs)\n (fromIntegral lns)\n return $ unsafeFromForeignPtr0 fp (bx * by)\n\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand' :: forall a. HasDatatype a\n => (RWBand a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBand' = writeBand\n\nwriteBand :: forall a t. HasDatatype a\n => (RWBand t)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBand band xoff yoff sx sy bx by pxs lns vec = do\n let nElems = bx * by\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw $ GDALException CE_Failure \"vector of wrong size\"\n else withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not write band\" $\n rasterIO_\n band\n (fromEnumC GF_Write) \n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (datatype (undefined :: a)))\n (fromIntegral pxs)\n (fromIntegral lns)\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\n\ntype IOVector a = IO (Vector a)\n\nclass (HasDatatype t, b ~ Band)\n => HasBand b a t where\n readBandBlock :: b a t -> Int -> Int -> IOVector t\n readBandBlock b x y\n = if not $ isValidDatatype b (undefined :: Vector t)\n then throw $ GDALException CE_Failure \"wrong band type\"\n else do\n f <- mallocForeignPtrArray (bandBlockLen b)\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ unsafeFromForeignPtr0 f (bandBlockLen b)\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nclass (HasBand b a t, a ~ ReadWrite) => HasWritebaleBand b a t where\n writeBandBlock :: b a t -> Int -> Int -> Vector t -> IO ()\n writeBandBlock b x y vec = do\n let nElems = bandBlockLen b\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw $ GDALException CE_Failure \"wrongly sized vector\"\n else if not $ isValidDatatype b vec\n then throw $ GDALException CE_Failure \"wrongly typed vector\"\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y)\n (castPtr ptr)\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: (RWBand t) -> CInt -> CInt -> Ptr () -> IO CInt\n\n\n\ninstance forall a. HasBand Band a Word8 where\ninstance forall a. HasBand Band a Word16 where\ninstance forall a. HasBand Band a Word32 where\ninstance forall a. HasBand Band a Int16 where\ninstance forall a. HasBand Band a Int32 where\ninstance forall a. HasBand Band a Float where\ninstance forall a. HasBand Band a Double where\ninstance forall a. HasBand Band a (GComplex Int16) where\ninstance forall a. HasBand Band a (GComplex Int32) where\ninstance forall a. HasBand Band a (GComplex Float) where\ninstance forall a. HasBand Band a (GComplex Double) where\n\ninstance HasWritebaleBand Band ReadWrite Word8\ninstance HasWritebaleBand Band ReadWrite Word16\ninstance HasWritebaleBand Band ReadWrite Word32\ninstance HasWritebaleBand Band ReadWrite Int16\ninstance HasWritebaleBand Band ReadWrite Int32\ninstance HasWritebaleBand Band ReadWrite Float\ninstance HasWritebaleBand Band ReadWrite Double\ninstance HasWritebaleBand Band ReadWrite (GComplex Int16) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Int32) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Float) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Double) where\n\nclass (Storable a, Typeable a) => HasDatatype a where\n datatype :: a -> Datatype\n\ninstance HasDatatype Word8 where datatype _ = GDT_Byte\ninstance HasDatatype Word16 where datatype _ = GDT_UInt16\ninstance HasDatatype Word32 where datatype _ = GDT_UInt32\ninstance HasDatatype Int16 where datatype _ = GDT_Int16\ninstance HasDatatype Int32 where datatype _ = GDT_Int32\ninstance HasDatatype Float where datatype _ = GDT_Float32\ninstance HasDatatype Double where datatype _ = GDT_Float64\ninstance HasDatatype (GComplex Int16) where datatype _ = GDT_CInt16\ninstance HasDatatype (GComplex Int32) where datatype _ = GDT_CInt32\ninstance HasDatatype (GComplex Float) where datatype _ = GDT_CFloat32\ninstance HasDatatype (GComplex Double) where datatype _ = GDT_CFloat64\n\nisValidDatatype :: forall a t v. Typeable v\n => Band a t -> v -> Bool\nisValidDatatype b v = typeOfBand b == typeOf v\n where\n typeOfBand = typeOfdatatype . bandDatatype\n typeOfdatatype dt =\n case dt of\n GDT_Byte -> typeOf (undefined :: Vector Word8)\n GDT_UInt16 -> typeOf (undefined :: Vector Word16)\n GDT_UInt32 -> typeOf (undefined :: Vector Word32)\n GDT_Int16 -> typeOf (undefined :: Vector Int16)\n GDT_Int32 -> typeOf (undefined :: Vector Int32)\n GDT_Float32 -> typeOf (undefined :: Vector Float)\n GDT_Float64 -> typeOf (undefined :: Vector Double)\n GDT_CInt16 -> typeOf (undefined :: Vector (GComplex Int16))\n GDT_CInt32 -> typeOf (undefined :: Vector (GComplex Int32))\n GDT_CFloat32 -> typeOf (undefined :: Vector (GComplex Float))\n GDT_CFloat64 -> typeOf (undefined :: Vector (GComplex Double))\n _ -> typeOf (undefined :: Bool) -- will never match a vector\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nmodule OSGeo.GDAL.Internal (\n HasDataset\n , HasBand\n , HasWritebaleBand\n , HasDatatype\n , Datatype (..)\n , GDALException\n , isGDALException\n , Geotransform (..)\n , IOVector\n , DriverOptions\n , MajorObject\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Driver\n , DriverName\n , ColorTable\n , RasterAttributeTable\n , GComplex (..)\n\n , setQuietErrorHandler\n , unDataset\n , unBand\n\n , withAllDriversRegistered\n , registerAllDrivers\n , destroyDriverManager\n , driverByName\n , create\n , create'\n , createMem\n , flushCache\n , openReadOnly\n , openReadWrite\n , createCopy\n\n , datatypeSize\n , datatypeByName\n , datatypeUnion\n , datatypeIsComplex\n\n , datasetProjection\n , setDatasetProjection\n , datasetGeotransform\n , setDatasetGeotransform\n , datasetBandCount\n\n , withBand\n , bandDatatype\n , bandBlockSize\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , readBand\n , readBandBlock\n , writeBand\n , writeBand'\n , writeBandBlock\n , fillBand\n\n , toComplex\n , fromComplex\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception (bracket, throw, Exception(..), SomeException,\n finally)\nimport Control.Monad (liftM, foldM)\n\nimport Data.Int (Int16, Int32)\nimport qualified Data.Complex as Complex\nimport Data.Maybe (isJust)\nimport Data.Typeable (Typeable, typeOf)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector, unsafeFromForeignPtr0, unsafeToForeignPtr0)\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (ForeignPtr, withForeignPtr, newForeignPtr\n ,mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport OSGeo.Util\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\ntype DriverName = String\n\n\ndata GDALException = GDALException Error String\n deriving (Show, Typeable)\n\ninstance Exception GDALException\n\nisGDALException :: SomeException -> Bool\nisGDALException e = isJust (fromException e :: Maybe GDALException)\n\n{# enum CPLErr as Error {upcaseFirstLetter} deriving (Eq,Show) #}\n\n\ntype ErrorHandler = CInt -> CInt -> CString -> IO ()\n\nforeign import ccall \"cpl_error.h &CPLQuietErrorHandler\"\n c_quietErrorHandler :: FunPtr ErrorHandler\n\nforeign import ccall \"cpl_error.h CPLSetErrorHandler\"\n c_setErrorHandler :: FunPtr ErrorHandler -> IO (FunPtr ErrorHandler)\n\nsetQuietErrorHandler :: IO ()\nsetQuietErrorHandler = setErrorHandler c_quietErrorHandler\n\nsetErrorHandler :: FunPtr ErrorHandler -> IO ()\nsetErrorHandler h = c_setErrorHandler h >>= (\\_->return ())\n\n\nthrowIfError :: String -> IO CInt -> IO ()\nthrowIfError msg act = do\n e <- liftM toEnumC act\n case e of\n CE_None -> return ()\n e' -> throw $ GDALException e' msg\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\ninstance Show Datatype where\n show = getDatatypeName\n\n{# fun pure unsafe GDALGetDataTypeSize as datatypeSize\n { fromEnumC `Datatype' } -> `Int' #}\n\n{# fun pure unsafe GDALDataTypeIsComplex as datatypeIsComplex\n { fromEnumC `Datatype' } -> `Bool' #}\n\n{# fun pure unsafe GDALGetDataTypeName as getDatatypeName\n { fromEnumC `Datatype' } -> `String' #}\n\n{# fun pure unsafe GDALGetDataTypeByName as datatypeByName\n { `String' } -> `Datatype' toEnumC #}\n\n{# fun pure unsafe GDALDataTypeUnion as datatypeUnion\n { fromEnumC `Datatype', fromEnumC `Datatype' } -> `Datatype' toEnumC #}\n\n\n{# enum GDALAccess as Access {upcaseFirstLetter} deriving (Eq, Show) #}\n\n{# enum GDALRWFlag as RwFlag {upcaseFirstLetter} deriving (Eq, Show) #}\n\n{#pointer GDALMajorObjectH as MajorObject newtype#}\n{#pointer GDALDatasetH as Dataset foreign newtype nocode#}\n\ndata ReadOnly\ndata ReadWrite\nnewtype (Dataset a t) = Dataset (ForeignPtr (Dataset a t), Mutex)\n\nunDataset (Dataset (d, _)) = d\n\ntype RODataset = Dataset ReadOnly\ntype RWDataset = Dataset ReadWrite\nwithDataset, withDataset' :: (Dataset a t) -> (Ptr (Dataset a t) -> IO b) -> IO b\nwithDataset ds@(Dataset (_, m)) fun = withMutex m $ withDataset' ds fun\n\nwithDataset' (Dataset (fptr,_)) = withForeignPtr fptr\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band a t) = Band (Ptr ((Band a t)))\n\nunBand (Band b) = b\n\ntype ROBand = Band ReadOnly\ntype RWBand = Band ReadWrite\n\n\n{#pointer GDALDriverH as Driver newtype#}\n{#pointer GDALColorTableH as ColorTable newtype#}\n{#pointer GDALRasterAttributeTableH as RasterAttributeTable newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\nwithAllDriversRegistered act\n = registerAllDrivers >> finally act destroyDriverManager\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `Driver' id #}\n\ndriverByName :: String -> IO Driver\ndriverByName s = do\n driver@(Driver ptr) <- c_driverByName s\n if ptr==nullPtr\n then throw $ GDALException CE_Failure \"failed to load driver\"\n else return driver\n\ntype DriverOptions = [(String,String)]\n\nclass ( HasDatatype t\n , a ~ ReadWrite\n , d ~ Dataset,\n HasWritebaleBand Band ReadWrite t)\n => HasDataset d a t where\n create :: String -> String -> Int -> Int -> Int -> DriverOptions\n -> IO (d a t)\n create drv path nx ny bands options = do\n d <- driverByName drv\n create' d path nx ny bands (datatype (undefined :: t)) options\n\ncreate' :: Driver -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO (Dataset ReadWrite t)\ncreate' drv path nx ny bands dtype options = withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC dtype\n withOptionList options $ \\opts ->\n create_ drv path' nx' ny' bands' dtype' opts >>= newDatasetHandle\n\nwithOptionList ::\n [(String, String)] -> (Ptr CString -> IO c) -> IO c\nwithOptionList opts = bracket (toOptionList opts) freeOptionList\n where toOptionList = foldM folder nullPtr\n folder acc (k,v) = withCString k $ \\k' -> withCString v $ \\v' ->\n {#call unsafe CSLSetNameValue as ^#} acc k' v'\n freeOptionList = {#call unsafe CSLDestroy as ^#} . castPtr\n\ninstance HasDataset Dataset ReadWrite Word8 where\ninstance HasDataset Dataset ReadWrite Int16 where\ninstance HasDataset Dataset ReadWrite Int32 where\ninstance HasDataset Dataset ReadWrite Word16 where\ninstance HasDataset Dataset ReadWrite Word32 where\ninstance HasDataset Dataset ReadWrite Float where\ninstance HasDataset Dataset ReadWrite Double where\ninstance HasDataset Dataset ReadWrite (GComplex Int16) where\ninstance HasDataset Dataset ReadWrite (GComplex Int32) where\ninstance HasDataset Dataset ReadWrite (GComplex Float) where\ninstance HasDataset Dataset ReadWrite (GComplex Double) where\n\n\nforeign import ccall safe \"gdal.h GDALCreate\" create_\n :: Driver\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset t))\n\nopenReadOnly :: String -> IO (RODataset t)\nopenReadOnly p = withCString p openIt\n where openIt p' = open_ p' (fromEnumC GA_ReadOnly) >>= newDatasetHandle\n\nopenReadWrite :: String -> IO (RWDataset t)\nopenReadWrite p = withCString p openIt\n where openIt p' = open_ p' (fromEnumC GA_Update) >>= newDatasetHandle\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset a t))\n\n\ncreateCopy' ::\n Driver -> String -> (Dataset a t) -> Bool -> DriverOptions\n -> ProgressFun -> IO (RWDataset t)\ncreateCopy' driver path dataset strict options progressFun\n = withCString path $ \\p ->\n withDataset dataset $ \\ds ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n createCopy_ driver p ds s o pFunc (castPtr nullPtr)\n >>= newDatasetHandle\n\n\ncreateCopy ::\n String -> String -> (Dataset a t) -> Bool -> DriverOptions\n -> IO (RWDataset t)\ncreateCopy driver path dataset strict options = do\n d <- driverByName driver\n createCopy' d path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" createCopy_\n :: Driver\n -> Ptr CChar\n -> Ptr (Dataset a t)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset t))\n\n\nwithProgressFun :: forall c.\n ProgressFun -> (FunPtr ProgressFun -> IO c) -> IO c\nwithProgressFun = withCCallback wrapProgressFun\n\nwithCCallback :: forall c t a.\n (t -> IO (FunPtr a)) -> t -> (FunPtr a -> IO c) -> IO c\nwithCCallback w f = bracket (w f) freeHaskellFunPtr\n\ntype ProgressFun = CDouble -> Ptr CChar -> Ptr () -> IO CInt\n\nforeign import ccall \"wrapper\"\n wrapProgressFun :: ProgressFun -> IO (FunPtr ProgressFun)\n\n\nnewDatasetHandle :: Ptr (Dataset a t) -> IO (Dataset a t)\nnewDatasetHandle p =\n if p==nullPtr\n then throw $ GDALException CE_Failure \"Could not create dataset\"\n else do fp <- newForeignPtr closeDataset p\n mutex <- newMutex\n return $ Dataset (fp, mutex)\n\nforeign import ccall \"gdal.h &GDALClose\"\n closeDataset :: FunPtr (Ptr (Dataset a t) -> IO ())\n\ncreateMem:: HasDataset d a t\n => Int -> Int -> Int -> DriverOptions -> IO (d a t)\ncreateMem = create \"MEM\" \"\"\n\nflushCache :: forall a t. Dataset a t -> IO ()\nflushCache d = withDataset d flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: Ptr (Dataset a t) -> IO ()\n\n\ndatasetProjection :: Dataset a t -> IO String\ndatasetProjection d = withDataset d $ \\d' -> do\n p <- getProjection_ d'\n peekCString p\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset a t) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset t) -> String -> IO ()\nsetDatasetProjection d p = throwIfError \"could not set projection\" f\n where f = withDataset d $ \\d' -> withCString p $ \\p' -> setProjection' d' p'\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset a t) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset a t -> IO Geotransform\ndatasetGeotransform ds = withDataset' ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n throwIfError \"could not get geotransform\" $ getGeoTransform dPtr a\n Geotransform <$> liftM realToFrac (peekElemOff a 0)\n <*> liftM realToFrac (peekElemOff a 1)\n <*> liftM realToFrac (peekElemOff a 2)\n <*> liftM realToFrac (peekElemOff a 3)\n <*> liftM realToFrac (peekElemOff a 4)\n <*> liftM realToFrac (peekElemOff a 5)\n\nforeign import ccall unsafe \"gdal.h GDALGetGeoTransform\" getGeoTransform\n :: Ptr (Dataset a t) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset t) -> Geotransform -> IO ()\nsetDatasetGeotransform ds gt = withDataset ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n let (Geotransform g0 g1 g2 g3 g4 g5) = gt\n pokeElemOff a 0 (realToFrac g0)\n pokeElemOff a 1 (realToFrac g1)\n pokeElemOff a 2 (realToFrac g2)\n pokeElemOff a 3 (realToFrac g3)\n pokeElemOff a 4 (realToFrac g4)\n pokeElemOff a 5 (realToFrac g5)\n throwIfError \"could not set geotransform\" $ setGeoTransform dPtr a\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset a t) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset a t -> IO (Int)\ndatasetBandCount d = liftM fromIntegral $ withDataset d bandCount_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset a t) -> IO CInt\n\nwithBand :: Dataset a t -> Int -> (Band a t -> IO b) -> IO b\nwithBand ds band f = withDataset ds $ \\dPtr -> do\n rBand@(Band p) <- getRasterBand dPtr (fromIntegral band)\n if p == nullPtr\n then throw $\n GDALException CE_Failure (\"could not get band #\" ++ show band)\n else f rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset a t) -> CInt -> IO ((Band a t))\n\n\nbandDatatype :: (Band a t) -> Datatype\nbandDatatype band = toEnumC . getDatatype_ $ band\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band a t) -> CInt\n\n\nbandBlockSize :: (Band a t) -> (Int,Int)\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n -- unsafePerformIO is safe here since the block size cant change once\n -- a dataset is created\n getBlockSize_ band xPtr yPtr\n liftA2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nforeign import ccall unsafe \"gdal.h GDALGetBlockSize\" getBlockSize_\n :: (Band a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band a t) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band a t) -> (Int, Int)\nbandSize band\n = (fromIntegral . getXSize_ $ band, fromIntegral . getYSize_ $ band)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getXSize_\n :: (Band a t) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getYSize_\n :: (Band a t) -> CInt\n\n\nbandNodataValue :: (Band a t) -> IO (Maybe Double)\nbandNodataValue b = alloca $ \\p -> do\n value <- liftM realToFrac $ getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: (Band a t) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: (RWBand t) -> Double -> IO ()\nsetBandNodataValue b v = throwIfError \"could not set nodata\" $\n setNodata_ b (realToFrac v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand t) -> CDouble -> IO CInt\n\n\nfillBand :: (RWBand t) -> Double -> Double -> IO ()\nfillBand b r i = throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand t) -> CDouble -> CDouble -> IO CInt\n\n\n\n\ndata GComplex a = (:+) !a !a deriving (Eq, Typeable)\ninfix 6 :+\ninstance Show a => Show (GComplex a) where\n show (r :+ i) = show r ++ \" :+ \" ++ show i\n\nclass IsGComplex a where\n type ComplexType a :: *\n toComplex :: GComplex a -> Complex.Complex (ComplexType a)\n fromComplex :: Complex.Complex (ComplexType a) -> GComplex a\n\n toComplex (r :+ i) = (toUnit r) Complex.:+ (toUnit i)\n fromComplex (r Complex.:+ i) = (fromUnit r) :+ (fromUnit i)\n\n toUnit :: a -> ComplexType a\n fromUnit :: ComplexType a -> a\n\ninstance IsGComplex Int16 where\n type ComplexType Int16 = Float\n toUnit = fromIntegral\n fromUnit = round\n\ninstance IsGComplex Int32 where\n type ComplexType Int32 = Double\n toUnit = fromIntegral\n fromUnit = round\n\ninstance IsGComplex Float where\n type ComplexType Float = Float\n toUnit = id\n fromUnit = id\n\ninstance IsGComplex Double where\n type ComplexType Double = Double\n toUnit = id\n fromUnit = id\n\n\ninstance Storable a => Storable (GComplex a) where\n sizeOf _ = sizeOf (undefined :: a) * 2\n alignment _ = alignment (undefined :: a)\n \n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Double) -> IO (GComplex Double) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Float) -> IO (GComplex Float) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Int16) -> IO (GComplex Int16) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Int32) -> IO (GComplex Int32) #-}\n peek p = (:+) <$> peekElemOff (castPtr p) 0 <*> peekElemOff (castPtr p) 1\n\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Float) -> GComplex Float -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Double) -> GComplex Double -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Int16) -> GComplex Int16 -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Int32) -> GComplex Int32 -> IO () #-}\n poke p (r :+ i)\n = pokeElemOff (castPtr p) 0 r >> pokeElemOff (castPtr p) 1 i\n\n\n\nreadBand :: forall a b t. HasDatatype a\n => (Band b t)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector a)\nreadBand band xoff yoff sx sy bx by pxs lns = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (undefined :: a))\n withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\n adviseRead_\n band\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (fromIntegral bx)\n (fromIntegral by)\n dtype\n (castPtr nullPtr)\n throwIfError \"could not read band\" $\n rasterIO_\n band\n (fromEnumC GF_Read) \n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n dtype\n (fromIntegral pxs)\n (fromIntegral lns)\n return $ unsafeFromForeignPtr0 fp (bx * by)\n\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand' :: forall a. HasDatatype a\n => (RWBand a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBand' = writeBand\n\nwriteBand :: forall a t. HasDatatype a\n => (RWBand t)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBand band xoff yoff sx sy bx by pxs lns vec = do\n let nElems = bx * by\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw $ GDALException CE_Failure \"vector of wrong size\"\n else withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not write band\" $\n rasterIO_\n band\n (fromEnumC GF_Write) \n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (datatype (undefined :: a)))\n (fromIntegral pxs)\n (fromIntegral lns)\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\n\ntype IOVector a = IO (Vector a)\n\nclass (HasDatatype t, b ~ Band)\n => HasBand b a t where\n readBandBlock :: b a t -> Int -> Int -> IOVector t\n readBandBlock b x y\n = if not $ isValidDatatype b (undefined :: Vector t)\n then throw $ GDALException CE_Failure \"wrong band type\"\n else do\n f <- mallocForeignPtrArray (bandBlockLen b)\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ unsafeFromForeignPtr0 f (bandBlockLen b)\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nclass (HasBand b a t, a ~ ReadWrite) => HasWritebaleBand b a t where\n writeBandBlock :: b a t -> Int -> Int -> Vector t -> IO ()\n writeBandBlock b x y vec = do\n let nElems = bandBlockLen b\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw $ GDALException CE_Failure \"wrongly sized vector\"\n else if not $ isValidDatatype b vec\n then throw $ GDALException CE_Failure \"wrongly typed vector\"\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y)\n (castPtr ptr)\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: (RWBand t) -> CInt -> CInt -> Ptr () -> IO CInt\n\n\n\ninstance forall a. HasBand Band a Word8 where\ninstance forall a. HasBand Band a Word16 where\ninstance forall a. HasBand Band a Word32 where\ninstance forall a. HasBand Band a Int16 where\ninstance forall a. HasBand Band a Int32 where\ninstance forall a. HasBand Band a Float where\ninstance forall a. HasBand Band a Double where\ninstance forall a. HasBand Band a (GComplex Int16) where\ninstance forall a. HasBand Band a (GComplex Int32) where\ninstance forall a. HasBand Band a (GComplex Float) where\ninstance forall a. HasBand Band a (GComplex Double) where\n\ninstance HasWritebaleBand Band ReadWrite Word8\ninstance HasWritebaleBand Band ReadWrite Word16\ninstance HasWritebaleBand Band ReadWrite Word32\ninstance HasWritebaleBand Band ReadWrite Int16\ninstance HasWritebaleBand Band ReadWrite Int32\ninstance HasWritebaleBand Band ReadWrite Float\ninstance HasWritebaleBand Band ReadWrite Double\ninstance HasWritebaleBand Band ReadWrite (GComplex Int16) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Int32) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Float) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Double) where\n\nclass (Storable a, Typeable a) => HasDatatype a where\n datatype :: a -> Datatype\n\ninstance HasDatatype Word8 where datatype _ = GDT_Byte\ninstance HasDatatype Word16 where datatype _ = GDT_UInt16\ninstance HasDatatype Word32 where datatype _ = GDT_UInt32\ninstance HasDatatype Int16 where datatype _ = GDT_Int16\ninstance HasDatatype Int32 where datatype _ = GDT_Int32\ninstance HasDatatype Float where datatype _ = GDT_Float32\ninstance HasDatatype Double where datatype _ = GDT_Float64\ninstance HasDatatype (GComplex Int16) where datatype _ = GDT_CInt16\ninstance HasDatatype (GComplex Int32) where datatype _ = GDT_CInt32\ninstance HasDatatype (GComplex Float) where datatype _ = GDT_CFloat32\ninstance HasDatatype (GComplex Double) where datatype _ = GDT_CFloat64\n\nisValidDatatype :: forall a t v. Typeable v\n => Band a t -> v -> Bool\nisValidDatatype b v = typeOfBand b == typeOf v\n where\n typeOfBand = typeOfdatatype . bandDatatype\n typeOfdatatype dt =\n case dt of\n GDT_Byte -> typeOf (undefined :: Vector Word8)\n GDT_UInt16 -> typeOf (undefined :: Vector Word16)\n GDT_UInt32 -> typeOf (undefined :: Vector Word32)\n GDT_Int16 -> typeOf (undefined :: Vector Int16)\n GDT_Int32 -> typeOf (undefined :: Vector Int32)\n GDT_Float32 -> typeOf (undefined :: Vector Float)\n GDT_Float64 -> typeOf (undefined :: Vector Double)\n GDT_CInt16 -> typeOf (undefined :: Vector (GComplex Int16))\n GDT_CInt32 -> typeOf (undefined :: Vector (GComplex Int32))\n GDT_CFloat32 -> typeOf (undefined :: Vector (GComplex Float))\n GDT_CFloat64 -> typeOf (undefined :: Vector (GComplex Double))\n _ -> typeOf (undefined :: Bool) -- will never match a vector\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"dead77e4b5befcfb6f0af90f7c085a2936d1bb06","subject":"Use pure where it makes sense","message":"Use pure where it makes sense\n","repos":"cocreature\/nanovg-hs","old_file":"src\/NanoVG\/Internal.chs","new_file":"src\/NanoVG\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RecordWildCards #-}\nmodule NanoVG.Internal where\n\nimport Data.Bits\nimport Data.ByteString hiding (null)\nimport qualified Data.Set as S\nimport qualified Data.Text as T\nimport qualified Data.Text.Encoding as T\nimport Data.Word\nimport Foreign.C.String (CString)\nimport Foreign.C.Types\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Linear.Matrix\nimport Linear.V2\nimport Linear.V3\nimport Linear.V4\nimport Prelude hiding (null)\n\n-- For now only the GL3 backend is supported\n#define NANOVG_GL3\n-- We need to include this to define GLuint\n#include \"GL\/glew.h\"\n#include \"nanovg.h\"\n#include \"nanovg_gl.h\"\n#include \"nanovg_wrapper.h\"\n\nwithCString :: T.Text -> (CString -> IO b) -> IO b\nwithCString t = useAsCString (T.encodeUtf8 t)\n\nuseAsCStringLen' :: ByteString -> ((Ptr CUChar,CInt) -> IO a) -> IO a\nuseAsCStringLen' bs f = useAsCStringLen bs (\\(ptr,len) -> f (castPtr ptr,fromIntegral len))\n\nuseAsPtr :: ByteString -> (Ptr CUChar -> IO a) -> IO a\nuseAsPtr bs f = useAsCStringLen bs (\\(ptr,_) -> f (castPtr ptr))\n\nzero :: Num a => (a -> b) -> b\nzero f = f 0\n\nnull :: (Ptr a -> b) -> b\nnull f = f nullPtr\n\nnewtype FileName = FileName { unwrapFileName :: T.Text }\n\nnewtype Image = Image {imageHandle :: CInt} deriving (Show,Read,Eq,Ord)\n\nnewtype Font = Font {fontHandle :: CInt} deriving (Show,Read,Eq,Ord)\n\n{#pointer *NVGcontext as Context newtype#}\n\nnewtype Transformation = Transformation (M23 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Transformation where\n sizeOf _ = sizeOf (0 :: CFloat) * 6\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peek p'\n b <- peekElemOff p' 1\n c <- peekElemOff p' 2\n d <- peekElemOff p' 3\n e <- peekElemOff p' 4\n f <- peekElemOff p' 5\n pure (Transformation\n (V2 (V3 a c e)\n (V3 b d f)))\n poke p (Transformation (V2 (V3 a c e) (V3 b d f))) =\n do let p' = castPtr p :: Ptr CFloat\n poke p' a\n pokeElemOff p' 1 b\n pokeElemOff p' 2 c\n pokeElemOff p' 3 d\n pokeElemOff p' 4 e\n pokeElemOff p' 5 f\n\nnewtype Extent = Extent (V2 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Extent where\n sizeOf _ = sizeOf (0 :: CFloat) * 4\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peekElemOff p' 0\n b <- peekElemOff p' 1\n pure (Extent (V2 a b))\n poke p (Extent (V2 a b)) =\n do let p' = castPtr p :: Ptr CFloat\n pokeElemOff p' 0 a\n pokeElemOff p' 1 b\n\n-- | rgba\ndata Color = Color !CFloat !CFloat !CFloat !CFloat deriving (Show,Read,Eq,Ord)\n\n{#pointer *NVGcolor as ColorPtr -> Color#}\n\ninstance Storable Color where\n sizeOf _ = sizeOf (0 :: CFloat) * 4\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n r <- peek p'\n g <- peekElemOff p' 1\n b <- peekElemOff p' 2\n a <- peekElemOff p' 3\n pure (Color r g b a)\n poke p (Color r g b a) =\n do let p' = castPtr p :: Ptr CFloat\n poke p' r\n pokeElemOff p' 1 g\n pokeElemOff p' 2 b\n pokeElemOff p' 3 a\n\ndata Paint =\n Paint {xform :: Transformation\n ,extent :: Extent\n ,radius :: !CFloat\n ,feather :: !CFloat\n ,innerColor :: !Color\n ,outerColor :: !Color\n ,image :: !Image} deriving (Show,Read,Eq,Ord)\n\n{#pointer *NVGpaint as PaintPtr -> Paint#}\n\ninstance Storable Paint where\n sizeOf _ = 76\n alignment _ = 4\n peek p =\n do xform <- peek (castPtr (p `plusPtr` {#offsetof NVGpaint->xform#}))\n extent <- peek (castPtr (p `plusPtr` {#offsetof NVGpaint->extent#}))\n radius <- {#get NVGpaint->radius#} p\n feather <- {#get NVGpaint->feather#} p\n innerColor <- peek (castPtr (p `plusPtr` 40))\n outerColor <- peek (castPtr (p `plusPtr` 56))\n image <- peek (castPtr (p `plusPtr` 72))\n pure (Paint xform extent radius feather innerColor outerColor (Image image))\n poke p (Paint{..}) =\n do poke (castPtr (p `plusPtr` {#offsetof NVGpaint->xform#})) xform\n poke (castPtr (p `plusPtr` {#offsetof NVGpaint->extent#})) extent\n {#set NVGpaint->radius#} p radius\n {#set NVGpaint->feather#} p feather\n poke (castPtr (p `plusPtr` 40)) innerColor\n poke (castPtr (p `plusPtr` 56)) outerColor\n poke (castPtr (p `plusPtr` 72)) (imageHandle image)\n\n{#enum NVGwinding as Winding\n {} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGsolidity as Solidity\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGlineCap as LineCap\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGalign as Align \n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\ndata GlyphPosition =\n GlyphPosition { str :: !(Ptr CChar)\n , glyphX :: !CFloat\n -- Remove prefix once GHC 8 is released\n , glyphPosMinX :: !CFloat\n , glyphPosMaxX :: !CFloat}\n\n{#pointer *NVGglyphPosition as GlyphPositionPtr -> GlyphPosition#}\n\ninstance Storable GlyphPosition where\n sizeOf _ = {#sizeof NVGglyphPosition#}\n alignment _ = {#alignof NVGglyphPosition#}\n peek p =\n do str <- {#get NVGglyphPosition->str#} p\n x <- {#get NVGglyphPosition->x#} p\n minx <- {#get NVGglyphPosition->minx#} p\n maxx <- {#get NVGglyphPosition->maxx#} p\n pure (GlyphPosition str x minx maxx)\n poke p (GlyphPosition str x minx maxx) =\n do {#set NVGglyphPosition->str#} p str\n {#set NVGglyphPosition->x#} p x\n {#set NVGglyphPosition->minx#} p minx\n {#set NVGglyphPosition->maxx#} p maxx\n\ndata TextRow =\n TextRow {start :: !(Ptr CChar)\n ,end :: !(Ptr CChar)\n ,next :: !(Ptr CChar)\n ,width :: !CFloat\n -- Remove prefix once GHC 8 is released\n ,textRowMinX :: !CFloat\n ,textRowMaxX :: !CFloat}\n\n{#pointer *NVGtextRow as TextRowPtr -> TextRow#}\n\n{#enum NVGimageFlags as ImageFlags\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#fun unsafe nvgBeginFrame as beginFrame\n {`Context',`CInt',`CInt',`Float'} -> `()'#}\n\n{#fun unsafe nvgCancelFrame as canelFrame\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgEndFrame as endFrame\n {`Context'} -> `()'#}\n\n{#fun pure unsafe nvgRGB_ as rgb\n {id`CUChar',id`CUChar',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgRGBf_ as rgbf\n {`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgRGBA_ as rgba\n {id`CUChar',id`CUChar',id`CUChar',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgRGBAf_ as rgbaf\n {`CFloat',`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgLerpRGBA_ as lerpRGBA\n {with*`Color',with*`Color',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgTransRGBA_ as transRGBA\n {with*`Color',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgTransRGBAf_ as transRGBAf\n {with*`Color',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgHSL_ as hsl\n {`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgHSLA_ as hsla\n {`CFloat',`CFloat',`CFloat',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun unsafe nvgSave as save\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgRestore as restore\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgReset as reset\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgStrokeColor_ as strokeColor\n {`Context',with*`Color'} -> `()'#}\n\n{#fun unsafe nvgStrokePaint_ as strokePaint\n {`Context',with*`Paint'} -> `()'#}\n\n{#fun unsafe nvgFillColor_ as fillColor\n {`Context',with*`Color'} -> `()'#}\n\n{#fun unsafe nvgFillPaint_ as fillPaint\n {`Context',with*`Paint'} -> `()'#}\n\n{#fun unsafe nvgMiterLimit as miterLimit\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgStrokeWidth as strokeWidth\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgLineCap as lineCap\n {`Context',`LineCap'} -> `()'#}\n\n{#fun unsafe nvgLineJoin as lineJoin\n {`Context',`LineCap'} -> `()'#}\n\n{#fun unsafe nvgGlobalAlpha as globalAlpha\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgResetTransform as resetTransform\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgTransform as transform\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTranslate as translate\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgRotate as rotate\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgSkewX as skewX\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgSkewY as skewY\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgScale as scale\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\npeekTransformation :: Ptr CFloat -> IO Transformation\npeekTransformation = peek . castPtr\n\nallocaTransformation :: (Ptr CFloat -> IO b) -> IO b\nallocaTransformation f = alloca (\\(p :: Ptr Transformation) -> f (castPtr p))\n\nwithTransformation :: Transformation -> (Ptr CFloat -> IO b) -> IO b\nwithTransformation t f = with t (\\p -> f (castPtr p)) \n\n{#fun unsafe nvgCurrentTransform as currentTransform\n {`Context',allocaTransformation-`Transformation'peekTransformation*} -> `()'#}\n\n{#fun unsafe nvgTransformIdentity as transformIdentity\n {allocaTransformation-`Transformation'peekTransformation*} -> `()'#}\n\n{#fun unsafe nvgTransformTranslate as transformTranslate\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformScale as transformScale\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformRotate as transformRotate\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformSkewX as transformSkewX\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformSkewY as transformSkewY\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformMultiply as transformMultiply\n {allocaTransformation-`Transformation'peekTransformation*,withTransformation*`Transformation'} -> `()'#}\n\n{#fun unsafe nvgTransformInverse as transformInverse\n {allocaTransformation-`Transformation'peekTransformation*,withTransformation*`Transformation'} -> `()'#}\n\n{#fun pure unsafe nvgTransformPoint as transformPoint\n {alloca-`CFloat'peek*,alloca-`CFloat'peek*,withTransformation*`Transformation',`CFloat',`CFloat'} -> `()'#}\n\n{#fun pure unsafe nvgDegToRad as degtoRad\n {`CFloat'} -> `CFloat'#}\n\n{#fun pure unsafe nvgRadToDeg as radToDeg\n {`CFloat'} -> `CFloat'#}\n\n{#fun unsafe nvgCreateImage as createImage\n {`Context','withCString.unwrapFileName'*`FileName',`CInt'} -> `Image'Image#}\n\n{#fun unsafe nvgCreateImageMem as createImageMem\n {`Context',`ImageFlags',useAsCStringLen'*`ByteString'&} -> `Image'Image#}\n\n{#fun unsafe nvgCreateImageRGBA as createImageRGBA\n {`Context',`CInt',`CInt',`ImageFlags',useAsPtr*`ByteString'} -> `Image'Image#}\n\n{#fun unsafe nvgUpdateImage as updateImage\n {`Context',imageHandle`Image',useAsPtr*`ByteString'} -> `()'#}\n\n{#fun unsafe nvgImageSize as imageSize\n {`Context',imageHandle`Image',alloca-`CInt'peek*,alloca-`CInt'peek*} -> `()'#}\n\n{#fun unsafe nvgDeleteImage as deleteImage\n {`Context',imageHandle`Image'} -> `()'#}\n\n{#fun unsafe nvgLinearGradient_ as linearGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgBoxGradient_ as boxGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgRadialGradient_ as radialGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgImagePattern_ as imagePattern\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',imageHandle`Image',`CFloat',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgScissor as scissor\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgIntersectScissor as intersectScissor\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgResetScissor as resetScissor\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgBeginPath as beginPath\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgMoveTo as moveTo\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgLineTo as lineTo\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgBezierTo as bezierTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgQuadTo as quadTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgArcTo as arcTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgClosePath as closePath\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgPathWinding as pathWinding\n {`Context', `CInt'} -> `()'#}\n\n{#fun unsafe nvgArc as arc\n {`Context',`CFloat',`CFloat', `CFloat', `CFloat', `CFloat', `Winding'} -> `()'#}\n\n{#fun unsafe nvgRect as rect\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgRoundedRect as roundedRect\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgEllipse as ellipse\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgCircle as circle\n {`Context',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgFill as fill\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgStroke as stroke\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgCreateFont as createFont\n {`Context',withCString*`T.Text','withCString.unwrapFileName'*`FileName'} -> `Font'Font#}\n\n{#fun unsafe nvgCreateFontMem as createFontMem\n {`Context',withCString*`T.Text',useAsCStringLen'*`ByteString'&,zero-`CInt'} -> `Font'Font#}\n\n{#fun unsafe nvgFindFont as findFont\n {`Context', withCString*`T.Text'} -> `Font'Font#}\n\n{#fun unsafe nvgFontSize as fontSize\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgFontBlur as fontBlur\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTextLetterSpacing as textLetterSpacing\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTextLineHeight as textLineHeight\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTextAlign as textAlign\n {`Context',bitMask`S.Set Align'} -> `()'#}\n\n{#fun unsafe nvgFontFaceId as fontFaceId\n {`Context',fontHandle`Font'} -> `()'#}\n\n{#fun unsafe nvgFontFace as fontFace\n {`Context',withCString*`T.Text'} -> `()'#}\n\n{#fun unsafe nvgText as text\n {`Context',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar'} -> `()'#}\n\n{#fun unsafe nvgTextBox as textBox\n {`Context',`CFloat',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar'} -> `()'#}\n\nnewtype Bounds = Bounds (V4 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Bounds where\n sizeOf _ = sizeOf (0 :: CFloat) * 4\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peekElemOff p' 0\n b <- peekElemOff p' 1\n c <- peekElemOff p' 2\n d <- peekElemOff p' 3\n pure (Bounds (V4 a b c d))\n poke p (Bounds (V4 a b c d)) =\n do let p' = castPtr p :: Ptr CFloat\n pokeElemOff p' 0 a\n pokeElemOff p' 1 b\n pokeElemOff p' 2 c\n pokeElemOff p' 3 d\n\npeekBounds :: Ptr CFloat -> IO Bounds\npeekBounds = peek . castPtr\n\nallocaBounds :: (Ptr CFloat -> IO b) -> IO b\nallocaBounds f = alloca (\\(p :: Ptr Bounds) -> f (castPtr p))\n\nwithBounds :: Bounds -> (Ptr CFloat -> IO b) -> IO b\nwithBounds t f = with t (\\p -> f (castPtr p)) \n\n{#fun unsafe nvgTextBounds as textBounds\n {`Context',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar', allocaBounds-`Bounds'peekBounds*} -> `()'#}\n\n{#fun unsafe nvgTextBoxBounds as textBoxBounds\n {`Context',`CFloat',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar',allocaBounds-`Bounds'peekBounds*} -> `()'#}\n\n-- TODO: This should probably take a vector\n{#fun unsafe nvgTextGlyphPositions as textGlyphPositions\n {`Context',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar',`GlyphPositionPtr', `CInt'} -> `CInt'#}\n\n{#fun unsafe nvgTextMetrics as textMetrics\n {`Context',alloca-`CFloat'peek*,alloca-`CFloat'peek*,alloca-`CFloat'peek*} -> `()'#}\n\n-- TODO: This should probably take a vector\n{#fun unsafe nvgTextBreakLines as textBreakLines\n {`Context',withCString*`T.Text',null-`Ptr CUChar',`CFloat',`TextRowPtr',`CInt'} -> `CInt'#}\n\n{#enum NVGcreateFlags as CreateFlags\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\nbitMask :: Enum a => S.Set a -> CInt\nbitMask = S.fold (.|.) 0 . S.map (fromIntegral . fromEnum)\n\n{#fun unsafe nvgCreateGL3 as createGL3\n {bitMask`S.Set CreateFlags'} -> `Context'#}\n{#fun unsafe nvgDeleteGL3 as deleteGL3\n {`Context'} -> `()'#}\n\ntype GLuint = Word32\n\n{#fun unsafe nvglCreateImageFromHandleGL3 as createImageFromHandleGL3\n {`Context',fromIntegral`GLuint',`CInt',`CInt',`CreateFlags'} -> `Image'Image#}\n\n{#fun unsafe nvglImageHandleGL3 as imageHandleGL3\n {`Context',imageHandle`Image'} -> `GLuint'fromIntegral#}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RecordWildCards #-}\nmodule NanoVG.Internal where\n\nimport Data.Bits\nimport Data.ByteString hiding (null)\nimport qualified Data.Set as S\nimport qualified Data.Text as T\nimport qualified Data.Text.Encoding as T\nimport Data.Word\nimport Foreign.C.String (CString)\nimport Foreign.C.Types\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Linear.Matrix\nimport Linear.V2\nimport Linear.V3\nimport Linear.V4\nimport Prelude hiding (null)\n\n-- For now only the GL3 backend is supported\n#define NANOVG_GL3\n-- We need to include this to define GLuint\n#include \"GL\/glew.h\"\n#include \"nanovg.h\"\n#include \"nanovg_gl.h\"\n#include \"nanovg_wrapper.h\"\n\nwithCString :: T.Text -> (CString -> IO b) -> IO b\nwithCString t = useAsCString (T.encodeUtf8 t)\n\nuseAsCStringLen' :: ByteString -> ((Ptr CUChar,CInt) -> IO a) -> IO a\nuseAsCStringLen' bs f = useAsCStringLen bs (\\(ptr,len) -> f (castPtr ptr,fromIntegral len))\n\nuseAsPtr :: ByteString -> (Ptr CUChar -> IO a) -> IO a\nuseAsPtr bs f = useAsCStringLen bs (\\(ptr,_) -> f (castPtr ptr))\n\nzero :: Num a => (a -> b) -> b\nzero f = f 0\n\nnull :: (Ptr a -> b) -> b\nnull f = f nullPtr\n\nnewtype FileName = FileName { unwrapFileName :: T.Text }\n\nnewtype Image = Image {imageHandle :: CInt} deriving (Show,Read,Eq,Ord)\n\nnewtype Font = Font {fontHandle :: CInt} deriving (Show,Read,Eq,Ord)\n\n{#pointer *NVGcontext as Context newtype#}\n\nnewtype Transformation = Transformation (M23 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Transformation where\n sizeOf _ = sizeOf (0 :: CFloat) * 6\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peek p'\n b <- peekElemOff p' 1\n c <- peekElemOff p' 2\n d <- peekElemOff p' 3\n e <- peekElemOff p' 4\n f <- peekElemOff p' 5\n pure (Transformation\n (V2 (V3 a c e)\n (V3 b d f)))\n poke p (Transformation (V2 (V3 a c e) (V3 b d f))) =\n do let p' = castPtr p :: Ptr CFloat\n poke p' a\n pokeElemOff p' 1 b\n pokeElemOff p' 2 c\n pokeElemOff p' 3 d\n pokeElemOff p' 4 e\n pokeElemOff p' 5 f\n\nnewtype Extent = Extent (V2 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Extent where\n sizeOf _ = sizeOf (0 :: CFloat) * 4\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peekElemOff p' 0\n b <- peekElemOff p' 1\n pure (Extent (V2 a b))\n poke p (Extent (V2 a b)) =\n do let p' = castPtr p :: Ptr CFloat\n pokeElemOff p' 0 a\n pokeElemOff p' 1 b\n\n-- | rgba\ndata Color = Color !CFloat !CFloat !CFloat !CFloat deriving (Show,Read,Eq,Ord)\n\n{#pointer *NVGcolor as ColorPtr -> Color#}\n\ninstance Storable Color where\n sizeOf _ = sizeOf (0 :: CFloat) * 4\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n r <- peek p'\n g <- peekElemOff p' 1\n b <- peekElemOff p' 2\n a <- peekElemOff p' 3\n pure (Color r g b a)\n poke p (Color r g b a) =\n do let p' = castPtr p :: Ptr CFloat\n poke p' r\n pokeElemOff p' 1 g\n pokeElemOff p' 2 b\n pokeElemOff p' 3 a\n\ndata Paint =\n Paint {xform :: Transformation\n ,extent :: Extent\n ,radius :: !CFloat\n ,feather :: !CFloat\n ,innerColor :: !Color\n ,outerColor :: !Color\n ,image :: !Image} deriving (Show,Read,Eq,Ord)\n\n{#pointer *NVGpaint as PaintPtr -> Paint#}\n\ninstance Storable Paint where\n sizeOf _ = 76\n alignment _ = 4\n peek p =\n do xform <- peek (castPtr (p `plusPtr` {#offsetof NVGpaint->xform#}))\n extent <- peek (castPtr (p `plusPtr` {#offsetof NVGpaint->extent#}))\n radius <- {#get NVGpaint->radius#} p\n feather <- {#get NVGpaint->feather#} p\n innerColor <- peek (castPtr (p `plusPtr` 40))\n outerColor <- peek (castPtr (p `plusPtr` 56))\n image <- peek (castPtr (p `plusPtr` 72))\n pure (Paint xform extent radius feather innerColor outerColor (Image image))\n poke p (Paint{..}) =\n do poke (castPtr (p `plusPtr` {#offsetof NVGpaint->xform#})) xform\n poke (castPtr (p `plusPtr` {#offsetof NVGpaint->extent#})) extent\n {#set NVGpaint->radius#} p radius\n {#set NVGpaint->feather#} p feather\n poke (castPtr (p `plusPtr` 40)) innerColor\n poke (castPtr (p `plusPtr` 56)) outerColor\n poke (castPtr (p `plusPtr` 72)) (imageHandle image)\n\n{#enum NVGwinding as Winding\n {} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGsolidity as Solidity\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGlineCap as LineCap\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGalign as Align \n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\ndata GlyphPosition =\n GlyphPosition { str :: !(Ptr CChar)\n , x :: !CFloat\n -- Remove prefix once GHC 8 is released\n , glyphPosMinX :: !CFloat\n , glyphPosMaxX :: !CFloat}\n\n{#pointer *NVGglyphPosition as GlyphPositionPtr -> GlyphPosition#}\n\ninstance Storable GlyphPosition where\n sizeOf _ = {#sizeof NVGglyphPosition#}\n alignment _ = {#alignof NVGglyphPosition#}\n peek p =\n do str <- {#get NVGglyphPosition->str#} p\n x <- {#get NVGglyphPosition->x#} p\n minx <- {#get NVGglyphPosition->minx#} p\n maxx <- {#get NVGglyphPosition->maxx#} p\n pure (GlyphPosition str x minx maxx)\n poke p (GlyphPosition str x minx maxx) =\n do {#set NVGglyphPosition->str#} p str\n {#set NVGglyphPosition->x#} p x\n {#set NVGglyphPosition->minx#} p minx\n {#set NVGglyphPosition->maxx#} p maxx\n\ndata TextRow =\n TextRow {start :: !(Ptr CChar)\n ,end :: !(Ptr CChar)\n ,next :: !(Ptr CChar)\n ,width :: !CFloat\n -- Remove prefix once GHC 8 is released\n ,textRowMinX :: !CFloat\n ,textRowMaxX :: !CFloat}\n\n{#pointer *NVGtextRow as TextRowPtr -> TextRow#}\n\n{#enum NVGimageFlags as ImageFlags\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#fun unsafe nvgBeginFrame as beginFrame\n {`Context',`CInt',`CInt',`Float'} -> `()'#}\n\n{#fun unsafe nvgCancelFrame as canelFrame\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgEndFrame as endFrame\n {`Context'} -> `()'#}\n\n{#fun pure unsafe nvgRGB_ as rgb\n {id`CUChar',id`CUChar',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgRGBf_ as rgbf\n {`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgRGBA_ as rgba\n {id`CUChar',id`CUChar',id`CUChar',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgRGBAf_ as rgbaf\n {`CFloat',`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgLerpRGBA_ as lerpRGBA\n {with*`Color',with*`Color',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgTransRGBA_ as transRGBA\n {with*`Color',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgTransRGBAf_ as transRGBAf\n {with*`Color',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgHSL_ as hsl\n {`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgHSLA_ as hsla\n {`CFloat',`CFloat',`CFloat',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun unsafe nvgSave as save\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgRestore as restore\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgReset as reset\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgStrokeColor_ as strokeColor\n {`Context',with*`Color'} -> `()'#}\n\n{#fun unsafe nvgStrokePaint_ as strokePaint\n {`Context',with*`Paint'} -> `()'#}\n\n{#fun unsafe nvgFillColor_ as fillColor\n {`Context',with*`Color'} -> `()'#}\n\n{#fun unsafe nvgFillPaint_ as fillPaint\n {`Context',with*`Paint'} -> `()'#}\n\n{#fun unsafe nvgMiterLimit as miterLimit\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgStrokeWidth as strokeWidth\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgLineCap as lineCap\n {`Context',`LineCap'} -> `()'#}\n\n{#fun unsafe nvgLineJoin as lineJoin\n {`Context',`LineCap'} -> `()'#}\n\n{#fun unsafe nvgGlobalAlpha as globalAlpha\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgResetTransform as resetTransform\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgTransform as transform\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTranslate as translate\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgRotate as rotate\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgSkewX as skewX\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgSkewY as skewY\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgScale as scale\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\npeekTransformation :: Ptr CFloat -> IO Transformation\npeekTransformation = peek . castPtr\n\nallocaTransformation :: (Ptr CFloat -> IO b) -> IO b\nallocaTransformation f = alloca (\\(p :: Ptr Transformation) -> f (castPtr p))\n\nwithTransformation :: Transformation -> (Ptr CFloat -> IO b) -> IO b\nwithTransformation t f = with t (\\p -> f (castPtr p)) \n\n{#fun unsafe nvgCurrentTransform as currentTransform\n {`Context',allocaTransformation-`Transformation'peekTransformation*} -> `()'#}\n\n{#fun unsafe nvgTransformIdentity as transformIdentity\n {allocaTransformation-`Transformation'peekTransformation*} -> `()'#}\n\n{#fun unsafe nvgTransformTranslate as transformTranslate\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformScale as transformScale\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformRotate as transformRotate\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformSkewX as transformSkewX\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformSkewY as transformSkewY\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformMultiply as transformMultiply\n {allocaTransformation-`Transformation'peekTransformation*,withTransformation*`Transformation'} -> `()'#}\n\n{#fun unsafe nvgTransformInverse as transformInverse\n {allocaTransformation-`Transformation'peekTransformation*,withTransformation*`Transformation'} -> `()'#}\n\n{#fun unsafe nvgTransformPoint as transformPoint\n {alloca-`CFloat'peek*,alloca-`CFloat'peek*,withTransformation*`Transformation',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgDegToRad as degtoRad\n {`CFloat'} -> `CFloat'#}\n\n{#fun unsafe nvgRadToDeg as radToDeg\n {`CFloat'} -> `CFloat'#}\n\n{#fun unsafe nvgCreateImage as createImage\n {`Context','withCString.unwrapFileName'*`FileName',`CInt'} -> `Image'Image#}\n\n{#fun unsafe nvgCreateImageMem as createImageMem\n {`Context',`ImageFlags',useAsCStringLen'*`ByteString'&} -> `Image'Image#}\n\n{#fun unsafe nvgCreateImageRGBA as createImageRGBA\n {`Context',`CInt',`CInt',`ImageFlags',useAsPtr*`ByteString'} -> `Image'Image#}\n\n{#fun unsafe nvgUpdateImage as updateImage\n {`Context',imageHandle`Image',useAsPtr*`ByteString'} -> `()'#}\n\n{#fun unsafe nvgImageSize as imageSize\n {`Context',imageHandle`Image',alloca-`CInt'peek*,alloca-`CInt'peek*} -> `()'#}\n\n{#fun unsafe nvgDeleteImage as deleteImage\n {`Context',imageHandle`Image'} -> `()'#}\n\n{#fun unsafe nvgLinearGradient_ as linearGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgBoxGradient_ as boxGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgRadialGradient_ as radialGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgImagePattern_ as imagePattern\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',imageHandle`Image',`CFloat',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgScissor as scissor\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgIntersectScissor as intersectScissor\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgResetScissor as resetScissor\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgBeginPath as beginPath\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgMoveTo as moveTo\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgLineTo as lineTo\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgBezierTo as bezierTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgQuadTo as quadTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgArcTo as arcTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgClosePath as closePath\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgPathWinding as pathWinding\n {`Context', `CInt'} -> `()'#}\n\n{#fun unsafe nvgArc as arc\n {`Context',`CFloat',`CFloat', `CFloat', `CFloat', `CFloat', `Winding'} -> `()'#}\n\n{#fun unsafe nvgRect as rect\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgRoundedRect as roundedRect\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgEllipse as ellipse\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgCircle as circle\n {`Context',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgFill as fill\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgStroke as stroke\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgCreateFont as createFont\n {`Context',withCString*`T.Text','withCString.unwrapFileName'*`FileName'} -> `Font'Font#}\n\n{#fun unsafe nvgCreateFontMem as createFontMem\n {`Context',withCString*`T.Text',useAsCStringLen'*`ByteString'&,zero-`CInt'} -> `Font'Font#}\n\n{#fun unsafe nvgFindFont as findFont\n {`Context', withCString*`T.Text'} -> `Font'Font#}\n\n{#fun unsafe nvgFontSize as fontSize\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgFontBlur as fontBlur\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTextLetterSpacing as textLetterSpacing\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTextLineHeight as textLineHeight\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTextAlign as textAlign\n {`Context',bitMask`S.Set Align'} -> `()'#}\n\n{#fun unsafe nvgFontFaceId as fontFaceId\n {`Context',fontHandle`Font'} -> `()'#}\n\n{#fun unsafe nvgFontFace as fontFace\n {`Context',withCString*`T.Text'} -> `()'#}\n\n{#fun unsafe nvgText as text\n {`Context',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar'} -> `()'#}\n\n{#fun unsafe nvgTextBox as textBox\n {`Context',`CFloat',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar'} -> `()'#}\n\nnewtype Bounds = Bounds (V4 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Bounds where\n sizeOf _ = sizeOf (0 :: CFloat) * 4\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peekElemOff p' 0\n b <- peekElemOff p' 1\n c <- peekElemOff p' 2\n d <- peekElemOff p' 3\n pure (Bounds (V4 a b c d))\n poke p (Bounds (V4 a b c d)) =\n do let p' = castPtr p :: Ptr CFloat\n pokeElemOff p' 0 a\n pokeElemOff p' 1 b\n pokeElemOff p' 2 c\n pokeElemOff p' 3 d\n\npeekBounds :: Ptr CFloat -> IO Bounds\npeekBounds = peek . castPtr\n\nallocaBounds :: (Ptr CFloat -> IO b) -> IO b\nallocaBounds f = alloca (\\(p :: Ptr Bounds) -> f (castPtr p))\n\nwithBounds :: Bounds -> (Ptr CFloat -> IO b) -> IO b\nwithBounds t f = with t (\\p -> f (castPtr p)) \n\n{#fun unsafe nvgTextBounds as textBounds\n {`Context',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar', allocaBounds-`Bounds'peekBounds*} -> `()'#}\n\n{#fun unsafe nvgTextBoxBounds as textBoxBounds\n {`Context',`CFloat',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar',allocaBounds-`Bounds'peekBounds*} -> `()'#}\n\n-- TODO: This should probably take a vector\n{#fun unsafe nvgTextGlyphPositions as textGlyphPositions\n {`Context',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar',`GlyphPositionPtr', `CInt'} -> `CInt'#}\n\n{#fun unsafe nvgTextMetrics as textMetrics\n {`Context',alloca-`CFloat'peek*,alloca-`CFloat'peek*,alloca-`CFloat'peek*} -> `()'#}\n\n-- TODO: This should probably take a vector\n{#fun unsafe nvgTextBreakLines as textBreakLines\n {`Context',withCString*`T.Text',null-`Ptr CUChar',`CFloat',`TextRowPtr',`CInt'} -> `CInt'#}\n\n{#enum NVGcreateFlags as CreateFlags\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\nbitMask :: Enum a => S.Set a -> CInt\nbitMask = S.fold (.|.) 0 . S.map (fromIntegral . fromEnum)\n\n{#fun unsafe nvgCreateGL3 as createGL3\n {bitMask`S.Set CreateFlags'} -> `Context'#}\n{#fun unsafe nvgDeleteGL3 as deleteGL3\n {`Context'} -> `()'#}\n\ntype GLuint = Word32\n\n{#fun unsafe nvglCreateImageFromHandleGL3 as createImageFromHandleGL3\n {`Context',fromIntegral`GLuint',`CInt',`CInt',`CreateFlags'} -> `Image'Image#}\n\n{#fun unsafe nvglImageHandleGL3 as imageHandleGL3\n {`Context',imageHandle`Image'} -> `GLuint'fromIntegral#}\n","returncode":0,"stderr":"","license":"isc","lang":"C2hs Haskell"}
{"commit":"3e557e57a321093785186e41fc34aa341f1b976b","subject":"Break the cycles in the type construction (I think)","message":"Break the cycles in the type construction (I think)\n","repos":"wangxiayang\/llvm-analysis,travitch\/llvm-analysis,travitch\/llvm-analysis,wangxiayang\/llvm-analysis","old_file":"src\/Data\/LLVM\/Private\/Parser\/Unmarshal.chs","new_file":"src\/Data\/LLVM\/Private\/Parser\/Unmarshal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, RankNTypes #-}\nmodule Data.LLVM.Private.Parser.Unmarshal ( parseBitcode ) where\n\n#include \"c++\/marshal.h\"\n\nimport Control.Applicative\nimport Control.DeepSeq\nimport Control.Exception\nimport Control.Monad.State\nimport Data.Array.Storable\nimport Data.ByteString.Char8 ( ByteString )\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport Data.IORef\nimport Data.Map ( Map )\nimport qualified Data.Map as M\nimport Data.Maybe ( catMaybes )\nimport Data.Typeable\nimport Foreign.C\nimport Foreign.ForeignPtr\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Data.LLVM.Private.C2HS\nimport Data.LLVM.Private.Parser.Options\nimport Data.LLVM.Types\n\ndata TranslationException = TooManyReturnValues\n | InvalidBranchInst\n | InvalidSwitchLayout\n | InvalidIndirectBranchOperands\n | KnotTyingFailure\n | TypeKnotTyingFailure\n | InvalidSelectArgs !Int\n | InvalidExtractElementInst !Int\n | InvalidInsertElementInst !Int\n | InvalidShuffleVectorInst !Int\n | InvalidFunctionInTranslateValue\n | InvalidAliasInTranslateValue\n | InvalidGlobalVarInTranslateValue\n | InvalidBinaryOp !Int\n | InvalidUnaryOp !Int\n | InvalidGEPInst !Int\n | InvalidExtractValueInst !Int\n | InvalidInsertValueInst !Int\n deriving (Show, Typeable)\ninstance Exception TranslationException\n\n\n{#enum TypeTag {} deriving (Show, Eq) #}\n{#enum ValueTag {underscoreToCase} deriving (Show, Eq) #}\n\ndata CModule\n{#pointer *CModule as ModulePtr -> CModule #}\n\ncModuleIdentifier :: ModulePtr -> IO ByteString\ncModuleIdentifier m = ({#get CModule->moduleIdentifier#} m) >>= BS.packCString\n\ncModuleDataLayout :: ModulePtr -> IO ByteString\ncModuleDataLayout m = ({#get CModule->moduleDataLayout#} m) >>= BS.packCString\n\ncModuleTargetTriple :: ModulePtr -> IO ByteString\ncModuleTargetTriple m = ({#get CModule->targetTriple#} m) >>= BS.packCString\n\ncModuleInlineAsm :: ModulePtr -> IO ByteString\ncModuleInlineAsm m = ({#get CModule->moduleInlineAsm#} m) >>= BS.packCString\n\ncModuleHasError :: ModulePtr -> IO Bool\ncModuleHasError m = cToBool <$> ({#get CModule->hasError#} m)\n\ncModuleErrorMessage :: ModulePtr -> IO String\ncModuleErrorMessage m = ({#get CModule->errMsg#} m) >>= peekCString\n\ncModuleLittleEndian :: ModulePtr -> IO Bool\ncModuleLittleEndian m = cToBool <$> ({#get CModule->littleEndian#} m)\n\ncModulePointerSize :: ModulePtr -> IO Int\ncModulePointerSize m = cIntConv <$> ({#get CModule->pointerSize#} m)\n\ncModuleGlobalVariables :: ModulePtr -> IO [ValuePtr]\ncModuleGlobalVariables m =\n peekArray m {#get CModule->globalVariables#} {#get CModule->numGlobalVariables#}\n\ncModuleGlobalAliases :: ModulePtr -> IO [ValuePtr]\ncModuleGlobalAliases m =\n peekArray m ({#get CModule->globalAliases#}) ({#get CModule->numGlobalAliases#})\n\ncModuleFunctions :: ModulePtr -> IO [ValuePtr]\ncModuleFunctions m =\n peekArray m ({#get CModule->functions#}) ({#get CModule->numFunctions#})\n\npeekArray :: forall a b c e . (Integral c, Storable e) =>\n a -> (a -> IO (Ptr b)) -> (a -> IO c) -> IO [e]\npeekArray obj arrAccessor sizeAccessor = do\n nElts <- sizeAccessor obj\n arrPtr <- arrAccessor obj\n fArrPtr <- newForeignPtr_ (castPtr arrPtr)\n arr <- unsafeForeignPtrToStorableArray fArrPtr (1, cIntConv nElts)\n getElems arr\n\ndata CType\n{#pointer *CType as TypePtr -> CType #}\ncTypeTag :: TypePtr -> IO TypeTag\ncTypeTag t = cToEnum <$> {#get CType->typeTag#} t\ncTypeSize :: TypePtr -> IO Int\ncTypeSize t = cIntConv <$> {#get CType->size#} t\ncTypeIsVarArg :: TypePtr -> IO Bool\ncTypeIsVarArg t = cToBool <$> {#get CType->isVarArg#} t\ncTypeIsPacked :: TypePtr -> IO Bool\ncTypeIsPacked t = cToBool <$> {#get CType->isPacked#} t\ncTypeList :: TypePtr -> IO [TypePtr]\ncTypeList t =\n peekArray t {#get CType->typeList#} {#get CType->typeListLen#}\ncTypeInner :: TypePtr -> IO TypePtr\ncTypeInner = {#get CType->innerType#}\ncTypeName :: TypePtr -> IO String\ncTypeName t = {#get CType->name#} t >>= peekCString\ncTypeAddrSpace :: TypePtr -> IO Int\ncTypeAddrSpace t = cIntConv <$> {#get CType->addrSpace#} t\n\ndata CValue\n{#pointer *CValue as ValuePtr -> CValue #}\n\ncValueTag :: ValuePtr -> IO ValueTag\ncValueTag v = cToEnum <$> ({#get CValue->valueTag#} v)\ncValueType :: ValuePtr -> IO TypePtr\ncValueType = {#get CValue->valueType#}\ncValueName :: ValuePtr -> IO (Maybe Identifier)\ncValueName v = do\n namePtr <- ({#get CValue->name#}) v\n case namePtr == nullPtr of\n True -> return Nothing\n False -> do\n name <- BS.packCString namePtr\n return $! (Just . makeIdentifier) name\ncValueData :: ValuePtr -> IO (Ptr ())\ncValueData = {#get CValue->data#}\n\ndata CGlobalInfo\n{#pointer *CGlobalInfo as GlobalInfoPtr -> CGlobalInfo #}\ncGlobalIsExternal :: GlobalInfoPtr -> IO Bool\ncGlobalIsExternal g = cToBool <$> ({#get CGlobalInfo->isExternal#} g)\ncGlobalAlignment :: GlobalInfoPtr -> IO Int64\ncGlobalAlignment g = cIntConv <$> ({#get CGlobalInfo->alignment#} g)\ncGlobalVisibility :: GlobalInfoPtr -> IO VisibilityStyle\ncGlobalVisibility g = cToEnum <$> ({#get CGlobalInfo->visibility#} g)\ncGlobalLinkage :: GlobalInfoPtr -> IO LinkageType\ncGlobalLinkage g = cToEnum <$> ({#get CGlobalInfo->linkage#} g)\ncGlobalSection :: GlobalInfoPtr -> IO (Maybe ByteString)\ncGlobalSection g = do\n s <- {#get CGlobalInfo->section#} g\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just bs\ncGlobalInitializer :: GlobalInfoPtr -> IO ValuePtr\ncGlobalInitializer = {#get CGlobalInfo->initializer#}\ncGlobalIsThreadLocal :: GlobalInfoPtr -> IO Bool\ncGlobalIsThreadLocal g = cToBool <$> ({#get CGlobalInfo->isThreadLocal#} g)\ncGlobalAliasee :: GlobalInfoPtr -> IO ValuePtr\ncGlobalAliasee = {#get CGlobalInfo->aliasee#}\ncGlobalIsConstant :: GlobalInfoPtr -> IO Bool\ncGlobalIsConstant g = cToBool <$> {#get CGlobalInfo->isConstant#} g\n\ndata CFunctionInfo\n{#pointer *CFunctionInfo as FunctionInfoPtr -> CFunctionInfo #}\ncFunctionIsExternal :: FunctionInfoPtr -> IO Bool\ncFunctionIsExternal f = cToBool <$> {#get CFunctionInfo->isExternal#} f\ncFunctionAlignment :: FunctionInfoPtr -> IO Int64\ncFunctionAlignment f = cIntConv <$> {#get CFunctionInfo->alignment#} f\ncFunctionVisibility :: FunctionInfoPtr -> IO VisibilityStyle\ncFunctionVisibility f = cToEnum <$> {#get CFunctionInfo->visibility#} f\ncFunctionLinkage :: FunctionInfoPtr -> IO LinkageType\ncFunctionLinkage f = cToEnum <$> {#get CFunctionInfo->linkage#} f\ncFunctionSection :: FunctionInfoPtr -> IO (Maybe ByteString)\ncFunctionSection f = do\n s <- {#get CFunctionInfo->section#} f\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just bs\ncFunctionIsVarArg :: FunctionInfoPtr -> IO Bool\ncFunctionIsVarArg f = cToBool <$> {#get CFunctionInfo->isVarArg#} f\ncFunctionCallingConvention :: FunctionInfoPtr -> IO CallingConvention\ncFunctionCallingConvention f = cToEnum <$> {#get CFunctionInfo->callingConvention#} f\ncFunctionGCName :: FunctionInfoPtr -> IO (Maybe GCName)\ncFunctionGCName f = do\n s <- {#get CFunctionInfo->gcName#} f\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just (GCName bs)\ncFunctionArguments :: FunctionInfoPtr -> IO [ValuePtr]\ncFunctionArguments f =\n peekArray f {#get CFunctionInfo->arguments#} {#get CFunctionInfo->argListLen#}\ncFunctionBlocks :: FunctionInfoPtr -> IO [ValuePtr]\ncFunctionBlocks f =\n peekArray f {#get CFunctionInfo->body#} {#get CFunctionInfo->blockListLen#}\n\ndata CArgInfo\n{#pointer *CArgumentInfo as ArgInfoPtr -> CArgInfo #}\ncArgInfoHasSRet :: ArgInfoPtr -> IO Bool\ncArgInfoHasSRet a = cToBool <$> ({#get CArgumentInfo->hasSRet#} a)\ncArgInfoHasByVal :: ArgInfoPtr -> IO Bool\ncArgInfoHasByVal a = cToBool <$> ({#get CArgumentInfo->hasByVal#} a)\ncArgInfoHasNest :: ArgInfoPtr -> IO Bool\ncArgInfoHasNest a = cToBool <$> ({#get CArgumentInfo->hasNest#} a)\ncArgInfoHasNoAlias :: ArgInfoPtr -> IO Bool\ncArgInfoHasNoAlias a = cToBool <$> ({#get CArgumentInfo->hasNoAlias#} a)\ncArgInfoHasNoCapture :: ArgInfoPtr -> IO Bool\ncArgInfoHasNoCapture a = cToBool <$> ({#get CArgumentInfo->hasNoCapture#} a)\n\ndata CBasicBlockInfo\n{#pointer *CBasicBlockInfo as BasicBlockPtr -> CBasicBlockInfo #}\n\ncBasicBlockInstructions :: BasicBlockPtr -> IO [ValuePtr]\ncBasicBlockInstructions b =\n peekArray b {#get CBasicBlockInfo->instructions#} {#get CBasicBlockInfo->blockLen#}\n\ndata CInlineAsmInfo\n{#pointer *CInlineAsmInfo as InlineAsmInfoPtr -> CInlineAsmInfo #}\n\ncInlineAsmString :: InlineAsmInfoPtr -> IO ByteString\ncInlineAsmString a =\n ({#get CInlineAsmInfo->asmString#} a) >>= BS.packCString\ncInlineAsmConstraints :: InlineAsmInfoPtr -> IO ByteString\ncInlineAsmConstraints a =\n ({#get CInlineAsmInfo->constraintString#} a) >>= BS.packCString\n\ndata CBlockAddrInfo\n{#pointer *CBlockAddrInfo as BlockAddrInfoPtr -> CBlockAddrInfo #}\n\ncBlockAddrFunc :: BlockAddrInfoPtr -> IO ValuePtr\ncBlockAddrFunc = {#get CBlockAddrInfo->func #}\ncBlockAddrBlock :: BlockAddrInfoPtr -> IO ValuePtr\ncBlockAddrBlock = {#get CBlockAddrInfo->block #}\n\ndata CAggregateInfo\n{#pointer *CConstAggregate as AggregateInfoPtr -> CAggregateInfo #}\n\ncAggregateValues :: AggregateInfoPtr -> IO [ValuePtr]\ncAggregateValues a =\n peekArray a {#get CConstAggregate->constants#} {#get CConstAggregate->numElements#}\n\ndata CConstFP\n{#pointer *CConstFP as FPInfoPtr -> CConstFP #}\ncFPVal :: FPInfoPtr -> IO Double\ncFPVal f = cFloatConv <$> ({#get CConstFP->val#} f)\n\ndata CConstInt\n{#pointer *CConstInt as IntInfoPtr -> CConstInt #}\ncIntVal :: IntInfoPtr -> IO Integer\ncIntVal i = cIntConv <$> ({#get CConstInt->val#} i)\n\ndata CInstructionInfo\n{#pointer *CInstructionInfo as InstInfoPtr -> CInstructionInfo #}\ncInstructionOperands :: InstInfoPtr -> IO [ValuePtr]\ncInstructionOperands i =\n peekArray i {#get CInstructionInfo->operands#} {#get CInstructionInfo->numOperands#}\ncInstructionArithFlags :: InstInfoPtr -> IO ArithFlags\ncInstructionArithFlags o = cToEnum <$> {#get CInstructionInfo->flags#} o\ncInstructionAlign :: InstInfoPtr -> IO Int64\ncInstructionAlign u = cIntConv <$> {#get CInstructionInfo->align#} u\ncInstructionIsVolatile :: InstInfoPtr -> IO Bool\ncInstructionIsVolatile u = cToBool <$> {#get CInstructionInfo->isVolatile#} u\ncInstructionAddrSpace :: InstInfoPtr -> IO Int\ncInstructionAddrSpace u = cIntConv <$> {#get CInstructionInfo->addrSpace#} u\ncInstructionCmpPred :: InstInfoPtr -> IO CmpPredicate\ncInstructionCmpPred c = cToEnum <$> {#get CInstructionInfo->cmpPred#} c\ncInstructionInBounds :: InstInfoPtr -> IO Bool\ncInstructionInBounds g = cToBool <$> {#get CInstructionInfo->inBounds#} g\ncInstructionIndices :: InstInfoPtr -> IO [Int]\ncInstructionIndices i =\n peekArray i {#get CInstructionInfo->indices#} {#get CInstructionInfo->numIndices#}\n\ndata CConstExprInfo\n{#pointer *CConstExprInfo as ConstExprPtr -> CConstExprInfo #}\ncConstExprTag :: ConstExprPtr -> IO ValueTag\ncConstExprTag e = cToEnum <$> {#get CConstExprInfo->instrType#} e\ncConstExprInstInfo :: ConstExprPtr -> IO InstInfoPtr\ncConstExprInstInfo = {#get CConstExprInfo->ii#}\n\ndata CPHIInfo\n{#pointer *CPHIInfo as PHIInfoPtr -> CPHIInfo #}\ncPHIValues :: PHIInfoPtr -> IO [ValuePtr]\ncPHIValues p =\n peekArray p {#get CPHIInfo->incomingValues#} {#get CPHIInfo->numIncomingValues#}\ncPHIBlocks :: PHIInfoPtr -> IO [ValuePtr]\ncPHIBlocks p =\n peekArray p {#get CPHIInfo->valueBlocks#} {#get CPHIInfo->numIncomingValues#}\n\ndata CCallInfo\n{#pointer *CCallInfo as CallInfoPtr -> CCallInfo #}\ncCallValue :: CallInfoPtr -> IO ValuePtr\ncCallValue = {#get CCallInfo->calledValue #}\ncCallArguments :: CallInfoPtr -> IO [ValuePtr]\ncCallArguments c =\n peekArray c {#get CCallInfo->arguments#} {#get CCallInfo->argListLen#}\ncCallConvention :: CallInfoPtr -> IO CallingConvention\ncCallConvention c = cToEnum <$> {#get CCallInfo->callingConvention#} c\ncCallHasSRet :: CallInfoPtr -> IO Bool\ncCallHasSRet c = cToBool <$> {#get CCallInfo->hasSRet#} c\ncCallIsTail :: CallInfoPtr -> IO Bool\ncCallIsTail c = cToBool <$> {#get CCallInfo->isTail#} c\ncCallUnwindDest :: CallInfoPtr -> IO ValuePtr\ncCallUnwindDest = {#get CCallInfo->unwindDest#}\ncCallNormalDest :: CallInfoPtr -> IO ValuePtr\ncCallNormalDest = {#get CCallInfo->normalDest#}\n\n-- | Parse the named file into an FFI-friendly representation of an\n-- LLVM module.\n{#fun marshalLLVM { `String' } -> `ModulePtr' id #}\n\n-- | Free all of the resources allocated by 'marshalLLVM'\n{#fun disposeCModule { id `ModulePtr' } -> `()' #}\n\n-- FIXME: add accessors for value metadata\n\ntype KnotMonad = StateT KnotState IO\ndata KnotState = KnotState { valueMap :: Map IntPtr Value\n , typeMap :: Map IntPtr Type\n , idSrc :: IORef Int\n }\nemptyState :: IORef Int -> KnotState\nemptyState r = KnotState { valueMap = M.empty\n , typeMap = M.empty\n , idSrc = r\n }\n\nnextId :: KnotMonad Int\nnextId = do\n s <- get\n let r = idSrc s\n thisId <- liftIO $ readIORef r\n liftIO $ modifyIORef r (+1)\n\n return thisId\n\nparseBitcode :: ParserOptions -> FilePath -> IO (Either String Module)\nparseBitcode _ bitcodefile = do\n m <- marshalLLVM bitcodefile\n\n hasError <- cModuleHasError m\n case hasError of\n True -> do\n err <- cModuleErrorMessage m\n disposeCModule m\n return $! Left err\n False -> do\n ref <- newIORef 0\n (ir, _) <- evalStateT (mfix (tieKnot m)) (emptyState ref)\n\n disposeCModule m\n return $! Right (ir `deepseq` ir)\n\n\ntieKnot :: ModulePtr -> (Module, KnotState) -> KnotMonad (Module, KnotState)\ntieKnot m (_, finalState) = do\n modIdent <- liftIO $ cModuleIdentifier m\n dataLayout <- liftIO $ cModuleDataLayout m\n triple <- liftIO $ cModuleTargetTriple m\n inlineAsm <- liftIO $ cModuleInlineAsm m\n\n vars <- liftIO $ cModuleGlobalVariables m\n aliases <- liftIO $ cModuleGlobalAliases m\n funcs <- liftIO $ cModuleFunctions m\n\n vars' <- mapM (translateGlobalVariable finalState) vars\n aliases' <- mapM (translateAlias finalState) aliases\n funcs' <- mapM (translateFunction finalState) funcs\n\n let ir = Module { moduleIdentifier = modIdent\n , moduleDataLayout = undefined\n , moduleTarget = undefined\n , moduleAssembly = Assembly inlineAsm\n , moduleAliases = aliases'\n , moduleGlobalVariables = vars'\n , moduleFunctions = funcs'\n }\n s <- get\n return (ir, s)\n\ntranslateType :: KnotState -> TypePtr -> KnotMonad Type\ntranslateType finalState tp = do\n s <- get\n case M.lookup (ptrToIntPtr tp) (typeMap s) of\n Just t -> return t\n Nothing -> translateType' finalState tp\n\ntranslateTypeRec :: KnotState -> TypePtr -> KnotMonad Type\ntranslateTypeRec finalState tp = do\n s <- get\n case M.lookup (ptrToIntPtr tp) (typeMap s) of\n -- If we already translated, just do the simple thing.\n Just t -> return t\n Nothing -> do\n tag <- liftIO $ cTypeTag tp\n case tag of\n -- Break recursive cycles here - just look up the named type in\n -- the final result. The outer wrappers will have been\n -- translated, so this should be sufficient to tie the type knot.\n TYPE_NAMED -> case M.lookup (ptrToIntPtr tp) (typeMap finalState) of\n Just t -> return t\n Nothing -> throw TypeKnotTyingFailure\n _ -> translateType' finalState tp\n\ntranslateType' :: KnotState -> TypePtr -> KnotMonad Type\ntranslateType' finalState tp = do\n s <- get\n tag <- liftIO $ cTypeTag tp\n t <- case tag of\n TYPE_VOID -> return TypeVoid\n TYPE_FLOAT -> return TypeFloat\n TYPE_DOUBLE -> return TypeDouble\n TYPE_X86_FP80 -> return TypeX86FP80\n TYPE_FP128 -> return TypeFP128\n TYPE_PPC_FP128 -> return TypePPCFP128\n TYPE_LABEL -> return TypeLabel\n TYPE_METADATA -> return TypeMetadata\n TYPE_X86_MMX -> return TypeX86MMX\n TYPE_OPAQUE -> return TypeOpaque\n TYPE_INTEGER -> do\n sz <- liftIO $ cTypeSize tp\n return $! TypeInteger sz\n TYPE_FUNCTION -> do\n isVa <- liftIO $ cTypeIsVarArg tp\n rtp <- liftIO $ cTypeInner tp\n argTypePtrs <- liftIO $ cTypeList tp\n\n rType <- translateTypeRec finalState rtp\n argTypes <- mapM (translateTypeRec finalState) argTypePtrs\n\n return $! TypeFunction rType argTypes isVa\n TYPE_STRUCT -> do\n isPacked <- liftIO $ cTypeIsPacked tp\n ptrs <- liftIO $ cTypeList tp\n\n types <- mapM (translateTypeRec finalState) ptrs\n\n return $! TypeStruct types isPacked\n TYPE_ARRAY -> do\n sz <- liftIO $ cTypeSize tp\n itp <- liftIO $ cTypeInner tp\n innerType <- translateTypeRec finalState itp\n\n return $! TypeArray sz innerType\n TYPE_POINTER -> do\n itp <- liftIO $ cTypeInner tp\n addrSpc <- liftIO $ cTypeAddrSpace tp\n innerType <- translateTypeRec finalState itp\n\n return $! TypePointer innerType addrSpc\n TYPE_VECTOR -> do\n sz <- liftIO $ cTypeSize tp\n itp <- liftIO $ cTypeInner tp\n innerType <- translateTypeRec finalState itp\n\n return $! TypeVector sz innerType\n TYPE_NAMED -> do\n name <- liftIO $ cTypeName tp\n itp <- liftIO $ cTypeInner tp\n innerType <- translateTypeRec finalState itp\n\n return $! TypeNamed name innerType\n put s { typeMap = M.insert (ptrToIntPtr tp) t (typeMap s) }\n return t\n\nrecordValue :: ValuePtr -> Value -> KnotMonad ()\nrecordValue vp v = do\n s <- get\n let key = ptrToIntPtr vp\n oldMap = valueMap s\n put s { valueMap = M.insert key v oldMap }\n\ntranslateAlias :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateAlias finalState vp = do\n name <- liftIO $ cValueName vp\n typePtr <- liftIO $ cValueType vp\n dataPtr <- liftIO $ cValueData vp\n let dataPtr' = castPtr dataPtr\n\n vis <- liftIO $ cGlobalVisibility dataPtr'\n link <- liftIO $ cGlobalLinkage dataPtr'\n aliasee <- liftIO $ cGlobalAliasee dataPtr'\n\n ta <- translateConstOrRef finalState aliasee\n tt <- translateType finalState typePtr\n\n uid <- nextId\n\n let ga = GlobalAlias { globalAliasLinkage = link\n , globalAliasVisibility = vis\n , globalAliasValue = ta\n }\n v = Value { valueType = tt\n , valueName = name\n , valueMetadata = Nothing\n , valueContent = ga\n , valueUniqueId = uid\n }\n\n recordValue vp v\n\n return v\n\ntranslateGlobalVariable :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateGlobalVariable finalState vp = do\n name <- liftIO $ cValueName vp\n typePtr <- liftIO $ cValueType vp\n dataPtr <- liftIO $ cValueData vp\n tt <- translateType finalState typePtr\n\n uid <- nextId\n\n let dataPtr' = castPtr dataPtr\n basicVal = Value { valueName = name\n , valueType = tt\n , valueMetadata = Nothing\n , valueContent = ExternalValue\n , valueUniqueId = uid\n }\n isExtern <- liftIO $ cGlobalIsExternal dataPtr'\n\n case isExtern of\n True -> do\n recordValue vp basicVal\n return basicVal\n False -> do\n align <- liftIO $ cGlobalAlignment dataPtr'\n vis <- liftIO $ cGlobalVisibility dataPtr'\n link <- liftIO $ cGlobalLinkage dataPtr'\n section <- liftIO $ cGlobalSection dataPtr'\n isThreadLocal <- liftIO $ cGlobalIsThreadLocal dataPtr'\n initializer <- liftIO $ cGlobalInitializer dataPtr'\n isConst <- liftIO $ cGlobalIsConstant dataPtr'\n\n ti <- case initializer == nullPtr of\n True -> return Nothing\n False -> do\n tv <- translateConstOrRef finalState initializer\n return $ Just tv\n\n let gv = GlobalDeclaration { globalVariableLinkage = link\n , globalVariableVisibility = vis\n , globalVariableInitializer = ti\n , globalVariableAlignment = align\n , globalVariableSection = section\n , globalVariableIsThreadLocal = isThreadLocal\n , globalVariableIsConstant = isConst\n }\n v = basicVal { valueContent = gv }\n recordValue vp v\n return v\n\ntranslateFunction :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateFunction finalState vp = do\n name <- liftIO $ cValueName vp\n typePtr <- liftIO $ cValueType vp\n dataPtr <- liftIO $ cValueData vp\n tt <- translateType finalState typePtr\n\n uid <- nextId\n\n let dataPtr' = castPtr dataPtr\n basicVal = Value { valueName = name\n , valueType = tt\n , valueMetadata = Nothing\n , valueContent = ExternalFunction [] -- FIXME: there are attributes here\n , valueUniqueId = uid\n }\n isExtern <- liftIO $ cFunctionIsExternal dataPtr'\n\n case isExtern of\n True -> do\n recordValue vp basicVal\n return basicVal\n False -> do\n align <- liftIO $ cFunctionAlignment dataPtr'\n vis <- liftIO $ cFunctionVisibility dataPtr'\n link <- liftIO $ cFunctionLinkage dataPtr'\n section <- liftIO $ cFunctionSection dataPtr'\n cc <- liftIO $ cFunctionCallingConvention dataPtr'\n gcname <- liftIO $ cFunctionGCName dataPtr'\n args <- liftIO $ cFunctionArguments dataPtr'\n blocks <- liftIO $ cFunctionBlocks dataPtr'\n isVarArg <- liftIO $ cFunctionIsVarArg dataPtr'\n\n args' <- mapM (translateValue finalState) args\n blocks' <- mapM (translateValue finalState) blocks\n\n let f = Function { functionParameters = args'\n , functionBody = blocks'\n , functionLinkage = link\n , functionVisibility = vis\n , functionCC = cc\n , functionRetAttrs = [] -- FIXME\n , functionAttrs = [] -- FIXME\n , functionSection = section\n , functionAlign = align\n , functionGCName = gcname\n , functionIsVararg = isVarArg\n }\n v = basicVal { valueContent = f }\n recordValue vp v\n return v\n\n-- | This wrapper checks to see if we have translated the value yet\n-- (but not against the final state - only the internal running\n-- state). This way we really translate it if it hasn't been seen\n-- yet, but get the translated value if we have touched it before.\ntranslateValue :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateValue finalState vp = do\n s <- get\n case M.lookup (ptrToIntPtr vp) (valueMap s) of\n Nothing -> translateValue' finalState vp\n Just v -> return v\n\n-- | Only the top-level translators should call this: Globals and BasicBlocks\n-- (Or translateConstOrRef when translating constants)\ntranslateValue' :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateValue' finalState vp = do\n tag <- liftIO $ cValueTag vp\n name <- liftIO $ cValueName vp\n typePtr <- liftIO $ cValueType vp\n dataPtr <- liftIO $ cValueData vp\n\n tt <- translateType finalState typePtr\n\n content <- case tag of\n ValArgument -> translateArgument finalState (castPtr dataPtr)\n ValBasicblock -> translateBasicBlock finalState (castPtr dataPtr)\n ValInlineasm -> translateInlineAsm finalState (castPtr dataPtr)\n ValBlockaddress -> translateBlockAddress finalState (castPtr dataPtr)\n ValConstantaggregatezero -> return ConstantAggregateZero\n ValConstantpointernull -> return ConstantPointerNull\n ValUndefvalue -> return UndefValue\n ValConstantarray -> translateConstantAggregate finalState ConstantArray (castPtr dataPtr)\n ValConstantstruct -> translateConstantAggregate finalState ConstantStruct (castPtr dataPtr)\n ValConstantvector -> translateConstantAggregate finalState ConstantVector (castPtr dataPtr)\n ValConstantfp -> translateConstantFP finalState (castPtr dataPtr)\n ValConstantint -> translateConstantInt finalState (castPtr dataPtr)\n ValRetinst -> translateRetInst finalState (castPtr dataPtr)\n ValBranchinst -> translateBranchInst finalState (castPtr dataPtr)\n ValSwitchinst -> translateSwitchInst finalState (castPtr dataPtr)\n ValIndirectbrinst -> translateIndirectBrInst finalState (castPtr dataPtr)\n ValInvokeinst -> translateInvokeInst finalState (castPtr dataPtr)\n ValUnwindinst -> return UnwindInst\n ValUnreachableinst -> return UnreachableInst\n ValAddinst -> translateFlaggedBinaryOp finalState AddInst (castPtr dataPtr)\n ValFaddinst -> translateFlaggedBinaryOp finalState AddInst (castPtr dataPtr)\n ValSubinst -> translateFlaggedBinaryOp finalState SubInst (castPtr dataPtr)\n ValFsubinst -> translateFlaggedBinaryOp finalState SubInst (castPtr dataPtr)\n ValMulinst -> translateFlaggedBinaryOp finalState MulInst (castPtr dataPtr)\n ValFmulinst -> translateFlaggedBinaryOp finalState MulInst (castPtr dataPtr)\n ValUdivinst -> translateBinaryOp finalState DivInst (castPtr dataPtr)\n ValSdivinst -> translateBinaryOp finalState DivInst (castPtr dataPtr)\n ValFdivinst -> translateBinaryOp finalState DivInst (castPtr dataPtr)\n ValUreminst -> translateBinaryOp finalState RemInst (castPtr dataPtr)\n ValSreminst -> translateBinaryOp finalState RemInst (castPtr dataPtr)\n ValFreminst -> translateBinaryOp finalState RemInst (castPtr dataPtr)\n ValShlinst -> translateBinaryOp finalState ShlInst (castPtr dataPtr)\n ValLshrinst -> translateBinaryOp finalState LshrInst (castPtr dataPtr)\n ValAshrinst -> translateBinaryOp finalState AshrInst (castPtr dataPtr)\n ValAndinst -> translateBinaryOp finalState AndInst (castPtr dataPtr)\n ValOrinst -> translateBinaryOp finalState OrInst (castPtr dataPtr)\n ValXorinst -> translateBinaryOp finalState XorInst (castPtr dataPtr)\n ValAllocainst -> translateAllocaInst finalState (castPtr dataPtr)\n ValLoadinst -> translateLoadInst finalState (castPtr dataPtr)\n ValStoreinst -> translateStoreInst finalState (castPtr dataPtr)\n ValGetelementptrinst -> translateGEPInst finalState (castPtr dataPtr)\n ValTruncinst -> translateCastInst finalState TruncInst (castPtr dataPtr)\n ValZextinst -> translateCastInst finalState ZExtInst (castPtr dataPtr)\n ValSextinst -> translateCastInst finalState SExtInst (castPtr dataPtr)\n ValFptruncinst -> translateCastInst finalState FPTruncInst (castPtr dataPtr)\n ValFpextinst -> translateCastInst finalState FPExtInst (castPtr dataPtr)\n ValFptouiinst -> translateCastInst finalState FPToUIInst (castPtr dataPtr)\n ValFptosiinst -> translateCastInst finalState FPToSIInst (castPtr dataPtr)\n ValUitofpinst -> translateCastInst finalState UIToFPInst (castPtr dataPtr)\n ValSitofpinst -> translateCastInst finalState SIToFPInst (castPtr dataPtr)\n ValPtrtointinst -> translateCastInst finalState PtrToIntInst (castPtr dataPtr)\n ValInttoptrinst -> translateCastInst finalState IntToPtrInst (castPtr dataPtr)\n ValBitcastinst -> translateCastInst finalState BitcastInst (castPtr dataPtr)\n ValIcmpinst -> translateCmpInst finalState ICmpInst (castPtr dataPtr)\n ValFcmpinst -> translateCmpInst finalState FCmpInst (castPtr dataPtr)\n ValPhinode -> translatePhiNode finalState (castPtr dataPtr)\n ValCallinst -> translateCallInst finalState (castPtr dataPtr)\n ValSelectinst -> translateSelectInst finalState (castPtr dataPtr)\n ValVaarginst -> translateVarArgInst finalState (castPtr dataPtr)\n ValExtractelementinst -> translateExtractElementInst finalState (castPtr dataPtr)\n ValInsertelementinst -> translateInsertElementInst finalState (castPtr dataPtr)\n ValShufflevectorinst -> translateShuffleVectorInst finalState (castPtr dataPtr)\n ValExtractvalueinst -> translateExtractValueInst finalState (castPtr dataPtr)\n ValInsertvalueinst -> translateInsertValueInst finalState (castPtr dataPtr)\n ValFunction -> throw InvalidFunctionInTranslateValue\n ValAlias -> throw InvalidAliasInTranslateValue\n ValGlobalvariable -> throw InvalidGlobalVarInTranslateValue\n ValConstantexpr -> translateConstantExpr finalState (castPtr dataPtr)\n\n uid <- nextId\n\n let tv = Value { valueType = tt\n , valueName = name\n , valueMetadata = Nothing\n , valueContent = content\n , valueUniqueId = uid\n }\n\n recordValue vp tv\n\n return tv\n\nisConstant :: ValueTag -> Bool\nisConstant vt = case vt of\n ValConstantaggregatezero -> True\n ValConstantarray -> True\n ValConstantfp -> True\n ValConstantint -> True\n ValConstantpointernull -> True\n ValConstantstruct -> True\n ValConstantvector -> True\n ValUndefvalue -> True\n ValConstantexpr -> True\n ValBlockaddress -> True\n _ -> False\n\ntranslateConstOrRef :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateConstOrRef finalState vp = do\n tag <- liftIO $ cValueTag vp\n if isConstant tag\n then translateValue finalState vp\n else case M.lookup (ptrToIntPtr vp) (valueMap finalState) of\n Just v -> return v\n Nothing -> throw KnotTyingFailure\n\n\ntranslateArgument :: KnotState -> ArgInfoPtr -> KnotMonad ValueT\ntranslateArgument _ dataPtr = do\n hasSRet <- liftIO $ cArgInfoHasSRet dataPtr\n hasByVal <- liftIO $ cArgInfoHasByVal dataPtr\n hasNest <- liftIO $ cArgInfoHasNest dataPtr\n hasNoAlias <- liftIO $ cArgInfoHasNoAlias dataPtr\n hasNoCapture <- liftIO $ cArgInfoHasNoCapture dataPtr\n let attrOrNothing b att = if b then Just att else Nothing\n atts = [ attrOrNothing hasSRet PASRet\n , attrOrNothing hasByVal PAByVal\n , attrOrNothing hasNest PANest\n , attrOrNothing hasNoAlias PANoAlias\n , attrOrNothing hasNoCapture PANoCapture\n ]\n return $! Argument (catMaybes atts)\n\ntranslateBasicBlock :: KnotState -> BasicBlockPtr -> KnotMonad ValueT\ntranslateBasicBlock finalState dataPtr = do\n insts <- liftIO $ cBasicBlockInstructions dataPtr\n tinsts <- mapM (translateValue finalState) insts\n return $! BasicBlock tinsts\n\ntranslateInlineAsm :: KnotState -> InlineAsmInfoPtr -> KnotMonad ValueT\ntranslateInlineAsm _ dataPtr = do\n asmString <- liftIO $ cInlineAsmString dataPtr\n constraints <- liftIO $ cInlineAsmConstraints dataPtr\n return $! InlineAsm asmString constraints\n\ntranslateBlockAddress :: KnotState -> BlockAddrInfoPtr -> KnotMonad ValueT\ntranslateBlockAddress finalState dataPtr = do\n fval <- liftIO $ cBlockAddrFunc dataPtr\n bval <- liftIO $ cBlockAddrBlock dataPtr\n f' <- translateConstOrRef finalState fval\n b' <- translateConstOrRef finalState bval\n return $! BlockAddress f' b'\n\ntranslateConstantAggregate :: KnotState -> ([Value] -> ValueT) -> AggregateInfoPtr -> KnotMonad ValueT\ntranslateConstantAggregate finalState constructor dataPtr = do\n vals <- liftIO $ cAggregateValues dataPtr\n vals' <- mapM (translateConstOrRef finalState) vals\n return $! constructor vals'\n\ntranslateConstantFP :: KnotState -> FPInfoPtr -> KnotMonad ValueT\ntranslateConstantFP _ dataPtr = do\n fpval <- liftIO $ cFPVal dataPtr\n return $! ConstantFP fpval\n\ntranslateConstantInt :: KnotState -> IntInfoPtr -> KnotMonad ValueT\ntranslateConstantInt _ dataPtr = do\n intval <- liftIO $ cIntVal dataPtr\n return $! ConstantInt intval\n\ntranslateRetInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateRetInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n case opPtrs of\n [] -> return $! RetInst Nothing\n [val] -> do\n val' <- translateConstOrRef finalState val\n return $! RetInst (Just val')\n _ -> throw TooManyReturnValues\n\ntranslateBranchInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateBranchInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n case opPtrs of\n [dst] -> do\n dst' <- translateConstOrRef finalState dst\n return $! UnconditionalBranchInst dst'\n [val, t, f] -> do\n val' <- translateConstOrRef finalState val\n tbranch <- translateConstOrRef finalState t\n fbranch <- translateConstOrRef finalState f\n return $! BranchInst { branchCondition = val'\n , branchTrueTarget = tbranch\n , branchFalseTarget = fbranch\n }\n _ -> throw InvalidBranchInst\n\ntranslateSwitchInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateSwitchInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n case opPtrs of\n (swVal:defTarget:cases) -> do\n val' <- translateConstOrRef finalState swVal\n def' <- translateConstOrRef finalState defTarget\n -- Process the rest of the list in pairs since that is how LLVM\n -- stores them, but transform it into a nice list of actual\n -- pairs\n let tpairs acc (v1:dest:rest) = do\n v1' <- translateConstOrRef finalState v1\n dest' <- translateConstOrRef finalState dest\n tpairs ((v1', dest'):acc) rest\n tpairs acc [] = return $ reverse acc\n tpairs _ _ = throw InvalidSwitchLayout\n cases' <- tpairs [] cases\n return $! SwitchInst { switchValue = val'\n , switchDefaultTarget = def'\n , switchCases = cases'\n }\n _ -> throw InvalidSwitchLayout\n\ntranslateIndirectBrInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateIndirectBrInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n case opPtrs of\n (addr:targets) -> do\n addr' <- translateConstOrRef finalState addr\n targets' <- mapM (translateConstOrRef finalState) targets\n return $! IndirectBranchInst { indirectBranchAddress = addr'\n , indirectBranchTargets = targets'\n }\n _ -> throw InvalidIndirectBranchOperands\n\ntranslateInvokeInst :: KnotState -> CallInfoPtr -> KnotMonad ValueT\ntranslateInvokeInst finalState dataPtr = do\n func <- liftIO $ cCallValue dataPtr\n args <- liftIO $ cCallArguments dataPtr\n cc <- liftIO $ cCallConvention dataPtr\n hasSRet <- liftIO $ cCallHasSRet dataPtr\n ndest <- liftIO $ cCallNormalDest dataPtr\n udest <- liftIO $ cCallUnwindDest dataPtr\n\n f' <- translateConstOrRef finalState func\n args' <- mapM (translateConstOrRef finalState) args\n n' <- translateConstOrRef finalState ndest\n u' <- translateConstOrRef finalState udest\n\n return $! InvokeInst { invokeConvention = cc\n , invokeParamAttrs = [] -- FIXME\n , invokeFunction = f'\n , invokeArguments = zip args' (repeat []) -- FIXME\n , invokeAttrs = [] -- FIXME\n , invokeNormalLabel = n'\n , invokeUnwindLabel = u'\n , invokeHasSRet = hasSRet\n }\n\ntranslateFlaggedBinaryOp :: KnotState -> (ArithFlags -> Value -> Value -> ValueT) ->\n InstInfoPtr -> KnotMonad ValueT\ntranslateFlaggedBinaryOp finalState constructor dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n flags <- liftIO $ cInstructionArithFlags dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [lhs, rhs] -> return $! constructor flags lhs rhs\n _ -> throw $ InvalidBinaryOp (length ops)\n\ntranslateBinaryOp :: KnotState -> (Value -> Value -> ValueT) ->\n InstInfoPtr -> KnotMonad ValueT\ntranslateBinaryOp finalState constructor dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [lhs, rhs] -> return $! constructor lhs rhs\n _ -> throw $ InvalidBinaryOp (length ops)\n\ntranslateAllocaInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateAllocaInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n align <- liftIO $ cInstructionAlign dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [val] -> return $! AllocaInst val align\n _ -> throw $ InvalidUnaryOp (length ops)\n\n\ntranslateLoadInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateLoadInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n align <- liftIO $ cInstructionAlign dataPtr\n vol <- liftIO $ cInstructionIsVolatile dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [addr] -> return $! LoadInst vol addr align\n _ -> throw $ InvalidUnaryOp (length ops)\n\ntranslateStoreInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateStoreInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n addrSpace <- liftIO $ cInstructionAddrSpace dataPtr\n align <- liftIO $ cInstructionAlign dataPtr\n isVol <- liftIO $ cInstructionIsVolatile dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [val, ptr] -> return $! StoreInst isVol val ptr align\n _ -> throw $ InvalidBinaryOp (length ops)\n\ntranslateGEPInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateGEPInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n inBounds <- liftIO $ cInstructionInBounds dataPtr\n addrSpace <- liftIO $ cInstructionAddrSpace dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n (val:indices) -> return $! GetElementPtrInst { getElementPtrInBounds = inBounds\n , getElementPtrValue = val\n , getElementPtrIndices = indices\n }\n _ -> throw $ InvalidGEPInst (length ops)\n\ntranslateCastInst :: KnotState -> (Value -> ValueT) -> InstInfoPtr -> KnotMonad ValueT\ntranslateCastInst finalState constructor dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [v] -> return $! constructor v\n _ -> throw $ InvalidUnaryOp (length ops)\n\ntranslateCmpInst :: KnotState -> (CmpPredicate -> Value -> Value -> ValueT) ->\n InstInfoPtr -> KnotMonad ValueT\ntranslateCmpInst finalState constructor dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n predicate <- liftIO $ cInstructionCmpPred dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [op1, op2] -> return $! constructor predicate op1 op2\n _ -> throw $ InvalidBinaryOp (length ops)\n\ntranslatePhiNode :: KnotState -> PHIInfoPtr -> KnotMonad ValueT\ntranslatePhiNode finalState dataPtr = do\n vptrs <- liftIO $ cPHIValues dataPtr\n bptrs <- liftIO $ cPHIBlocks dataPtr\n\n vals <- mapM (translateConstOrRef finalState) vptrs\n blocks <- mapM (translateConstOrRef finalState) bptrs\n\n return $! PhiNode $ zip vals blocks\n\ntranslateCallInst :: KnotState -> CallInfoPtr -> KnotMonad ValueT\ntranslateCallInst finalState dataPtr = do\n vptr <- liftIO $ cCallValue dataPtr\n aptrs <- liftIO $ cCallArguments dataPtr\n cc <- liftIO $ cCallConvention dataPtr\n hasSRet <- liftIO $ cCallHasSRet dataPtr\n isTail <- liftIO $ cCallIsTail dataPtr\n\n val <- translateConstOrRef finalState vptr\n args <- mapM (translateConstOrRef finalState) aptrs\n\n return $! CallInst { callIsTail = isTail\n , callConvention = cc\n , callParamAttrs = [] -- FIXME\n , callFunction = val\n , callArguments = zip args (repeat []) -- FIXME\n , callAttrs = [] -- FIXME\n , callHasSRet = hasSRet\n }\n\ntranslateSelectInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateSelectInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [cond, trueval, falseval] -> do\n return $! SelectInst cond trueval falseval\n _ -> throw $ InvalidSelectArgs (length ops)\n\ntranslateVarArgInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateVarArgInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [op] -> return $! VaArgInst op\n _ -> throw $ InvalidUnaryOp (length ops)\n\ntranslateExtractElementInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateExtractElementInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [vec, idx] -> do\n return $! ExtractElementInst { extractElementVector = vec\n , extractElementIndex = idx\n }\n _ -> throw $ InvalidExtractElementInst (length ops)\n\ntranslateInsertElementInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateInsertElementInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [vec, val, idx] -> do\n return $! InsertElementInst { insertElementVector = vec\n , insertElementValue = val\n , insertElementIndex = idx\n }\n _ -> throw $ InvalidInsertElementInst (length ops)\n\ntranslateShuffleVectorInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateShuffleVectorInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [v1, v2, vecMask] -> do\n return $! ShuffleVectorInst { shuffleVectorV1 = v1\n , shuffleVectorV2 = v2\n , shuffleVectorMask = vecMask\n }\n _ -> throw $ InvalidShuffleVectorInst (length ops)\n\ntranslateExtractValueInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateExtractValueInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n indices <- liftIO $ cInstructionIndices dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [agg] -> return $! ExtractValueInst { extractValueAggregate = agg\n , extractValueIndices = indices\n }\n _ -> throw $ InvalidExtractValueInst (length ops)\n\ntranslateInsertValueInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateInsertValueInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n indices <- liftIO $ cInstructionIndices dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [agg, val] ->\n return $! InsertValueInst { insertValueAggregate = agg\n , insertValueValue = val\n , insertValueIndices = indices\n }\n _ -> throw $ InvalidInsertValueInst (length ops)\n\ntranslateConstantExpr :: KnotState -> ConstExprPtr -> KnotMonad ValueT\ntranslateConstantExpr finalState dataPtr = do\n ii <- liftIO $ cConstExprInstInfo dataPtr\n tag <- liftIO $ cConstExprTag dataPtr\n vt <- case tag of\n ValAddinst -> translateFlaggedBinaryOp finalState AddInst ii\n ValFaddinst -> translateFlaggedBinaryOp finalState AddInst ii\n ValSubinst -> translateFlaggedBinaryOp finalState SubInst ii\n ValFsubinst -> translateFlaggedBinaryOp finalState SubInst ii\n ValMulinst -> translateFlaggedBinaryOp finalState MulInst ii\n ValFmulinst -> translateFlaggedBinaryOp finalState MulInst ii\n ValUdivinst -> translateBinaryOp finalState DivInst ii\n ValSdivinst -> translateBinaryOp finalState DivInst ii\n ValFdivinst -> translateBinaryOp finalState DivInst ii\n ValUreminst -> translateBinaryOp finalState RemInst ii\n ValSreminst -> translateBinaryOp finalState RemInst ii\n ValFreminst -> translateBinaryOp finalState RemInst ii\n ValShlinst -> translateBinaryOp finalState ShlInst ii\n ValLshrinst -> translateBinaryOp finalState LshrInst ii\n ValAshrinst -> translateBinaryOp finalState AshrInst ii\n ValAndinst -> translateBinaryOp finalState AndInst ii\n ValOrinst -> translateBinaryOp finalState OrInst ii\n ValXorinst -> translateBinaryOp finalState XorInst ii\n ValGetelementptrinst -> translateGEPInst finalState ii\n ValTruncinst -> translateCastInst finalState TruncInst ii\n ValZextinst -> translateCastInst finalState ZExtInst ii\n ValSextinst -> translateCastInst finalState SExtInst ii\n ValFptruncinst -> translateCastInst finalState FPTruncInst ii\n ValFpextinst -> translateCastInst finalState FPExtInst ii\n ValFptouiinst -> translateCastInst finalState FPToUIInst ii\n ValFptosiinst -> translateCastInst finalState FPToSIInst ii\n ValUitofpinst -> translateCastInst finalState UIToFPInst ii\n ValSitofpinst -> translateCastInst finalState SIToFPInst ii\n ValPtrtointinst -> translateCastInst finalState PtrToIntInst ii\n ValInttoptrinst -> translateCastInst finalState IntToPtrInst ii\n ValBitcastinst -> translateCastInst finalState BitcastInst ii\n ValIcmpinst -> translateCmpInst finalState ICmpInst ii\n ValFcmpinst -> translateCmpInst finalState FCmpInst ii\n ValSelectinst -> translateSelectInst finalState ii\n ValVaarginst -> translateVarArgInst finalState ii\n ValExtractelementinst -> translateExtractElementInst finalState ii\n ValInsertelementinst -> translateInsertElementInst finalState ii\n ValShufflevectorinst -> translateShuffleVectorInst finalState ii\n ValExtractvalueinst -> translateExtractValueInst finalState ii\n ValInsertvalueinst -> translateInsertValueInst finalState ii\n return $! ConstantValue vt","old_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, RankNTypes #-}\nmodule Data.LLVM.Private.Parser.Unmarshal ( parseBitcode ) where\n\n#include \"c++\/marshal.h\"\n\nimport Control.Applicative\nimport Control.DeepSeq\nimport Control.Exception\nimport Control.Monad.State\nimport Data.Array.Storable\nimport Data.ByteString.Char8 ( ByteString )\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport Data.IORef\nimport Data.Map ( Map )\nimport qualified Data.Map as M\nimport Data.Maybe ( catMaybes )\nimport Data.Typeable\nimport Foreign.C\nimport Foreign.ForeignPtr\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Data.LLVM.Private.C2HS\nimport Data.LLVM.Private.Parser.Options\nimport Data.LLVM.Types\n\ndata TranslationException = TooManyReturnValues\n | InvalidBranchInst\n | InvalidSwitchLayout\n | InvalidIndirectBranchOperands\n | KnotTyingFailure\n | InvalidSelectArgs !Int\n | InvalidExtractElementInst !Int\n | InvalidInsertElementInst !Int\n | InvalidShuffleVectorInst !Int\n | InvalidFunctionInTranslateValue\n | InvalidAliasInTranslateValue\n | InvalidGlobalVarInTranslateValue\n | InvalidBinaryOp !Int\n | InvalidUnaryOp !Int\n | InvalidGEPInst !Int\n | InvalidExtractValueInst !Int\n | InvalidInsertValueInst !Int\n deriving (Show, Typeable)\ninstance Exception TranslationException\n\n\n{#enum TypeTag {} deriving (Show, Eq) #}\n{#enum ValueTag {underscoreToCase} deriving (Show, Eq) #}\n\ndata CModule\n{#pointer *CModule as ModulePtr -> CModule #}\n\ncModuleIdentifier :: ModulePtr -> IO ByteString\ncModuleIdentifier m = ({#get CModule->moduleIdentifier#} m) >>= BS.packCString\n\ncModuleDataLayout :: ModulePtr -> IO ByteString\ncModuleDataLayout m = ({#get CModule->moduleDataLayout#} m) >>= BS.packCString\n\ncModuleTargetTriple :: ModulePtr -> IO ByteString\ncModuleTargetTriple m = ({#get CModule->targetTriple#} m) >>= BS.packCString\n\ncModuleInlineAsm :: ModulePtr -> IO ByteString\ncModuleInlineAsm m = ({#get CModule->moduleInlineAsm#} m) >>= BS.packCString\n\ncModuleHasError :: ModulePtr -> IO Bool\ncModuleHasError m = cToBool <$> ({#get CModule->hasError#} m)\n\ncModuleErrorMessage :: ModulePtr -> IO String\ncModuleErrorMessage m = ({#get CModule->errMsg#} m) >>= peekCString\n\ncModuleLittleEndian :: ModulePtr -> IO Bool\ncModuleLittleEndian m = cToBool <$> ({#get CModule->littleEndian#} m)\n\ncModulePointerSize :: ModulePtr -> IO Int\ncModulePointerSize m = cIntConv <$> ({#get CModule->pointerSize#} m)\n\ncModuleGlobalVariables :: ModulePtr -> IO [ValuePtr]\ncModuleGlobalVariables m =\n peekArray m {#get CModule->globalVariables#} {#get CModule->numGlobalVariables#}\n\ncModuleGlobalAliases :: ModulePtr -> IO [ValuePtr]\ncModuleGlobalAliases m =\n peekArray m ({#get CModule->globalAliases#}) ({#get CModule->numGlobalAliases#})\n\ncModuleFunctions :: ModulePtr -> IO [ValuePtr]\ncModuleFunctions m =\n peekArray m ({#get CModule->functions#}) ({#get CModule->numFunctions#})\n\npeekArray :: forall a b c e . (Integral c, Storable e) =>\n a -> (a -> IO (Ptr b)) -> (a -> IO c) -> IO [e]\npeekArray obj arrAccessor sizeAccessor = do\n nElts <- sizeAccessor obj\n arrPtr <- arrAccessor obj\n fArrPtr <- newForeignPtr_ (castPtr arrPtr)\n arr <- unsafeForeignPtrToStorableArray fArrPtr (1, cIntConv nElts)\n getElems arr\n\ndata CType\n{#pointer *CType as TypePtr -> CType #}\ncTypeTag :: TypePtr -> IO TypeTag\ncTypeTag t = cToEnum <$> {#get CType->typeTag#} t\ncTypeSize :: TypePtr -> IO Int\ncTypeSize t = cIntConv <$> {#get CType->size#} t\ncTypeIsVarArg :: TypePtr -> IO Bool\ncTypeIsVarArg t = cToBool <$> {#get CType->isVarArg#} t\ncTypeIsPacked :: TypePtr -> IO Bool\ncTypeIsPacked t = cToBool <$> {#get CType->isPacked#} t\ncTypeList :: TypePtr -> IO [TypePtr]\ncTypeList t =\n peekArray t {#get CType->typeList#} {#get CType->typeListLen#}\ncTypeInner :: TypePtr -> IO TypePtr\ncTypeInner = {#get CType->innerType#}\ncTypeName :: TypePtr -> IO String\ncTypeName t = {#get CType->name#} t >>= peekCString\ncTypeAddrSpace :: TypePtr -> IO Int\ncTypeAddrSpace t = cIntConv <$> {#get CType->addrSpace#} t\n\ndata CValue\n{#pointer *CValue as ValuePtr -> CValue #}\n\ncValueTag :: ValuePtr -> IO ValueTag\ncValueTag v = cToEnum <$> ({#get CValue->valueTag#} v)\ncValueType :: ValuePtr -> IO TypePtr\ncValueType = {#get CValue->valueType#}\ncValueName :: ValuePtr -> IO (Maybe Identifier)\ncValueName v = do\n namePtr <- ({#get CValue->name#}) v\n case namePtr == nullPtr of\n True -> return Nothing\n False -> do\n name <- BS.packCString namePtr\n return $! (Just . makeIdentifier) name\ncValueData :: ValuePtr -> IO (Ptr ())\ncValueData = {#get CValue->data#}\n\ndata CGlobalInfo\n{#pointer *CGlobalInfo as GlobalInfoPtr -> CGlobalInfo #}\ncGlobalIsExternal :: GlobalInfoPtr -> IO Bool\ncGlobalIsExternal g = cToBool <$> ({#get CGlobalInfo->isExternal#} g)\ncGlobalAlignment :: GlobalInfoPtr -> IO Int64\ncGlobalAlignment g = cIntConv <$> ({#get CGlobalInfo->alignment#} g)\ncGlobalVisibility :: GlobalInfoPtr -> IO VisibilityStyle\ncGlobalVisibility g = cToEnum <$> ({#get CGlobalInfo->visibility#} g)\ncGlobalLinkage :: GlobalInfoPtr -> IO LinkageType\ncGlobalLinkage g = cToEnum <$> ({#get CGlobalInfo->linkage#} g)\ncGlobalSection :: GlobalInfoPtr -> IO (Maybe ByteString)\ncGlobalSection g = do\n s <- {#get CGlobalInfo->section#} g\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just bs\ncGlobalInitializer :: GlobalInfoPtr -> IO ValuePtr\ncGlobalInitializer = {#get CGlobalInfo->initializer#}\ncGlobalIsThreadLocal :: GlobalInfoPtr -> IO Bool\ncGlobalIsThreadLocal g = cToBool <$> ({#get CGlobalInfo->isThreadLocal#} g)\ncGlobalAliasee :: GlobalInfoPtr -> IO ValuePtr\ncGlobalAliasee = {#get CGlobalInfo->aliasee#}\ncGlobalIsConstant :: GlobalInfoPtr -> IO Bool\ncGlobalIsConstant g = cToBool <$> {#get CGlobalInfo->isConstant#} g\n\ndata CFunctionInfo\n{#pointer *CFunctionInfo as FunctionInfoPtr -> CFunctionInfo #}\ncFunctionIsExternal :: FunctionInfoPtr -> IO Bool\ncFunctionIsExternal f = cToBool <$> {#get CFunctionInfo->isExternal#} f\ncFunctionAlignment :: FunctionInfoPtr -> IO Int64\ncFunctionAlignment f = cIntConv <$> {#get CFunctionInfo->alignment#} f\ncFunctionVisibility :: FunctionInfoPtr -> IO VisibilityStyle\ncFunctionVisibility f = cToEnum <$> {#get CFunctionInfo->visibility#} f\ncFunctionLinkage :: FunctionInfoPtr -> IO LinkageType\ncFunctionLinkage f = cToEnum <$> {#get CFunctionInfo->linkage#} f\ncFunctionSection :: FunctionInfoPtr -> IO (Maybe ByteString)\ncFunctionSection f = do\n s <- {#get CFunctionInfo->section#} f\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just bs\ncFunctionIsVarArg :: FunctionInfoPtr -> IO Bool\ncFunctionIsVarArg f = cToBool <$> {#get CFunctionInfo->isVarArg#} f\ncFunctionCallingConvention :: FunctionInfoPtr -> IO CallingConvention\ncFunctionCallingConvention f = cToEnum <$> {#get CFunctionInfo->callingConvention#} f\ncFunctionGCName :: FunctionInfoPtr -> IO (Maybe GCName)\ncFunctionGCName f = do\n s <- {#get CFunctionInfo->gcName#} f\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just (GCName bs)\ncFunctionArguments :: FunctionInfoPtr -> IO [ValuePtr]\ncFunctionArguments f =\n peekArray f {#get CFunctionInfo->arguments#} {#get CFunctionInfo->argListLen#}\ncFunctionBlocks :: FunctionInfoPtr -> IO [ValuePtr]\ncFunctionBlocks f =\n peekArray f {#get CFunctionInfo->body#} {#get CFunctionInfo->blockListLen#}\n\ndata CArgInfo\n{#pointer *CArgumentInfo as ArgInfoPtr -> CArgInfo #}\ncArgInfoHasSRet :: ArgInfoPtr -> IO Bool\ncArgInfoHasSRet a = cToBool <$> ({#get CArgumentInfo->hasSRet#} a)\ncArgInfoHasByVal :: ArgInfoPtr -> IO Bool\ncArgInfoHasByVal a = cToBool <$> ({#get CArgumentInfo->hasByVal#} a)\ncArgInfoHasNest :: ArgInfoPtr -> IO Bool\ncArgInfoHasNest a = cToBool <$> ({#get CArgumentInfo->hasNest#} a)\ncArgInfoHasNoAlias :: ArgInfoPtr -> IO Bool\ncArgInfoHasNoAlias a = cToBool <$> ({#get CArgumentInfo->hasNoAlias#} a)\ncArgInfoHasNoCapture :: ArgInfoPtr -> IO Bool\ncArgInfoHasNoCapture a = cToBool <$> ({#get CArgumentInfo->hasNoCapture#} a)\n\ndata CBasicBlockInfo\n{#pointer *CBasicBlockInfo as BasicBlockPtr -> CBasicBlockInfo #}\n\ncBasicBlockInstructions :: BasicBlockPtr -> IO [ValuePtr]\ncBasicBlockInstructions b =\n peekArray b {#get CBasicBlockInfo->instructions#} {#get CBasicBlockInfo->blockLen#}\n\ndata CInlineAsmInfo\n{#pointer *CInlineAsmInfo as InlineAsmInfoPtr -> CInlineAsmInfo #}\n\ncInlineAsmString :: InlineAsmInfoPtr -> IO ByteString\ncInlineAsmString a =\n ({#get CInlineAsmInfo->asmString#} a) >>= BS.packCString\ncInlineAsmConstraints :: InlineAsmInfoPtr -> IO ByteString\ncInlineAsmConstraints a =\n ({#get CInlineAsmInfo->constraintString#} a) >>= BS.packCString\n\ndata CBlockAddrInfo\n{#pointer *CBlockAddrInfo as BlockAddrInfoPtr -> CBlockAddrInfo #}\n\ncBlockAddrFunc :: BlockAddrInfoPtr -> IO ValuePtr\ncBlockAddrFunc = {#get CBlockAddrInfo->func #}\ncBlockAddrBlock :: BlockAddrInfoPtr -> IO ValuePtr\ncBlockAddrBlock = {#get CBlockAddrInfo->block #}\n\ndata CAggregateInfo\n{#pointer *CConstAggregate as AggregateInfoPtr -> CAggregateInfo #}\n\ncAggregateValues :: AggregateInfoPtr -> IO [ValuePtr]\ncAggregateValues a =\n peekArray a {#get CConstAggregate->constants#} {#get CConstAggregate->numElements#}\n\ndata CConstFP\n{#pointer *CConstFP as FPInfoPtr -> CConstFP #}\ncFPVal :: FPInfoPtr -> IO Double\ncFPVal f = cFloatConv <$> ({#get CConstFP->val#} f)\n\ndata CConstInt\n{#pointer *CConstInt as IntInfoPtr -> CConstInt #}\ncIntVal :: IntInfoPtr -> IO Integer\ncIntVal i = cIntConv <$> ({#get CConstInt->val#} i)\n\ndata CInstructionInfo\n{#pointer *CInstructionInfo as InstInfoPtr -> CInstructionInfo #}\ncInstructionOperands :: InstInfoPtr -> IO [ValuePtr]\ncInstructionOperands i =\n peekArray i {#get CInstructionInfo->operands#} {#get CInstructionInfo->numOperands#}\ncInstructionArithFlags :: InstInfoPtr -> IO ArithFlags\ncInstructionArithFlags o = cToEnum <$> {#get CInstructionInfo->flags#} o\ncInstructionAlign :: InstInfoPtr -> IO Int64\ncInstructionAlign u = cIntConv <$> {#get CInstructionInfo->align#} u\ncInstructionIsVolatile :: InstInfoPtr -> IO Bool\ncInstructionIsVolatile u = cToBool <$> {#get CInstructionInfo->isVolatile#} u\ncInstructionAddrSpace :: InstInfoPtr -> IO Int\ncInstructionAddrSpace u = cIntConv <$> {#get CInstructionInfo->addrSpace#} u\ncInstructionCmpPred :: InstInfoPtr -> IO CmpPredicate\ncInstructionCmpPred c = cToEnum <$> {#get CInstructionInfo->cmpPred#} c\ncInstructionInBounds :: InstInfoPtr -> IO Bool\ncInstructionInBounds g = cToBool <$> {#get CInstructionInfo->inBounds#} g\ncInstructionIndices :: InstInfoPtr -> IO [Int]\ncInstructionIndices i =\n peekArray i {#get CInstructionInfo->indices#} {#get CInstructionInfo->numIndices#}\n\ndata CConstExprInfo\n{#pointer *CConstExprInfo as ConstExprPtr -> CConstExprInfo #}\ncConstExprTag :: ConstExprPtr -> IO ValueTag\ncConstExprTag e = cToEnum <$> {#get CConstExprInfo->instrType#} e\ncConstExprInstInfo :: ConstExprPtr -> IO InstInfoPtr\ncConstExprInstInfo = {#get CConstExprInfo->ii#}\n\ndata CPHIInfo\n{#pointer *CPHIInfo as PHIInfoPtr -> CPHIInfo #}\ncPHIValues :: PHIInfoPtr -> IO [ValuePtr]\ncPHIValues p =\n peekArray p {#get CPHIInfo->incomingValues#} {#get CPHIInfo->numIncomingValues#}\ncPHIBlocks :: PHIInfoPtr -> IO [ValuePtr]\ncPHIBlocks p =\n peekArray p {#get CPHIInfo->valueBlocks#} {#get CPHIInfo->numIncomingValues#}\n\ndata CCallInfo\n{#pointer *CCallInfo as CallInfoPtr -> CCallInfo #}\ncCallValue :: CallInfoPtr -> IO ValuePtr\ncCallValue = {#get CCallInfo->calledValue #}\ncCallArguments :: CallInfoPtr -> IO [ValuePtr]\ncCallArguments c =\n peekArray c {#get CCallInfo->arguments#} {#get CCallInfo->argListLen#}\ncCallConvention :: CallInfoPtr -> IO CallingConvention\ncCallConvention c = cToEnum <$> {#get CCallInfo->callingConvention#} c\ncCallHasSRet :: CallInfoPtr -> IO Bool\ncCallHasSRet c = cToBool <$> {#get CCallInfo->hasSRet#} c\ncCallIsTail :: CallInfoPtr -> IO Bool\ncCallIsTail c = cToBool <$> {#get CCallInfo->isTail#} c\ncCallUnwindDest :: CallInfoPtr -> IO ValuePtr\ncCallUnwindDest = {#get CCallInfo->unwindDest#}\ncCallNormalDest :: CallInfoPtr -> IO ValuePtr\ncCallNormalDest = {#get CCallInfo->normalDest#}\n\n-- | Parse the named file into an FFI-friendly representation of an\n-- LLVM module.\n{#fun marshalLLVM { `String' } -> `ModulePtr' id #}\n\n-- | Free all of the resources allocated by 'marshalLLVM'\n{#fun disposeCModule { id `ModulePtr' } -> `()' #}\n\n-- FIXME: add accessors for value metadata\n\ntype KnotMonad = StateT KnotState IO\ndata KnotState = KnotState { valueMap :: Map IntPtr Value\n , typeMap :: Map IntPtr Type\n , idSrc :: IORef Int\n }\nemptyState :: IORef Int -> KnotState\nemptyState r = KnotState { valueMap = M.empty\n , typeMap = M.empty\n , idSrc = r\n }\n\nnextId :: KnotMonad Int\nnextId = do\n s <- get\n let r = idSrc s\n thisId <- liftIO $ readIORef r\n liftIO $ modifyIORef r (+1)\n\n return thisId\n\nparseBitcode :: ParserOptions -> FilePath -> IO (Either String Module)\nparseBitcode _ bitcodefile = do\n m <- marshalLLVM bitcodefile\n\n hasError <- cModuleHasError m\n case hasError of\n True -> do\n err <- cModuleErrorMessage m\n disposeCModule m\n return $! Left err\n False -> do\n ref <- newIORef 0\n (ir, _) <- evalStateT (mfix (tieKnot m)) (emptyState ref)\n\n disposeCModule m\n return $! Right (ir `deepseq` ir)\n\n\ntieKnot :: ModulePtr -> (Module, KnotState) -> KnotMonad (Module, KnotState)\ntieKnot m (_, finalState) = do\n modIdent <- liftIO $ cModuleIdentifier m\n dataLayout <- liftIO $ cModuleDataLayout m\n triple <- liftIO $ cModuleTargetTriple m\n inlineAsm <- liftIO $ cModuleInlineAsm m\n\n vars <- liftIO $ cModuleGlobalVariables m\n aliases <- liftIO $ cModuleGlobalAliases m\n funcs <- liftIO $ cModuleFunctions m\n\n vars' <- mapM (translateGlobalVariable finalState) vars\n aliases' <- mapM (translateAlias finalState) aliases\n funcs' <- mapM (translateFunction finalState) funcs\n\n let ir = Module { moduleIdentifier = modIdent\n , moduleDataLayout = undefined\n , moduleTarget = undefined\n , moduleAssembly = Assembly inlineAsm\n , moduleAliases = aliases'\n , moduleGlobalVariables = vars'\n , moduleFunctions = funcs'\n }\n s <- get\n return (ir, s)\n\ntranslateType :: TypePtr -> KnotMonad Type\ntranslateType tp = do\n s <- get\n case M.lookup (ptrToIntPtr tp) (typeMap s) of\n Just t -> return t\n Nothing -> translateType' tp\n\n{-\ncTypeTag :: TypePtr -> IO TypeTag\ncTypeSize :: TypePtr -> IO Int\ncTypeIsVarArg :: TypePtr -> IO Bool\ncTypeIsPacked :: TypePtr -> IO Bool\ncTypeList :: TypePtr -> IO [TypePtr]\ncTypeInner :: TypePtr -> IO TypePtr\ncTypeName :: TypePtr -> IO String\ncTypeAddrSpace :: TypePtr -> IO Int\n-}\ntranslateType' :: TypePtr -> KnotMonad Type\ntranslateType' tp = do\n s <- get\n tag <- liftIO $ cTypeTag tp\n t <- case tag of\n TYPE_VOID -> return TypeVoid\n TYPE_FLOAT -> return TypeFloat\n TYPE_DOUBLE -> return TypeDouble\n TYPE_X86_FP80 -> return TypeX86FP80\n TYPE_FP128 -> return TypeFP128\n TYPE_PPC_FP128 -> return TypePPCFP128\n TYPE_LABEL -> return TypeLabel\n TYPE_METADATA -> return TypeMetadata\n TYPE_X86_MMX -> return TypeX86MMX\n TYPE_OPAQUE -> return TypeOpaque\n TYPE_INTEGER -> do\n sz <- liftIO $ cTypeSize tp\n return $! TypeInteger sz\n TYPE_FUNCTION -> do\n isVa <- liftIO $ cTypeIsVarArg tp\n rtp <- liftIO $ cTypeInner tp\n argTypePtrs <- liftIO $ cTypeList tp\n\n rType <- translateType rtp\n argTypes <- mapM translateType argTypePtrs\n\n return $! TypeFunction rType argTypes isVa\n TYPE_STRUCT -> do\n isPacked <- liftIO $ cTypeIsPacked tp\n ptrs <- liftIO $ cTypeList tp\n\n types <- mapM translateType ptrs\n\n return $! TypeStruct types isPacked\n TYPE_ARRAY -> do\n sz <- liftIO $ cTypeSize tp\n itp <- liftIO $ cTypeInner tp\n innerType <- translateType itp\n\n return $! TypeArray sz innerType\n TYPE_POINTER -> do\n itp <- liftIO $ cTypeInner tp\n addrSpc <- liftIO $ cTypeAddrSpace tp\n innerType <- translateType itp\n\n return $! TypePointer innerType addrSpc\n TYPE_VECTOR -> do\n sz <- liftIO $ cTypeSize tp\n itp <- liftIO $ cTypeInner tp\n innerType <- translateType itp\n\n return $! TypeVector sz innerType\n TYPE_NAMED -> do\n name <- liftIO $ cTypeName tp\n itp <- liftIO $ cTypeInner tp\n innerType <- translateType itp\n\n return $! TypeNamed name innerType\n put s { typeMap = M.insert (ptrToIntPtr tp) t (typeMap s) }\n return t\n\nrecordValue :: ValuePtr -> Value -> KnotMonad ()\nrecordValue vp v = do\n s <- get\n let key = ptrToIntPtr vp\n oldMap = valueMap s\n put s { valueMap = M.insert key v oldMap }\n\ntranslateAlias :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateAlias finalState vp = do\n name <- liftIO $ cValueName vp\n typePtr <- liftIO $ cValueType vp\n dataPtr <- liftIO $ cValueData vp\n let dataPtr' = castPtr dataPtr\n\n vis <- liftIO $ cGlobalVisibility dataPtr'\n link <- liftIO $ cGlobalLinkage dataPtr'\n aliasee <- liftIO $ cGlobalAliasee dataPtr'\n\n ta <- translateConstOrRef finalState aliasee\n tt <- translateType typePtr\n\n uid <- nextId\n\n let ga = GlobalAlias { globalAliasLinkage = link\n , globalAliasVisibility = vis\n , globalAliasValue = ta\n }\n v = Value { valueType = tt\n , valueName = name\n , valueMetadata = Nothing\n , valueContent = ga\n , valueUniqueId = uid\n }\n\n recordValue vp v\n\n return v\n\ntranslateGlobalVariable :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateGlobalVariable finalState vp = do\n name <- liftIO $ cValueName vp\n typePtr <- liftIO $ cValueType vp\n dataPtr <- liftIO $ cValueData vp\n tt <- translateType typePtr\n\n uid <- nextId\n\n let dataPtr' = castPtr dataPtr\n basicVal = Value { valueName = name\n , valueType = tt\n , valueMetadata = Nothing\n , valueContent = ExternalValue\n , valueUniqueId = uid\n }\n isExtern <- liftIO $ cGlobalIsExternal dataPtr'\n\n case isExtern of\n True -> do\n recordValue vp basicVal\n return basicVal\n False -> do\n align <- liftIO $ cGlobalAlignment dataPtr'\n vis <- liftIO $ cGlobalVisibility dataPtr'\n link <- liftIO $ cGlobalLinkage dataPtr'\n section <- liftIO $ cGlobalSection dataPtr'\n isThreadLocal <- liftIO $ cGlobalIsThreadLocal dataPtr'\n initializer <- liftIO $ cGlobalInitializer dataPtr'\n isConst <- liftIO $ cGlobalIsConstant dataPtr'\n\n ti <- case initializer == nullPtr of\n True -> return Nothing\n False -> do\n tv <- translateConstOrRef finalState initializer\n return $ Just tv\n\n let gv = GlobalDeclaration { globalVariableLinkage = link\n , globalVariableVisibility = vis\n , globalVariableInitializer = ti\n , globalVariableAlignment = align\n , globalVariableSection = section\n , globalVariableIsThreadLocal = isThreadLocal\n , globalVariableIsConstant = isConst\n }\n v = basicVal { valueContent = gv }\n recordValue vp v\n return v\n\ntranslateFunction :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateFunction finalState vp = do\n name <- liftIO $ cValueName vp\n typePtr <- liftIO $ cValueType vp\n dataPtr <- liftIO $ cValueData vp\n tt <- translateType typePtr\n\n uid <- nextId\n\n let dataPtr' = castPtr dataPtr\n basicVal = Value { valueName = name\n , valueType = tt\n , valueMetadata = Nothing\n , valueContent = ExternalFunction [] -- FIXME: there are attributes here\n , valueUniqueId = uid\n }\n isExtern <- liftIO $ cFunctionIsExternal dataPtr'\n\n case isExtern of\n True -> do\n recordValue vp basicVal\n return basicVal\n False -> do\n align <- liftIO $ cFunctionAlignment dataPtr'\n vis <- liftIO $ cFunctionVisibility dataPtr'\n link <- liftIO $ cFunctionLinkage dataPtr'\n section <- liftIO $ cFunctionSection dataPtr'\n cc <- liftIO $ cFunctionCallingConvention dataPtr'\n gcname <- liftIO $ cFunctionGCName dataPtr'\n args <- liftIO $ cFunctionArguments dataPtr'\n blocks <- liftIO $ cFunctionBlocks dataPtr'\n isVarArg <- liftIO $ cFunctionIsVarArg dataPtr'\n\n args' <- mapM (translateValue finalState) args\n blocks' <- mapM (translateValue finalState) blocks\n\n let f = Function { functionParameters = args'\n , functionBody = blocks'\n , functionLinkage = link\n , functionVisibility = vis\n , functionCC = cc\n , functionRetAttrs = [] -- FIXME\n , functionAttrs = [] -- FIXME\n , functionSection = section\n , functionAlign = align\n , functionGCName = gcname\n , functionIsVararg = isVarArg\n }\n v = basicVal { valueContent = f }\n recordValue vp v\n return v\n\n-- | This wrapper checks to see if we have translated the value yet\n-- (but not against the final state - only the internal running\n-- state). This way we really translate it if it hasn't been seen\n-- yet, but get the translated value if we have touched it before.\ntranslateValue :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateValue finalState vp = do\n s <- get\n case M.lookup (ptrToIntPtr vp) (valueMap s) of\n Nothing -> translateValue' finalState vp\n Just v -> return v\n\n-- | Only the top-level translators should call this: Globals and BasicBlocks\n-- (Or translateConstOrRef when translating constants)\ntranslateValue' :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateValue' finalState vp = do\n tag <- liftIO $ cValueTag vp\n name <- liftIO $ cValueName vp\n typePtr <- liftIO $ cValueType vp\n dataPtr <- liftIO $ cValueData vp\n\n tt <- translateType typePtr\n\n content <- case tag of\n ValArgument -> translateArgument finalState (castPtr dataPtr)\n ValBasicblock -> translateBasicBlock finalState (castPtr dataPtr)\n ValInlineasm -> translateInlineAsm finalState (castPtr dataPtr)\n ValBlockaddress -> translateBlockAddress finalState (castPtr dataPtr)\n ValConstantaggregatezero -> return ConstantAggregateZero\n ValConstantpointernull -> return ConstantPointerNull\n ValUndefvalue -> return UndefValue\n ValConstantarray -> translateConstantAggregate finalState ConstantArray (castPtr dataPtr)\n ValConstantstruct -> translateConstantAggregate finalState ConstantStruct (castPtr dataPtr)\n ValConstantvector -> translateConstantAggregate finalState ConstantVector (castPtr dataPtr)\n ValConstantfp -> translateConstantFP finalState (castPtr dataPtr)\n ValConstantint -> translateConstantInt finalState (castPtr dataPtr)\n ValRetinst -> translateRetInst finalState (castPtr dataPtr)\n ValBranchinst -> translateBranchInst finalState (castPtr dataPtr)\n ValSwitchinst -> translateSwitchInst finalState (castPtr dataPtr)\n ValIndirectbrinst -> translateIndirectBrInst finalState (castPtr dataPtr)\n ValInvokeinst -> translateInvokeInst finalState (castPtr dataPtr)\n ValUnwindinst -> return UnwindInst\n ValUnreachableinst -> return UnreachableInst\n ValAddinst -> translateFlaggedBinaryOp finalState AddInst (castPtr dataPtr)\n ValFaddinst -> translateFlaggedBinaryOp finalState AddInst (castPtr dataPtr)\n ValSubinst -> translateFlaggedBinaryOp finalState SubInst (castPtr dataPtr)\n ValFsubinst -> translateFlaggedBinaryOp finalState SubInst (castPtr dataPtr)\n ValMulinst -> translateFlaggedBinaryOp finalState MulInst (castPtr dataPtr)\n ValFmulinst -> translateFlaggedBinaryOp finalState MulInst (castPtr dataPtr)\n ValUdivinst -> translateBinaryOp finalState DivInst (castPtr dataPtr)\n ValSdivinst -> translateBinaryOp finalState DivInst (castPtr dataPtr)\n ValFdivinst -> translateBinaryOp finalState DivInst (castPtr dataPtr)\n ValUreminst -> translateBinaryOp finalState RemInst (castPtr dataPtr)\n ValSreminst -> translateBinaryOp finalState RemInst (castPtr dataPtr)\n ValFreminst -> translateBinaryOp finalState RemInst (castPtr dataPtr)\n ValShlinst -> translateBinaryOp finalState ShlInst (castPtr dataPtr)\n ValLshrinst -> translateBinaryOp finalState LshrInst (castPtr dataPtr)\n ValAshrinst -> translateBinaryOp finalState AshrInst (castPtr dataPtr)\n ValAndinst -> translateBinaryOp finalState AndInst (castPtr dataPtr)\n ValOrinst -> translateBinaryOp finalState OrInst (castPtr dataPtr)\n ValXorinst -> translateBinaryOp finalState XorInst (castPtr dataPtr)\n ValAllocainst -> translateAllocaInst finalState (castPtr dataPtr)\n ValLoadinst -> translateLoadInst finalState (castPtr dataPtr)\n ValStoreinst -> translateStoreInst finalState (castPtr dataPtr)\n ValGetelementptrinst -> translateGEPInst finalState (castPtr dataPtr)\n ValTruncinst -> translateCastInst finalState TruncInst (castPtr dataPtr)\n ValZextinst -> translateCastInst finalState ZExtInst (castPtr dataPtr)\n ValSextinst -> translateCastInst finalState SExtInst (castPtr dataPtr)\n ValFptruncinst -> translateCastInst finalState FPTruncInst (castPtr dataPtr)\n ValFpextinst -> translateCastInst finalState FPExtInst (castPtr dataPtr)\n ValFptouiinst -> translateCastInst finalState FPToUIInst (castPtr dataPtr)\n ValFptosiinst -> translateCastInst finalState FPToSIInst (castPtr dataPtr)\n ValUitofpinst -> translateCastInst finalState UIToFPInst (castPtr dataPtr)\n ValSitofpinst -> translateCastInst finalState SIToFPInst (castPtr dataPtr)\n ValPtrtointinst -> translateCastInst finalState PtrToIntInst (castPtr dataPtr)\n ValInttoptrinst -> translateCastInst finalState IntToPtrInst (castPtr dataPtr)\n ValBitcastinst -> translateCastInst finalState BitcastInst (castPtr dataPtr)\n ValIcmpinst -> translateCmpInst finalState ICmpInst (castPtr dataPtr)\n ValFcmpinst -> translateCmpInst finalState FCmpInst (castPtr dataPtr)\n ValPhinode -> translatePhiNode finalState (castPtr dataPtr)\n ValCallinst -> translateCallInst finalState (castPtr dataPtr)\n ValSelectinst -> translateSelectInst finalState (castPtr dataPtr)\n ValVaarginst -> translateVarArgInst finalState (castPtr dataPtr)\n ValExtractelementinst -> translateExtractElementInst finalState (castPtr dataPtr)\n ValInsertelementinst -> translateInsertElementInst finalState (castPtr dataPtr)\n ValShufflevectorinst -> translateShuffleVectorInst finalState (castPtr dataPtr)\n ValExtractvalueinst -> translateExtractValueInst finalState (castPtr dataPtr)\n ValInsertvalueinst -> translateInsertValueInst finalState (castPtr dataPtr)\n ValFunction -> throw InvalidFunctionInTranslateValue\n ValAlias -> throw InvalidAliasInTranslateValue\n ValGlobalvariable -> throw InvalidGlobalVarInTranslateValue\n ValConstantexpr -> translateConstantExpr finalState (castPtr dataPtr)\n\n uid <- nextId\n\n let tv = Value { valueType = tt\n , valueName = name\n , valueMetadata = Nothing\n , valueContent = content\n , valueUniqueId = uid\n }\n\n recordValue vp tv\n\n return tv\n\nisConstant :: ValueTag -> Bool\nisConstant vt = case vt of\n ValConstantaggregatezero -> True\n ValConstantarray -> True\n ValConstantfp -> True\n ValConstantint -> True\n ValConstantpointernull -> True\n ValConstantstruct -> True\n ValConstantvector -> True\n ValUndefvalue -> True\n ValConstantexpr -> True\n ValBlockaddress -> True\n _ -> False\n\ntranslateConstOrRef :: KnotState -> ValuePtr -> KnotMonad Value\ntranslateConstOrRef finalState vp = do\n tag <- liftIO $ cValueTag vp\n if isConstant tag\n then translateValue finalState vp\n else case M.lookup (ptrToIntPtr vp) (valueMap finalState) of\n Just v -> return v\n Nothing -> throw KnotTyingFailure\n\n\ntranslateArgument :: KnotState -> ArgInfoPtr -> KnotMonad ValueT\ntranslateArgument _ dataPtr = do\n hasSRet <- liftIO $ cArgInfoHasSRet dataPtr\n hasByVal <- liftIO $ cArgInfoHasByVal dataPtr\n hasNest <- liftIO $ cArgInfoHasNest dataPtr\n hasNoAlias <- liftIO $ cArgInfoHasNoAlias dataPtr\n hasNoCapture <- liftIO $ cArgInfoHasNoCapture dataPtr\n let attrOrNothing b att = if b then Just att else Nothing\n atts = [ attrOrNothing hasSRet PASRet\n , attrOrNothing hasByVal PAByVal\n , attrOrNothing hasNest PANest\n , attrOrNothing hasNoAlias PANoAlias\n , attrOrNothing hasNoCapture PANoCapture\n ]\n return $! Argument (catMaybes atts)\n\ntranslateBasicBlock :: KnotState -> BasicBlockPtr -> KnotMonad ValueT\ntranslateBasicBlock finalState dataPtr = do\n insts <- liftIO $ cBasicBlockInstructions dataPtr\n tinsts <- mapM (translateValue finalState) insts\n return $! BasicBlock tinsts\n\ntranslateInlineAsm :: KnotState -> InlineAsmInfoPtr -> KnotMonad ValueT\ntranslateInlineAsm _ dataPtr = do\n asmString <- liftIO $ cInlineAsmString dataPtr\n constraints <- liftIO $ cInlineAsmConstraints dataPtr\n return $! InlineAsm asmString constraints\n\ntranslateBlockAddress :: KnotState -> BlockAddrInfoPtr -> KnotMonad ValueT\ntranslateBlockAddress finalState dataPtr = do\n fval <- liftIO $ cBlockAddrFunc dataPtr\n bval <- liftIO $ cBlockAddrBlock dataPtr\n f' <- translateConstOrRef finalState fval\n b' <- translateConstOrRef finalState bval\n return $! BlockAddress f' b'\n\ntranslateConstantAggregate :: KnotState -> ([Value] -> ValueT) -> AggregateInfoPtr -> KnotMonad ValueT\ntranslateConstantAggregate finalState constructor dataPtr = do\n vals <- liftIO $ cAggregateValues dataPtr\n vals' <- mapM (translateConstOrRef finalState) vals\n return $! constructor vals'\n\ntranslateConstantFP :: KnotState -> FPInfoPtr -> KnotMonad ValueT\ntranslateConstantFP _ dataPtr = do\n fpval <- liftIO $ cFPVal dataPtr\n return $! ConstantFP fpval\n\ntranslateConstantInt :: KnotState -> IntInfoPtr -> KnotMonad ValueT\ntranslateConstantInt _ dataPtr = do\n intval <- liftIO $ cIntVal dataPtr\n return $! ConstantInt intval\n\ntranslateRetInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateRetInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n case opPtrs of\n [] -> return $! RetInst Nothing\n [val] -> do\n val' <- translateConstOrRef finalState val\n return $! RetInst (Just val')\n _ -> throw TooManyReturnValues\n\ntranslateBranchInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateBranchInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n case opPtrs of\n [dst] -> do\n dst' <- translateConstOrRef finalState dst\n return $! UnconditionalBranchInst dst'\n [val, t, f] -> do\n val' <- translateConstOrRef finalState val\n tbranch <- translateConstOrRef finalState t\n fbranch <- translateConstOrRef finalState f\n return $! BranchInst { branchCondition = val'\n , branchTrueTarget = tbranch\n , branchFalseTarget = fbranch\n }\n _ -> throw InvalidBranchInst\n\ntranslateSwitchInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateSwitchInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n case opPtrs of\n (swVal:defTarget:cases) -> do\n val' <- translateConstOrRef finalState swVal\n def' <- translateConstOrRef finalState defTarget\n -- Process the rest of the list in pairs since that is how LLVM\n -- stores them, but transform it into a nice list of actual\n -- pairs\n let tpairs acc (v1:dest:rest) = do\n v1' <- translateConstOrRef finalState v1\n dest' <- translateConstOrRef finalState dest\n tpairs ((v1', dest'):acc) rest\n tpairs acc [] = return $ reverse acc\n tpairs _ _ = throw InvalidSwitchLayout\n cases' <- tpairs [] cases\n return $! SwitchInst { switchValue = val'\n , switchDefaultTarget = def'\n , switchCases = cases'\n }\n _ -> throw InvalidSwitchLayout\n\ntranslateIndirectBrInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateIndirectBrInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n case opPtrs of\n (addr:targets) -> do\n addr' <- translateConstOrRef finalState addr\n targets' <- mapM (translateConstOrRef finalState) targets\n return $! IndirectBranchInst { indirectBranchAddress = addr'\n , indirectBranchTargets = targets'\n }\n _ -> throw InvalidIndirectBranchOperands\n\ntranslateInvokeInst :: KnotState -> CallInfoPtr -> KnotMonad ValueT\ntranslateInvokeInst finalState dataPtr = do\n func <- liftIO $ cCallValue dataPtr\n args <- liftIO $ cCallArguments dataPtr\n cc <- liftIO $ cCallConvention dataPtr\n hasSRet <- liftIO $ cCallHasSRet dataPtr\n ndest <- liftIO $ cCallNormalDest dataPtr\n udest <- liftIO $ cCallUnwindDest dataPtr\n\n f' <- translateConstOrRef finalState func\n args' <- mapM (translateConstOrRef finalState) args\n n' <- translateConstOrRef finalState ndest\n u' <- translateConstOrRef finalState udest\n\n return $! InvokeInst { invokeConvention = cc\n , invokeParamAttrs = [] -- FIXME\n , invokeFunction = f'\n , invokeArguments = zip args' (repeat []) -- FIXME\n , invokeAttrs = [] -- FIXME\n , invokeNormalLabel = n'\n , invokeUnwindLabel = u'\n , invokeHasSRet = hasSRet\n }\n\ntranslateFlaggedBinaryOp :: KnotState -> (ArithFlags -> Value -> Value -> ValueT) ->\n InstInfoPtr -> KnotMonad ValueT\ntranslateFlaggedBinaryOp finalState constructor dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n flags <- liftIO $ cInstructionArithFlags dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [lhs, rhs] -> return $! constructor flags lhs rhs\n _ -> throw $ InvalidBinaryOp (length ops)\n\ntranslateBinaryOp :: KnotState -> (Value -> Value -> ValueT) ->\n InstInfoPtr -> KnotMonad ValueT\ntranslateBinaryOp finalState constructor dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [lhs, rhs] -> return $! constructor lhs rhs\n _ -> throw $ InvalidBinaryOp (length ops)\n\ntranslateAllocaInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateAllocaInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n align <- liftIO $ cInstructionAlign dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [val] -> return $! AllocaInst val align\n _ -> throw $ InvalidUnaryOp (length ops)\n\n\ntranslateLoadInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateLoadInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n align <- liftIO $ cInstructionAlign dataPtr\n vol <- liftIO $ cInstructionIsVolatile dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [addr] -> return $! LoadInst vol addr align\n _ -> throw $ InvalidUnaryOp (length ops)\n\ntranslateStoreInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateStoreInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n addrSpace <- liftIO $ cInstructionAddrSpace dataPtr\n align <- liftIO $ cInstructionAlign dataPtr\n isVol <- liftIO $ cInstructionIsVolatile dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [val, ptr] -> return $! StoreInst isVol val ptr align\n _ -> throw $ InvalidBinaryOp (length ops)\n\ntranslateGEPInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateGEPInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n inBounds <- liftIO $ cInstructionInBounds dataPtr\n addrSpace <- liftIO $ cInstructionAddrSpace dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n (val:indices) -> return $! GetElementPtrInst { getElementPtrInBounds = inBounds\n , getElementPtrValue = val\n , getElementPtrIndices = indices\n }\n _ -> throw $ InvalidGEPInst (length ops)\n\ntranslateCastInst :: KnotState -> (Value -> ValueT) -> InstInfoPtr -> KnotMonad ValueT\ntranslateCastInst finalState constructor dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [v] -> return $! constructor v\n _ -> throw $ InvalidUnaryOp (length ops)\n\ntranslateCmpInst :: KnotState -> (CmpPredicate -> Value -> Value -> ValueT) ->\n InstInfoPtr -> KnotMonad ValueT\ntranslateCmpInst finalState constructor dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n predicate <- liftIO $ cInstructionCmpPred dataPtr\n\n ops <- mapM (translateConstOrRef finalState) opPtrs\n\n case ops of\n [op1, op2] -> return $! constructor predicate op1 op2\n _ -> throw $ InvalidBinaryOp (length ops)\n\ntranslatePhiNode :: KnotState -> PHIInfoPtr -> KnotMonad ValueT\ntranslatePhiNode finalState dataPtr = do\n vptrs <- liftIO $ cPHIValues dataPtr\n bptrs <- liftIO $ cPHIBlocks dataPtr\n\n vals <- mapM (translateConstOrRef finalState) vptrs\n blocks <- mapM (translateConstOrRef finalState) bptrs\n\n return $! PhiNode $ zip vals blocks\n\ntranslateCallInst :: KnotState -> CallInfoPtr -> KnotMonad ValueT\ntranslateCallInst finalState dataPtr = do\n vptr <- liftIO $ cCallValue dataPtr\n aptrs <- liftIO $ cCallArguments dataPtr\n cc <- liftIO $ cCallConvention dataPtr\n hasSRet <- liftIO $ cCallHasSRet dataPtr\n isTail <- liftIO $ cCallIsTail dataPtr\n\n val <- translateConstOrRef finalState vptr\n args <- mapM (translateConstOrRef finalState) aptrs\n\n return $! CallInst { callIsTail = isTail\n , callConvention = cc\n , callParamAttrs = [] -- FIXME\n , callFunction = val\n , callArguments = zip args (repeat []) -- FIXME\n , callAttrs = [] -- FIXME\n , callHasSRet = hasSRet\n }\n\ntranslateSelectInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateSelectInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [cond, trueval, falseval] -> do\n return $! SelectInst cond trueval falseval\n _ -> throw $ InvalidSelectArgs (length ops)\n\ntranslateVarArgInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateVarArgInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [op] -> return $! VaArgInst op\n _ -> throw $ InvalidUnaryOp (length ops)\n\ntranslateExtractElementInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateExtractElementInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [vec, idx] -> do\n return $! ExtractElementInst { extractElementVector = vec\n , extractElementIndex = idx\n }\n _ -> throw $ InvalidExtractElementInst (length ops)\n\ntranslateInsertElementInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateInsertElementInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [vec, val, idx] -> do\n return $! InsertElementInst { insertElementVector = vec\n , insertElementValue = val\n , insertElementIndex = idx\n }\n _ -> throw $ InvalidInsertElementInst (length ops)\n\ntranslateShuffleVectorInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateShuffleVectorInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [v1, v2, vecMask] -> do\n return $! ShuffleVectorInst { shuffleVectorV1 = v1\n , shuffleVectorV2 = v2\n , shuffleVectorMask = vecMask\n }\n _ -> throw $ InvalidShuffleVectorInst (length ops)\n\ntranslateExtractValueInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateExtractValueInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n indices <- liftIO $ cInstructionIndices dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [agg] -> return $! ExtractValueInst { extractValueAggregate = agg\n , extractValueIndices = indices\n }\n _ -> throw $ InvalidExtractValueInst (length ops)\n\ntranslateInsertValueInst :: KnotState -> InstInfoPtr -> KnotMonad ValueT\ntranslateInsertValueInst finalState dataPtr = do\n opPtrs <- liftIO $ cInstructionOperands dataPtr\n indices <- liftIO $ cInstructionIndices dataPtr\n ops <- mapM (translateConstOrRef finalState) opPtrs\n case ops of\n [agg, val] ->\n return $! InsertValueInst { insertValueAggregate = agg\n , insertValueValue = val\n , insertValueIndices = indices\n }\n _ -> throw $ InvalidInsertValueInst (length ops)\n\ntranslateConstantExpr :: KnotState -> ConstExprPtr -> KnotMonad ValueT\ntranslateConstantExpr finalState dataPtr = do\n ii <- liftIO $ cConstExprInstInfo dataPtr\n tag <- liftIO $ cConstExprTag dataPtr\n vt <- case tag of\n ValAddinst -> translateFlaggedBinaryOp finalState AddInst ii\n ValFaddinst -> translateFlaggedBinaryOp finalState AddInst ii\n ValSubinst -> translateFlaggedBinaryOp finalState SubInst ii\n ValFsubinst -> translateFlaggedBinaryOp finalState SubInst ii\n ValMulinst -> translateFlaggedBinaryOp finalState MulInst ii\n ValFmulinst -> translateFlaggedBinaryOp finalState MulInst ii\n ValUdivinst -> translateBinaryOp finalState DivInst ii\n ValSdivinst -> translateBinaryOp finalState DivInst ii\n ValFdivinst -> translateBinaryOp finalState DivInst ii\n ValUreminst -> translateBinaryOp finalState RemInst ii\n ValSreminst -> translateBinaryOp finalState RemInst ii\n ValFreminst -> translateBinaryOp finalState RemInst ii\n ValShlinst -> translateBinaryOp finalState ShlInst ii\n ValLshrinst -> translateBinaryOp finalState LshrInst ii\n ValAshrinst -> translateBinaryOp finalState AshrInst ii\n ValAndinst -> translateBinaryOp finalState AndInst ii\n ValOrinst -> translateBinaryOp finalState OrInst ii\n ValXorinst -> translateBinaryOp finalState XorInst ii\n ValGetelementptrinst -> translateGEPInst finalState ii\n ValTruncinst -> translateCastInst finalState TruncInst ii\n ValZextinst -> translateCastInst finalState ZExtInst ii\n ValSextinst -> translateCastInst finalState SExtInst ii\n ValFptruncinst -> translateCastInst finalState FPTruncInst ii\n ValFpextinst -> translateCastInst finalState FPExtInst ii\n ValFptouiinst -> translateCastInst finalState FPToUIInst ii\n ValFptosiinst -> translateCastInst finalState FPToSIInst ii\n ValUitofpinst -> translateCastInst finalState UIToFPInst ii\n ValSitofpinst -> translateCastInst finalState SIToFPInst ii\n ValPtrtointinst -> translateCastInst finalState PtrToIntInst ii\n ValInttoptrinst -> translateCastInst finalState IntToPtrInst ii\n ValBitcastinst -> translateCastInst finalState BitcastInst ii\n ValIcmpinst -> translateCmpInst finalState ICmpInst ii\n ValFcmpinst -> translateCmpInst finalState FCmpInst ii\n ValSelectinst -> translateSelectInst finalState ii\n ValVaarginst -> translateVarArgInst finalState ii\n ValExtractelementinst -> translateExtractElementInst finalState ii\n ValInsertelementinst -> translateInsertElementInst finalState ii\n ValShufflevectorinst -> translateShuffleVectorInst finalState ii\n ValExtractvalueinst -> translateExtractValueInst finalState ii\n ValInsertvalueinst -> translateInsertValueInst finalState ii\n return $! ConstantValue vt","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"e58e61332c148c618428d4c995f81fe6c88f1a87","subject":"gstreamer: M.S.G.Core.ElementFactory: Control.Monad.>=> not available before ghc 6.8","message":"gstreamer: M.S.G.Core.ElementFactory: Control.Monad.>=> not available before ghc 6.8\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/ElementFactory.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/ElementFactory.chs","new_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gstreamer -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GStreamer, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GStreamer documentation.\n-- \n-- |\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\n-- \n-- A factory for creating 'Element's.\nmodule Media.Streaming.GStreamer.Core.ElementFactory (\n\n-- * Detail\n\n -- | 'ElementFactory' is used to create instances of 'Element's.\n -- \n -- Use 'elementFactoryFind' and 'elementFactoryCreate' to create\n -- element instances, or use 'elementFactoryMake' as a convenient\n -- shortcut.\n\n-- * Types \n ElementFactory,\n ElementFactoryClass,\n castToElementFactory,\n toElementFactory,\n \n-- * ElementFactory Operations\n elementFactoryFind,\n elementFactoryGetElementType,\n elementFactoryGetLongname,\n elementFactoryGetKlass,\n elementFactoryGetDescription,\n elementFactoryGetAuthor,\n elementFactoryGetNumPadTemplates,\n elementFactoryGetURIType,\n elementFactoryGetURIProtocols,\n elementFactoryHasInterface,\n elementFactoryCreate,\n elementFactoryMake,\n elementFactoryCanSinkCaps,\n elementFactoryCanSrcCaps,\n elementFactoryGetPadTemplates\n \n ) where\n\nimport Control.Monad ( liftM )\nimport Data.Maybe ( fromMaybe )\nimport System.Glib.FFI\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString\n , peekUTFStringArray0 )\nimport System.Glib.GType ( GType )\nimport System.Glib.GList ( readGList )\n{# import Media.Streaming.GStreamer.Core.Types #}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\n-- | Search for an element factory with the given name.\nelementFactoryFind :: String -- ^ @name@ - the name of the desired factory\n -> IO (Maybe ElementFactory) -- ^ the factory if found, otherwise 'Nothing'\nelementFactoryFind name =\n withUTFString name {# call element_factory_find #} >>= maybePeek takeObject\n\n-- | Get the 'GType' for elements managed by the given factory. The type\n-- can only be retrieved if the element factory is loaded, which can\n-- be assured with\n-- 'Media.Streaming.GStreamer.Core.PluginFeature.pluginFeatureLoad'.\nelementFactoryGetElementType :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO (Maybe GType) -- ^ the type of elements managed\n -- by the factory, or 'Nothing' if\n -- the factory is not loaded\nelementFactoryGetElementType factory =\n do gtype <- {# call element_factory_get_element_type #} (toElementFactory factory)\n if gtype == 0\n then return $ Just $ fromIntegral gtype\n else return Nothing\n\n-- | Get the long name for the given factory.\nelementFactoryGetLongname :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO String -- ^ the factory's long name\nelementFactoryGetLongname factory =\n {# call element_factory_get_longname #} (toElementFactory factory) >>=\n peekUTFString\n\n-- | Get the class for the given factory.\nelementFactoryGetKlass :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO String -- ^ the factory's class\nelementFactoryGetKlass factory =\n {# call element_factory_get_klass #} (toElementFactory factory) >>=\n peekUTFString\n\n-- | Get the description for the given factory.\nelementFactoryGetDescription :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO String -- ^ the factory's description\nelementFactoryGetDescription factory =\n {# call element_factory_get_description #} (toElementFactory factory) >>=\n peekUTFString\n\n-- | Get the author of the given factory.\nelementFactoryGetAuthor :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO String -- ^ the factory's author\nelementFactoryGetAuthor factory =\n {# call element_factory_get_author #} (toElementFactory factory) >>=\n peekUTFString\n\n-- | Get the number of 'PadTemplate's provided by the given factory.\nelementFactoryGetNumPadTemplates :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO Word -- ^ the number of 'PadTemplate's\nelementFactoryGetNumPadTemplates factory =\n liftM fromIntegral $\n {# call element_factory_get_num_pad_templates #} $ toElementFactory factory\n\n-- | Get the type of URIs supported by the given factory.\nelementFactoryGetURIType :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO Int -- ^ the type of URIs supported by the factory\nelementFactoryGetURIType factory =\n liftM fromIntegral $\n {# call element_factory_get_uri_type #} $ toElementFactory factory\n\n-- | Get the list of protocols supported by the given factory.\nelementFactoryGetURIProtocols :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO [String] -- ^ the supported protocols\nelementFactoryGetURIProtocols factory =\n {# call element_factory_get_uri_protocols #} (toElementFactory factory) >>=\n liftM (fromMaybe []) . maybePeek peekUTFStringArray0\n\n-- | Check if the given factory implements the interface with the given name.\nelementFactoryHasInterface :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> String -- ^ @name@ - the interface name\n -> IO Bool -- ^ true if the interface is implemented\nelementFactoryHasInterface factory name =\n liftM toBool .\n withUTFString name .\n {# call element_factory_has_interface #} .\n toElementFactory $\n factory\n\n-- | Create a new element of the type supplied by the given\n-- factory. It will be given the name supplied.\nelementFactoryCreate :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> String -- ^ @name@ - the new element's name\n -> IO (Maybe Element) -- ^ the new element if it could be created,\n -- otherwise 'Nothing'\nelementFactoryCreate factory name =\n withUTFString name $ \\cName ->\n {# call element_factory_create #} (toElementFactory factory) cName >>=\n maybePeek takeObject\n\n-- | Create a new element of the type supplied by the named\n-- factory.\nelementFactoryMake :: String -- ^ @factoryName@ - the name of an element factory\n -> Maybe String -- ^ @name@ - the new element's name, or\n -- 'Nothing' generate a unique name\n -> IO (Maybe Element) -- ^ the new element if it could be created,\n -- otherwise 'Nothing'\nelementFactoryMake factoryName name =\n withUTFString factoryName $ \\cFactoryName ->\n maybeWith withUTFString name $ \\cName ->\n {# call element_factory_make #} cFactoryName cName >>=\n maybePeek takeObject\n\n-- | Check if the given factory can sink the given capabilities.\nelementFactoryCanSinkCaps :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> Caps -- ^ @caps@ - the capabilities to check for\n -> IO Bool -- ^ 'True' if @factory@ can sink the given capabilities\nelementFactoryCanSinkCaps factory caps =\n liftM toBool $ {# call element_factory_can_sink_caps #} (toElementFactory factory) caps\n\n-- | Check if the given factory can source the given capabilities.\nelementFactoryCanSrcCaps :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> Caps -- ^ @caps@ - the capabilities to check for\n -> IO Bool -- ^ 'True' if @factory@ can source the given capabilities\nelementFactoryCanSrcCaps factory caps =\n liftM toBool $ {# call element_factory_can_src_caps #} (toElementFactory factory) caps\n\n-- | Get the pad templates provided by the given factory.\nelementFactoryGetPadTemplates :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO [PadTemplate] -- ^ the provided pad templates\nelementFactoryGetPadTemplates =\n {# call element_factory_get_static_pad_templates #} . toElementFactory >=>\n readGList >=> mapM staticPadTemplateGet\n where infixr 8 >=>\n a >=> b = \\x -> a x >>= b\n","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gstreamer -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GStreamer, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GStreamer documentation.\n-- \n-- |\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\n-- \n-- A factory for creating 'Element's.\nmodule Media.Streaming.GStreamer.Core.ElementFactory (\n\n-- * Detail\n\n -- | 'ElementFactory' is used to create instances of 'Element's.\n -- \n -- Use 'elementFactoryFind' and 'elementFactoryCreate' to create\n -- element instances, or use 'elementFactoryMake' as a convenient\n -- shortcut.\n\n-- * Types \n ElementFactory,\n ElementFactoryClass,\n castToElementFactory,\n toElementFactory,\n \n-- * ElementFactory Operations\n elementFactoryFind,\n elementFactoryGetElementType,\n elementFactoryGetLongname,\n elementFactoryGetKlass,\n elementFactoryGetDescription,\n elementFactoryGetAuthor,\n elementFactoryGetNumPadTemplates,\n elementFactoryGetURIType,\n elementFactoryGetURIProtocols,\n elementFactoryHasInterface,\n elementFactoryCreate,\n elementFactoryMake,\n elementFactoryCanSinkCaps,\n elementFactoryCanSrcCaps,\n elementFactoryGetPadTemplates\n \n ) where\n\nimport Control.Monad ( liftM\n , (>=>) )\nimport Data.Maybe ( fromMaybe )\nimport System.Glib.FFI\nimport System.Glib.UTFString ( withUTFString\n , peekUTFString\n , peekUTFStringArray0 )\nimport System.Glib.GType ( GType )\nimport System.Glib.GList ( readGList )\n{# import Media.Streaming.GStreamer.Core.Types #}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\n-- | Search for an element factory with the given name.\nelementFactoryFind :: String -- ^ @name@ - the name of the desired factory\n -> IO (Maybe ElementFactory) -- ^ the factory if found, otherwise 'Nothing'\nelementFactoryFind name =\n withUTFString name {# call element_factory_find #} >>= maybePeek takeObject\n\n-- | Get the 'GType' for elements managed by the given factory. The type\n-- can only be retrieved if the element factory is loaded, which can\n-- be assured with\n-- 'Media.Streaming.GStreamer.Core.PluginFeature.pluginFeatureLoad'.\nelementFactoryGetElementType :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO (Maybe GType) -- ^ the type of elements managed\n -- by the factory, or 'Nothing' if\n -- the factory is not loaded\nelementFactoryGetElementType factory =\n do gtype <- {# call element_factory_get_element_type #} (toElementFactory factory)\n if gtype == 0\n then return $ Just $ fromIntegral gtype\n else return Nothing\n\n-- | Get the long name for the given factory.\nelementFactoryGetLongname :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO String -- ^ the factory's long name\nelementFactoryGetLongname factory =\n {# call element_factory_get_longname #} (toElementFactory factory) >>=\n peekUTFString\n\n-- | Get the class for the given factory.\nelementFactoryGetKlass :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO String -- ^ the factory's class\nelementFactoryGetKlass factory =\n {# call element_factory_get_klass #} (toElementFactory factory) >>=\n peekUTFString\n\n-- | Get the description for the given factory.\nelementFactoryGetDescription :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO String -- ^ the factory's description\nelementFactoryGetDescription factory =\n {# call element_factory_get_description #} (toElementFactory factory) >>=\n peekUTFString\n\n-- | Get the author of the given factory.\nelementFactoryGetAuthor :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO String -- ^ the factory's author\nelementFactoryGetAuthor factory =\n {# call element_factory_get_author #} (toElementFactory factory) >>=\n peekUTFString\n\n-- | Get the number of 'PadTemplate's provided by the given factory.\nelementFactoryGetNumPadTemplates :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO Word -- ^ the number of 'PadTemplate's\nelementFactoryGetNumPadTemplates factory =\n liftM fromIntegral $\n {# call element_factory_get_num_pad_templates #} $ toElementFactory factory\n\n-- | Get the type of URIs supported by the given factory.\nelementFactoryGetURIType :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO Int -- ^ the type of URIs supported by the factory\nelementFactoryGetURIType factory =\n liftM fromIntegral $\n {# call element_factory_get_uri_type #} $ toElementFactory factory\n\n-- | Get the list of protocols supported by the given factory.\nelementFactoryGetURIProtocols :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO [String] -- ^ the supported protocols\nelementFactoryGetURIProtocols factory =\n {# call element_factory_get_uri_protocols #} (toElementFactory factory) >>=\n liftM (fromMaybe []) . maybePeek peekUTFStringArray0\n\n-- | Check if the given factory implements the interface with the given name.\nelementFactoryHasInterface :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> String -- ^ @name@ - the interface name\n -> IO Bool -- ^ true if the interface is implemented\nelementFactoryHasInterface factory name =\n liftM toBool .\n withUTFString name .\n {# call element_factory_has_interface #} .\n toElementFactory $\n factory\n\n-- | Create a new element of the type supplied by the given\n-- factory. It will be given the name supplied.\nelementFactoryCreate :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> String -- ^ @name@ - the new element's name\n -> IO (Maybe Element) -- ^ the new element if it could be created,\n -- otherwise 'Nothing'\nelementFactoryCreate factory name =\n withUTFString name $ \\cName ->\n {# call element_factory_create #} (toElementFactory factory) cName >>=\n maybePeek takeObject\n\n-- | Create a new element of the type supplied by the named\n-- factory.\nelementFactoryMake :: String -- ^ @factoryName@ - the name of an element factory\n -> Maybe String -- ^ @name@ - the new element's name, or\n -- 'Nothing' generate a unique name\n -> IO (Maybe Element) -- ^ the new element if it could be created,\n -- otherwise 'Nothing'\nelementFactoryMake factoryName name =\n withUTFString factoryName $ \\cFactoryName ->\n maybeWith withUTFString name $ \\cName ->\n {# call element_factory_make #} cFactoryName cName >>=\n maybePeek takeObject\n\n-- | Check if the given factory can sink the given capabilities.\nelementFactoryCanSinkCaps :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> Caps -- ^ @caps@ - the capabilities to check for\n -> IO Bool -- ^ 'True' if @factory@ can sink the given capabilities\nelementFactoryCanSinkCaps factory caps =\n liftM toBool $ {# call element_factory_can_sink_caps #} (toElementFactory factory) caps\n\n-- | Check if the given factory can source the given capabilities.\nelementFactoryCanSrcCaps :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> Caps -- ^ @caps@ - the capabilities to check for\n -> IO Bool -- ^ 'True' if @factory@ can source the given capabilities\nelementFactoryCanSrcCaps factory caps =\n liftM toBool $ {# call element_factory_can_src_caps #} (toElementFactory factory) caps\n\n-- | Get the pad templates provided by the given factory.\nelementFactoryGetPadTemplates :: (ElementFactoryClass elementFactory)\n => elementFactory -- ^ @factory@ - an element factory\n -> IO [PadTemplate] -- ^ the provided pad templates\nelementFactoryGetPadTemplates =\n {# call element_factory_get_static_pad_templates #} . toElementFactory >=>\n readGList >=> mapM staticPadTemplateGet\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"a9f519d5271f59adcb69595e480b7fafef27d259","subject":"Fixed typing bug in CV.ImageMath.sum","message":"Fixed typing bug in CV.ImageMath.sum\n","repos":"aleator\/CV,TomMD\/CV,aleator\/CV,BeautifulDestinations\/CV","old_file":"CV\/ImageMath.chs","new_file":"CV\/ImageMath.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ScopedTypeVariables, FlexibleContexts#-}\n#include \"cvWrapLEO.h\"\nmodule CV.ImageMath where\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.ForeignPtr\nimport Foreign.Ptr\n\nimport CV.Image \nimport CV.ImageOp\n\n-- import C2HSTools\n{#import CV.Image#}\nimport Foreign.Marshal\nimport Foreign.Ptr\nimport System.IO.Unsafe\nimport Control.Applicative ((<$>))\n\nimport C2HS\n\nmkBinaryImageOpIO f = \\a -> \\b -> \n withGenImage a $ \\ia -> \n withGenImage b $ \\ib ->\n withCloneValue a $ \\clone ->\n withGenImage clone $ \\cl -> do\n f ia ib cl \n return clone\n \nmkBinaryImageOp\n :: (Ptr () -> Ptr () -> Ptr () -> IO a)\n -> CV.Image.Image c1 d1\n -> CV.Image.Image c1 d1\n -> CV.Image.Image c1 d1\n\nmkBinaryImageOp f = \\a -> \\b -> unsafePerformIO $\n withGenImage a $ \\ia -> \n withGenImage b $ \\ib ->\n withCloneValue a $ \\clone ->\n withGenImage clone $ \\cl -> do\n f ia ib cl \n return clone\n\n\n-- I just can't think of a proper name for this\n -- Friday Evening\nabcNullPtr f = \\a b c -> f a b c nullPtr\naddOp imageToBeAdded = ImgOp $ \\target ->\n withGenImage target $ \\ctarget -> \n withGenImage imageToBeAdded $ \\cadd ->\n {#call cvAdd#} ctarget cadd ctarget nullPtr\n\nadd = mkBinaryImageOp $ abcNullPtr {#call cvAdd#}\nsub = mkBinaryImageOp $ abcNullPtr {#call cvSub#}\nsubFrom what = ImgOp $ \\from ->\n withGenImage from $ \\ifrom -> \n withGenImage what $ \\iwhat ->\n {#call cvSub#} ifrom iwhat ifrom nullPtr\n\nlogOp :: ImageOperation GrayScale D32\nlogOp = ImgOp $ \\i -> withGenImage i (\\img -> {#call cvLog#} img img)\nlog = unsafeOperate logOp\n\nsqrtOp = ImgOp $ \\i -> withGenImage i (\\img -> {#call sqrtImage#} img img)\nsqrt = unsafeOperate sqrtOp\n\nlimitToOp what = ImgOp $ \\from ->\n withGenImage from $ \\ifrom -> \n withGenImage what $ \\iwhat ->\n {#call cvMin#} ifrom iwhat ifrom\n\nlimitTo x y = unsafeOperate (limitToOp x) y \n\nmul = mkBinaryImageOp \n (\\a b c -> {#call cvMul#} a b c 1)\n\ndiv = mkBinaryImageOp \n (\\a b c -> {#call cvDiv#} a b c 1)\n\nmin = mkBinaryImageOp {#call cvMin#}\n\nmax = mkBinaryImageOp {#call cvMax#}\n\nabsDiff = mkBinaryImageOp {#call cvAbsDiff#}\n\natan :: Image GrayScale D32 -> Image GrayScale D32\natan i = unsafePerformIO $ do\n let (w,h) = getSize i\n res <- create (w,h) \n withImage i $ \\s -> \n withImage res $ \\r -> do\n {#call calculateAtan#} s r\n return res\n\natan2 a b = unsafePerformIO $ do\n res <- create (getSize a)\n withImage a $ \\c_a -> \n withImage b $ \\c_b -> \n withImage res $ \\c_res -> do\n {#call calculateAtan2#} c_a c_b c_res \n return res\n \n\n-- Operation that subtracts image mean from image\nsubtractMeanAbsOp = ImgOp $ \\image -> do\n av <- average' image\n withGenImage image $ \\i -> \n {#call wrapAbsDiffS#} i (realToFrac av) i -- TODO: check C datatype sizes\n\n-- Logical inversion of image (Ie. invert, but stay on [0..1] range)\ninvert i = addS 1 $ mulS (-1) i\n\nabsOp = ImgOp $ \\image -> do\n withGenImage image $ \\i -> \n {#call wrapAbsDiffS#} i 0 i\n\nabs = unsafeOperate absOp\n\nsubtractMeanOp :: ImageOperation GrayScale D32\nsubtractMeanOp = ImgOp $ \\image -> do\n let s = CV.ImageMath.sum image\n let mean = s \/ (fromIntegral $ getArea image )\n let (ImgOp subop) = subRSOp (realToFrac mean)\n subop image\n\nsubRSOp :: D32 -> ImageOperation GrayScale D32\nsubRSOp scalar = ImgOp $ \\a -> \n withGenImage a $ \\ia -> do\n {#call wrapSubRS#} ia (realToFrac scalar) ia \n\nsubRS s a= unsafeOperate (subRSOp s) a\n\nsubSOp scalar = ImgOp $ \\a -> \n withGenImage a $ \\ia -> do\n {#call wrapSubS#} ia (realToFrac scalar) ia \n\nsubS a s = unsafeOperate (subSOp s) a\n\n-- Multiply the image with scalar \nmulSOp :: D32 -> ImageOperation GrayScale D32\nmulSOp scalar = ImgOp $ \\a -> \n withGenImage a $ \\ia -> do\n {#call cvConvertScale#} ia ia s 0 \n return ()\n where s = realToFrac scalar \n -- I've heard this will lose information\nmulS s = unsafeOperate $ mulSOp s\n\nmkImgScalarOp op scalar = ImgOp $ \\a -> \n withGenImage a $ \\ia -> do\n op ia (realToFrac scalar) ia \n return ()\n -- where s = realToFrac scalar \n -- I've heard this will lose information\n\n-- TODO: Relax the addition so it works on multiple image depths\naddSOp :: D32 -> ImageOperation GrayScale D32\naddSOp = mkImgScalarOp $ {#call wrapAddS#}\naddS s = unsafeOperate $ addSOp s\n\nminSOp = mkImgScalarOp $ {#call cvMinS#} \nminS s = unsafeOperate $ minSOp s\n\nmaxSOp = mkImgScalarOp $ {#call cvMaxS#}\nmaxS s = unsafeOperate $ maxSOp s\n\n\n-- Comparison operators\ncmpEQ = 0\ncmpGT = 1\ncmpGE = 2\ncmpLT = 3\ncmpLE = 4\ncmpNE = 5\n\n-- TODO: For some reason the below was going through 8U images. Investigate\nmkCmpOp :: CInt -> D32 -> (Image GrayScale D32 -> Image GrayScale D8)\nmkCmpOp cmp = \\scalar a -> unsafePerformIO $ do\n withGenImage a $ \\ia -> do\n new <- create (getSize a) --8UC1\n withGenImage new $ \\cl -> do\n {#call cvCmpS#} ia (realToFrac scalar) cl cmp\n --imageTo32F new\n return new\n\n-- TODO: For some reason the below was going through 8U images. Investigate\nmkCmp2Op :: (CreateImage (Image GrayScale d)) => \n CInt -> (Image GrayScale d -> Image GrayScale d -> Image GrayScale D8)\nmkCmp2Op cmp = \\imgA imgB -> unsafePerformIO $ do\n withGenImage imgA $ \\ia -> do\n withGenImage imgB $ \\ib -> do\n new <- create (getSize imgA) -- 8U\n withGenImage new $ \\cl -> do\n {#call cvCmp#} ia ib cl cmp\n return new\n --imageTo32F new\n\n-- Compare Image to Scalar\nlessThan, moreThan :: D32 -> Image GrayScale D32 ->Image GrayScale D8\n\nlessThan = mkCmpOp cmpLT\nmoreThan = mkCmpOp cmpGT\n\nless2Than,lessEq2Than,more2Than :: (CreateImage (Image GrayScale d)) => Image GrayScale d \n -> Image GrayScale d -> Image GrayScale D8 \nless2Than = mkCmp2Op cmpLT\nlessEq2Than = mkCmp2Op cmpLE\nmore2Than = mkCmp2Op cmpGT\n\n-- Statistics\naverage' :: Image GrayScale a -> IO D32\naverage' img = withGenImage img $ \\image -> -- TODO: Check c datatype size\n {#call wrapAvg#} image >>= return . realToFrac \n\naverage :: Image GrayScale D32 -> D32\naverage = realToFrac.unsafePerformIO.average'\n\n-- | Sum the pixels in the image. Notice that OpenCV automatically casts the\n-- result to double sum :: Image GrayScale D32 -> D32\nsum :: Image GrayScale D32 -> D32\nsum img = realToFrac $ unsafePerformIO $ withGenImage img $ \\image ->\n {#call wrapSum#} image\n\naverageImages is = ( (1\/(fromIntegral $ length is)) `mulS`) (foldl1 add is)\n\n-- sum img = unsafePerformIO $ withGenImage img $ \\image ->\n-- {#call wrapSum#} image\n\nstdDeviation' img = withGenImage img {#call wrapStdDev#} \nstdDeviation :: Image GrayScale D32 -> D32\nstdDeviation = realToFrac . unsafePerformIO . stdDeviation' \n\nstdDeviationMask img mask = unsafePerformIO $ \n withGenImage img $ \\i ->\n withGenImage mask $ \\m ->\n {#call wrapStdDevMask#} i m\n\naverageMask img mask = unsafePerformIO $ \n withGenImage img $ \\i ->\n withGenImage mask $ \\m ->\n {#call wrapStdDevMask#} i m\n\n\n{#fun wrapMinMax as findMinMax' \n { withGenBareImage* `BareImage'\n , withGenBareImage* `BareImage'\n , alloca- `D32' peekFloatConv*\n , alloca- `D32' peekFloatConv*} -- TODO: Check datatype sizes used in C!\n -> `()'#}\n\nfindMinMaxLoc img = unsafePerformIO $ \n\t alloca $ \\(ptrintmaxx :: Ptr CInt)->\n\t alloca $ \\(ptrintmaxy :: Ptr CInt)->\n alloca $ \\(ptrintminx :: Ptr CInt)->\n alloca $ \\(ptrintminy :: Ptr CInt)->\n alloca $ \\(ptrintmin :: Ptr CDouble)->\n alloca $ \\(ptrintmax :: Ptr CDouble)->\n withImage img $ \\cimg -> do {\n {#call wrapMinMaxLoc#} cimg ptrintminx ptrintminy ptrintmaxx ptrintmaxy ptrintmin ptrintmax;\n\t\t minx <- fromIntegral <$> peek ptrintminx;\n\t\t miny <- fromIntegral <$> peek ptrintminy;\n\t\t maxx <- fromIntegral <$> peek ptrintmaxx;\n\t\t maxy <- fromIntegral <$> peek ptrintmaxy;\n\t\t maxval <- realToFrac <$> peek ptrintmax;\n\t\t minval <- realToFrac <$> peek ptrintmin;\n return (((minx,miny),minval),((maxx,maxy),maxval));}\n\nfindMinMax i = unsafePerformIO $ do\n nullp <- newForeignPtr_ nullPtr\n (findMinMax' (unS i) (BareImage nullp)) \n\n-- |Find minimum and maximum value of image i in area specified by the mask.\nfindMinMaxMask i mask = unsafePerformIO (findMinMax' i mask) \n-- let a = getAllPixels i in (minimum a,maximum a)\n\nmaxValue,minValue :: Image GrayScale D32 -> D32\nmaxValue = snd.findMinMax\nminValue = fst.findMinMax\n\n--\u00a0| Render image of 2D gaussian curve with standard deviation of (stdX,stdY) to image size (w,h)\n-- The origin\/center of curve is in center of the image\ngaussianImage :: (Int,Int) -> (Double,Double) -> Image GrayScale D32\ngaussianImage (w,h) (stdX,stdY) = unsafePerformIO $ do\n dst <- create (w,h) -- 32F_C1\n withImage dst $ \\d-> do\n {#call render_gaussian#} d (realToFrac stdX) (realToFrac stdY)\n return dst\n\n-- | Produce white image with 'edgeW' amount of edges fading to black\nfadedEdgeImage (w,h) edgeW = unsafePerformIO $\u00a0creatingImage ({#call fadedEdges#} w h edgeW)\n\n-- | Produce image where pixel is coloured according to distance from the edge\nfadeToCenter (w,h) = unsafePerformIO $\u00a0creatingImage ({#call rectangularDistance#} w h )\n\n-- | Merge two images according to a mask. Result R is R = A*m+B*(m-1) .\n-- TODO: Fix C-code of masked_merge to accept D8 input for the mask\nmaskedMerge :: Image GrayScale D8 -> Image GrayScale D32 -> Image GrayScale D32 -> Image GrayScale D32\nmaskedMerge mask img img2 = unsafePerformIO $ do\n res <- create (getSize img) -- 32FC1\n withImage img $ \\cimg ->\n withImage img2 $ \\cimg2 ->\n withImage res $ \\cres ->\n withImage (unsafeImageTo32F mask) $ \\cmask ->\n {#call masked_merge#} cimg cmask cimg2 cres\n return res\n\n\n\n-- | Given a distance map and a circle, return the biggest circle with radius less\n-- than given in the distance map that fully covers the previous one\n\nmaximalCoveringCircle distMap (x,y,r) \n = unsafePerformIO $ \n withImage distMap $ \\c_distmap ->\n alloca $ \\(ptr_int_max_x :: Ptr CInt) ->\n alloca $ \\(ptr_int_max_y :: Ptr CInt) ->\n alloca $ \\(ptr_double_max_r :: Ptr CDouble) -> \n do\n {#call maximal_covering_circle#} x y r c_distmap ptr_int_max_x ptr_int_max_y ptr_double_max_r\n max_x <- fromIntegral <$> peek ptr_int_max_x\n max_y <- fromIntegral <$> peek ptr_int_max_y\n max_r <- realToFrac <$> peek ptr_double_max_r\n return (max_x,max_y,max_r)\n\n \n\n \n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ScopedTypeVariables, FlexibleContexts#-}\n#include \"cvWrapLEO.h\"\nmodule CV.ImageMath where\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.ForeignPtr\nimport Foreign.Ptr\n\nimport CV.Image \nimport CV.ImageOp\n\n-- import C2HSTools\n{#import CV.Image#}\nimport Foreign.Marshal\nimport Foreign.Ptr\nimport System.IO.Unsafe\nimport Control.Applicative ((<$>))\n\nimport C2HS\n\nmkBinaryImageOpIO f = \\a -> \\b -> \n withGenImage a $ \\ia -> \n withGenImage b $ \\ib ->\n withCloneValue a $ \\clone ->\n withGenImage clone $ \\cl -> do\n f ia ib cl \n return clone\n \nmkBinaryImageOp\n :: (Ptr () -> Ptr () -> Ptr () -> IO a)\n -> CV.Image.Image c1 d1\n -> CV.Image.Image c1 d1\n -> CV.Image.Image c1 d1\n\nmkBinaryImageOp f = \\a -> \\b -> unsafePerformIO $\n withGenImage a $ \\ia -> \n withGenImage b $ \\ib ->\n withCloneValue a $ \\clone ->\n withGenImage clone $ \\cl -> do\n f ia ib cl \n return clone\n\n\n-- I just can't think of a proper name for this\n -- Friday Evening\nabcNullPtr f = \\a b c -> f a b c nullPtr\naddOp imageToBeAdded = ImgOp $ \\target ->\n withGenImage target $ \\ctarget -> \n withGenImage imageToBeAdded $ \\cadd ->\n {#call cvAdd#} ctarget cadd ctarget nullPtr\n\nadd = mkBinaryImageOp $ abcNullPtr {#call cvAdd#}\nsub = mkBinaryImageOp $ abcNullPtr {#call cvSub#}\nsubFrom what = ImgOp $ \\from ->\n withGenImage from $ \\ifrom -> \n withGenImage what $ \\iwhat ->\n {#call cvSub#} ifrom iwhat ifrom nullPtr\n\nlogOp :: ImageOperation GrayScale D32\nlogOp = ImgOp $ \\i -> withGenImage i (\\img -> {#call cvLog#} img img)\nlog = unsafeOperate logOp\n\nsqrtOp = ImgOp $ \\i -> withGenImage i (\\img -> {#call sqrtImage#} img img)\nsqrt = unsafeOperate sqrtOp\n\nlimitToOp what = ImgOp $ \\from ->\n withGenImage from $ \\ifrom -> \n withGenImage what $ \\iwhat ->\n {#call cvMin#} ifrom iwhat ifrom\n\nlimitTo x y = unsafeOperate (limitToOp x) y \n\nmul = mkBinaryImageOp \n (\\a b c -> {#call cvMul#} a b c 1)\n\ndiv = mkBinaryImageOp \n (\\a b c -> {#call cvDiv#} a b c 1)\n\nmin = mkBinaryImageOp {#call cvMin#}\n\nmax = mkBinaryImageOp {#call cvMax#}\n\nabsDiff = mkBinaryImageOp {#call cvAbsDiff#}\n\natan :: Image GrayScale D32 -> Image GrayScale D32\natan i = unsafePerformIO $ do\n let (w,h) = getSize i\n res <- create (w,h) \n withImage i $ \\s -> \n withImage res $ \\r -> do\n {#call calculateAtan#} s r\n return res\n\natan2 a b = unsafePerformIO $ do\n res <- create (getSize a)\n withImage a $ \\c_a -> \n withImage b $ \\c_b -> \n withImage res $ \\c_res -> do\n {#call calculateAtan2#} c_a c_b c_res \n return res\n \n\n-- Operation that subtracts image mean from image\nsubtractMeanAbsOp = ImgOp $ \\image -> do\n av <- average' image\n withGenImage image $ \\i -> \n {#call wrapAbsDiffS#} i (realToFrac av) i -- TODO: check C datatype sizes\n\n-- Logical inversion of image (Ie. invert, but stay on [0..1] range)\ninvert i = addS 1 $ mulS (-1) i\n\nabsOp = ImgOp $ \\image -> do\n withGenImage image $ \\i -> \n {#call wrapAbsDiffS#} i 0 i\n\nabs = unsafeOperate absOp\n\nsubtractMeanOp :: ImageOperation GrayScale D32\nsubtractMeanOp = ImgOp $ \\image -> do\n let s = CV.ImageMath.sum image\n let mean = s \/ (fromIntegral $ getArea image )\n let (ImgOp subop) = subRSOp (realToFrac mean)\n subop image\n\nsubRSOp :: D32 -> ImageOperation GrayScale D32\nsubRSOp scalar = ImgOp $ \\a -> \n withGenImage a $ \\ia -> do\n {#call wrapSubRS#} ia (realToFrac scalar) ia \n\nsubRS s a= unsafeOperate (subRSOp s) a\n\nsubSOp scalar = ImgOp $ \\a -> \n withGenImage a $ \\ia -> do\n {#call wrapSubS#} ia (realToFrac scalar) ia \n\nsubS a s = unsafeOperate (subSOp s) a\n\n-- Multiply the image with scalar \nmulSOp :: D32 -> ImageOperation GrayScale D32\nmulSOp scalar = ImgOp $ \\a -> \n withGenImage a $ \\ia -> do\n {#call cvConvertScale#} ia ia s 0 \n return ()\n where s = realToFrac scalar \n -- I've heard this will lose information\nmulS s = unsafeOperate $ mulSOp s\n\nmkImgScalarOp op scalar = ImgOp $ \\a -> \n withGenImage a $ \\ia -> do\n op ia (realToFrac scalar) ia \n return ()\n -- where s = realToFrac scalar \n -- I've heard this will lose information\n\n-- TODO: Relax the addition so it works on multiple image depths\naddSOp :: D32 -> ImageOperation GrayScale D32\naddSOp = mkImgScalarOp $ {#call wrapAddS#}\naddS s = unsafeOperate $ addSOp s\n\nminSOp = mkImgScalarOp $ {#call cvMinS#} \nminS s = unsafeOperate $ minSOp s\n\nmaxSOp = mkImgScalarOp $ {#call cvMaxS#}\nmaxS s = unsafeOperate $ maxSOp s\n\n\n-- Comparison operators\ncmpEQ = 0\ncmpGT = 1\ncmpGE = 2\ncmpLT = 3\ncmpLE = 4\ncmpNE = 5\n\n-- TODO: For some reason the below was going through 8U images. Investigate\nmkCmpOp :: CInt -> D32 -> (Image GrayScale D32 -> Image GrayScale D8)\nmkCmpOp cmp = \\scalar a -> unsafePerformIO $ do\n withGenImage a $ \\ia -> do\n new <- create (getSize a) --8UC1\n withGenImage new $ \\cl -> do\n {#call cvCmpS#} ia (realToFrac scalar) cl cmp\n --imageTo32F new\n return new\n\n-- TODO: For some reason the below was going through 8U images. Investigate\nmkCmp2Op :: (CreateImage (Image GrayScale d)) => \n CInt -> (Image GrayScale d -> Image GrayScale d -> Image GrayScale D8)\nmkCmp2Op cmp = \\imgA imgB -> unsafePerformIO $ do\n withGenImage imgA $ \\ia -> do\n withGenImage imgB $ \\ib -> do\n new <- create (getSize imgA) -- 8U\n withGenImage new $ \\cl -> do\n {#call cvCmp#} ia ib cl cmp\n return new\n --imageTo32F new\n\n-- Compare Image to Scalar\nlessThan, moreThan :: D32 -> Image GrayScale D32 ->Image GrayScale D8\n\nlessThan = mkCmpOp cmpLT\nmoreThan = mkCmpOp cmpGT\n\nless2Than,lessEq2Than,more2Than :: (CreateImage (Image GrayScale d)) => Image GrayScale d \n -> Image GrayScale d -> Image GrayScale D8 \nless2Than = mkCmp2Op cmpLT\nlessEq2Than = mkCmp2Op cmpLE\nmore2Than = mkCmp2Op cmpGT\n\n-- Statistics\naverage' :: Image GrayScale a -> IO D32\naverage' img = withGenImage img $ \\image -> -- TODO: Check c datatype size\n {#call wrapAvg#} image >>= return . realToFrac \n\naverage :: Image GrayScale D32 -> D32\naverage = realToFrac.unsafePerformIO.average'\n\n-- | Sum the pixels in the image. Notice that OpenCV automatically casts the\n-- result to double sum :: Image GrayScale D32 -> D32\nsum :: Image GrayScale a -> Double\nsum img = realToFrac $ unsafePerformIO $ withGenImage img $ \\image ->\n {#call wrapSum#} image\n\naverageImages is = ( (1\/(fromIntegral $ length is)) `mulS`) (foldl1 add is)\n\n-- sum img = unsafePerformIO $ withGenImage img $ \\image ->\n-- {#call wrapSum#} image\n\nstdDeviation' img = withGenImage img {#call wrapStdDev#} \nstdDeviation :: Image GrayScale D32 -> D32\nstdDeviation = realToFrac . unsafePerformIO . stdDeviation' \n\nstdDeviationMask img mask = unsafePerformIO $ \n withGenImage img $ \\i ->\n withGenImage mask $ \\m ->\n {#call wrapStdDevMask#} i m\n\naverageMask img mask = unsafePerformIO $ \n withGenImage img $ \\i ->\n withGenImage mask $ \\m ->\n {#call wrapStdDevMask#} i m\n\n\n{#fun wrapMinMax as findMinMax' \n { withGenBareImage* `BareImage'\n , withGenBareImage* `BareImage'\n , alloca- `D32' peekFloatConv*\n , alloca- `D32' peekFloatConv*} -- TODO: Check datatype sizes used in C!\n -> `()'#}\n\nfindMinMaxLoc img = unsafePerformIO $ \n\t alloca $ \\(ptrintmaxx :: Ptr CInt)->\n\t alloca $ \\(ptrintmaxy :: Ptr CInt)->\n alloca $ \\(ptrintminx :: Ptr CInt)->\n alloca $ \\(ptrintminy :: Ptr CInt)->\n alloca $ \\(ptrintmin :: Ptr CDouble)->\n alloca $ \\(ptrintmax :: Ptr CDouble)->\n withImage img $ \\cimg -> do {\n {#call wrapMinMaxLoc#} cimg ptrintminx ptrintminy ptrintmaxx ptrintmaxy ptrintmin ptrintmax;\n\t\t minx <- fromIntegral <$> peek ptrintminx;\n\t\t miny <- fromIntegral <$> peek ptrintminy;\n\t\t maxx <- fromIntegral <$> peek ptrintmaxx;\n\t\t maxy <- fromIntegral <$> peek ptrintmaxy;\n\t\t maxval <- realToFrac <$> peek ptrintmax;\n\t\t minval <- realToFrac <$> peek ptrintmin;\n return (((minx,miny),minval),((maxx,maxy),maxval));}\n\nfindMinMax i = unsafePerformIO $ do\n nullp <- newForeignPtr_ nullPtr\n (findMinMax' (unS i) (BareImage nullp)) \n\n-- |Find minimum and maximum value of image i in area specified by the mask.\nfindMinMaxMask i mask = unsafePerformIO (findMinMax' i mask) \n-- let a = getAllPixels i in (minimum a,maximum a)\n\nmaxValue,minValue :: Image GrayScale D32 -> D32\nmaxValue = snd.findMinMax\nminValue = fst.findMinMax\n\n--\u00a0| Render image of 2D gaussian curve with standard deviation of (stdX,stdY) to image size (w,h)\n-- The origin\/center of curve is in center of the image\ngaussianImage :: (Int,Int) -> (Double,Double) -> Image GrayScale D32\ngaussianImage (w,h) (stdX,stdY) = unsafePerformIO $ do\n dst <- create (w,h) -- 32F_C1\n withImage dst $ \\d-> do\n {#call render_gaussian#} d (realToFrac stdX) (realToFrac stdY)\n return dst\n\n-- | Produce white image with 'edgeW' amount of edges fading to black\nfadedEdgeImage (w,h) edgeW = unsafePerformIO $\u00a0creatingImage ({#call fadedEdges#} w h edgeW)\n\n-- | Produce image where pixel is coloured according to distance from the edge\nfadeToCenter (w,h) = unsafePerformIO $\u00a0creatingImage ({#call rectangularDistance#} w h )\n\n-- | Merge two images according to a mask. Result R is R = A*m+B*(m-1) .\n-- TODO: Fix C-code of masked_merge to accept D8 input for the mask\nmaskedMerge :: Image GrayScale D8 -> Image GrayScale D32 -> Image GrayScale D32 -> Image GrayScale D32\nmaskedMerge mask img img2 = unsafePerformIO $ do\n res <- create (getSize img) -- 32FC1\n withImage img $ \\cimg ->\n withImage img2 $ \\cimg2 ->\n withImage res $ \\cres ->\n withImage (unsafeImageTo32F mask) $ \\cmask ->\n {#call masked_merge#} cimg cmask cimg2 cres\n return res\n\n\n\n-- | Given a distance map and a circle, return the biggest circle with radius less\n-- than given in the distance map that fully covers the previous one\n\nmaximalCoveringCircle distMap (x,y,r) \n = unsafePerformIO $ \n withImage distMap $ \\c_distmap ->\n alloca $ \\(ptr_int_max_x :: Ptr CInt) ->\n alloca $ \\(ptr_int_max_y :: Ptr CInt) ->\n alloca $ \\(ptr_double_max_r :: Ptr CDouble) -> \n do\n {#call maximal_covering_circle#} x y r c_distmap ptr_int_max_x ptr_int_max_y ptr_double_max_r\n max_x <- fromIntegral <$> peek ptr_int_max_x\n max_y <- fromIntegral <$> peek ptr_int_max_y\n max_r <- realToFrac <$> peek ptr_double_max_r\n return (max_x,max_y,max_r)\n\n \n\n \n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"222780843aef0556ce0658b8f7424f81ba585890","subject":"Update to WebKitGTK+ 1.1.20","message":"Update to WebKitGTK+ 1.1.20","repos":"vincenthz\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/WebView.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/WebView.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebView\n-- Author : Cjacker Huang\n-- Copyright : (c) 2009 Cjacker Huang \n-- Copyright : (c) 2010 Andy Stewart \n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Note:\n--\n-- Signal `window-object-cleared` can't bidning now, \n-- because it need JavaScriptCore that haven't binding.\n--\n-- Signal `create-plugin-widget` can't binding now, \n-- no idea how to binding `GHaskellTable`\n--\n--\n-- TODO:\n--\n-- `webViewGetHitTestResult`\n--\n-- The central class of the WebKit\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebView (\n-- * Types\n WebView,\n WebViewClass,\n\n-- * Enums\n NavigationResponse(..),\n TargetInfo(..),\n LoadStatus(..),\n\n-- * Constructors\n webViewNew,\n\n-- * Methods\n webViewLoadUri,\n webViewLoadHtmlString,\n webViewLoadRequest,\n webViewLoadString,\n\n webViewGetTitle,\n webViewGetUri,\n\n webViewCanGoBack,\n webViewCanGoForward,\n webViewGoBack,\n webViewGoForward,\n webViewGetBackForwardList,\n webViewSetMaintainsBackForwardList,\n webViewGoToBackForwardItem,\n webViewCanGoBackOrForward,\n webViewGoBackOrForward,\n\n\n webViewGetZoomLevel,\n webViewSetZoomLevel,\n webViewZoomIn,\n webViewZoomOut,\n webViewGetFullContentZoom,\n webViewSetFullContentZoom,\n\n webViewStopLoading,\n webViewReload,\n webViewReloadBypassCache,\n\n webViewExecuteScript,\n\n webViewCanCutClipboard,\n webViewCanCopyClipboard,\n webViewCanPasteClipboard,\n webViewCutClipboard,\n webViewCopyClipboard,\n webViewPasteClipboard,\n\n webViewCanRedo,\n webViewCanUndo,\n webViewRedo,\n webViewUndo,\n \n webViewCanShowMimeType,\n webViewGetEditable,\n webViewSetEditable,\n webViewGetInspector,\n webViewGetTransparent,\n webViewSetTransparent,\n webViewGetViewSourceMode,\n webViewSetViewSourceMode,\n\n webViewDeleteSelection,\n webViewHasSelection,\n webViewSelectAll,\n\n webViewGetEncoding,\n webViewSetCustomEncoding,\n webViewGetCustomEncoding,\n webViewGetProgress,\n\n webViewGetCopyTargetList,\n webViewGetPasteTargetList,\n\n webViewSearchText,\n webViewMarkTextMatches,\n webViewUnMarkTextMatches,\n webViewSetHighlightTextMatches,\n\n webViewMoveCursor,\n\n webViewGetMainFrame,\n webViewGetFocusedFrame,\n\n webViewSetWebSettings,\n webViewGetWebSettings,\n\n webViewGetWindowFeatures,\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n webViewGetIconUri,\n#endif\n-- * Attributes\n webViewZoomLevel,\n webViewFullContentZoom,\n webViewEncoding,\n webViewCustomEncoding,\n webViewLoadStatus,\n webViewProgress,\n webViewTitle,\n webViewInspector,\n webViewWebSettings,\n webViewViewSourceMode,\n webViewTransparent,\n webViewEditable,\n webViewUri,\n webViewCopyTargetList,\n webViewPasteTargetList,\n webViewWindowFeatures,\n#if WEBKIT_CHECK_VERSION (1,1,18)\n webViewIconUri,\n#endif\n\n#if WEBKIT_CHECK_VERSION (1,1,20)\n webViewImContext,\n#endif\n\n \n-- * Signals\n loadStarted,\n loadCommitted,\n progressChanged,\n loadFinished,\n loadError,\n titleChanged,\n hoveringOverLink,\n createWebView,\n webViewReady,\n closeWebView,\n consoleMessage,\n copyClipboard,\n cutClipboard,\n pasteClipboard,\n populatePopup,\n printRequested,\n scriptAlert,\n scriptConfirm,\n scriptPrompt,\n statusBarTextChanged,\n selectAll,\n selectionChanged,\n setScrollAdjustments,\n databaseQuotaExceeded,\n documentLoadFinished,\n downloadRequested,\n#if WEBKIT_CHECK_VERSION (1,1,18)\n iconLoaded,\n#endif\n redo,\n undo,\n mimeTypePolicyDecisionRequested,\n moveCursor,\n navigationPolicyDecisionRequested,\n newWindowPolicyDecisionRequested,\n resourceRequestStarting,\n) where\n\nimport Control.Monad\t\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GList\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GError \nimport Graphics.UI.Gtk.Gdk.Events\n\n{#import Graphics.UI.Gtk.Abstract.Object#}\t(makeNewObject)\n{#import Graphics.UI.Gtk.WebKit.Types#}\n{#import Graphics.UI.Gtk.WebKit.Signals#}\n{#import Graphics.UI.Gtk.WebKit.Internal#}\n{#import System.Glib.GObject#}\n{#import Graphics.UI.Gtk.General.Selection#} ( TargetList )\n{#import Graphics.UI.Gtk.MenuComboToolbar.Menu#}\n{#import Graphics.UI.Gtk.General.Enums#}\n\n{#context lib=\"webkit\" prefix =\"webkit\"#}\n\n------------------\n-- Enums\n\n{#enum NavigationResponse {underscoreToCase}#}\n\n{#enum WebViewTargetInfo as TargetInfo {underscoreToCase}#}\n\n{#enum LoadStatus {underscoreToCase}#}\n\n------------------\n-- Constructors\n\n\n-- | Create a new 'WebView' widget.\n-- \n-- It is a 'Widget' you can embed in a 'ScrolledWindow'.\n-- \n-- You can load any URI into the 'WebView' or any kind of data string.\nwebViewNew :: IO WebView \nwebViewNew = do\n isGthreadInited <- liftM toBool {#call g_thread_get_initialized#}\n if not isGthreadInited then {#call g_thread_init#} nullPtr \n else return ()\n makeNewObject mkWebView $ liftM castPtr {#call web_view_new#}\n\n\n-- | Apply 'WebSettings' to a given 'WebView'\n-- \n-- !!NOTE!!, currently lack of useful APIs of 'WebSettings' in webkitgtk.\n-- If you want to set the encoding, font family or font size of the 'WebView',\n-- please use related functions.\n\nwebViewSetWebSettings :: \n (WebViewClass self, WebSettingsClass settings) => self\n -> settings\n -> IO ()\nwebViewSetWebSettings webview websettings = \n {#call web_view_set_settings#} (toWebView webview) (toWebSettings websettings)\n\n-- | Return the 'WebSettings' currently used by 'WebView'.\nwebViewGetWebSettings :: \n WebViewClass self => self\n -> IO WebSettings\nwebViewGetWebSettings webview = \n makeNewGObject mkWebSettings $ {#call web_view_get_settings#} (toWebView webview)\n\n-- | Returns the instance of WebKitWebWindowFeatures held by the given WebKitWebView.\nwebViewGetWindowFeatures ::\n WebViewClass self => self\n -> IO WebWindowFeatures \nwebViewGetWindowFeatures webview =\n makeNewGObject mkWebWindowFeatures $ {#call web_view_get_window_features#} (toWebView webview)\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n-- | Obtains the URI for the favicon for the given WebKitWebView, or 'Nothing' if there is none.\n--\n-- * Since 1.1.18\nwebViewGetIconUri :: WebViewClass self => self -> IO (Maybe String)\nwebViewGetIconUri webview =\n {#call webkit_web_view_get_icon_uri #} (toWebView webview)\n >>= maybePeek peekUTFString\n#endif\n\n\n-- | Return the main 'WebFrame' of the given 'WebView'.\nwebViewGetMainFrame :: \n WebViewClass self => self\n -> IO WebFrame\nwebViewGetMainFrame webview = \n makeNewGObject mkWebFrame $ {#call web_view_get_main_frame#} (toWebView webview)\n\n-- | Return the focused 'WebFrame' of the given 'WebView'.\nwebViewGetFocusedFrame :: \n WebViewClass self => self\n -> IO WebFrame\nwebViewGetFocusedFrame webview = \n makeNewGObject mkWebFrame $ {#call web_view_get_focused_frame#} (toWebView webview)\n\n\n-- |Requests loading of the specified URI string in a 'WebView'\nwebViewLoadUri :: \n WebViewClass self => self \n -> String -- ^ @uri@ - an URI string.\n -> IO()\nwebViewLoadUri webview url =\n withCString url $ \\urlPtr -> {#call web_view_load_uri#}\n (toWebView webview)\n urlPtr\n\n-- |Determine whether 'WebView' has a previous history item.\nwebViewCanGoBack :: \n WebViewClass self => self\n -> IO Bool -- ^ True if able to move back, False otherwise.\nwebViewCanGoBack webview = \n liftM toBool $ {#call web_view_can_go_back#} (toWebView webview)\n\n-- |Determine whether 'WebView' has a next history item.\nwebViewCanGoForward :: \n WebViewClass self => self \n -> IO Bool -- ^ True if able to move forward, False otherwise.\nwebViewCanGoForward webview = \n liftM toBool $ {#call web_view_can_go_forward#} (toWebView webview)\n\n-- |Loads the previous history item.\nwebViewGoBack :: \n WebViewClass self => self\n -> IO () \nwebViewGoBack webview =\n {#call web_view_go_back#} (toWebView webview)\n\n-- |Loads the next history item.\nwebViewGoForward :: \n WebViewClass self => self\n -> IO ()\nwebViewGoForward webview =\n {#call web_view_go_forward#} (toWebView webview)\n\n-- |Set the 'WebView' to maintian a back or forward list of history items.\nwebViewSetMaintainsBackForwardList :: \n WebViewClass self => self \n -> Bool -- ^ @flag@ - to tell the view to maintain a back or forward list. \n -> IO()\nwebViewSetMaintainsBackForwardList webview flag = \n {#call web_view_set_maintains_back_forward_list#} \n (toWebView webview)\n (fromBool flag)\n\n-- |Return the 'WebBackForwardList'\nwebViewGetBackForwardList :: \n WebViewClass self => self\n -> IO WebBackForwardList\nwebViewGetBackForwardList webview = \n makeNewGObject mkWebBackForwardList $ \n {#call web_view_get_back_forward_list#} \n (toWebView webview)\n\n-- |Go to the specified 'WebHistoryItem'\n\nwebViewGoToBackForwardItem :: \n (WebViewClass self, WebHistoryItemClass item) => self \n -> item\n -> IO Bool -- ^ True if loading of item is successful, False if not.\nwebViewGoToBackForwardItem webview item = \n liftM toBool $ {#call web_view_go_to_back_forward_item#} (toWebView webview) (toWebHistoryItem item)\n\n-- |Determines whether 'WebView' has a history item of @steps@.\n--\n-- Negative values represent steps backward while positive values\n-- represent steps forward\n\nwebViewCanGoBackOrForward :: \n WebViewClass self => self\n -> Int -- ^ @steps@ - the number of steps \n -> IO Bool -- ^ True if able to move back or forward the given number of steps,\n -- False otherwise\nwebViewCanGoBackOrForward webview steps =\n liftM toBool $ \n {#call web_view_can_go_back_or_forward#} \n (toWebView webview)\n (fromIntegral steps)\n\n-- |Loads the history item that is the number of @steps@ away from the current item.\n--\n-- Negative values represent steps backward while positive values represent steps forward.\n\nwebViewGoBackOrForward :: \n WebViewClass self => self\n -> Int\n -> IO ()\nwebViewGoBackOrForward webview steps =\n {#call web_view_go_back_or_forward#} \n (toWebView webview)\n (fromIntegral steps)\n\n-- |Determines whether or not it is currently possible to redo the last editing command in the view\nwebViewCanRedo :: \n WebViewClass self => self\n -> IO Bool\nwebViewCanRedo webview = \n liftM toBool $\n {#call web_view_can_redo#} (toWebView webview)\n-- |Determines whether or not it is currently possible to undo the last editing command in the view\nwebViewCanUndo :: \n WebViewClass self => self\n -> IO Bool\nwebViewCanUndo webview =\n liftM toBool $\n {#call web_view_can_undo#} (toWebView webview)\n\n-- |Redoes the last editing command in the view, if possible.\nwebViewRedo :: \n WebViewClass self => self\n -> IO()\nwebViewRedo webview =\n {#call web_view_redo#} (toWebView webview)\n\n-- |Undoes the last editing command in the view, if possible.\nwebViewUndo :: \n WebViewClass self => self\n -> IO()\nwebViewUndo webview =\n {#call web_view_undo#} (toWebView webview)\n\n-- | Returns whether or not a @mimetype@ can be displayed using this view.\nwebViewCanShowMimeType :: \n WebViewClass self => self\n -> String -- ^ @mimetype@ - a MIME type\n -> IO Bool -- ^ True if the @mimetype@ can be displayed, otherwise False\nwebViewCanShowMimeType webview mime =\n withCString mime $ \\mimePtr ->\n liftM toBool $\n {#call web_view_can_show_mime_type#}\n (toWebView webview)\n mimePtr\n\n-- | Returns whether the user is allowed to edit the document.\nwebViewGetEditable :: \n WebViewClass self => self\n -> IO Bool\nwebViewGetEditable webview =\n liftM toBool $\n {#call web_view_get_editable#} (toWebView webview)\n\n-- | Sets whether allows the user to edit its HTML document.\nwebViewSetEditable :: \n WebViewClass self => self\n -> Bool\n -> IO ()\nwebViewSetEditable webview editable =\n {#call web_view_set_editable#} (toWebView webview) (fromBool editable)\n\n-- | Returns whether 'WebView' is in view source mode\nwebViewGetViewSourceMode :: \n WebViewClass self => self\n -> IO Bool\nwebViewGetViewSourceMode webview =\n liftM toBool $\n {#call web_view_get_view_source_mode#} (toWebView webview)\n\n-- | Set whether the view should be in view source mode. \n--\n-- Setting this mode to TRUE before loading a URI will display \n-- the source of the web page in a nice and readable format.\nwebViewSetViewSourceMode :: \n WebViewClass self => self\n -> Bool\n -> IO ()\nwebViewSetViewSourceMode webview mode =\n {#call web_view_set_view_source_mode#} (toWebView webview) (fromBool mode)\n\n-- | Returns whether the 'WebView' has a transparent background\nwebViewGetTransparent :: \n WebViewClass self => self\n -> IO Bool\nwebViewGetTransparent webview =\n liftM toBool $\n {#call web_view_get_transparent#} (toWebView webview)\n-- |Sets whether the WebKitWebView has a transparent background.\n--\n-- Pass False to have the 'WebView' draw a solid background (the default), \n-- otherwise pass True.\nwebViewSetTransparent :: \n WebViewClass self => self\n -> Bool\n -> IO ()\nwebViewSetTransparent webview trans =\n {#call web_view_set_transparent#} (toWebView webview) (fromBool trans)\n\n-- |Obtains the 'WebInspector' associated with the 'WebView'\nwebViewGetInspector :: \n WebViewClass self => self\n -> IO WebInspector\nwebViewGetInspector webview =\n makeNewGObject mkWebInspector $ {#call web_view_get_inspector#} (toWebView webview)\n\n-- |Requests loading of the specified asynchronous client request.\n--\n-- Creates a provisional data source that will transition to a committed data source once\n-- any data has been received. \n-- use 'webViewStopLoading' to stop the load.\n\nwebViewLoadRequest :: \n (WebViewClass self, NetworkRequestClass request) => self\n -> request\n -> IO()\nwebViewLoadRequest webview request =\n {#call web_view_load_request#} (toWebView webview) (toNetworkRequest request)\n\n\n\n\n-- |Returns the zoom level of 'WebView'\n--\n-- i.e. the factor by which elements in the page are scaled with respect to their original size.\n\nwebViewGetZoomLevel :: \n WebViewClass self => self\n -> IO Float -- ^ the zoom level of 'WebView'\nwebViewGetZoomLevel webview =\n liftM realToFrac $\n\t{#call web_view_get_zoom_level#} (toWebView webview)\n\n-- |Sets the zoom level of 'WebView'.\nwebViewSetZoomLevel :: \n WebViewClass self => self \n -> Float -- ^ @zoom_level@ - the new zoom level \n -> IO ()\nwebViewSetZoomLevel webview zlevel = \n {#call web_view_set_zoom_level#} (toWebView webview) (realToFrac zlevel)\n\n-- |Loading the @content@ string as html. The URI passed in base_uri has to be an absolute URI.\n\nwebViewLoadHtmlString :: \n WebViewClass self => self \n -> String -- ^ @content@ - the html string\n -> String -- ^ @base_uri@ - the base URI\n -> IO()\nwebViewLoadHtmlString webview htmlstr url =\n withCString htmlstr $ \\htmlPtr ->\n withCString url $ \\urlPtr ->\n {#call web_view_load_html_string#} (toWebView webview) htmlPtr urlPtr\n\n-- | Requests loading of the given @content@ with the specified @mime_type@, @encoding@ and @base_uri@.\n-- \n-- If @mime_type@ is @Nothing@, \"text\/html\" is assumed.\n--\n-- If @encoding@ is @Nothing@, \"UTF-8\" is assumed.\n--\nwebViewLoadString :: \n WebViewClass self => self \n -> String -- ^ @content@ - the content string to be loaded.\n -> (Maybe String) -- ^ @mime_type@ - the MIME type or @Nothing@. \n -> (Maybe String) -- ^ @encoding@ - the encoding or @Nothing@.\n -> String -- ^ @base_uri@ - the base URI for relative locations.\n -> IO()\nwebViewLoadString webview content mimetype encoding baseuri = \n withCString content $ \\contentPtr ->\n maybeWith withCString mimetype $ \\mimetypePtr ->\n maybeWith withCString encoding $ \\encodingPtr ->\n withCString baseuri $ \\baseuriPtr ->\n {#call web_view_load_string#} \n (toWebView webview)\n contentPtr\n mimetypePtr\n encodingPtr\n baseuriPtr\n\n-- |Returns the 'WebView' document title\nwebViewGetTitle :: \n WebViewClass self => self\n -> IO (Maybe String) -- ^ the title of 'WebView' or Nothing in case of failed.\nwebViewGetTitle webview =\n {#call web_view_get_title#} (toWebView webview) >>= maybePeek peekUTFString\n\n-- |Returns the current URI of the contents displayed by the 'WebView'\nwebViewGetUri :: \n WebViewClass self => self\n -> IO (Maybe String) -- ^ the URI of 'WebView' or Nothing in case of failed.\nwebViewGetUri webview = \n {#call web_view_get_uri#} (toWebView webview) >>= maybePeek peekUTFString\n\n\n-- | Stops and pending loads on the given data source.\nwebViewStopLoading :: \n WebViewClass self => self\n -> IO ()\nwebViewStopLoading webview = \n {#call web_view_stop_loading#} (toWebView webview)\n\n-- | Reloads the 'WebView'\nwebViewReload :: \n WebViewClass self => self\n -> IO ()\nwebViewReload webview = \n {#call web_view_reload#} (toWebView webview)\n\n-- | Reloads the 'WebView' without using any cached data.\nwebViewReloadBypassCache :: \n WebViewClass self => self\n -> IO()\nwebViewReloadBypassCache webview = \n {#call web_view_reload_bypass_cache#} (toWebView webview)\n\n-- | Increases the zoom level of 'WebView'.\nwebViewZoomIn :: \n WebViewClass self => self\n -> IO()\nwebViewZoomIn webview = \n {#call web_view_zoom_in#} (toWebView webview)\n\n-- | Decreases the zoom level of 'WebView'.\nwebViewZoomOut :: \n WebViewClass self => self\n -> IO()\nwebViewZoomOut webview = \n {#call web_view_zoom_out#} (toWebView webview)\n\n-- | Looks for a specified string inside 'WebView'\nwebViewSearchText :: \n WebViewClass self => self\n -> String -- ^ @text@ - a string to look for\n -> Bool -- ^ @case_sensitive@ - whether to respect the case of text\n -> Bool -- ^ @forward@ - whether to find forward or not\n -> Bool -- ^ @wrap@ - whether to continue looking at beginning\n -- after reaching the end\n -> IO Bool -- ^ True on success or False on failure\nwebViewSearchText webview text case_sensitive forward wrap =\n withCString text $ \\textPtr ->\n\tliftM toBool $\n {#call web_view_search_text#} \n (toWebView webview)\n textPtr\n (fromBool case_sensitive) \n (fromBool forward) \n (fromBool wrap)\n\n-- |Attempts to highlight all occurances of string inside 'WebView'\nwebViewMarkTextMatches :: \n WebViewClass self => self\n -> String -- ^ @string@ - a string to look for\n -> Bool -- ^ @case_sensitive@ - whether to respect the case of text\n -> Int -- ^ @limit@ - the maximum number of strings to look for or 0 for all\n -> IO Int -- ^ the number of strings highlighted\nwebViewMarkTextMatches webview text case_sensitive limit = \n withCString text $ \\textPtr ->\n\tliftM fromIntegral $ \n {#call web_view_mark_text_matches#} \n (toWebView webview)\n textPtr\n (fromBool case_sensitive)\n (fromIntegral limit)\n\n-- | Move the cursor in view as described by step and count.\nwebViewMoveCursor ::\n WebViewClass self => self\n -> MovementStep\n -> Int\n -> IO () \nwebViewMoveCursor webview step count =\n {#call web_view_move_cursor#} (toWebView webview) (fromIntegral $ fromEnum step) (fromIntegral count)\n\n-- | Removes highlighting previously set by 'webViewMarkTextMarches'\nwebViewUnMarkTextMatches :: \n WebViewClass self => self\n -> IO ()\nwebViewUnMarkTextMatches webview = \n {#call web_view_unmark_text_matches#} (toWebView webview)\n\n-- | Highlights text matches previously marked by 'webViewMarkTextMatches'\nwebViewSetHighlightTextMatches :: \n WebViewClass self => self\n -> Bool -- ^ @highlight@ - whether to highlight text matches \n -> IO ()\nwebViewSetHighlightTextMatches webview highlight =\n {#call web_view_set_highlight_text_matches#} \n (toWebView webview)\n (fromBool highlight)\n\n-- | Execute the script specified by @script@\nwebViewExecuteScript :: \n WebViewClass self => self \n -> String -- ^ @script@ - script to be executed\n -> IO()\nwebViewExecuteScript webview script =\n withCString script $ \\scriptPtr ->\n\t{#call web_view_execute_script#} (toWebView webview) scriptPtr\n\n-- | Determines whether can cuts the current selection\n-- inside 'WebView' to the clipboard\nwebViewCanCutClipboard :: \n WebViewClass self => self\n -> IO Bool\nwebViewCanCutClipboard webview = \n liftM toBool $ {#call web_view_can_cut_clipboard#} (toWebView webview)\n\n-- | Determines whether can copies the current selection\n-- inside 'WebView' to the clipboard\nwebViewCanCopyClipboard :: WebViewClass self => self -> IO Bool\nwebViewCanCopyClipboard webview = \n liftM toBool $ {#call web_view_can_copy_clipboard#} (toWebView webview)\n\n-- | Determines whether can pastes the current contents of the clipboard\n-- to the 'WebView'\nwebViewCanPasteClipboard :: WebViewClass self => self -> IO Bool\nwebViewCanPasteClipboard webview = \n liftM toBool $ {#call web_view_can_paste_clipboard#} (toWebView webview)\n\n-- | Cuts the current selection inside 'WebView' to the clipboard.\nwebViewCutClipboard :: WebViewClass self => self -> IO()\nwebViewCutClipboard webview = \n {#call web_view_cut_clipboard#} (toWebView webview)\n\n-- | Copies the current selection inside 'WebView' to the clipboard.\nwebViewCopyClipboard :: WebViewClass self => self -> IO()\nwebViewCopyClipboard webview = \n {#call web_view_copy_clipboard#} (toWebView webview)\n\n-- | Pastes the current contents of the clipboard to the 'WebView'\nwebViewPasteClipboard :: WebViewClass self => self -> IO()\nwebViewPasteClipboard webview = \n {#call web_view_paste_clipboard#} (toWebView webview)\n\n-- | Deletes the current selection inside the 'WebView'\nwebViewDeleteSelection :: WebViewClass self => self -> IO ()\nwebViewDeleteSelection webview = \n {#call web_view_delete_selection#} (toWebView webview)\n\n-- | Determines whether text was selected\nwebViewHasSelection :: WebViewClass self => self -> IO Bool\nwebViewHasSelection webview = \n liftM toBool $ {#call web_view_has_selection#} (toWebView webview)\n\n-- | Attempts to select everything inside the 'WebView'\nwebViewSelectAll :: WebViewClass self => self -> IO ()\nwebViewSelectAll webview = \n {#call web_view_select_all#} (toWebView webview)\n\n-- | Returns whether the zoom level affects only text or all elements.\nwebViewGetFullContentZoom :: \n WebViewClass self => self \n -> IO Bool -- ^ False if only text should be scaled(the default)\n -- True if the full content of the view should be scaled.\nwebViewGetFullContentZoom webview = \n liftM toBool $ {#call web_view_get_full_content_zoom#} (toWebView webview)\n\n-- | Sets whether the zoom level affects only text or all elements.\nwebViewSetFullContentZoom :: \n WebViewClass self => self \n -> Bool -- ^ @full_content_zoom@ - False if only text should be scaled (the default)\n -- True if the full content of the view should be scaled. \n -> IO ()\nwebViewSetFullContentZoom webview full =\n {#call web_view_set_full_content_zoom#} (toWebView webview) (fromBool full)\n\n-- | Returns the default encoding of the 'WebView'\nwebViewGetEncoding :: \n WebViewClass self => self \n -> IO (Maybe String) -- ^ the default encoding or @Nothing@ in case of failed\nwebViewGetEncoding webview =\n {#call web_view_get_encoding#} (toWebView webview) >>= maybePeek peekUTFString\n\n-- | Sets the current 'WebView' encoding, \n-- without modifying the default one, and reloads the page\nwebViewSetCustomEncoding :: \n WebViewClass self => self\n -> (Maybe String) -- ^ @encoding@ - the new encoding, \n -- or @Nothing@ to restore the default encoding. \n -> IO ()\nwebViewSetCustomEncoding webview encoding = \n maybeWith withCString encoding $ \\encodingPtr ->\n\t{#call web_view_set_custom_encoding#} (toWebView webview) encodingPtr\n\n-- | Returns the current encoding of 'WebView',not the default encoding.\nwebViewGetCustomEncoding :: \n WebViewClass self => self \n -> IO (Maybe String) -- ^ the current encoding string\n -- or @Nothing@ if there is none set.\nwebViewGetCustomEncoding webview = \n {#call web_view_get_custom_encoding#} (toWebView webview) >>= maybePeek peekUTFString\n\n-- | Determines the current status of the load.\nwebViewGetLoadStatus :: \n WebViewClass self => self \n -> IO LoadStatus -- ^ the current load status:'LoadStatus'\nwebViewGetLoadStatus webview = \n liftM (toEnum . fromIntegral) $ {#call web_view_get_load_status#} (toWebView webview)\n\n-- | Determines the current progress of the load\nwebViewGetProgress :: \n WebViewClass self => self \n -> IO Double -- ^ the load progress\nwebViewGetProgress webview =\n liftM realToFrac $ {#call web_view_get_progress#} (toWebView webview)\n\n-- | This function returns the list of targets this 'WebView' can provide for clipboard copying and as DND source. \n-- The targets in the list are added with values from the 'WebViewTargetInfo' enum, \n-- using 'targetListAdd' and 'targetListAddTextTargets'.\nwebViewGetCopyTargetList ::\n WebViewClass self => self \n -> IO (Maybe TargetList)\nwebViewGetCopyTargetList webview = do\n tlPtr <- {#call web_view_get_copy_target_list#} (toWebView webview)\n if tlPtr==nullPtr then return Nothing else liftM Just (mkTargetList tlPtr)\n\n-- | This function returns the list of targets this 'WebView' can provide for clipboard pasteing and as DND source. \n-- The targets in the list are added with values from the 'WebViewTargetInfo' enum, \n-- using 'targetListAdd' and 'targetListAddTextTargets'.\nwebViewGetPasteTargetList ::\n WebViewClass self => self \n -> IO (Maybe TargetList)\nwebViewGetPasteTargetList webview = do\n tlPtr <- {#call web_view_get_paste_target_list#} (toWebView webview)\n if tlPtr==nullPtr then return Nothing else liftM Just (mkTargetList tlPtr)\n\n-- * Attibutes\n\n-- | Zoom level of the 'WebView' instance\nwebViewZoomLevel :: WebViewClass self => Attr self Float\nwebViewZoomLevel = newAttr\n webViewGetZoomLevel\n webViewSetZoomLevel\n\n-- | Whether the full content is scaled when zooming\n--\n-- Default value: False\nwebViewFullContentZoom :: WebViewClass self => Attr self Bool\nwebViewFullContentZoom = newAttr\n webViewGetFullContentZoom\n webViewSetFullContentZoom\n\n-- | The default encoding of the 'WebView' instance\n--\n-- Default value: @Nothing@\nwebViewEncoding :: WebViewClass self => ReadAttr self (Maybe String)\nwebViewEncoding = readAttr webViewGetEncoding\n\n-- | Determines the current status of the load.\n--\n-- Default value: @LoadFinished@\nwebViewLoadStatus :: WebViewClass self => ReadAttr self LoadStatus\nwebViewLoadStatus = readAttr webViewGetLoadStatus\n\n-- |Determines the current progress of the load\n--\n-- Default Value: 1\nwebViewProgress :: WebViewClass self => ReadAttr self Double\nwebViewProgress = readAttr webViewGetProgress\n\n\n-- | The associated webSettings of the 'WebView' instance\nwebViewWebSettings :: WebViewClass self => Attr self WebSettings\nwebViewWebSettings = newAttr\n webViewGetWebSettings\n webViewSetWebSettings\n\n\n-- | Title of the 'WebView' instance\nwebViewTitle :: WebViewClass self => ReadAttr self (Maybe String)\nwebViewTitle = readAttr webViewGetTitle\n\n-- | The associated webInspector instance of the 'WebView'\nwebViewInspector :: WebViewClass self => ReadAttr self WebInspector\nwebViewInspector = readAttr webViewGetInspector\n\n\n-- | The custom encoding of the 'WebView' instance\n--\n-- Default value: @Nothing@\nwebViewCustomEncoding :: WebViewClass self => Attr self (Maybe String)\nwebViewCustomEncoding = newAttr\n webViewGetCustomEncoding\n webViewSetCustomEncoding\n\n-- | view source mode of the 'WebView' instance\nwebViewViewSourceMode :: WebViewClass self => Attr self Bool\nwebViewViewSourceMode = newAttr\n webViewGetViewSourceMode\n webViewSetViewSourceMode\n\n-- | transparent background of the 'WebView' instance\nwebViewTransparent :: WebViewClass self => Attr self Bool\nwebViewTransparent = newAttr\n webViewGetTransparent\n webViewSetTransparent\n\n-- | Whether content of the 'WebView' can be modified by the user\n--\n-- Default value: @False@\nwebViewEditable :: WebViewClass self => Attr self Bool\nwebViewEditable = newAttr\n webViewGetEditable\n webViewSetEditable\n\n-- | Returns the current URI of the contents displayed by the @web_view@.\n--\n-- Default value: Nothing\nwebViewUri :: WebViewClass self => ReadAttr self (Maybe String)\nwebViewUri = readAttr webViewGetUri\n\n-- | The list of targets this web view supports for clipboard copying.\nwebViewCopyTargetList :: WebViewClass self => ReadAttr self (Maybe TargetList)\nwebViewCopyTargetList = readAttr webViewGetCopyTargetList\n\n-- | The list of targets this web view supports for clipboard pasteing.\nwebViewPasteTargetList :: WebViewClass self => ReadAttr self (Maybe TargetList)\nwebViewPasteTargetList = readAttr webViewGetPasteTargetList\n\n-- | An associated 'WebWindowFeatures' instance.\nwebViewWindowFeatures :: WebViewClass self => Attr self WebWindowFeatures\nwebViewWindowFeatures = \n newAttrFromObjectProperty \"window-features\"\n {#call pure webkit_web_window_features_get_type#}\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n-- | The URI for the favicon for the WebKitWebView.\n-- \n-- Default value: 'Nothing'\n-- \n-- * Since 1.1.18\nwebViewIconUri :: WebViewClass self => ReadAttr self String\nwebViewIconUri = readAttrFromStringProperty \"icon-uri\"\n#endif\n\n#if WEBKIT_CHECK_VERSION (1,1,20)\n-- | The 'IMMulticontext' for the WebKitWebView.\n-- \n-- This is the input method context used for all text entry widgets inside the WebKitWebView. It can be\n-- used to generate context menu items for controlling the active input method.\n-- \n-- * Since 1.1.20\nwebViewImContext :: WebViewClass self => ReadAttr self IMContext\nwebViewImContext = \n readAttrFromObjectProperty \"im-context\"\n {#call pure gtk_im_context_get_type #}\n#endif\n\n-- * Signals\n\n-- | When Document title changed, this signal is emitted.\n--\n-- It can be used to set the Application 'Window' title.\n--\n-- the user function signature is (WebFrame->String->IO())\n--\n-- webframe - which 'WebFrame' changes the document title.\n--\n-- title - current title string.\ntitleChanged :: WebViewClass self => Signal self ( WebFrame -> String -> IO() )\ntitleChanged = \n Signal (connect_OBJECT_STRING__NONE \"title-changed\")\n\n\n-- | When the cursor is over a link, this signal is emitted.\n-- \n-- the user function signature is (Maybe String -> Maybe String -> IO () )\n-- \n-- title - the link's title or @Nothing@ in case of failure.\n--\n-- uri - the URI the link points to or @Nothing@ in case of failure.\nhoveringOverLink :: WebViewClass self => Signal self (String -> String -> IO())\nhoveringOverLink =\n Signal (connect_STRING_STRING__NONE \"hovering-over-link\")\n\n-- | When a 'WebFrame' begins to load, this signal is emitted\nloadStarted :: WebViewClass self => Signal self (WebFrame -> IO())\nloadStarted = Signal (connect_OBJECT__NONE \"load-started\")\n\n-- | When a 'WebFrame' loaded the first data, this signal is emitted\nloadCommitted :: WebViewClass self => Signal self (WebFrame -> IO())\nloadCommitted = Signal (connect_OBJECT__NONE \"load-committed\")\n\n\n-- | When the global progress changed, this signal is emitted\n--\n-- the global progress will be passed back to user function\nprogressChanged :: WebViewClass self => Signal self (Int-> IO())\nprogressChanged = \n Signal (connect_INT__NONE \"load-progress-changed\")\n\n-- | When loading finished, this signal is emitted\nloadFinished :: WebViewClass self => Signal self (WebFrame -> IO())\nloadFinished = \n Signal (connect_OBJECT__NONE \"load-finished\")\n\n-- | When An error occurred while loading. \n--\n-- By default, if the signal is not handled,\n-- the WebView will display a stock error page. \n--\n-- You need to handle the signal\n-- if you want to provide your own error page.\n-- \n-- The URI that triggered the error and the 'GError' will be passed back to user function.\nloadError :: WebViewClass self => Signal self (WebFrame -> String -> GError -> IO Bool)\nloadError = Signal (connect_OBJECT_STRING_BOXED__BOOL \"load-error\" peek)\n\ncreateWebView :: WebViewClass self => Signal self (WebFrame -> IO WebView)\ncreateWebView = Signal (connect_OBJECT__OBJECTPTR \"create-web-view\")\n\n-- | Emitted when closing a WebView is requested. \n--\n-- This occurs when a call is made from JavaScript's window.close function. \n-- The default signal handler does not do anything. \n-- It is the owner's responsibility to hide or delete the 'WebView', if necessary.\n-- \n-- User function should return True to stop the handlers from being invoked for the event \n-- or False to propagate the event furter\ncloseWebView :: WebViewClass self => Signal self (IO Bool)\ncloseWebView = \n Signal (connect_NONE__BOOL \"close-web-view\")\n\n-- | A JavaScript console message was created.\nconsoleMessage :: WebViewClass self => Signal self (String -> String -> Int -> String -> IO Bool)\nconsoleMessage = Signal (connect_STRING_STRING_INT_STRING__BOOL \"console-message\")\n\n-- | The 'copyClipboard' signal is a keybinding signal which gets emitted to copy the selection to the clipboard.\n--\n-- The default bindings for this signal are Ctrl-c and Ctrl-Insert.\ncopyClipboard :: WebViewClass self => Signal self (IO ())\ncopyClipboard = Signal (connect_NONE__NONE \"copy-clipboard\")\n\n-- | The 'cutClipboard' signal is a keybinding signal which gets emitted to cut the selection to the clipboard.\n--\n-- The default bindings for this signal are Ctrl-x and Shift-Delete.\ncutClipboard :: WebViewClass self => Signal self (IO ())\ncutClipboard = Signal (connect_NONE__NONE \"cut-clipboard\")\n\n-- | The 'pasteClipboard' signal is a keybinding signal which gets emitted to paste the contents of the clipboard into the Web view.\n--\n-- The default bindings for this signal are Ctrl-v and Shift-Insert.\npasteClipboard :: WebViewClass self => Signal self (IO ())\npasteClipboard = Signal (connect_NONE__NONE \"paste-clipboard\")\n\n-- | When a context menu is about to be displayed this signal is emitted.\npopulatePopup :: WebViewClass self => Signal self (Menu -> IO ())\npopulatePopup = Signal (connect_OBJECT__NONE \"populate-popup\")\n\n-- | Emitted when printing is requested by the frame, usually because of a javascript call. \n-- When handling this signal you should call 'webFramePrintFull' or 'webFramePrint' to do the actual printing.\n--\n-- The default handler will present a print dialog and carry a print operation. \n-- Notice that this means that if you intend to ignore a print\n-- request you must connect to this signal, and return True.\nprintRequested :: WebViewClass self => Signal self (WebFrame -> IO Bool)\nprintRequested = Signal (connect_OBJECT__BOOL \"print-requested\")\n\n-- | A JavaScript alert dialog was created.\nscriptAlert :: WebViewClass self => Signal self (WebFrame -> String -> IO Bool)\nscriptAlert = Signal (connect_OBJECT_STRING__BOOL \"scriptAlert\")\n\n-- | A JavaScript confirm dialog was created, providing Yes and No buttons.\nscriptConfirm :: WebViewClass self => Signal self (WebFrame -> String -> IO Bool)\nscriptConfirm = Signal (connect_OBJECT_STRING__BOOL \"script-confirm\")\n\n-- | A JavaScript prompt dialog was created, providing an entry to input text.\nscriptPrompt :: WebViewClass self => Signal self (WebFrame -> String -> String -> IO Bool)\nscriptPrompt = Signal (connect_OBJECT_STRING_STRING__BOOL \"script-prompt\")\n\n-- | When status-bar text changed, this signal will emitted.\nstatusBarTextChanged :: WebViewClass self => Signal self (String -> IO ())\nstatusBarTextChanged = Signal (connect_STRING__NONE \"status-bar-text-changed\")\n\n\n\n-- | The 'selectAll' signal is a keybinding signal which gets emitted to select the complete contents of the text view.\n-- \n-- The default bindings for this signal is Ctrl-a.\nselectAll :: WebViewClass self => Signal self (IO ())\nselectAll = Signal (connect_NONE__NONE \"select-all\")\n\n-- | When selection changed, this signal is emitted.\nselectionChanged :: WebViewClass self => Signal self (IO ())\nselectionChanged = Signal (connect_NONE__NONE \"selection-changed\")\n\n-- | When set scroll adjustments, this signal is emitted.\nsetScrollAdjustments :: WebViewClass self => Signal self (Adjustment -> Adjustment -> IO ())\nsetScrollAdjustments = Signal (connect_OBJECT_OBJECT__NONE \"set-scroll-adjustments\")\n\n-- | The 'databaseQuotaExceeded' signal will be emitted when a Web Database exceeds the quota of its security origin. \n-- This signal may be used to increase the size of the quota before the originating operation fails.\ndatabaseQuotaExceeded :: WebViewClass self => Signal self (WebFrame -> WebDatabase -> IO ())\ndatabaseQuotaExceeded = Signal (connect_OBJECT_OBJECT__NONE \"database-quota-exceeded\")\n\n-- | When document loading finished, this signal is emitted\ndocumentLoadFinished :: WebViewClass self => Signal self (WebFrame -> IO ())\ndocumentLoadFinished = Signal (connect_OBJECT__NONE \"document-load-finished\")\n\n\n-- | Emitted after new 'WebView' instance had been created in 'onCreateWebView' user function\n-- when the new 'WebView' should be displayed to the user.\n-- \n-- All the information about how the window should look, \n-- including size,position,whether the location, status and scroll bars should be displayed, \n-- is ready set.\nwebViewReady:: WebViewClass self => Signal self (IO Bool)\nwebViewReady =\n Signal (connect_NONE__BOOL \"web-view-ready\")\n\n-- | Emitted after A new 'Download' is being requested. \n--\n-- By default, if the signal is not handled, the download is cancelled.\n-- \n-- Notice that while handling this signal you must set the target URI using 'downloadSetDestinationUri'\n-- \n-- If you intend to handle downloads yourself, return False in user function.\ndownloadRequested :: WebViewClass self => Signal self (Download -> IO Bool)\ndownloadRequested =\n Signal (connect_OBJECT__BOOL \"download-requested\")\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n-- | Emitted after Icon loaded\niconLoaded :: WebViewClass self => Signal self (IO ())\niconLoaded =\n Signal (connect_NONE__NONE \"icon-loaded\")\n#endif\n\n-- | The \"redo\" signal is a keybinding signal which gets emitted to redo the last editing command.\n--\n-- The default binding for this signal is Ctrl-Shift-z\nredo :: WebViewClass self => Signal self (IO ())\nredo =\n Signal (connect_NONE__NONE \"redo\")\n\n-- | The \"undo\" signal is a keybinding signal which gets emitted to undo the last editing command.\n--\n-- The default binding for this signal is Ctrl-z\nundo :: WebViewClass self => Signal self (IO ())\nundo =\n Signal (connect_NONE__NONE \"undo\")\n\n-- | Decide whether or not to display the given MIME type. \n-- If this signal is not handled, the default behavior is to show the content of the\n-- requested URI if WebKit can show this MIME type and the content disposition is not a download; \n-- if WebKit is not able to show the MIME type nothing happens.\n--\n-- Notice that if you return True, meaning that you handled the signal, \n-- you are expected to be aware of the \"Content-Disposition\" header. \n-- A value of \"attachment\" usually indicates a download regardless of the MIME type, \n-- see also soupMessageHeadersGetContentDisposition'\n-- And you must call 'webPolicyDecisionIgnore', 'webPolicyDecisionDownload', or 'webPolicyDecisionUse' \n-- on the 'webPolicyDecision' object.\nmimeTypePolicyDecisionRequested :: WebViewClass self => Signal self (WebFrame -> NetworkRequest -> String -> WebPolicyDecision -> IO Bool)\nmimeTypePolicyDecisionRequested = Signal (connect_OBJECT_OBJECT_STRING_OBJECT__BOOL \"mime-type-policy-decision-requested\")\n\n-- | The 'moveCursor' will be emitted to apply the cursor movement described by its parameters to the view.\nmoveCursor :: WebViewClass self => Signal self (MovementStep -> Int -> IO Bool)\nmoveCursor = Signal (connect_ENUM_INT__BOOL \"move-cursor\")\n\n-- | Emitted when frame requests a navigation to another page. \n-- If this signal is not handled, the default behavior is to allow the navigation.\n--\n-- Notice that if you return True, meaning that you handled the signal, \n-- you are expected to be aware of the \"Content-Disposition\" header. \n-- A value of \"attachment\" usually indicates a download regardless of the MIME type, \n-- see also soupMessageHeadersGetContentDisposition'\n-- And you must call 'webPolicyDecisionIgnore', 'webPolicyDecisionDownload', or 'webPolicyDecisionUse' \n-- on the 'webPolicyDecision' object.\nnavigationPolicyDecisionRequested :: WebViewClass self => Signal self (WebFrame -> NetworkRequest -> WebNavigationAction -> WebPolicyDecision -> IO Bool)\nnavigationPolicyDecisionRequested = Signal (connect_OBJECT_OBJECT_OBJECT_OBJECT__BOOL \"navigation-policy-decision-requested\")\n\n-- | Emitted when frame requests opening a new window. \n-- With this signal the browser can use the context of the request to decide about the new window. \n-- If the request is not handled the default behavior is to allow opening the new window to load the URI, \n-- which will cause a 'createWebView' signal emission where the browser handles the new window action \n-- but without information of the context that caused the navigation. \n-- The following 'navigationPolicyDecisionRequested' emissions will load the page \n-- after the creation of the new window just with the information of this new navigation context, \n-- without any information about the action that made this new window to be opened.\n--\n-- Notice that if you return True, meaning that you handled the signal, \n-- you are expected to be aware of the \"Content-Disposition\" header. \n-- A value of \"attachment\" usually indicates a download regardless of the MIME type, \n-- see also soupMessageHeadersGetContentDisposition'\n-- And you must call 'webPolicyDecisionIgnore', 'webPolicyDecisionDownload', or 'webPolicyDecisionUse' \n-- on the 'webPolicyDecision' object.\nnewWindowPolicyDecisionRequested :: WebViewClass self => Signal self (WebFrame -> NetworkRequest -> WebNavigationAction -> WebPolicyDecision -> IO Bool)\nnewWindowPolicyDecisionRequested = Signal (connect_OBJECT_OBJECT_OBJECT_OBJECT__BOOL \"new-window-policy-decision-requested\")\n\n-- | Emitted when a request is about to be sent. \n-- You can modify the request while handling this signal. \n-- You can set the URI in the 'NetworkRequest' object itself, \n-- and add\/remove\/replace headers using the SoupMessage object it carries, \n-- if it is present. See 'networkRequestGetMessage'. \n-- Setting the request URI to \"about:blank\" will effectively cause the request to load nothing, \n-- and can be used to disable the loading of specific resources.\n--\n-- Notice that information about an eventual redirect is available in response's SoupMessage, \n-- not in the SoupMessage carried by the request.\n-- If response is NULL, then this is not a redirected request.\n--\n-- The 'WebResource' object will be the same throughout all the lifetime of the resource, \n-- but the contents may change from inbetween signal emissions.\nresourceRequestStarting :: WebViewClass self => Signal self (WebFrame -> WebResource -> NetworkRequest -> NetworkResponse -> IO ())\nresourceRequestStarting = Signal (connect_OBJECT_OBJECT_OBJECT_OBJECT__NONE \"resource-request-starting\")\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebView\n-- Author : Cjacker Huang\n-- Copyright : (c) 2009 Cjacker Huang \n-- Copyright : (c) 2010 Andy Stewart \n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Note:\n--\n-- Signal `window-object-cleared` can't bidning now, \n-- because it need JavaScriptCore that haven't binding.\n--\n-- Signal `create-plugin-widget` can't binding now, \n-- no idea how to binding `GHaskellTable`\n--\n--\n-- TODO:\n--\n-- `webViewGetHitTestResult`\n--\n-- The central class of the WebKit\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebView (\n-- * Types\n WebView,\n WebViewClass,\n\n-- * Enums\n NavigationResponse(..),\n TargetInfo(..),\n LoadStatus(..),\n\n-- * Constructors\n webViewNew,\n\n-- * Methods\n webViewLoadUri,\n webViewLoadHtmlString,\n webViewLoadRequest,\n webViewLoadString,\n\n webViewGetTitle,\n webViewGetUri,\n\n webViewCanGoBack,\n webViewCanGoForward,\n webViewGoBack,\n webViewGoForward,\n webViewGetBackForwardList,\n webViewSetMaintainsBackForwardList,\n webViewGoToBackForwardItem,\n webViewCanGoBackOrForward,\n webViewGoBackOrForward,\n\n\n webViewGetZoomLevel,\n webViewSetZoomLevel,\n webViewZoomIn,\n webViewZoomOut,\n webViewGetFullContentZoom,\n webViewSetFullContentZoom,\n\n webViewStopLoading,\n webViewReload,\n webViewReloadBypassCache,\n\n webViewExecuteScript,\n\n webViewCanCutClipboard,\n webViewCanCopyClipboard,\n webViewCanPasteClipboard,\n webViewCutClipboard,\n webViewCopyClipboard,\n webViewPasteClipboard,\n\n webViewCanRedo,\n webViewCanUndo,\n webViewRedo,\n webViewUndo,\n \n webViewCanShowMimeType,\n webViewGetEditable,\n webViewSetEditable,\n webViewGetInspector,\n webViewGetTransparent,\n webViewSetTransparent,\n webViewGetViewSourceMode,\n webViewSetViewSourceMode,\n\n webViewDeleteSelection,\n webViewHasSelection,\n webViewSelectAll,\n\n webViewGetEncoding,\n webViewSetCustomEncoding,\n webViewGetCustomEncoding,\n webViewGetProgress,\n\n webViewGetCopyTargetList,\n webViewGetPasteTargetList,\n\n webViewSearchText,\n webViewMarkTextMatches,\n webViewUnMarkTextMatches,\n webViewSetHighlightTextMatches,\n\n webViewMoveCursor,\n\n webViewGetMainFrame,\n webViewGetFocusedFrame,\n\n webViewSetWebSettings,\n webViewGetWebSettings,\n\n webViewGetWindowFeatures,\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n webViewGetIconUri,\n#endif\n\n-- * Attributes\n webViewZoomLevel,\n webViewFullContentZoom,\n webViewEncoding,\n webViewCustomEncoding,\n webViewLoadStatus,\n webViewProgress,\n webViewTitle,\n webViewInspector,\n webViewWebSettings,\n webViewViewSourceMode,\n webViewTransparent,\n webViewEditable,\n webViewUri,\n webViewCopyTargetList,\n webViewPasteTargetList,\n webViewWindowFeatures,\n#if WEBKIT_CHECK_VERSION (1,1,18)\n webViewIconUri,\n#endif\n \n-- * Signals\n loadStarted,\n loadCommitted,\n progressChanged,\n loadFinished,\n loadError,\n titleChanged,\n hoveringOverLink,\n createWebView,\n webViewReady,\n closeWebView,\n consoleMessage,\n copyClipboard,\n cutClipboard,\n pasteClipboard,\n populatePopup,\n printRequested,\n scriptAlert,\n scriptConfirm,\n scriptPrompt,\n statusBarTextChanged,\n selectAll,\n selectionChanged,\n setScrollAdjustments,\n databaseQuotaExceeded,\n documentLoadFinished,\n downloadRequested,\n#if WEBKIT_CHECK_VERSION (1,1,18)\n iconLoaded,\n#endif\n redo,\n undo,\n mimeTypePolicyDecisionRequested,\n moveCursor,\n navigationPolicyDecisionRequested,\n newWindowPolicyDecisionRequested,\n resourceRequestStarting,\n) where\n\nimport Control.Monad\t\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GList\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GError \nimport Graphics.UI.Gtk.Gdk.Events\n\n{#import Graphics.UI.Gtk.Abstract.Object#}\t(makeNewObject)\n{#import Graphics.UI.Gtk.WebKit.Types#}\n{#import Graphics.UI.Gtk.WebKit.Signals#}\n{#import Graphics.UI.Gtk.WebKit.Internal#}\n{#import System.Glib.GObject#}\n{#import Graphics.UI.Gtk.General.Selection#} ( TargetList )\n{#import Graphics.UI.Gtk.MenuComboToolbar.Menu#}\n{#import Graphics.UI.Gtk.General.Enums#}\n\n{#context lib=\"webkit\" prefix =\"webkit\"#}\n\n------------------\n-- Enums\n\n{#enum NavigationResponse {underscoreToCase}#}\n\n{#enum WebViewTargetInfo as TargetInfo {underscoreToCase}#}\n\n{#enum LoadStatus {underscoreToCase}#}\n\n------------------\n-- Constructors\n\n\n-- | Create a new 'WebView' widget.\n-- \n-- It is a 'Widget' you can embed in a 'ScrolledWindow'.\n-- \n-- You can load any URI into the 'WebView' or any kind of data string.\nwebViewNew :: IO WebView \nwebViewNew = do\n isGthreadInited <- liftM toBool {#call g_thread_get_initialized#}\n if not isGthreadInited then {#call g_thread_init#} nullPtr \n else return ()\n makeNewObject mkWebView $ liftM castPtr {#call web_view_new#}\n\n\n-- | Apply 'WebSettings' to a given 'WebView'\n-- \n-- !!NOTE!!, currently lack of useful APIs of 'WebSettings' in webkitgtk.\n-- If you want to set the encoding, font family or font size of the 'WebView',\n-- please use related functions.\n\nwebViewSetWebSettings :: \n (WebViewClass self, WebSettingsClass settings) => self\n -> settings\n -> IO ()\nwebViewSetWebSettings webview websettings = \n {#call web_view_set_settings#} (toWebView webview) (toWebSettings websettings)\n\n-- | Return the 'WebSettings' currently used by 'WebView'.\nwebViewGetWebSettings :: \n WebViewClass self => self\n -> IO WebSettings\nwebViewGetWebSettings webview = \n makeNewGObject mkWebSettings $ {#call web_view_get_settings#} (toWebView webview)\n\n-- | Returns the instance of WebKitWebWindowFeatures held by the given WebKitWebView.\nwebViewGetWindowFeatures ::\n WebViewClass self => self\n -> IO WebWindowFeatures \nwebViewGetWindowFeatures webview =\n makeNewGObject mkWebWindowFeatures $ {#call web_view_get_window_features#} (toWebView webview)\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n-- | Obtains the URI for the favicon for the given WebKitWebView, or 'Nothing' if there is none.\n--\n-- * Since 1.1.18\nwebViewGetIconUri :: WebViewClass self => self -> IO (Maybe String)\nwebViewGetIconUri webview =\n {#call webkit_web_view_get_icon_uri #} (toWebView webview)\n >>= maybePeek peekUTFString\n#endif\n\n-- | Return the main 'WebFrame' of the given 'WebView'.\nwebViewGetMainFrame :: \n WebViewClass self => self\n -> IO WebFrame\nwebViewGetMainFrame webview = \n makeNewGObject mkWebFrame $ {#call web_view_get_main_frame#} (toWebView webview)\n\n-- | Return the focused 'WebFrame' of the given 'WebView'.\nwebViewGetFocusedFrame :: \n WebViewClass self => self\n -> IO WebFrame\nwebViewGetFocusedFrame webview = \n makeNewGObject mkWebFrame $ {#call web_view_get_focused_frame#} (toWebView webview)\n\n\n-- |Requests loading of the specified URI string in a 'WebView'\nwebViewLoadUri :: \n WebViewClass self => self \n -> String -- ^ @uri@ - an URI string.\n -> IO()\nwebViewLoadUri webview url =\n withCString url $ \\urlPtr -> {#call web_view_load_uri#}\n (toWebView webview)\n urlPtr\n\n-- |Determine whether 'WebView' has a previous history item.\nwebViewCanGoBack :: \n WebViewClass self => self\n -> IO Bool -- ^ True if able to move back, False otherwise.\nwebViewCanGoBack webview = \n liftM toBool $ {#call web_view_can_go_back#} (toWebView webview)\n\n-- |Determine whether 'WebView' has a next history item.\nwebViewCanGoForward :: \n WebViewClass self => self \n -> IO Bool -- ^ True if able to move forward, False otherwise.\nwebViewCanGoForward webview = \n liftM toBool $ {#call web_view_can_go_forward#} (toWebView webview)\n\n-- |Loads the previous history item.\nwebViewGoBack :: \n WebViewClass self => self\n -> IO () \nwebViewGoBack webview =\n {#call web_view_go_back#} (toWebView webview)\n\n-- |Loads the next history item.\nwebViewGoForward :: \n WebViewClass self => self\n -> IO ()\nwebViewGoForward webview =\n {#call web_view_go_forward#} (toWebView webview)\n\n-- |Set the 'WebView' to maintian a back or forward list of history items.\nwebViewSetMaintainsBackForwardList :: \n WebViewClass self => self \n -> Bool -- ^ @flag@ - to tell the view to maintain a back or forward list. \n -> IO()\nwebViewSetMaintainsBackForwardList webview flag = \n {#call web_view_set_maintains_back_forward_list#} \n (toWebView webview)\n (fromBool flag)\n\n-- |Return the 'WebBackForwardList'\nwebViewGetBackForwardList :: \n WebViewClass self => self\n -> IO WebBackForwardList\nwebViewGetBackForwardList webview = \n makeNewGObject mkWebBackForwardList $ \n {#call web_view_get_back_forward_list#} \n (toWebView webview)\n\n-- |Go to the specified 'WebHistoryItem'\n\nwebViewGoToBackForwardItem :: \n (WebViewClass self, WebHistoryItemClass item) => self \n -> item\n -> IO Bool -- ^ True if loading of item is successful, False if not.\nwebViewGoToBackForwardItem webview item = \n liftM toBool $ {#call web_view_go_to_back_forward_item#} (toWebView webview) (toWebHistoryItem item)\n\n-- |Determines whether 'WebView' has a history item of @steps@.\n--\n-- Negative values represent steps backward while positive values\n-- represent steps forward\n\nwebViewCanGoBackOrForward :: \n WebViewClass self => self\n -> Int -- ^ @steps@ - the number of steps \n -> IO Bool -- ^ True if able to move back or forward the given number of steps,\n -- False otherwise\nwebViewCanGoBackOrForward webview steps =\n liftM toBool $ \n {#call web_view_can_go_back_or_forward#} \n (toWebView webview)\n (fromIntegral steps)\n\n-- |Loads the history item that is the number of @steps@ away from the current item.\n--\n-- Negative values represent steps backward while positive values represent steps forward.\n\nwebViewGoBackOrForward :: \n WebViewClass self => self\n -> Int\n -> IO ()\nwebViewGoBackOrForward webview steps =\n {#call web_view_go_back_or_forward#} \n (toWebView webview)\n (fromIntegral steps)\n\n-- |Determines whether or not it is currently possible to redo the last editing command in the view\nwebViewCanRedo :: \n WebViewClass self => self\n -> IO Bool\nwebViewCanRedo webview = \n liftM toBool $\n {#call web_view_can_redo#} (toWebView webview)\n-- |Determines whether or not it is currently possible to undo the last editing command in the view\nwebViewCanUndo :: \n WebViewClass self => self\n -> IO Bool\nwebViewCanUndo webview =\n liftM toBool $\n {#call web_view_can_undo#} (toWebView webview)\n\n-- |Redoes the last editing command in the view, if possible.\nwebViewRedo :: \n WebViewClass self => self\n -> IO()\nwebViewRedo webview =\n {#call web_view_redo#} (toWebView webview)\n\n-- |Undoes the last editing command in the view, if possible.\nwebViewUndo :: \n WebViewClass self => self\n -> IO()\nwebViewUndo webview =\n {#call web_view_undo#} (toWebView webview)\n\n-- | Returns whether or not a @mimetype@ can be displayed using this view.\nwebViewCanShowMimeType :: \n WebViewClass self => self\n -> String -- ^ @mimetype@ - a MIME type\n -> IO Bool -- ^ True if the @mimetype@ can be displayed, otherwise False\nwebViewCanShowMimeType webview mime =\n withCString mime $ \\mimePtr ->\n liftM toBool $\n {#call web_view_can_show_mime_type#}\n (toWebView webview)\n mimePtr\n\n-- | Returns whether the user is allowed to edit the document.\nwebViewGetEditable :: \n WebViewClass self => self\n -> IO Bool\nwebViewGetEditable webview =\n liftM toBool $\n {#call web_view_get_editable#} (toWebView webview)\n\n-- | Sets whether allows the user to edit its HTML document.\nwebViewSetEditable :: \n WebViewClass self => self\n -> Bool\n -> IO ()\nwebViewSetEditable webview editable =\n {#call web_view_set_editable#} (toWebView webview) (fromBool editable)\n\n-- | Returns whether 'WebView' is in view source mode\nwebViewGetViewSourceMode :: \n WebViewClass self => self\n -> IO Bool\nwebViewGetViewSourceMode webview =\n liftM toBool $\n {#call web_view_get_view_source_mode#} (toWebView webview)\n\n-- | Set whether the view should be in view source mode. \n--\n-- Setting this mode to TRUE before loading a URI will display \n-- the source of the web page in a nice and readable format.\nwebViewSetViewSourceMode :: \n WebViewClass self => self\n -> Bool\n -> IO ()\nwebViewSetViewSourceMode webview mode =\n {#call web_view_set_view_source_mode#} (toWebView webview) (fromBool mode)\n\n-- | Returns whether the 'WebView' has a transparent background\nwebViewGetTransparent :: \n WebViewClass self => self\n -> IO Bool\nwebViewGetTransparent webview =\n liftM toBool $\n {#call web_view_get_transparent#} (toWebView webview)\n-- |Sets whether the WebKitWebView has a transparent background.\n--\n-- Pass False to have the 'WebView' draw a solid background (the default), \n-- otherwise pass True.\nwebViewSetTransparent :: \n WebViewClass self => self\n -> Bool\n -> IO ()\nwebViewSetTransparent webview trans =\n {#call web_view_set_transparent#} (toWebView webview) (fromBool trans)\n\n-- |Obtains the 'WebInspector' associated with the 'WebView'\nwebViewGetInspector :: \n WebViewClass self => self\n -> IO WebInspector\nwebViewGetInspector webview =\n makeNewGObject mkWebInspector $ {#call web_view_get_inspector#} (toWebView webview)\n\n-- |Requests loading of the specified asynchronous client request.\n--\n-- Creates a provisional data source that will transition to a committed data source once\n-- any data has been received. \n-- use 'webViewStopLoading' to stop the load.\n\nwebViewLoadRequest :: \n (WebViewClass self, NetworkRequestClass request) => self\n -> request\n -> IO()\nwebViewLoadRequest webview request =\n {#call web_view_load_request#} (toWebView webview) (toNetworkRequest request)\n\n\n\n\n-- |Returns the zoom level of 'WebView'\n--\n-- i.e. the factor by which elements in the page are scaled with respect to their original size.\n\nwebViewGetZoomLevel :: \n WebViewClass self => self\n -> IO Float -- ^ the zoom level of 'WebView'\nwebViewGetZoomLevel webview =\n liftM realToFrac $\n\t{#call web_view_get_zoom_level#} (toWebView webview)\n\n-- |Sets the zoom level of 'WebView'.\nwebViewSetZoomLevel :: \n WebViewClass self => self \n -> Float -- ^ @zoom_level@ - the new zoom level \n -> IO ()\nwebViewSetZoomLevel webview zlevel = \n {#call web_view_set_zoom_level#} (toWebView webview) (realToFrac zlevel)\n\n-- |Loading the @content@ string as html. The URI passed in base_uri has to be an absolute URI.\n\nwebViewLoadHtmlString :: \n WebViewClass self => self \n -> String -- ^ @content@ - the html string\n -> String -- ^ @base_uri@ - the base URI\n -> IO()\nwebViewLoadHtmlString webview htmlstr url =\n withCString htmlstr $ \\htmlPtr ->\n withCString url $ \\urlPtr ->\n {#call web_view_load_html_string#} (toWebView webview) htmlPtr urlPtr\n\n-- | Requests loading of the given @content@ with the specified @mime_type@, @encoding@ and @base_uri@.\n-- \n-- If @mime_type@ is @Nothing@, \"text\/html\" is assumed.\n--\n-- If @encoding@ is @Nothing@, \"UTF-8\" is assumed.\n--\nwebViewLoadString :: \n WebViewClass self => self \n -> String -- ^ @content@ - the content string to be loaded.\n -> (Maybe String) -- ^ @mime_type@ - the MIME type or @Nothing@. \n -> (Maybe String) -- ^ @encoding@ - the encoding or @Nothing@.\n -> String -- ^ @base_uri@ - the base URI for relative locations.\n -> IO()\nwebViewLoadString webview content mimetype encoding baseuri = \n withCString content $ \\contentPtr ->\n maybeWith withCString mimetype $ \\mimetypePtr ->\n maybeWith withCString encoding $ \\encodingPtr ->\n withCString baseuri $ \\baseuriPtr ->\n {#call web_view_load_string#} \n (toWebView webview)\n contentPtr\n mimetypePtr\n encodingPtr\n baseuriPtr\n\n-- |Returns the 'WebView' document title\nwebViewGetTitle :: \n WebViewClass self => self\n -> IO (Maybe String) -- ^ the title of 'WebView' or Nothing in case of failed.\nwebViewGetTitle webview =\n {#call web_view_get_title#} (toWebView webview) >>= maybePeek peekUTFString\n\n-- |Returns the current URI of the contents displayed by the 'WebView'\nwebViewGetUri :: \n WebViewClass self => self\n -> IO (Maybe String) -- ^ the URI of 'WebView' or Nothing in case of failed.\nwebViewGetUri webview = \n {#call web_view_get_uri#} (toWebView webview) >>= maybePeek peekUTFString\n\n\n-- | Stops and pending loads on the given data source.\nwebViewStopLoading :: \n WebViewClass self => self\n -> IO ()\nwebViewStopLoading webview = \n {#call web_view_stop_loading#} (toWebView webview)\n\n-- | Reloads the 'WebView'\nwebViewReload :: \n WebViewClass self => self\n -> IO ()\nwebViewReload webview = \n {#call web_view_reload#} (toWebView webview)\n\n-- | Reloads the 'WebView' without using any cached data.\nwebViewReloadBypassCache :: \n WebViewClass self => self\n -> IO()\nwebViewReloadBypassCache webview = \n {#call web_view_reload_bypass_cache#} (toWebView webview)\n\n-- | Increases the zoom level of 'WebView'.\nwebViewZoomIn :: \n WebViewClass self => self\n -> IO()\nwebViewZoomIn webview = \n {#call web_view_zoom_in#} (toWebView webview)\n\n-- | Decreases the zoom level of 'WebView'.\nwebViewZoomOut :: \n WebViewClass self => self\n -> IO()\nwebViewZoomOut webview = \n {#call web_view_zoom_out#} (toWebView webview)\n\n-- | Looks for a specified string inside 'WebView'\nwebViewSearchText :: \n WebViewClass self => self\n -> String -- ^ @text@ - a string to look for\n -> Bool -- ^ @case_sensitive@ - whether to respect the case of text\n -> Bool -- ^ @forward@ - whether to find forward or not\n -> Bool -- ^ @wrap@ - whether to continue looking at beginning\n -- after reaching the end\n -> IO Bool -- ^ True on success or False on failure\nwebViewSearchText webview text case_sensitive forward wrap =\n withCString text $ \\textPtr ->\n\tliftM toBool $\n {#call web_view_search_text#} \n (toWebView webview)\n textPtr\n (fromBool case_sensitive) \n (fromBool forward) \n (fromBool wrap)\n\n-- |Attempts to highlight all occurances of string inside 'WebView'\nwebViewMarkTextMatches :: \n WebViewClass self => self\n -> String -- ^ @string@ - a string to look for\n -> Bool -- ^ @case_sensitive@ - whether to respect the case of text\n -> Int -- ^ @limit@ - the maximum number of strings to look for or 0 for all\n -> IO Int -- ^ the number of strings highlighted\nwebViewMarkTextMatches webview text case_sensitive limit = \n withCString text $ \\textPtr ->\n\tliftM fromIntegral $ \n {#call web_view_mark_text_matches#} \n (toWebView webview)\n textPtr\n (fromBool case_sensitive)\n (fromIntegral limit)\n\n-- | Move the cursor in view as described by step and count.\nwebViewMoveCursor ::\n WebViewClass self => self\n -> MovementStep\n -> Int\n -> IO () \nwebViewMoveCursor webview step count =\n {#call web_view_move_cursor#} (toWebView webview) (fromIntegral $ fromEnum step) (fromIntegral count)\n\n-- | Removes highlighting previously set by 'webViewMarkTextMarches'\nwebViewUnMarkTextMatches :: \n WebViewClass self => self\n -> IO ()\nwebViewUnMarkTextMatches webview = \n {#call web_view_unmark_text_matches#} (toWebView webview)\n\n-- | Highlights text matches previously marked by 'webViewMarkTextMatches'\nwebViewSetHighlightTextMatches :: \n WebViewClass self => self\n -> Bool -- ^ @highlight@ - whether to highlight text matches \n -> IO ()\nwebViewSetHighlightTextMatches webview highlight =\n {#call web_view_set_highlight_text_matches#} \n (toWebView webview)\n (fromBool highlight)\n\n-- | Execute the script specified by @script@\nwebViewExecuteScript :: \n WebViewClass self => self \n -> String -- ^ @script@ - script to be executed\n -> IO()\nwebViewExecuteScript webview script =\n withCString script $ \\scriptPtr ->\n\t{#call web_view_execute_script#} (toWebView webview) scriptPtr\n\n-- | Determines whether can cuts the current selection\n-- inside 'WebView' to the clipboard\nwebViewCanCutClipboard :: \n WebViewClass self => self\n -> IO Bool\nwebViewCanCutClipboard webview = \n liftM toBool $ {#call web_view_can_cut_clipboard#} (toWebView webview)\n\n-- | Determines whether can copies the current selection\n-- inside 'WebView' to the clipboard\nwebViewCanCopyClipboard :: WebViewClass self => self -> IO Bool\nwebViewCanCopyClipboard webview = \n liftM toBool $ {#call web_view_can_copy_clipboard#} (toWebView webview)\n\n-- | Determines whether can pastes the current contents of the clipboard\n-- to the 'WebView'\nwebViewCanPasteClipboard :: WebViewClass self => self -> IO Bool\nwebViewCanPasteClipboard webview = \n liftM toBool $ {#call web_view_can_paste_clipboard#} (toWebView webview)\n\n-- | Cuts the current selection inside 'WebView' to the clipboard.\nwebViewCutClipboard :: WebViewClass self => self -> IO()\nwebViewCutClipboard webview = \n {#call web_view_cut_clipboard#} (toWebView webview)\n\n-- | Copies the current selection inside 'WebView' to the clipboard.\nwebViewCopyClipboard :: WebViewClass self => self -> IO()\nwebViewCopyClipboard webview = \n {#call web_view_copy_clipboard#} (toWebView webview)\n\n-- | Pastes the current contents of the clipboard to the 'WebView'\nwebViewPasteClipboard :: WebViewClass self => self -> IO()\nwebViewPasteClipboard webview = \n {#call web_view_paste_clipboard#} (toWebView webview)\n\n-- | Deletes the current selection inside the 'WebView'\nwebViewDeleteSelection :: WebViewClass self => self -> IO ()\nwebViewDeleteSelection webview = \n {#call web_view_delete_selection#} (toWebView webview)\n\n-- | Determines whether text was selected\nwebViewHasSelection :: WebViewClass self => self -> IO Bool\nwebViewHasSelection webview = \n liftM toBool $ {#call web_view_has_selection#} (toWebView webview)\n\n-- | Attempts to select everything inside the 'WebView'\nwebViewSelectAll :: WebViewClass self => self -> IO ()\nwebViewSelectAll webview = \n {#call web_view_select_all#} (toWebView webview)\n\n-- | Returns whether the zoom level affects only text or all elements.\nwebViewGetFullContentZoom :: \n WebViewClass self => self \n -> IO Bool -- ^ False if only text should be scaled(the default)\n -- True if the full content of the view should be scaled.\nwebViewGetFullContentZoom webview = \n liftM toBool $ {#call web_view_get_full_content_zoom#} (toWebView webview)\n\n-- | Sets whether the zoom level affects only text or all elements.\nwebViewSetFullContentZoom :: \n WebViewClass self => self \n -> Bool -- ^ @full_content_zoom@ - False if only text should be scaled (the default)\n -- True if the full content of the view should be scaled. \n -> IO ()\nwebViewSetFullContentZoom webview full =\n {#call web_view_set_full_content_zoom#} (toWebView webview) (fromBool full)\n\n-- | Returns the default encoding of the 'WebView'\nwebViewGetEncoding :: \n WebViewClass self => self \n -> IO (Maybe String) -- ^ the default encoding or @Nothing@ in case of failed\nwebViewGetEncoding webview =\n {#call web_view_get_encoding#} (toWebView webview) >>= maybePeek peekUTFString\n\n-- | Sets the current 'WebView' encoding, \n-- without modifying the default one, and reloads the page\nwebViewSetCustomEncoding :: \n WebViewClass self => self\n -> (Maybe String) -- ^ @encoding@ - the new encoding, \n -- or @Nothing@ to restore the default encoding. \n -> IO ()\nwebViewSetCustomEncoding webview encoding = \n maybeWith withCString encoding $ \\encodingPtr ->\n\t{#call web_view_set_custom_encoding#} (toWebView webview) encodingPtr\n\n-- | Returns the current encoding of 'WebView',not the default encoding.\nwebViewGetCustomEncoding :: \n WebViewClass self => self \n -> IO (Maybe String) -- ^ the current encoding string\n -- or @Nothing@ if there is none set.\nwebViewGetCustomEncoding webview = \n {#call web_view_get_custom_encoding#} (toWebView webview) >>= maybePeek peekUTFString\n\n-- | Determines the current status of the load.\nwebViewGetLoadStatus :: \n WebViewClass self => self \n -> IO LoadStatus -- ^ the current load status:'LoadStatus'\nwebViewGetLoadStatus webview = \n liftM (toEnum . fromIntegral) $ {#call web_view_get_load_status#} (toWebView webview)\n\n-- | Determines the current progress of the load\nwebViewGetProgress :: \n WebViewClass self => self \n -> IO Double -- ^ the load progress\nwebViewGetProgress webview =\n liftM realToFrac $ {#call web_view_get_progress#} (toWebView webview)\n\n-- | This function returns the list of targets this 'WebView' can provide for clipboard copying and as DND source. \n-- The targets in the list are added with values from the 'WebViewTargetInfo' enum, \n-- using 'targetListAdd' and 'targetListAddTextTargets'.\nwebViewGetCopyTargetList ::\n WebViewClass self => self \n -> IO (Maybe TargetList)\nwebViewGetCopyTargetList webview = do\n tlPtr <- {#call web_view_get_copy_target_list#} (toWebView webview)\n if tlPtr==nullPtr then return Nothing else liftM Just (mkTargetList tlPtr)\n\n-- | This function returns the list of targets this 'WebView' can provide for clipboard pasteing and as DND source. \n-- The targets in the list are added with values from the 'WebViewTargetInfo' enum, \n-- using 'targetListAdd' and 'targetListAddTextTargets'.\nwebViewGetPasteTargetList ::\n WebViewClass self => self \n -> IO (Maybe TargetList)\nwebViewGetPasteTargetList webview = do\n tlPtr <- {#call web_view_get_paste_target_list#} (toWebView webview)\n if tlPtr==nullPtr then return Nothing else liftM Just (mkTargetList tlPtr)\n\n-- * Attibutes\n\n-- | Zoom level of the 'WebView' instance\nwebViewZoomLevel :: WebViewClass self => Attr self Float\nwebViewZoomLevel = newAttr\n webViewGetZoomLevel\n webViewSetZoomLevel\n\n-- | Whether the full content is scaled when zooming\n--\n-- Default value: False\nwebViewFullContentZoom :: WebViewClass self => Attr self Bool\nwebViewFullContentZoom = newAttr\n webViewGetFullContentZoom\n webViewSetFullContentZoom\n\n-- | The default encoding of the 'WebView' instance\n--\n-- Default value: @Nothing@\nwebViewEncoding :: WebViewClass self => ReadAttr self (Maybe String)\nwebViewEncoding = readAttr webViewGetEncoding\n\n-- | Determines the current status of the load.\n--\n-- Default value: @LoadFinished@\nwebViewLoadStatus :: WebViewClass self => ReadAttr self LoadStatus\nwebViewLoadStatus = readAttr webViewGetLoadStatus\n\n-- |Determines the current progress of the load\n--\n-- Default Value: 1\nwebViewProgress :: WebViewClass self => ReadAttr self Double\nwebViewProgress = readAttr webViewGetProgress\n\n\n-- | The associated webSettings of the 'WebView' instance\nwebViewWebSettings :: WebViewClass self => Attr self WebSettings\nwebViewWebSettings = newAttr\n webViewGetWebSettings\n webViewSetWebSettings\n\n\n-- | Title of the 'WebView' instance\nwebViewTitle :: WebViewClass self => ReadAttr self (Maybe String)\nwebViewTitle = readAttr webViewGetTitle\n\n-- | The associated webInspector instance of the 'WebView'\nwebViewInspector :: WebViewClass self => ReadAttr self WebInspector\nwebViewInspector = readAttr webViewGetInspector\n\n\n-- | The custom encoding of the 'WebView' instance\n--\n-- Default value: @Nothing@\nwebViewCustomEncoding :: WebViewClass self => Attr self (Maybe String)\nwebViewCustomEncoding = newAttr\n webViewGetCustomEncoding\n webViewSetCustomEncoding\n\n-- | view source mode of the 'WebView' instance\nwebViewViewSourceMode :: WebViewClass self => Attr self Bool\nwebViewViewSourceMode = newAttr\n webViewGetViewSourceMode\n webViewSetViewSourceMode\n\n-- | transparent background of the 'WebView' instance\nwebViewTransparent :: WebViewClass self => Attr self Bool\nwebViewTransparent = newAttr\n webViewGetTransparent\n webViewSetTransparent\n\n-- | Whether content of the 'WebView' can be modified by the user\n--\n-- Default value: @False@\nwebViewEditable :: WebViewClass self => Attr self Bool\nwebViewEditable = newAttr\n webViewGetEditable\n webViewSetEditable\n\n-- | Returns the current URI of the contents displayed by the @web_view@.\n--\n-- Default value: Nothing\nwebViewUri :: WebViewClass self => ReadAttr self (Maybe String)\nwebViewUri = readAttr webViewGetUri\n\n-- | The list of targets this web view supports for clipboard copying.\nwebViewCopyTargetList :: WebViewClass self => ReadAttr self (Maybe TargetList)\nwebViewCopyTargetList = readAttr webViewGetCopyTargetList\n\n-- | The list of targets this web view supports for clipboard pasteing.\nwebViewPasteTargetList :: WebViewClass self => ReadAttr self (Maybe TargetList)\nwebViewPasteTargetList = readAttr webViewGetPasteTargetList\n\n-- | An associated 'WebWindowFeatures' instance.\nwebViewWindowFeatures :: WebViewClass self => Attr self WebWindowFeatures\nwebViewWindowFeatures = \n newAttrFromObjectProperty \"window-features\"\n {#call pure webkit_web_window_features_get_type#}\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n-- | The URI for the favicon for the WebKitWebView.\n-- \n-- Default value: 'Nothing'\n-- \n-- * Since 1.1.18\nwebViewIconUri :: WebViewClass self => ReadAttr self String\nwebViewIconUri = readAttrFromStringProperty \"icon-uri\"\n#endif\n\n-- * Signals\n\n-- | When Document title changed, this signal is emitted.\n--\n-- It can be used to set the Application 'Window' title.\n--\n-- the user function signature is (WebFrame->String->IO())\n--\n-- webframe - which 'WebFrame' changes the document title.\n--\n-- title - current title string.\ntitleChanged :: WebViewClass self => Signal self ( WebFrame -> String -> IO() )\ntitleChanged = \n Signal (connect_OBJECT_STRING__NONE \"title-changed\")\n\n\n-- | When the cursor is over a link, this signal is emitted.\n-- \n-- the user function signature is (Maybe String -> Maybe String -> IO () )\n-- \n-- title - the link's title or @Nothing@ in case of failure.\n--\n-- uri - the URI the link points to or @Nothing@ in case of failure.\nhoveringOverLink :: WebViewClass self => Signal self (String -> String -> IO())\nhoveringOverLink =\n Signal (connect_STRING_STRING__NONE \"hovering-over-link\")\n\n-- | When a 'WebFrame' begins to load, this signal is emitted\nloadStarted :: WebViewClass self => Signal self (WebFrame -> IO())\nloadStarted = Signal (connect_OBJECT__NONE \"load-started\")\n\n-- | When a 'WebFrame' loaded the first data, this signal is emitted\nloadCommitted :: WebViewClass self => Signal self (WebFrame -> IO())\nloadCommitted = Signal (connect_OBJECT__NONE \"load-committed\")\n\n\n-- | When the global progress changed, this signal is emitted\n--\n-- the global progress will be passed back to user function\nprogressChanged :: WebViewClass self => Signal self (Int-> IO())\nprogressChanged = \n Signal (connect_INT__NONE \"load-progress-changed\")\n\n-- | When loading finished, this signal is emitted\nloadFinished :: WebViewClass self => Signal self (WebFrame -> IO())\nloadFinished = \n Signal (connect_OBJECT__NONE \"load-finished\")\n\n-- | When An error occurred while loading. \n--\n-- By default, if the signal is not handled,\n-- the WebView will display a stock error page. \n--\n-- You need to handle the signal\n-- if you want to provide your own error page.\n-- \n-- The URI that triggered the error and the 'GError' will be passed back to user function.\nloadError :: WebViewClass self => Signal self (WebFrame -> String -> GError -> IO Bool)\nloadError = Signal (connect_OBJECT_STRING_BOXED__BOOL \"load-error\" peek)\n\ncreateWebView :: WebViewClass self => Signal self (WebFrame -> IO WebView)\ncreateWebView = Signal (connect_OBJECT__OBJECTPTR \"create-web-view\")\n\n-- | Emitted when closing a WebView is requested. \n--\n-- This occurs when a call is made from JavaScript's window.close function. \n-- The default signal handler does not do anything. \n-- It is the owner's responsibility to hide or delete the 'WebView', if necessary.\n-- \n-- User function should return True to stop the handlers from being invoked for the event \n-- or False to propagate the event furter\ncloseWebView :: WebViewClass self => Signal self (IO Bool)\ncloseWebView = \n Signal (connect_NONE__BOOL \"close-web-view\")\n\n-- | A JavaScript console message was created.\nconsoleMessage :: WebViewClass self => Signal self (String -> String -> Int -> String -> IO Bool)\nconsoleMessage = Signal (connect_STRING_STRING_INT_STRING__BOOL \"console-message\")\n\n-- | The 'copyClipboard' signal is a keybinding signal which gets emitted to copy the selection to the clipboard.\n--\n-- The default bindings for this signal are Ctrl-c and Ctrl-Insert.\ncopyClipboard :: WebViewClass self => Signal self (IO ())\ncopyClipboard = Signal (connect_NONE__NONE \"copy-clipboard\")\n\n-- | The 'cutClipboard' signal is a keybinding signal which gets emitted to cut the selection to the clipboard.\n--\n-- The default bindings for this signal are Ctrl-x and Shift-Delete.\ncutClipboard :: WebViewClass self => Signal self (IO ())\ncutClipboard = Signal (connect_NONE__NONE \"cut-clipboard\")\n\n-- | The 'pasteClipboard' signal is a keybinding signal which gets emitted to paste the contents of the clipboard into the Web view.\n--\n-- The default bindings for this signal are Ctrl-v and Shift-Insert.\npasteClipboard :: WebViewClass self => Signal self (IO ())\npasteClipboard = Signal (connect_NONE__NONE \"paste-clipboard\")\n\n-- | When a context menu is about to be displayed this signal is emitted.\npopulatePopup :: WebViewClass self => Signal self (Menu -> IO ())\npopulatePopup = Signal (connect_OBJECT__NONE \"populate-popup\")\n\n-- | Emitted when printing is requested by the frame, usually because of a javascript call. \n-- When handling this signal you should call 'webFramePrintFull' or 'webFramePrint' to do the actual printing.\n--\n-- The default handler will present a print dialog and carry a print operation. \n-- Notice that this means that if you intend to ignore a print\n-- request you must connect to this signal, and return True.\nprintRequested :: WebViewClass self => Signal self (WebFrame -> IO Bool)\nprintRequested = Signal (connect_OBJECT__BOOL \"print-requested\")\n\n-- | A JavaScript alert dialog was created.\nscriptAlert :: WebViewClass self => Signal self (WebFrame -> String -> IO Bool)\nscriptAlert = Signal (connect_OBJECT_STRING__BOOL \"scriptAlert\")\n\n-- | A JavaScript confirm dialog was created, providing Yes and No buttons.\nscriptConfirm :: WebViewClass self => Signal self (WebFrame -> String -> IO Bool)\nscriptConfirm = Signal (connect_OBJECT_STRING__BOOL \"script-confirm\")\n\n-- | A JavaScript prompt dialog was created, providing an entry to input text.\nscriptPrompt :: WebViewClass self => Signal self (WebFrame -> String -> String -> IO Bool)\nscriptPrompt = Signal (connect_OBJECT_STRING_STRING__BOOL \"script-prompt\")\n\n-- | When status-bar text changed, this signal will emitted.\nstatusBarTextChanged :: WebViewClass self => Signal self (String -> IO ())\nstatusBarTextChanged = Signal (connect_STRING__NONE \"status-bar-text-changed\")\n\n\n\n-- | The 'selectAll' signal is a keybinding signal which gets emitted to select the complete contents of the text view.\n-- \n-- The default bindings for this signal is Ctrl-a.\nselectAll :: WebViewClass self => Signal self (IO ())\nselectAll = Signal (connect_NONE__NONE \"select-all\")\n\n-- | When selection changed, this signal is emitted.\nselectionChanged :: WebViewClass self => Signal self (IO ())\nselectionChanged = Signal (connect_NONE__NONE \"selection-changed\")\n\n-- | When set scroll adjustments, this signal is emitted.\nsetScrollAdjustments :: WebViewClass self => Signal self (Adjustment -> Adjustment -> IO ())\nsetScrollAdjustments = Signal (connect_OBJECT_OBJECT__NONE \"set-scroll-adjustments\")\n\n-- | The 'databaseQuotaExceeded' signal will be emitted when a Web Database exceeds the quota of its security origin. \n-- This signal may be used to increase the size of the quota before the originating operation fails.\ndatabaseQuotaExceeded :: WebViewClass self => Signal self (WebFrame -> WebDatabase -> IO ())\ndatabaseQuotaExceeded = Signal (connect_OBJECT_OBJECT__NONE \"database-quota-exceeded\")\n\n-- | When document loading finished, this signal is emitted\ndocumentLoadFinished :: WebViewClass self => Signal self (WebFrame -> IO ())\ndocumentLoadFinished = Signal (connect_OBJECT__NONE \"document-load-finished\")\n\n\n-- | Emitted after new 'WebView' instance had been created in 'onCreateWebView' user function\n-- when the new 'WebView' should be displayed to the user.\n-- \n-- All the information about how the window should look, \n-- including size,position,whether the location, status and scroll bars should be displayed, \n-- is ready set.\nwebViewReady:: WebViewClass self => Signal self (IO Bool)\nwebViewReady =\n Signal (connect_NONE__BOOL \"web-view-ready\")\n\n-- | Emitted after A new 'Download' is being requested. \n--\n-- By default, if the signal is not handled, the download is cancelled.\n-- \n-- Notice that while handling this signal you must set the target URI using 'downloadSetDestinationUri'\n-- \n-- If you intend to handle downloads yourself, return False in user function.\ndownloadRequested :: WebViewClass self => Signal self (Download -> IO Bool)\ndownloadRequested =\n Signal (connect_OBJECT__BOOL \"download-requested\")\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n-- | Emitted after Icon loaded\niconLoaded :: WebViewClass self => Signal self (IO ())\niconLoaded =\n Signal (connect_NONE__NONE \"icon-loaded\")\n#endif\n\n-- | The \"redo\" signal is a keybinding signal which gets emitted to redo the last editing command.\n--\n-- The default binding for this signal is Ctrl-Shift-z\nredo :: WebViewClass self => Signal self (IO ())\nredo =\n Signal (connect_NONE__NONE \"redo\")\n\n-- | The \"undo\" signal is a keybinding signal which gets emitted to undo the last editing command.\n--\n-- The default binding for this signal is Ctrl-z\nundo :: WebViewClass self => Signal self (IO ())\nundo =\n Signal (connect_NONE__NONE \"undo\")\n\n-- | Decide whether or not to display the given MIME type. \n-- If this signal is not handled, the default behavior is to show the content of the\n-- requested URI if WebKit can show this MIME type and the content disposition is not a download; \n-- if WebKit is not able to show the MIME type nothing happens.\n--\n-- Notice that if you return True, meaning that you handled the signal, \n-- you are expected to be aware of the \"Content-Disposition\" header. \n-- A value of \"attachment\" usually indicates a download regardless of the MIME type, \n-- see also soupMessageHeadersGetContentDisposition'\n-- And you must call 'webPolicyDecisionIgnore', 'webPolicyDecisionDownload', or 'webPolicyDecisionUse' \n-- on the 'webPolicyDecision' object.\nmimeTypePolicyDecisionRequested :: WebViewClass self => Signal self (WebFrame -> NetworkRequest -> String -> WebPolicyDecision -> IO Bool)\nmimeTypePolicyDecisionRequested = Signal (connect_OBJECT_OBJECT_STRING_OBJECT__BOOL \"mime-type-policy-decision-requested\")\n\n-- | The 'moveCursor' will be emitted to apply the cursor movement described by its parameters to the view.\nmoveCursor :: WebViewClass self => Signal self (MovementStep -> Int -> IO Bool)\nmoveCursor = Signal (connect_ENUM_INT__BOOL \"move-cursor\")\n\n-- | Emitted when frame requests a navigation to another page. \n-- If this signal is not handled, the default behavior is to allow the navigation.\n--\n-- Notice that if you return True, meaning that you handled the signal, \n-- you are expected to be aware of the \"Content-Disposition\" header. \n-- A value of \"attachment\" usually indicates a download regardless of the MIME type, \n-- see also soupMessageHeadersGetContentDisposition'\n-- And you must call 'webPolicyDecisionIgnore', 'webPolicyDecisionDownload', or 'webPolicyDecisionUse' \n-- on the 'webPolicyDecision' object.\nnavigationPolicyDecisionRequested :: WebViewClass self => Signal self (WebFrame -> NetworkRequest -> WebNavigationAction -> WebPolicyDecision -> IO Bool)\nnavigationPolicyDecisionRequested = Signal (connect_OBJECT_OBJECT_OBJECT_OBJECT__BOOL \"navigation-policy-decision-requested\")\n\n-- | Emitted when frame requests opening a new window. \n-- With this signal the browser can use the context of the request to decide about the new window. \n-- If the request is not handled the default behavior is to allow opening the new window to load the URI, \n-- which will cause a 'createWebView' signal emission where the browser handles the new window action \n-- but without information of the context that caused the navigation. \n-- The following 'navigationPolicyDecisionRequested' emissions will load the page \n-- after the creation of the new window just with the information of this new navigation context, \n-- without any information about the action that made this new window to be opened.\n--\n-- Notice that if you return True, meaning that you handled the signal, \n-- you are expected to be aware of the \"Content-Disposition\" header. \n-- A value of \"attachment\" usually indicates a download regardless of the MIME type, \n-- see also soupMessageHeadersGetContentDisposition'\n-- And you must call 'webPolicyDecisionIgnore', 'webPolicyDecisionDownload', or 'webPolicyDecisionUse' \n-- on the 'webPolicyDecision' object.\nnewWindowPolicyDecisionRequested :: WebViewClass self => Signal self (WebFrame -> NetworkRequest -> WebNavigationAction -> WebPolicyDecision -> IO Bool)\nnewWindowPolicyDecisionRequested = Signal (connect_OBJECT_OBJECT_OBJECT_OBJECT__BOOL \"new-window-policy-decision-requested\")\n\n-- | Emitted when a request is about to be sent. \n-- You can modify the request while handling this signal. \n-- You can set the URI in the 'NetworkRequest' object itself, \n-- and add\/remove\/replace headers using the SoupMessage object it carries, \n-- if it is present. See 'networkRequestGetMessage'. \n-- Setting the request URI to \"about:blank\" will effectively cause the request to load nothing, \n-- and can be used to disable the loading of specific resources.\n--\n-- Notice that information about an eventual redirect is available in response's SoupMessage, \n-- not in the SoupMessage carried by the request.\n-- If response is NULL, then this is not a redirected request.\n--\n-- The 'WebResource' object will be the same throughout all the lifetime of the resource, \n-- but the contents may change from inbetween signal emissions.\nresourceRequestStarting :: WebViewClass self => Signal self (WebFrame -> WebResource -> NetworkRequest -> NetworkResponse -> IO ())\nresourceRequestStarting = Signal (connect_OBJECT_OBJECT_OBJECT_OBJECT__NONE \"resource-request-starting\")\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"3d4c9b7c01c11d8b7e4f728420c1bb76b8f1dc9b","subject":"cosmetic changes","message":"cosmetic changes\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/OSGeo\/GDAL\/Internal.chs","new_file":"src\/OSGeo\/GDAL\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nmodule OSGeo.GDAL.Internal (\n HasDataset\n , HasBand\n , HasWritebaleBand\n , HasDatatype\n , Datatype (..)\n , GDALException\n , isGDALException\n , Geotransform (..)\n , IOVector\n , DriverOptions\n , MajorObject\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Driver\n , DriverName\n , ColorTable\n , RasterAttributeTable\n , GComplex (..)\n\n , setQuietErrorHandler\n , unDataset\n , unBand\n\n , withAllDriversRegistered\n , registerAllDrivers\n , destroyDriverManager\n , driverByName\n , create\n , create'\n , createMem\n , flushCache\n , openReadOnly\n , openReadWrite\n , createCopy\n\n , datatypeSize\n , datatypeByName\n , datatypeUnion\n , datatypeIsComplex\n\n , datasetSize\n , datasetProjection\n , setDatasetProjection\n , datasetGeotransform\n , setDatasetGeotransform\n , datasetBandCount\n\n , withBand\n , bandDatatype\n , bandBlockSize\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , readBand\n , readBand'\n , readBandBlock\n , writeBand\n , writeBand'\n , writeBandBlock\n , fillBand\n\n , toComplex\n , fromComplex\n\n -- Internal Util\n , throwIfError\n , withDataset\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception (bracket, throw, Exception(..), SomeException,\n finally)\nimport Control.Monad (liftM, foldM)\n\nimport Data.Int (Int16, Int32)\nimport qualified Data.Complex as Complex\nimport Data.Maybe (isJust)\nimport Data.Typeable (Typeable, typeOf)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector, unsafeFromForeignPtr0, unsafeToForeignPtr0)\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (ForeignPtr, withForeignPtr, newForeignPtr\n ,mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport OSGeo.Util\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\ntype DriverName = String\n\n\ndata GDALException = GDALException Error String\n deriving (Show, Typeable)\n\ninstance Exception GDALException\n\nisGDALException :: SomeException -> Bool\nisGDALException e = isJust (fromException e :: Maybe GDALException)\n\n{# enum CPLErr as Error {upcaseFirstLetter} deriving (Eq,Show) #}\n\n\ntype ErrorHandler = CInt -> CInt -> CString -> IO ()\n\nforeign import ccall \"cpl_error.h &CPLQuietErrorHandler\"\n c_quietErrorHandler :: FunPtr ErrorHandler\n\nforeign import ccall \"cpl_error.h CPLSetErrorHandler\"\n c_setErrorHandler :: FunPtr ErrorHandler -> IO (FunPtr ErrorHandler)\n\nsetQuietErrorHandler :: IO ()\nsetQuietErrorHandler = setErrorHandler c_quietErrorHandler\n\nsetErrorHandler :: FunPtr ErrorHandler -> IO ()\nsetErrorHandler h = c_setErrorHandler h >>= (\\_->return ())\n\n\nthrowIfError :: String -> IO CInt -> IO ()\nthrowIfError msg act = do\n e <- liftM toEnumC act\n case e of\n CE_None -> return ()\n e' -> throw $ GDALException e' msg\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\ninstance Show Datatype where\n show = getDatatypeName\n\n{# fun pure unsafe GDALGetDataTypeSize as datatypeSize\n { fromEnumC `Datatype' } -> `Int' #}\n\n{# fun pure unsafe GDALDataTypeIsComplex as datatypeIsComplex\n { fromEnumC `Datatype' } -> `Bool' #}\n\n{# fun pure unsafe GDALGetDataTypeName as getDatatypeName\n { fromEnumC `Datatype' } -> `String' #}\n\n{# fun pure unsafe GDALGetDataTypeByName as datatypeByName\n { `String' } -> `Datatype' toEnumC #}\n\n{# fun pure unsafe GDALDataTypeUnion as datatypeUnion\n { fromEnumC `Datatype', fromEnumC `Datatype' } -> `Datatype' toEnumC #}\n\n\n{# enum GDALAccess as Access {upcaseFirstLetter} deriving (Eq, Show) #}\n\n{# enum GDALRWFlag as RwFlag {upcaseFirstLetter} deriving (Eq, Show) #}\n\n{#pointer GDALMajorObjectH as MajorObject newtype#}\n{#pointer GDALDatasetH as Dataset foreign newtype nocode#}\n\ndata ReadOnly\ndata ReadWrite\nnewtype Dataset a t = Dataset (ForeignPtr (Dataset a t), Mutex)\n\nunDataset (Dataset (d, _)) = d\n\ntype RODataset = Dataset ReadOnly\ntype RWDataset = Dataset ReadWrite\nwithDataset, withDataset' :: (Dataset a t) -> (Ptr (Dataset a t) -> IO b) -> IO b\nwithDataset ds@(Dataset (_, m)) fun = withMutex m $ withDataset' ds fun\n\nwithDataset' (Dataset (fptr,_)) = withForeignPtr fptr\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band a t) = Band (Ptr ((Band a t)))\n\nunBand (Band b) = b\n\ntype ROBand = Band ReadOnly\ntype RWBand = Band ReadWrite\n\n\n{#pointer GDALDriverH as Driver newtype#}\n{#pointer GDALColorTableH as ColorTable newtype#}\n{#pointer GDALRasterAttributeTableH as RasterAttributeTable newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{-# DEPRECATED withAllDriversRegistered \"Don't use this since it does not destry the driver manager anymore. registerAllDrivers manually and call destroyDriverManager at your own peril since it will likely cause a double free if a dataset's finalizer runs after destroyDriverManager\" #-}\nwithAllDriversRegistered act\n = registerAllDrivers >> act\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `Driver' id #}\n\ndriverByName :: String -> IO Driver\ndriverByName s = do\n driver@(Driver ptr) <- c_driverByName s\n if ptr==nullPtr\n then throw $ GDALException CE_Failure \"failed to load driver\"\n else return driver\n\ntype DriverOptions = [(String,String)]\n\nclass ( HasDatatype t\n , a ~ ReadWrite\n , d ~ Dataset,\n HasWritebaleBand Band ReadWrite t)\n => HasDataset d a t where\n create :: String -> FilePath -> Int -> Int -> Int -> DriverOptions\n -> IO (d a t)\n create drv path nx ny bands options = do\n d <- driverByName drv\n create' d path nx ny bands (datatype (undefined :: t)) options\n\ncreate' :: Driver -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO (Dataset ReadWrite t)\ncreate' drv path nx ny bands dtype options = withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC dtype\n withOptionList options $ \\opts ->\n create_ drv path' nx' ny' bands' dtype' opts >>= newDatasetHandle\n\nwithOptionList ::\n [(String, String)] -> (Ptr CString -> IO c) -> IO c\nwithOptionList opts = bracket (toOptionList opts) freeOptionList\n where toOptionList = foldM folder nullPtr\n folder acc (k,v) = withCString k $ \\k' -> withCString v $ \\v' ->\n {#call unsafe CSLSetNameValue as ^#} acc k' v'\n freeOptionList = {#call unsafe CSLDestroy as ^#} . castPtr\n\ninstance HasDataset Dataset ReadWrite Word8 where\ninstance HasDataset Dataset ReadWrite Int16 where\ninstance HasDataset Dataset ReadWrite Int32 where\ninstance HasDataset Dataset ReadWrite Word16 where\ninstance HasDataset Dataset ReadWrite Word32 where\ninstance HasDataset Dataset ReadWrite Float where\ninstance HasDataset Dataset ReadWrite Double where\ninstance HasDataset Dataset ReadWrite (GComplex Int16) where\ninstance HasDataset Dataset ReadWrite (GComplex Int32) where\ninstance HasDataset Dataset ReadWrite (GComplex Float) where\ninstance HasDataset Dataset ReadWrite (GComplex Double) where\n\n\nforeign import ccall safe \"gdal.h GDALCreate\" create_\n :: Driver\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset t))\n\nopenReadOnly :: String -> IO (RODataset t)\nopenReadOnly p = withCString p openIt\n where openIt p' = open_ p' (fromEnumC GA_ReadOnly) >>= newDatasetHandle\n\nopenReadWrite :: String -> IO (RWDataset t)\nopenReadWrite p = withCString p openIt\n where openIt p' = open_ p' (fromEnumC GA_Update) >>= newDatasetHandle\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset a t))\n\n\ncreateCopy' ::\n Driver -> String -> (Dataset a t) -> Bool -> DriverOptions\n -> ProgressFun -> IO (RWDataset t)\ncreateCopy' driver path dataset strict options progressFun\n = withCString path $ \\p ->\n withDataset dataset $ \\ds ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n createCopy_ driver p ds s o pFunc (castPtr nullPtr)\n >>= newDatasetHandle\n\n\ncreateCopy ::\n String -> String -> (Dataset a t) -> Bool -> DriverOptions\n -> IO (RWDataset t)\ncreateCopy driver path dataset strict options = do\n d <- driverByName driver\n createCopy' d path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" createCopy_\n :: Driver\n -> Ptr CChar\n -> Ptr (Dataset a t)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset t))\n\n\nwithProgressFun :: forall c.\n ProgressFun -> (FunPtr ProgressFun -> IO c) -> IO c\nwithProgressFun = withCCallback wrapProgressFun\n\nwithCCallback :: forall c t a.\n (t -> IO (FunPtr a)) -> t -> (FunPtr a -> IO c) -> IO c\nwithCCallback w f = bracket (w f) freeHaskellFunPtr\n\ntype ProgressFun = CDouble -> Ptr CChar -> Ptr () -> IO CInt\n\nforeign import ccall \"wrapper\"\n wrapProgressFun :: ProgressFun -> IO (FunPtr ProgressFun)\n\n\nnewDatasetHandle :: Ptr (Dataset a t) -> IO (Dataset a t)\nnewDatasetHandle p =\n if p==nullPtr\n then throw $ GDALException CE_Failure \"Could not create dataset\"\n else do fp <- newForeignPtr closeDataset p\n mutex <- newMutex\n return $ Dataset (fp, mutex)\n\nforeign import ccall \"gdal.h &GDALClose\"\n closeDataset :: FunPtr (Ptr (Dataset a t) -> IO ())\n\ncreateMem:: HasDataset d a t\n => Int -> Int -> Int -> DriverOptions -> IO (d a t)\ncreateMem = create \"MEM\" \"\"\n\nflushCache :: forall t. RWDataset t -> IO ()\nflushCache d = withDataset d flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: Ptr (Dataset a t) -> IO ()\n\ndatasetSize :: Dataset a t -> (Int, Int)\ndatasetSize ds = unsafePerformIO $ withDataset ds $ \\dsPtr ->\n return ( fromIntegral . getDatasetXSize_ $ dsPtr\n , fromIntegral . getDatasetYSize_ $ dsPtr)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset a t) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset a t) -> CInt\n\ndatasetProjection :: Dataset a t -> IO String\ndatasetProjection d = withDataset d $ \\d' -> do\n p <- getProjection_ d'\n peekCString p\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset a t) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset t) -> String -> IO ()\nsetDatasetProjection d p = throwIfError\n \"setDatasetProjection: could not set projection\" f\n where f = withDataset d $ \\d' -> withCString p $ \\p' -> setProjection' d' p'\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset a t) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset a t -> IO Geotransform\ndatasetGeotransform ds = withDataset' ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n throwIfError \"could not get geotransform\" $ getGeoTransform dPtr a\n Geotransform <$> liftM realToFrac (peekElemOff a 0)\n <*> liftM realToFrac (peekElemOff a 1)\n <*> liftM realToFrac (peekElemOff a 2)\n <*> liftM realToFrac (peekElemOff a 3)\n <*> liftM realToFrac (peekElemOff a 4)\n <*> liftM realToFrac (peekElemOff a 5)\n\nforeign import ccall unsafe \"gdal.h GDALGetGeoTransform\" getGeoTransform\n :: Ptr (Dataset a t) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset t) -> Geotransform -> IO ()\nsetDatasetGeotransform ds gt = withDataset ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n let (Geotransform g0 g1 g2 g3 g4 g5) = gt\n pokeElemOff a 0 (realToFrac g0)\n pokeElemOff a 1 (realToFrac g1)\n pokeElemOff a 2 (realToFrac g2)\n pokeElemOff a 3 (realToFrac g3)\n pokeElemOff a 4 (realToFrac g4)\n pokeElemOff a 5 (realToFrac g5)\n throwIfError \"could not set geotransform\" $ setGeoTransform dPtr a\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset a t) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset a t -> IO (Int)\ndatasetBandCount d = liftM fromIntegral $ withDataset d bandCount_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset a t) -> IO CInt\n\nwithBand :: Dataset a t -> Int -> (Band a t -> IO b) -> IO b\nwithBand ds band f = withDataset ds $ \\dPtr -> do\n rBand@(Band p) <- getRasterBand dPtr (fromIntegral band)\n if p == nullPtr\n then throw $\n GDALException CE_Failure (\"could not get band #\" ++ show band)\n else f rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset a t) -> CInt -> IO ((Band a t))\n\n\nbandDatatype :: (Band a t) -> Datatype\nbandDatatype band = toEnumC . getDatatype_ $ band\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band a t) -> CInt\n\n\nbandBlockSize :: (Band a t) -> (Int,Int)\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n -- unsafePerformIO is safe here since the block size cant change once\n -- a dataset is created\n getBlockSize_ band xPtr yPtr\n liftA2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nforeign import ccall unsafe \"gdal.h GDALGetBlockSize\" getBlockSize_\n :: (Band a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band a t) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band a t) -> (Int, Int)\nbandSize band\n = (fromIntegral . getBandXSize_ $ band, fromIntegral . getBandYSize_ $ band)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band a t) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band a t) -> CInt\n\n\nbandNodataValue :: (Band a t) -> IO (Maybe Double)\nbandNodataValue b = alloca $ \\p -> do\n value <- liftM realToFrac $ getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: (Band a t) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: (RWBand t) -> Double -> IO ()\nsetBandNodataValue b v = throwIfError \"could not set nodata\" $\n setNodata_ b (realToFrac v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand t) -> CDouble -> IO CInt\n\n\nfillBand :: (RWBand t) -> Double -> Double -> IO ()\nfillBand b r i = throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand t) -> CDouble -> CDouble -> IO CInt\n\n\n\n\ndata GComplex a = (:+) !a !a deriving (Eq, Typeable)\ninfix 6 :+\ninstance Show a => Show (GComplex a) where\n show (r :+ i) = show r ++ \" :+ \" ++ show i\n\nclass IsGComplex a where\n type ComplexType a :: *\n toComplex :: GComplex a -> Complex.Complex (ComplexType a)\n fromComplex :: Complex.Complex (ComplexType a) -> GComplex a\n\n toComplex (r :+ i) = (toUnit r) Complex.:+ (toUnit i)\n fromComplex (r Complex.:+ i) = (fromUnit r) :+ (fromUnit i)\n\n toUnit :: a -> ComplexType a\n fromUnit :: ComplexType a -> a\n\ninstance IsGComplex Int16 where\n type ComplexType Int16 = Float\n toUnit = fromIntegral\n fromUnit = round\n\ninstance IsGComplex Int32 where\n type ComplexType Int32 = Double\n toUnit = fromIntegral\n fromUnit = round\n\ninstance IsGComplex Float where\n type ComplexType Float = Float\n toUnit = id\n fromUnit = id\n\ninstance IsGComplex Double where\n type ComplexType Double = Double\n toUnit = id\n fromUnit = id\n\n\ninstance Storable a => Storable (GComplex a) where\n sizeOf _ = sizeOf (undefined :: a) * 2\n alignment _ = alignment (undefined :: a)\n \n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Double) -> IO (GComplex Double) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Float) -> IO (GComplex Float) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Int16) -> IO (GComplex Int16) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Int32) -> IO (GComplex Int32) #-}\n peek p = (:+) <$> peekElemOff (castPtr p) 0 <*> peekElemOff (castPtr p) 1\n\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Float) -> GComplex Float -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Double) -> GComplex Double -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Int16) -> GComplex Int16 -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Int32) -> GComplex Int32 -> IO () #-}\n poke p (r :+ i)\n = pokeElemOff (castPtr p) 0 r >> pokeElemOff (castPtr p) 1 i\n\n\n\nreadBand' :: HasDatatype a\n => (Band b a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector a)\nreadBand' = readBand\n\nreadBand :: forall a b t. HasDatatype a\n => (Band b t)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector a)\nreadBand band xoff yoff sx sy bx by pxs lns = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (undefined :: a))\n withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\n adviseRead_\n band\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (fromIntegral bx)\n (fromIntegral by)\n dtype\n (castPtr nullPtr)\n throwIfError \"could not read band\" $\n rasterIO_\n band\n (fromEnumC GF_Read) \n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n dtype\n (fromIntegral pxs)\n (fromIntegral lns)\n return $ unsafeFromForeignPtr0 fp (bx * by)\n\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand' :: forall a. HasDatatype a\n => (RWBand a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBand' = writeBand\n\nwriteBand :: forall a t. HasDatatype a\n => (RWBand t)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBand band xoff yoff sx sy bx by pxs lns vec = do\n let nElems = bx * by\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw $ GDALException CE_Failure \"vector of wrong size\"\n else withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not write band\" $\n rasterIO_\n band\n (fromEnumC GF_Write) \n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (datatype (undefined :: a)))\n (fromIntegral pxs)\n (fromIntegral lns)\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\n\ntype IOVector a = IO (Vector a)\n\nclass (HasDatatype t, b ~ Band)\n => HasBand b a t where\n readBandBlock :: b a t -> Int -> Int -> IOVector t\n readBandBlock b x y\n = if not $ isValidDatatype b (undefined :: Vector t)\n then throw $ GDALException CE_Failure \"wrong band type\"\n else do\n f <- mallocForeignPtrArray (bandBlockLen b)\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ unsafeFromForeignPtr0 f (bandBlockLen b)\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nclass (HasBand b a t, a ~ ReadWrite) => HasWritebaleBand b a t where\n writeBandBlock :: b a t -> Int -> Int -> Vector t -> IO ()\n writeBandBlock b x y vec = do\n let nElems = bandBlockLen b\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw $ GDALException CE_Failure \"wrongly sized vector\"\n else if not $ isValidDatatype b vec\n then throw $ GDALException CE_Failure \"wrongly typed vector\"\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y)\n (castPtr ptr)\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: (RWBand t) -> CInt -> CInt -> Ptr () -> IO CInt\n\n\n\ninstance forall a. HasBand Band a Word8 where\ninstance forall a. HasBand Band a Word16 where\ninstance forall a. HasBand Band a Word32 where\ninstance forall a. HasBand Band a Int16 where\ninstance forall a. HasBand Band a Int32 where\ninstance forall a. HasBand Band a Float where\ninstance forall a. HasBand Band a Double where\ninstance forall a. HasBand Band a (GComplex Int16) where\ninstance forall a. HasBand Band a (GComplex Int32) where\ninstance forall a. HasBand Band a (GComplex Float) where\ninstance forall a. HasBand Band a (GComplex Double) where\n\ninstance HasWritebaleBand Band ReadWrite Word8\ninstance HasWritebaleBand Band ReadWrite Word16\ninstance HasWritebaleBand Band ReadWrite Word32\ninstance HasWritebaleBand Band ReadWrite Int16\ninstance HasWritebaleBand Band ReadWrite Int32\ninstance HasWritebaleBand Band ReadWrite Float\ninstance HasWritebaleBand Band ReadWrite Double\ninstance HasWritebaleBand Band ReadWrite (GComplex Int16) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Int32) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Float) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Double) where\n\nclass (Storable a, Typeable a) => HasDatatype a where\n datatype :: a -> Datatype\n\ninstance HasDatatype Word8 where datatype _ = GDT_Byte\ninstance HasDatatype Word16 where datatype _ = GDT_UInt16\ninstance HasDatatype Word32 where datatype _ = GDT_UInt32\ninstance HasDatatype Int16 where datatype _ = GDT_Int16\ninstance HasDatatype Int32 where datatype _ = GDT_Int32\ninstance HasDatatype Float where datatype _ = GDT_Float32\ninstance HasDatatype Double where datatype _ = GDT_Float64\ninstance HasDatatype (GComplex Int16) where datatype _ = GDT_CInt16\ninstance HasDatatype (GComplex Int32) where datatype _ = GDT_CInt32\ninstance HasDatatype (GComplex Float) where datatype _ = GDT_CFloat32\ninstance HasDatatype (GComplex Double) where datatype _ = GDT_CFloat64\n\nisValidDatatype :: forall a t v. Typeable v\n => Band a t -> v -> Bool\nisValidDatatype b v = typeOfBand b == typeOf v\n where\n typeOfBand = typeOfdatatype . bandDatatype\n typeOfdatatype dt =\n case dt of\n GDT_Byte -> typeOf (undefined :: Vector Word8)\n GDT_UInt16 -> typeOf (undefined :: Vector Word16)\n GDT_UInt32 -> typeOf (undefined :: Vector Word32)\n GDT_Int16 -> typeOf (undefined :: Vector Int16)\n GDT_Int32 -> typeOf (undefined :: Vector Int32)\n GDT_Float32 -> typeOf (undefined :: Vector Float)\n GDT_Float64 -> typeOf (undefined :: Vector Double)\n GDT_CInt16 -> typeOf (undefined :: Vector (GComplex Int16))\n GDT_CInt32 -> typeOf (undefined :: Vector (GComplex Int32))\n GDT_CFloat32 -> typeOf (undefined :: Vector (GComplex Float))\n GDT_CFloat64 -> typeOf (undefined :: Vector (GComplex Double))\n _ -> typeOf (undefined :: Bool) -- will never match a vector\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nmodule OSGeo.GDAL.Internal (\n HasDataset\n , HasBand\n , HasWritebaleBand\n , HasDatatype\n , Datatype (..)\n , GDALException\n , isGDALException\n , Geotransform (..)\n , IOVector\n , DriverOptions\n , MajorObject\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Driver\n , DriverName\n , ColorTable\n , RasterAttributeTable\n , GComplex (..)\n\n , setQuietErrorHandler\n , unDataset\n , unBand\n\n , withAllDriversRegistered\n , registerAllDrivers\n , destroyDriverManager\n , driverByName\n , create\n , create'\n , createMem\n , flushCache\n , openReadOnly\n , openReadWrite\n , createCopy\n\n , datatypeSize\n , datatypeByName\n , datatypeUnion\n , datatypeIsComplex\n\n , datasetSize\n , datasetProjection\n , setDatasetProjection\n , datasetGeotransform\n , setDatasetGeotransform\n , datasetBandCount\n\n , withBand\n , bandDatatype\n , bandBlockSize\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , readBand\n , readBand'\n , readBandBlock\n , writeBand\n , writeBand'\n , writeBandBlock\n , fillBand\n\n , toComplex\n , fromComplex\n\n -- Internal Util\n , throwIfError\n , withDataset\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception (bracket, throw, Exception(..), SomeException,\n finally)\nimport Control.Monad (liftM, foldM)\n\nimport Data.Int (Int16, Int32)\nimport qualified Data.Complex as Complex\nimport Data.Maybe (isJust)\nimport Data.Typeable (Typeable, typeOf)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector, unsafeFromForeignPtr0, unsafeToForeignPtr0)\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (ForeignPtr, withForeignPtr, newForeignPtr\n ,mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport OSGeo.Util\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\ntype DriverName = String\n\n\ndata GDALException = GDALException Error String\n deriving (Show, Typeable)\n\ninstance Exception GDALException\n\nisGDALException :: SomeException -> Bool\nisGDALException e = isJust (fromException e :: Maybe GDALException)\n\n{# enum CPLErr as Error {upcaseFirstLetter} deriving (Eq,Show) #}\n\n\ntype ErrorHandler = CInt -> CInt -> CString -> IO ()\n\nforeign import ccall \"cpl_error.h &CPLQuietErrorHandler\"\n c_quietErrorHandler :: FunPtr ErrorHandler\n\nforeign import ccall \"cpl_error.h CPLSetErrorHandler\"\n c_setErrorHandler :: FunPtr ErrorHandler -> IO (FunPtr ErrorHandler)\n\nsetQuietErrorHandler :: IO ()\nsetQuietErrorHandler = setErrorHandler c_quietErrorHandler\n\nsetErrorHandler :: FunPtr ErrorHandler -> IO ()\nsetErrorHandler h = c_setErrorHandler h >>= (\\_->return ())\n\n\nthrowIfError :: String -> IO CInt -> IO ()\nthrowIfError msg act = do\n e <- liftM toEnumC act\n case e of\n CE_None -> return ()\n e' -> throw $ GDALException e' msg\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\ninstance Show Datatype where\n show = getDatatypeName\n\n{# fun pure unsafe GDALGetDataTypeSize as datatypeSize\n { fromEnumC `Datatype' } -> `Int' #}\n\n{# fun pure unsafe GDALDataTypeIsComplex as datatypeIsComplex\n { fromEnumC `Datatype' } -> `Bool' #}\n\n{# fun pure unsafe GDALGetDataTypeName as getDatatypeName\n { fromEnumC `Datatype' } -> `String' #}\n\n{# fun pure unsafe GDALGetDataTypeByName as datatypeByName\n { `String' } -> `Datatype' toEnumC #}\n\n{# fun pure unsafe GDALDataTypeUnion as datatypeUnion\n { fromEnumC `Datatype', fromEnumC `Datatype' } -> `Datatype' toEnumC #}\n\n\n{# enum GDALAccess as Access {upcaseFirstLetter} deriving (Eq, Show) #}\n\n{# enum GDALRWFlag as RwFlag {upcaseFirstLetter} deriving (Eq, Show) #}\n\n{#pointer GDALMajorObjectH as MajorObject newtype#}\n{#pointer GDALDatasetH as Dataset foreign newtype nocode#}\n\ndata ReadOnly\ndata ReadWrite\nnewtype (Dataset a t) = Dataset (ForeignPtr (Dataset a t), Mutex)\n\nunDataset (Dataset (d, _)) = d\n\ntype RODataset = Dataset ReadOnly\ntype RWDataset = Dataset ReadWrite\nwithDataset, withDataset' :: (Dataset a t) -> (Ptr (Dataset a t) -> IO b) -> IO b\nwithDataset ds@(Dataset (_, m)) fun = withMutex m $ withDataset' ds fun\n\nwithDataset' (Dataset (fptr,_)) = withForeignPtr fptr\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band a t) = Band (Ptr ((Band a t)))\n\nunBand (Band b) = b\n\ntype ROBand = Band ReadOnly\ntype RWBand = Band ReadWrite\n\n\n{#pointer GDALDriverH as Driver newtype#}\n{#pointer GDALColorTableH as ColorTable newtype#}\n{#pointer GDALRasterAttributeTableH as RasterAttributeTable newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\n{-# DEPRECATED withAllDriversRegistered \"Don't use this since it does not destry the driver manager anymore. registerAllDrivers manually and call destroyDriverManager at your own peril since it will likely cause a double free if a dataset's finalizer runs after destroyDriverManager\" #-}\nwithAllDriversRegistered act\n = registerAllDrivers >> act\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `Driver' id #}\n\ndriverByName :: String -> IO Driver\ndriverByName s = do\n driver@(Driver ptr) <- c_driverByName s\n if ptr==nullPtr\n then throw $ GDALException CE_Failure \"failed to load driver\"\n else return driver\n\ntype DriverOptions = [(String,String)]\n\nclass ( HasDatatype t\n , a ~ ReadWrite\n , d ~ Dataset,\n HasWritebaleBand Band ReadWrite t)\n => HasDataset d a t where\n create :: String -> String -> Int -> Int -> Int -> DriverOptions\n -> IO (d a t)\n create drv path nx ny bands options = do\n d <- driverByName drv\n create' d path nx ny bands (datatype (undefined :: t)) options\n\ncreate' :: Driver -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO (Dataset ReadWrite t)\ncreate' drv path nx ny bands dtype options = withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC dtype\n withOptionList options $ \\opts ->\n create_ drv path' nx' ny' bands' dtype' opts >>= newDatasetHandle\n\nwithOptionList ::\n [(String, String)] -> (Ptr CString -> IO c) -> IO c\nwithOptionList opts = bracket (toOptionList opts) freeOptionList\n where toOptionList = foldM folder nullPtr\n folder acc (k,v) = withCString k $ \\k' -> withCString v $ \\v' ->\n {#call unsafe CSLSetNameValue as ^#} acc k' v'\n freeOptionList = {#call unsafe CSLDestroy as ^#} . castPtr\n\ninstance HasDataset Dataset ReadWrite Word8 where\ninstance HasDataset Dataset ReadWrite Int16 where\ninstance HasDataset Dataset ReadWrite Int32 where\ninstance HasDataset Dataset ReadWrite Word16 where\ninstance HasDataset Dataset ReadWrite Word32 where\ninstance HasDataset Dataset ReadWrite Float where\ninstance HasDataset Dataset ReadWrite Double where\ninstance HasDataset Dataset ReadWrite (GComplex Int16) where\ninstance HasDataset Dataset ReadWrite (GComplex Int32) where\ninstance HasDataset Dataset ReadWrite (GComplex Float) where\ninstance HasDataset Dataset ReadWrite (GComplex Double) where\n\n\nforeign import ccall safe \"gdal.h GDALCreate\" create_\n :: Driver\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset t))\n\nopenReadOnly :: String -> IO (RODataset t)\nopenReadOnly p = withCString p openIt\n where openIt p' = open_ p' (fromEnumC GA_ReadOnly) >>= newDatasetHandle\n\nopenReadWrite :: String -> IO (RWDataset t)\nopenReadWrite p = withCString p openIt\n where openIt p' = open_ p' (fromEnumC GA_Update) >>= newDatasetHandle\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset a t))\n\n\ncreateCopy' ::\n Driver -> String -> (Dataset a t) -> Bool -> DriverOptions\n -> ProgressFun -> IO (RWDataset t)\ncreateCopy' driver path dataset strict options progressFun\n = withCString path $ \\p ->\n withDataset dataset $ \\ds ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n createCopy_ driver p ds s o pFunc (castPtr nullPtr)\n >>= newDatasetHandle\n\n\ncreateCopy ::\n String -> String -> (Dataset a t) -> Bool -> DriverOptions\n -> IO (RWDataset t)\ncreateCopy driver path dataset strict options = do\n d <- driverByName driver\n createCopy' d path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" createCopy_\n :: Driver\n -> Ptr CChar\n -> Ptr (Dataset a t)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset t))\n\n\nwithProgressFun :: forall c.\n ProgressFun -> (FunPtr ProgressFun -> IO c) -> IO c\nwithProgressFun = withCCallback wrapProgressFun\n\nwithCCallback :: forall c t a.\n (t -> IO (FunPtr a)) -> t -> (FunPtr a -> IO c) -> IO c\nwithCCallback w f = bracket (w f) freeHaskellFunPtr\n\ntype ProgressFun = CDouble -> Ptr CChar -> Ptr () -> IO CInt\n\nforeign import ccall \"wrapper\"\n wrapProgressFun :: ProgressFun -> IO (FunPtr ProgressFun)\n\n\nnewDatasetHandle :: Ptr (Dataset a t) -> IO (Dataset a t)\nnewDatasetHandle p =\n if p==nullPtr\n then throw $ GDALException CE_Failure \"Could not create dataset\"\n else do fp <- newForeignPtr closeDataset p\n mutex <- newMutex\n return $ Dataset (fp, mutex)\n\nforeign import ccall \"gdal.h &GDALClose\"\n closeDataset :: FunPtr (Ptr (Dataset a t) -> IO ())\n\ncreateMem:: HasDataset d a t\n => Int -> Int -> Int -> DriverOptions -> IO (d a t)\ncreateMem = create \"MEM\" \"\"\n\nflushCache :: forall t. RWDataset t -> IO ()\nflushCache d = withDataset d flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: Ptr (Dataset a t) -> IO ()\n\ndatasetSize :: Dataset a t -> (Int, Int)\ndatasetSize ds = unsafePerformIO $ withDataset ds $ \\dsPtr ->\n return ( fromIntegral . getDatasetXSize_ $ dsPtr\n , fromIntegral . getDatasetYSize_ $ dsPtr)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterXSize\" getDatasetXSize_\n :: Ptr (Dataset a t) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterYSize\" getDatasetYSize_\n :: Ptr (Dataset a t) -> CInt\n\ndatasetProjection :: Dataset a t -> IO String\ndatasetProjection d = withDataset d $ \\d' -> do\n p <- getProjection_ d'\n peekCString p\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset a t) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset t) -> String -> IO ()\nsetDatasetProjection d p = throwIfError\n \"setDatasetProjection: could not set projection\" f\n where f = withDataset d $ \\d' -> withCString p $ \\p' -> setProjection' d' p'\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset a t) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset a t -> IO Geotransform\ndatasetGeotransform ds = withDataset' ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n throwIfError \"could not get geotransform\" $ getGeoTransform dPtr a\n Geotransform <$> liftM realToFrac (peekElemOff a 0)\n <*> liftM realToFrac (peekElemOff a 1)\n <*> liftM realToFrac (peekElemOff a 2)\n <*> liftM realToFrac (peekElemOff a 3)\n <*> liftM realToFrac (peekElemOff a 4)\n <*> liftM realToFrac (peekElemOff a 5)\n\nforeign import ccall unsafe \"gdal.h GDALGetGeoTransform\" getGeoTransform\n :: Ptr (Dataset a t) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset t) -> Geotransform -> IO ()\nsetDatasetGeotransform ds gt = withDataset ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n let (Geotransform g0 g1 g2 g3 g4 g5) = gt\n pokeElemOff a 0 (realToFrac g0)\n pokeElemOff a 1 (realToFrac g1)\n pokeElemOff a 2 (realToFrac g2)\n pokeElemOff a 3 (realToFrac g3)\n pokeElemOff a 4 (realToFrac g4)\n pokeElemOff a 5 (realToFrac g5)\n throwIfError \"could not set geotransform\" $ setGeoTransform dPtr a\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset a t) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset a t -> IO (Int)\ndatasetBandCount d = liftM fromIntegral $ withDataset d bandCount_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset a t) -> IO CInt\n\nwithBand :: Dataset a t -> Int -> (Band a t -> IO b) -> IO b\nwithBand ds band f = withDataset ds $ \\dPtr -> do\n rBand@(Band p) <- getRasterBand dPtr (fromIntegral band)\n if p == nullPtr\n then throw $\n GDALException CE_Failure (\"could not get band #\" ++ show band)\n else f rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset a t) -> CInt -> IO ((Band a t))\n\n\nbandDatatype :: (Band a t) -> Datatype\nbandDatatype band = toEnumC . getDatatype_ $ band\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band a t) -> CInt\n\n\nbandBlockSize :: (Band a t) -> (Int,Int)\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n -- unsafePerformIO is safe here since the block size cant change once\n -- a dataset is created\n getBlockSize_ band xPtr yPtr\n liftA2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nforeign import ccall unsafe \"gdal.h GDALGetBlockSize\" getBlockSize_\n :: (Band a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band a t) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band a t) -> (Int, Int)\nbandSize band\n = (fromIntegral . getBandXSize_ $ band, fromIntegral . getBandYSize_ $ band)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getBandXSize_\n :: (Band a t) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getBandYSize_\n :: (Band a t) -> CInt\n\n\nbandNodataValue :: (Band a t) -> IO (Maybe Double)\nbandNodataValue b = alloca $ \\p -> do\n value <- liftM realToFrac $ getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: (Band a t) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: (RWBand t) -> Double -> IO ()\nsetBandNodataValue b v = throwIfError \"could not set nodata\" $\n setNodata_ b (realToFrac v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand t) -> CDouble -> IO CInt\n\n\nfillBand :: (RWBand t) -> Double -> Double -> IO ()\nfillBand b r i = throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand t) -> CDouble -> CDouble -> IO CInt\n\n\n\n\ndata GComplex a = (:+) !a !a deriving (Eq, Typeable)\ninfix 6 :+\ninstance Show a => Show (GComplex a) where\n show (r :+ i) = show r ++ \" :+ \" ++ show i\n\nclass IsGComplex a where\n type ComplexType a :: *\n toComplex :: GComplex a -> Complex.Complex (ComplexType a)\n fromComplex :: Complex.Complex (ComplexType a) -> GComplex a\n\n toComplex (r :+ i) = (toUnit r) Complex.:+ (toUnit i)\n fromComplex (r Complex.:+ i) = (fromUnit r) :+ (fromUnit i)\n\n toUnit :: a -> ComplexType a\n fromUnit :: ComplexType a -> a\n\ninstance IsGComplex Int16 where\n type ComplexType Int16 = Float\n toUnit = fromIntegral\n fromUnit = round\n\ninstance IsGComplex Int32 where\n type ComplexType Int32 = Double\n toUnit = fromIntegral\n fromUnit = round\n\ninstance IsGComplex Float where\n type ComplexType Float = Float\n toUnit = id\n fromUnit = id\n\ninstance IsGComplex Double where\n type ComplexType Double = Double\n toUnit = id\n fromUnit = id\n\n\ninstance Storable a => Storable (GComplex a) where\n sizeOf _ = sizeOf (undefined :: a) * 2\n alignment _ = alignment (undefined :: a)\n \n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Double) -> IO (GComplex Double) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Float) -> IO (GComplex Float) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Int16) -> IO (GComplex Int16) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Int32) -> IO (GComplex Int32) #-}\n peek p = (:+) <$> peekElemOff (castPtr p) 0 <*> peekElemOff (castPtr p) 1\n\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Float) -> GComplex Float -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Double) -> GComplex Double -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Int16) -> GComplex Int16 -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Int32) -> GComplex Int32 -> IO () #-}\n poke p (r :+ i)\n = pokeElemOff (castPtr p) 0 r >> pokeElemOff (castPtr p) 1 i\n\n\n\nreadBand' :: HasDatatype a\n => (Band b a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector a)\nreadBand' = readBand\n\nreadBand :: forall a b t. HasDatatype a\n => (Band b t)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector a)\nreadBand band xoff yoff sx sy bx by pxs lns = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (undefined :: a))\n withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\n adviseRead_\n band\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (fromIntegral bx)\n (fromIntegral by)\n dtype\n (castPtr nullPtr)\n throwIfError \"could not read band\" $\n rasterIO_\n band\n (fromEnumC GF_Read) \n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n dtype\n (fromIntegral pxs)\n (fromIntegral lns)\n return $ unsafeFromForeignPtr0 fp (bx * by)\n\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand' :: forall a. HasDatatype a\n => (RWBand a)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBand' = writeBand\n\nwriteBand :: forall a t. HasDatatype a\n => (RWBand t)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBand band xoff yoff sx sy bx by pxs lns vec = do\n let nElems = bx * by\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw $ GDALException CE_Failure \"vector of wrong size\"\n else withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not write band\" $\n rasterIO_\n band\n (fromEnumC GF_Write) \n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (datatype (undefined :: a)))\n (fromIntegral pxs)\n (fromIntegral lns)\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\n\ntype IOVector a = IO (Vector a)\n\nclass (HasDatatype t, b ~ Band)\n => HasBand b a t where\n readBandBlock :: b a t -> Int -> Int -> IOVector t\n readBandBlock b x y\n = if not $ isValidDatatype b (undefined :: Vector t)\n then throw $ GDALException CE_Failure \"wrong band type\"\n else do\n f <- mallocForeignPtrArray (bandBlockLen b)\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ unsafeFromForeignPtr0 f (bandBlockLen b)\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nclass (HasBand b a t, a ~ ReadWrite) => HasWritebaleBand b a t where\n writeBandBlock :: b a t -> Int -> Int -> Vector t -> IO ()\n writeBandBlock b x y vec = do\n let nElems = bandBlockLen b\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw $ GDALException CE_Failure \"wrongly sized vector\"\n else if not $ isValidDatatype b vec\n then throw $ GDALException CE_Failure \"wrongly typed vector\"\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y)\n (castPtr ptr)\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: (RWBand t) -> CInt -> CInt -> Ptr () -> IO CInt\n\n\n\ninstance forall a. HasBand Band a Word8 where\ninstance forall a. HasBand Band a Word16 where\ninstance forall a. HasBand Band a Word32 where\ninstance forall a. HasBand Band a Int16 where\ninstance forall a. HasBand Band a Int32 where\ninstance forall a. HasBand Band a Float where\ninstance forall a. HasBand Band a Double where\ninstance forall a. HasBand Band a (GComplex Int16) where\ninstance forall a. HasBand Band a (GComplex Int32) where\ninstance forall a. HasBand Band a (GComplex Float) where\ninstance forall a. HasBand Band a (GComplex Double) where\n\ninstance HasWritebaleBand Band ReadWrite Word8\ninstance HasWritebaleBand Band ReadWrite Word16\ninstance HasWritebaleBand Band ReadWrite Word32\ninstance HasWritebaleBand Band ReadWrite Int16\ninstance HasWritebaleBand Band ReadWrite Int32\ninstance HasWritebaleBand Band ReadWrite Float\ninstance HasWritebaleBand Band ReadWrite Double\ninstance HasWritebaleBand Band ReadWrite (GComplex Int16) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Int32) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Float) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Double) where\n\nclass (Storable a, Typeable a) => HasDatatype a where\n datatype :: a -> Datatype\n\ninstance HasDatatype Word8 where datatype _ = GDT_Byte\ninstance HasDatatype Word16 where datatype _ = GDT_UInt16\ninstance HasDatatype Word32 where datatype _ = GDT_UInt32\ninstance HasDatatype Int16 where datatype _ = GDT_Int16\ninstance HasDatatype Int32 where datatype _ = GDT_Int32\ninstance HasDatatype Float where datatype _ = GDT_Float32\ninstance HasDatatype Double where datatype _ = GDT_Float64\ninstance HasDatatype (GComplex Int16) where datatype _ = GDT_CInt16\ninstance HasDatatype (GComplex Int32) where datatype _ = GDT_CInt32\ninstance HasDatatype (GComplex Float) where datatype _ = GDT_CFloat32\ninstance HasDatatype (GComplex Double) where datatype _ = GDT_CFloat64\n\nisValidDatatype :: forall a t v. Typeable v\n => Band a t -> v -> Bool\nisValidDatatype b v = typeOfBand b == typeOf v\n where\n typeOfBand = typeOfdatatype . bandDatatype\n typeOfdatatype dt =\n case dt of\n GDT_Byte -> typeOf (undefined :: Vector Word8)\n GDT_UInt16 -> typeOf (undefined :: Vector Word16)\n GDT_UInt32 -> typeOf (undefined :: Vector Word32)\n GDT_Int16 -> typeOf (undefined :: Vector Int16)\n GDT_Int32 -> typeOf (undefined :: Vector Int32)\n GDT_Float32 -> typeOf (undefined :: Vector Float)\n GDT_Float64 -> typeOf (undefined :: Vector Double)\n GDT_CInt16 -> typeOf (undefined :: Vector (GComplex Int16))\n GDT_CInt32 -> typeOf (undefined :: Vector (GComplex Int32))\n GDT_CFloat32 -> typeOf (undefined :: Vector (GComplex Float))\n GDT_CFloat64 -> typeOf (undefined :: Vector (GComplex Double))\n _ -> typeOf (undefined :: Bool) -- will never match a vector\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"c2115ed8bbd0a00def424570096fdb2f18f4b34e","subject":"Fixed a typedec","message":"Fixed a typedec\n","repos":"aleator\/CV,TomMD\/CV,aleator\/CV,BeautifulDestinations\/CV","old_file":"CV\/Transforms.chs","new_file":"CV\/Transforms.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns, ScopedTypeVariables, PatternGuards, FlexibleContexts#-}\n#include \"cvWrapLEO.h\"\n-- |Various image transformations from opencv and other sources.\nmodule CV.Transforms where\n\nimport CV.Image\nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Foreign.Marshal.Array\nimport System.IO.Unsafe\n{#import CV.Image#}\nimport CV.ImageMathOp\n\n-- |Since DCT is valid only for even sized images, we provide a\n-- function to crop images to even sizes.\ntakeEvenSized img = getRegion (0,0) (w-wadjust,h-hadjust) img\n where\n (w,h) = getSize img\n hadjust | odd h = 1\n | otherwise = 2\n wadjust | odd w = 1\n | otherwise = 2\n\n-- |Perform Discrete Cosine Transform\ndct :: Image GrayScale d -> Image GrayScale d\ndct img | (x,y) <- getSize img, even x && even y \n = unsafePerformIO $\n withGenImage img $ \\i -> \n withClone img $ \\c' -> \n withGenImage c' $ \\c ->\n ({#call cvDCT#} i c 0)\n | otherwise = error \"DCT needs even sized image\"\n\n-- |Perform Inverse Discrete Cosine Transform\nidct :: Image GrayScale d -> Image GrayScale d\nidct img | (x,y) <- getSize img, even x && even y \n = unsafePerformIO $\n withGenImage img $ \\i -> \n withClone img $ \\c' -> \n withGenImage c' $ \\c ->\n ({#call cvDCT#} i c 1)\n | otherwise = error \"IDCT needs even sized image\"\n\ndata MirrorAxis = Vertical | Horizontal deriving (Show,Eq)\n\n-- |Mirror an image over a cardinal axis\nflip :: CreateImage (Image c d) => MirrorAxis -> Image c d -> Image c d\nflip axis img = unsafePerformIO $ do\n let cl = emptyCopy img\n withGenImage img $ \\cimg -> \n withGenImage cl $ \\ccl -> do\n {#call cvFlip#} cimg ccl (if axis == Vertical then 0 else 1)\n return cl\n\n-- |Rotate `img` `angle` radians.\nrotate :: Double -> Image c d -> Image c d\nrotate (realToFrac -> angle) img = unsafePerformIO $\n withImage img $ \\i -> \n creatingImage \n ({#call rotateImage#} i 1 angle)\n\ndata Interpolation = NearestNeighbour | Linear\n | Area | Cubic\n deriving (Eq,Ord,Enum,Show)\n\n-- |Simulate a radial distortion over an image\nradialDistort :: Image GrayScale D32 -> Double -> Image GrayScale D32\nradialDistort img k = unsafePerformIO $ do\n let target = emptyCopy img \n withImage img $ \\cimg ->\n withImage target $\u00a0\\ctarget ->\n {#call radialRemap#} cimg ctarget (realToFrac k)\n return target\n\n-- |Scale image by one ratio on both of the axes\nscaleSingleRatio tpe x img = scale tpe (x,x) img\n\n\n-- |Scale an image with different ratios for axes\nscale :: (CreateImage (Image c D32), RealFloat a) => Interpolation -> (a,a) -> Image c D32 -> Image c D32\nscale tpe (x,y) img = unsafePerformIO $ do\n target <- create (w',h') \n withGenImage img $ \\i -> \n withGenImage target $ \\t -> \n {#call cvResize#} i t \n (fromIntegral.fromEnum $ tpe)\n return target\n where\n (w,h) = getSize img\n (w',h') = (round $ fromIntegral w*y\n ,round $ fromIntegral h*x)\n\n-- |Scale an image to a given size\nscaleToSize :: (CreateImage (Image c D32)) => \n Interpolation -> Bool -> (Int,Int) -> Image c D32 -> Image c D32\nscaleToSize tpe retainRatio (w,h) img = unsafePerformIO $ do\n target <- create (w',h') \n withGenImage img $ \\i -> \n withGenImage target $ \\t -> \n {#call cvResize#} i t \n (fromIntegral.fromEnum $ tpe)\n return target\n where\n (ow,oh) = getSize img\n (w',h') = if retainRatio \n then (floor $ fromIntegral ow*ratio,floor $ fromIntegral oh*ratio)\n else (w,h)\n ratio = max (fromIntegral w\/fromIntegral ow)\n (fromIntegral h\/fromIntegral oh)\n\n-- |Apply a perspective transform to the image. The transformation 3x3 matrix is supplied as\n-- a row ordered, flat, list.\nperspectiveTransform :: Real a => Image c d -> [a] -> Image c d\nperspectiveTransform img (map realToFrac -> [a1,a2,a3,a4,a5,a6,a7,a8,a9])\n = unsafePerformIO $ \n withImage img $ \\cimg -> creatingImage $ {#call wrapPerspective#} cimg a1 a2 a3 a4 a5 a6 a7 a8 a9\n\n\n-- |Find a homography between two sets of points in. The resulting 3x3 matrix is returned as a list.\ngetHomography srcPts dstPts = \n unsafePerformIO $ withArray src $\u00a0\\c_src ->\n withArray dst $\u00a0\\c_dst ->\n allocaArray (3*3) $\u00a0\\c_hmg -> do\n {#call findHomography#} c_src c_dst (fromIntegral $ length srcPts) c_hmg\n peekArray (3*3) c_hmg\n where\n flatten = map realToFrac . concatMap (\\(a,b) -> [a,b]) \n src = flatten srcPts\n dst = flatten dstPts\n\n\n--- Pyramid transforms\n-- |Return a copy of an image with an even size\nevenize :: Image channels depth -> Image channels depth\nevenize img = if (odd w || odd h)\n then \n unsafePerformIO $ \n creatingImage $\n withGenImage img $\u00a0\\cImg -> {#call makeEvenUp#} cImg\n else img\n where\n (w,h) = getSize img\n\n-- |Return a copy of an image with an odd size\noddize :: Image channels depth -> Image channels depth\noddize img = if (even w || even h)\n then \n unsafePerformIO $ \n creatingImage $\n withGenImage img $\u00a0\\cImg -> {#call padUp#} cImg (toI $\u00a0even w) (toI $ even h)\n else img\n where\n toI True = 1\n toI False = 0\n (w,h) = getSize img\n\n-- |Pad images to same size\nsameSizePad :: Image channels depth -> Image c d -> Image channels depth\nsameSizePad img img2 = if (size1 \/= size2)\n then unsafePerformIO $ do\n r <- creatingImage $\n withGenImage img2 $\u00a0\\cImg -> {#call padUp#} cImg (toI $\u00a0w2 Image GrayScale a -> Image GrayScale a\npyrDown image = unsafePerformIO $ do\n res <- create size \n withGenImage image $\u00a0\\cImg -> \n withGenImage res $\u00a0\\cResImg -> \n {#call cvPyrDown#} cImg cResImg cv_Gaussian\n return res\n where\n size = (x`div`2,y`div`2)\n (x,y) = getSize image \n\n--\u00a0|Enlarge image to double in each dimension. Used to recover pyramidal layers\npyrUp :: (CreateImage (Image GrayScale a)) => Image GrayScale a -> Image GrayScale a\npyrUp image = unsafePerformIO $ do\n res <- create size \n withGenImage image $\u00a0\\cImg -> \n withGenImage res $\u00a0\\cResImg -> \n {#call cvPyrUp#} cImg cResImg cv_Gaussian\n return res\n where\n size = (x*2,y*2)\n (x,y) = getSize image \n\n\n-- TODO: For additional efficiency, make this so that pyrDown result is directly put into\n-- proper size image which is then padded\nsafePyrDown img = evenize result\n where\n result = pyrDown img \n (w,h) = getSize result \n\n-- |Calculate the laplacian pyramid of an image up to the nth level.\n-- Notice that the image size must be divisible by 2^n or opencv \n-- will abort (TODO!)\nlaplacianPyramid :: Int -> Image GrayScale D32 -> [Image GrayScale D32]\nlaplacianPyramid depth image = reverse laplacian\n where\n downs :: [Image GrayScale D32] = take depth $ iterate pyrDown (image)\n upsampled :: [Image GrayScale D32] = map pyrUp (tail downs)\n laplacian = zipWith (#-) downs upsampled ++ [last downs]\n\n-- |Reconstruct an image from a laplacian pyramid\nreconstructFromLaplacian :: [Image GrayScale D32] -> Image GrayScale D32 \nreconstructFromLaplacian pyramid = foldl1 (\\a b -> (pyrUp a) #+ b) (pyramid)\n -- where \n -- safeAdd x y = sameSizePad y x #+ y \n\n-- TODO: Could have wider type\n-- |Enlarge image so, that it's size is divisible by 2^n \nenlarge :: Int -> Image GrayScale D32 -> Image GrayScale D32\nenlarge n img = unsafePerformIO $ do\n i <- create (w2,h2)\n blit i img (0,0)\n return i\n where\n (w,h) = getSize img\n (w2,h2) = (pad w, pad h)\n pad x = x + (np - x `mod` np)\n np = 2^n\n\n#c\nenum DistanceType {\n C = CV_DIST_C\n ,L1 = CV_DIST_L1\n ,L2 = CV_DIST_L2\n};\n#endc\n{#enum DistanceType {}#}\n\n-- |Mask sizes accepted by distanceTransform\ndata MaskSize = M3 |\u00a0M5 deriving (Eq,Ord,Enum,Show)\n\n--\u00a0|Perform a distance transform on the image\ndistanceTransform :: DistanceType -> MaskSize -> Image GrayScale D8 -> Image GrayScale D32 --TODO: Input should be a black and white image\ndistanceTransform dtype maskSize source = unsafePerformIO $ do\n result :: Image GrayScale D32 <- create (getSize source)\n withGenImage source $ \\c_source ->\n withGenImage result $ \\c_result ->\n {#call cvDistTransform #} c_source c_result \n (fromIntegral . fromEnum $ dtype) \n (fromIntegral . fromEnum $ maskSize)\n nullPtr nullPtr\n return result\n -- TODO: Add handling for labels\n -- TODO: Add handling for custom masks\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns, ScopedTypeVariables, PatternGuards, FlexibleContexts#-}\n#include \"cvWrapLEO.h\"\n-- |Various image transformations from opencv and other sources.\nmodule CV.Transforms where\n\nimport CV.Image\nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Foreign.Marshal.Array\nimport System.IO.Unsafe\n{#import CV.Image#}\nimport CV.ImageMathOp\n\n-- |Since DCT is valid only for even sized images, we provide a\n-- function to crop images to even sizes.\ntakeEvenSized img = getRegion (0,0) (w-wadjust,h-hadjust) img\n where\n (w,h) = getSize img\n hadjust | odd h = 1\n | otherwise = 2\n wadjust | odd w = 1\n | otherwise = 2\n\n-- |Perform Discrete Cosine Transform\ndct :: Image GrayScale d -> Image GrayScale d\ndct img | (x,y) <- getSize img, even x && even y \n = unsafePerformIO $\n withGenImage img $ \\i -> \n withClone img $ \\c' -> \n withGenImage c' $ \\c ->\n ({#call cvDCT#} i c 0)\n | otherwise = error \"DCT needs even sized image\"\n\n-- |Perform Inverse Discrete Cosine Transform\nidct :: Image GrayScale d -> Image GrayScale d\nidct img | (x,y) <- getSize img, even x && even y \n = unsafePerformIO $\n withGenImage img $ \\i -> \n withClone img $ \\c' -> \n withGenImage c' $ \\c ->\n ({#call cvDCT#} i c 1)\n | otherwise = error \"IDCT needs even sized image\"\n\ndata MirrorAxis = Vertical | Horizontal deriving (Show,Eq)\n\n-- |Mirror an image over a cardinal axis\nflip :: CreateImage (Image c d) => MirrorAxis -> Image c d -> Image c d\nflip axis img = unsafePerformIO $ do\n let cl = emptyCopy img\n withGenImage img $ \\cimg -> \n withGenImage cl $ \\ccl -> do\n {#call cvFlip#} cimg ccl (if axis == Vertical then 0 else 1)\n return cl\n\n-- |Rotate `img` `angle` radians.\nrotate :: Double -> Image c d -> Image c d\nrotate (realToFrac -> angle) img = unsafePerformIO $\n withImage img $ \\i -> \n creatingImage \n ({#call rotateImage#} i 1 angle)\n\ndata Interpolation = NearestNeighbour | Linear\n | Area | Cubic\n deriving (Eq,Ord,Enum,Show)\n\n-- |Simulate a radial distortion over an image\nradialDistort :: Image GrayScale D32 -> Double -> Image GrayScale D32\nradialDistort img k = unsafePerformIO $ do\n let target = emptyCopy img \n withImage img $ \\cimg ->\n withImage target $\u00a0\\ctarget ->\n {#call radialRemap#} cimg ctarget (realToFrac k)\n return target\n\n-- |Scale image by one ratio on both of the axes\nscaleSingleRatio tpe x img = scale tpe (x,x) img\n\n\n-- |Scale an image with different ratios for axes\nscale :: (CreateImage (Image c D32), RealFloat a) => Interpolation -> (a,a) -> Image c D32 -> Image c D32\nscale tpe (x,y) img = unsafePerformIO $ do\n target <- create (w',h') \n withGenImage img $ \\i -> \n withGenImage target $ \\t -> \n {#call cvResize#} i t \n (fromIntegral.fromEnum $ tpe)\n return target\n where\n (w,h) = getSize img\n (w',h') = (round $ fromIntegral w*y\n ,round $ fromIntegral h*x)\n\n-- |Scale an image to a given size\nscaleToSize :: (CreateImage (Image c D32)) => \n Interpolation -> Bool -> (Int,Int) -> Image c D32 -> Image c D32\nscaleToSize tpe retainRatio (w,h) img = unsafePerformIO $ do\n target <- create (w',h') \n withGenImage img $ \\i -> \n withGenImage target $ \\t -> \n {#call cvResize#} i t \n (fromIntegral.fromEnum $ tpe)\n return target\n where\n (ow,oh) = getSize img\n (w',h') = if retainRatio \n then (floor $ fromIntegral ow*ratio,floor $ fromIntegral oh*ratio)\n else (w,h)\n ratio = max (fromIntegral w\/fromIntegral ow)\n (fromIntegral h\/fromIntegral oh)\n\n-- |Apply a perspective transform to the image. The transformation 3x3 matrix is supplied as\n-- a row ordered, flat, list.\nperspectiveTransform :: Real a => Image c d -> [a] -> Image c d\nperspectiveTransform img (map realToFrac -> [a1,a2,a3,a4,a5,a6,a7,a8,a9])\n = unsafePerformIO $ \n withImage img $ \\cimg -> creatingImage $ {#call wrapPerspective#} cimg a1 a2 a3 a4 a5 a6 a7 a8 a9\n\n\n-- |Find a homography between two sets of points in. The resulting 3x3 matrix is returned as a list.\ngetHomography srcPts dstPts = \n unsafePerformIO $ withArray src $\u00a0\\c_src ->\n withArray dst $\u00a0\\c_dst ->\n allocaArray (3*3) $\u00a0\\c_hmg -> do\n {#call findHomography#} c_src c_dst (fromIntegral $ length srcPts) c_hmg\n peekArray (3*3) c_hmg\n where\n flatten = concatMap (\\(a,b) -> [a,b]) \n src = flatten srcPts\n dst = flatten dstPts\n\n\n--- Pyramid transforms\n-- |Return a copy of an image with an even size\nevenize :: Image channels depth -> Image channels depth\nevenize img = if (odd w || odd h)\n then \n unsafePerformIO $ \n creatingImage $\n withGenImage img $\u00a0\\cImg -> {#call makeEvenUp#} cImg\n else img\n where\n (w,h) = getSize img\n\n-- |Return a copy of an image with an odd size\noddize :: Image channels depth -> Image channels depth\noddize img = if (even w || even h)\n then \n unsafePerformIO $ \n creatingImage $\n withGenImage img $\u00a0\\cImg -> {#call padUp#} cImg (toI $\u00a0even w) (toI $ even h)\n else img\n where\n toI True = 1\n toI False = 0\n (w,h) = getSize img\n\n-- |Pad images to same size\nsameSizePad :: Image channels depth -> Image c d -> Image channels depth\nsameSizePad img img2 = if (size1 \/= size2)\n then unsafePerformIO $ do\n r <- creatingImage $\n withGenImage img2 $\u00a0\\cImg -> {#call padUp#} cImg (toI $\u00a0w2 Image GrayScale a -> Image GrayScale a\npyrDown image = unsafePerformIO $ do\n res <- create size \n withGenImage image $\u00a0\\cImg -> \n withGenImage res $\u00a0\\cResImg -> \n {#call cvPyrDown#} cImg cResImg cv_Gaussian\n return res\n where\n size = (x`div`2,y`div`2)\n (x,y) = getSize image \n\n--\u00a0|Enlarge image to double in each dimension. Used to recover pyramidal layers\npyrUp :: (CreateImage (Image GrayScale a)) => Image GrayScale a -> Image GrayScale a\npyrUp image = unsafePerformIO $ do\n res <- create size \n withGenImage image $\u00a0\\cImg -> \n withGenImage res $\u00a0\\cResImg -> \n {#call cvPyrUp#} cImg cResImg cv_Gaussian\n return res\n where\n size = (x*2,y*2)\n (x,y) = getSize image \n\n\n-- TODO: For additional efficiency, make this so that pyrDown result is directly put into\n-- proper size image which is then padded\nsafePyrDown img = evenize result\n where\n result = pyrDown img \n (w,h) = getSize result \n\n-- |Calculate the laplacian pyramid of an image up to the nth level.\n-- Notice that the image size must be divisible by 2^n or opencv \n-- will abort (TODO!)\nlaplacianPyramid :: Int -> Image GrayScale D32 -> [Image GrayScale D32]\nlaplacianPyramid depth image = reverse laplacian\n where\n downs :: [Image GrayScale D32] = take depth $ iterate pyrDown (image)\n upsampled :: [Image GrayScale D32] = map pyrUp (tail downs)\n laplacian = zipWith (#-) downs upsampled ++ [last downs]\n\n-- |Reconstruct an image from a laplacian pyramid\nreconstructFromLaplacian :: [Image GrayScale D32] -> Image GrayScale D32 \nreconstructFromLaplacian pyramid = foldl1 (\\a b -> (pyrUp a) #+ b) (pyramid)\n -- where \n -- safeAdd x y = sameSizePad y x #+ y \n\n-- TODO: Could have wider type\n-- |Enlarge image so, that it's size is divisible by 2^n \nenlarge :: Int -> Image GrayScale D32 -> Image GrayScale D32\nenlarge n img = unsafePerformIO $ do\n i <- create (w2,h2)\n blit i img (0,0)\n return i\n where\n (w,h) = getSize img\n (w2,h2) = (pad w, pad h)\n pad x = x + (np - x `mod` np)\n np = 2^n\n\n#c\nenum DistanceType {\n C = CV_DIST_C\n ,L1 = CV_DIST_L1\n ,L2 = CV_DIST_L2\n};\n#endc\n{#enum DistanceType {}#}\n\n-- |Mask sizes accepted by distanceTransform\ndata MaskSize = M3 |\u00a0M5 deriving (Eq,Ord,Enum,Show)\n\n--\u00a0|Perform a distance transform on the image\ndistanceTransform :: DistanceType -> MaskSize -> Image GrayScale D8 -> Image GrayScale D32 --TODO: Input should be a black and white image\ndistanceTransform dtype maskSize source = unsafePerformIO $ do\n result :: Image GrayScale D32 <- create (getSize source)\n withGenImage source $ \\c_source ->\n withGenImage result $ \\c_result ->\n {#call cvDistTransform #} c_source c_result \n (fromIntegral . fromEnum $ dtype) \n (fromIntegral . fromEnum $ maskSize)\n nullPtr nullPtr\n return result\n -- TODO: Add handling for labels\n -- TODO: Add handling for custom masks\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"d7a1e68bb2eb9de43956771457ac3ac5391d90e4","subject":"Added Documentation and more type safety for CV.Edges","message":"Added Documentation and more type safety for CV.Edges","repos":"aleator\/CV,BeautifulDestinations\/CV,TomMD\/CV,aleator\/CV","old_file":"CV\/Edges.chs","new_file":"CV\/Edges.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface#-}\n#include \"cvWrapLEO.h\"\nmodule CV.Edges (sobelOp,sobel\n ,sScharr,s1,s3,s5,s7\n ,l1,l3,l5,l7\n ,laplaceOp,laplace,canny,susan) where\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.ForeignPtr\nimport Foreign.Ptr\n\nimport CV.ImageOp\n\nimport CV.Image \n{#import CV.Image#}\n\nimport C2HSTools\n\n-- | Perform Sobel filtering on image. First argument gives order of horizontal and vertical\n-- derivative estimates and second one is the aperture. This function can also calculate\n-- Scharr filter with aperture specification of sScharr\n-- TODO: Type the aperture size and possibly the derivative orders as well\n-- TODO: It is possible to define sobel with different target image with other bit depths.\nsobelOp :: (Int,Int) -> SobelAperture -> ImageOperation GrayScale D32\nsobelOp (dx,dy) (Sb aperture)\n | dx >=0 && dx <3\n && not ((aperture == -1) && (dx>1 || dy>1))\n && dy >=0 && dy<3 = ImgOp $ \\i -> withGenImage i $ \\image ->\n ({#call cvSobel#} image image cdx cdy cap)\n\n | otherwise = error \"Invalid aperture\" \n where [cdx,cdy,cap] = map fromIntegral [dx,dy,aperture]\n\nsobel dd ap im = unsafeOperate (sobelOp dd ap) im\n\n-- | Aperture sizes for sobel operator\nnewtype SobelAperture = Sb Int\nsScharr = Sb (-1)\ns1 = Sb 1\ns3 = Sb 3\ns5 = Sb 5\ns7 = Sb 7\n\n\n-- | Aperture sizes for laplacian operator\nnewtype LaplacianAperture = L Int\nl1 = L 1\nl3 = L 3\nl5 = L 5\nl7 = L 7\n\n-- |Perform laplacian filtering of given aperture to image\nlaplaceOp :: LaplacianAperture -> ImageOperation GrayScale D32\nlaplaceOp (L s) = ImgOp $ \\img -> withGenImage img $ \\image -> \n ({#call cvLaplace #} image image (fromIntegral s)) \n\nlaplace s i = unsafeOperate (laplaceOp s) i\n\n-- |Perform canny thresholding using two threshold values and given aperture\n-- Works only on 8-bit images\ncanny :: Int -> Int -> Int -> Image GrayScale D8 -> Image GrayScale D8\ncanny t1 t2 aperture src = unsafePerformIO $ do\n withClone src $ \\clone -> \n withGenImage src $ \\si ->\n withGenImage clone $ \\ci -> do\n {#call cvCanny#} si ci (fromIntegral t1) \n (fromIntegral t2) \n (fromIntegral aperture)\n return clone\n \n \n \n-- | SUSAN edge detection filter, see http:\/\/users.fmrib.ox.ac.uk\/~steve\/susan\/susan\/susan.html\n-- TODO: Should return a binary image\nsusan :: (Int,Int) -> D32 -> Image GrayScale D32 -> Image GrayScale D8\nsusan (w,h) t image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage\n ({#call susanEdge#} img (fromIntegral w) (fromIntegral h) (realToFrac t))\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface#-}\n#include \"cvWrapLEO.h\"\nmodule CV.Edges where\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.ForeignPtr\nimport Foreign.Ptr\n\nimport CV.ImageOp\n\nimport CV.Image \n{#import CV.Image#}\n\nimport C2HSTools\n\nsobelOp :: (Int,Int) -> Int -> ImageOperation GrayScale D32\nsobelOp (dx,dy) aperture \n | dx >=0 && dx <3\n && aperture `elem` [-1,1,3,5,7]\n && not ((aperture == -1) && (dx>1 || dy>1))\n && dy >=0 && dy<3 = ImgOp $ \\i -> withGenImage i $ \\image ->\n ({#call cvSobel#} image image cdx cdy cap)\n\n | otherwise = error \"Invalid aperture\" \n where [cdx,cdy,cap] = map fromIntegral [dx,dy,aperture]\n\nsobel dd ap im = unsafeOperate (sobelOp dd ap) im\n\n\nlaplaceOp :: Int -> ImageOperation GrayScale D32\nlaplaceOp s = ImgOp $ \\img -> withGenImage img $ \\image -> \n if s `elem` [1,3,5,7]\n then ({#call cvLaplace #} image image (fromIntegral s)) \n else error \"Laplace aperture must be 1, 3, 5 or 7\"\nlaplace s i = unsafeOperate (laplaceOp s) i\n\n-- TODO: Add tests below!\ncanny :: Int -> Int -> Int -> Image GrayScale D8 -> Image GrayScale D8\ncanny t1 t2 aperture src = unsafePerformIO $ do\n withClone src $ \\clone -> \n withGenImage src $ \\si ->\n withGenImage clone $ \\ci -> do\n {#call cvCanny#} si ci (fromIntegral t1) \n (fromIntegral t2) \n (fromIntegral aperture)\n return clone\n \n \n \n\nsusan :: (Int,Int) -> D32 -> Image GrayScale D32 -> Image GrayScale D8\nsusan (w,h) t image = unsafePerformIO $ do\n withGenImage image $ \\img ->\n creatingImage\n ({#call susanEdge#} img (fromIntegral w) (fromIntegral h) (realToFrac t))\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"a1925ea8a2ea95555c4e21f7f4a7625b32243c3a","subject":"glib: make module name for GDateTime the same as the filename :)","message":"glib: make module name for GDateTime the same as the filename :)\n\ndarcs-hash:20070712013200-21862-605397d819e2751a2a694a37a4d652365133d064.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"glib\/System\/Glib\/GDateTime.chs","new_file":"glib\/System\/Glib\/GDateTime.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK)\n--\n-- Author : Peter Gavin\n--\n-- Created: 19 March 2002\n--\n-- Copyright (C) 2002 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\nmodule System.Glib.GDateTime (\n GTimeValPart,\n GTimeVal(..),\n gGetCurrentTime,\n gUSleep,\n gTimeValAdd,\n gTimeValFromISO8601,\n gTimeValToISO8601,\n GDate(..),\n GDateDay,\n GDateMonth,\n GDateYear,\n GDateJulianDay,\n GDateWeekday,\n gDateValidJulian,\n gDateValidDMY,\n gDateNewJulian,\n gDateNewDMY,\n gDateSetDay,\n gDateSetMonth,\n gDateSetYear,\n gDateNewTimeVal,\n gDateParse,\n gDateAddDays,\n gDateSubtractDays,\n gDateAddMonths,\n gDateSubtractMonths,\n gDateAddYears,\n gDateSubtractYears,\n gDateDaysBetween,\n gDateCompare,\n gDateClamp,\n gDateDay,\n gDateMonth,\n gDateYear,\n gDateWeekday\n ) where\n\nimport Control.Monad (liftM)\nimport System.Glib.FFI\nimport System.Glib.UTFString\n\ntype GTimeValPart = {# type glong #}\ndata GTimeVal = GTimeVal { gTimeValSec :: GTimeValPart\n , gTimeValUSec :: GTimeValPart }\n deriving (Eq, Ord)\ninstance Storable GTimeVal where\n sizeOf _ = {# sizeof GTimeVal #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do sec <- {# get GTimeVal->tv_sec #} ptr\n uSec <- {# get GTimeVal->tv_usec #} ptr\n return $ GTimeVal sec uSec\n poke ptr (GTimeVal sec uSec) =\n do {# set GTimeVal->tv_sec #} ptr sec\n {# set GTimeVal->tv_usec #} ptr uSec\n\ngGetCurrentTime :: IO GTimeVal\ngGetCurrentTime =\n alloca $ \\ptr ->\n do {# call g_get_current_time #} $ castPtr ptr\n peek ptr\n\ngUSleep :: GTimeValPart\n -> IO ()\ngUSleep microseconds =\n {# call g_usleep #} $ fromIntegral microseconds\n\ngTimeValAdd :: GTimeVal\n -> GTimeValPart\n -> GTimeVal\ngTimeValAdd time microseconds =\n unsafePerformIO $ with time $ \\ptr ->\n do {# call g_time_val_add #} (castPtr ptr) microseconds\n peek ptr\n\ngTimeValFromISO8601 :: String\n -> Maybe GTimeVal\ngTimeValFromISO8601 isoDate =\n unsafePerformIO $ withUTFString isoDate $ \\cISODate ->\n alloca $ \\ptr ->\n do success <- liftM toBool $ {# call g_time_val_from_iso8601 #} cISODate $ castPtr ptr\n if success\n then liftM Just $ peek ptr\n else return Nothing\n\ngTimeValToISO8601 :: GTimeVal\n -> String\ngTimeValToISO8601 time =\n unsafePerformIO $ with time $ \\ptr ->\n {# call g_time_val_to_iso8601 #} (castPtr ptr) >>= readUTFString\n\nnewtype GDateDay = GDateDay {# type GDateDay #}\n deriving (Eq, Ord)\ninstance Bounded GDateDay where\n minBound = GDateDay 1\n maxBound = GDateDay 31\n\n{# enum GDateMonth {underscoreToCase} deriving (Eq, Ord) #}\ninstance Bounded GDateMonth where\n minBound = GDateJanuary\n maxBound = GDateDecember\n\nnewtype GDateYear = GDateYear {# type GDateYear #}\n deriving (Eq, Ord)\ninstance Bounded GDateYear where\n minBound = GDateYear 1\n maxBound = GDateYear (maxBound :: {# type guint16 #})\n\ntype GDateJulianDay = {# type guint32 #}\nnewtype GDate = GDate { gDateJulianDay :: GDateJulianDay }\n deriving (Eq)\ninstance Storable GDate where\n sizeOf _ = {# sizeof GDate #}\n alignment _ = alignment (undefined :: CString)\n peek =\n (liftM (GDate . fromIntegral)) . {# call g_date_get_julian #} . castPtr\n poke ptr val =\n {# call g_date_set_julian #} (castPtr ptr) $ gDateJulianDay val\n\n{# enum GDateWeekday {underscoreToCase} deriving (Eq, Ord) #}\ninstance Bounded GDateWeekday where\n minBound = GDateMonday\n maxBound = GDateSunday\n\ngDateValidJulian :: GDateJulianDay\n -> Bool\ngDateValidJulian =\n toBool . {# call fun g_date_valid_julian #}\n\ngDateValidDMY :: GDateDay\n -> GDateMonth\n -> GDateYear\n -> Bool\ngDateValidDMY (GDateDay day) month (GDateYear year) =\n toBool $ {# call fun g_date_valid_dmy #} day\n (fromIntegral $ fromEnum month)\n year\n\ngDateNewJulian :: GDateJulianDay\n -> Maybe GDate\ngDateNewJulian julian =\n if gDateValidJulian julian\n then Just $ GDate julian\n else Nothing\n\ngDateNewDMY :: GDateDay\n -> GDateMonth\n -> GDateYear\n -> Maybe GDate\ngDateNewDMY day month year =\n if gDateValidDMY day month year\n then Just $ unsafePerformIO $ alloca $ \\ptr ->\n do let GDateDay day' = day\n GDateYear year' = year\n {# call g_date_set_dmy #} (castPtr ptr)\n day'\n (fromIntegral $ fromEnum month)\n year'\n peek ptr\n else Nothing\n\ngDateSetDay :: GDate\n -> GDateDay\n -> Maybe GDate\ngDateSetDay date (GDateDay day) =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_set_day #} (castPtr ptr) day\n valid <- liftM toBool $ {# call g_date_valid #} $ castPtr ptr\n if valid\n then liftM Just $ peek ptr\n else return Nothing\n\ngDateSetMonth :: GDate\n -> GDateMonth\n -> Maybe GDate\ngDateSetMonth date month =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_set_month #} (castPtr ptr) $ fromIntegral $ fromEnum month\n valid <- liftM toBool $ {# call g_date_valid #} $ castPtr ptr\n if valid\n then liftM Just $ peek ptr\n else return Nothing\n\ngDateSetYear :: GDate\n -> GDateYear\n -> Maybe GDate\ngDateSetYear date (GDateYear year) =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_set_year #} (castPtr ptr) year\n valid <- liftM toBool $ {# call g_date_valid #} $ castPtr ptr\n if valid\n then liftM Just $ peek ptr\n else return Nothing\n\ngDateNewTimeVal :: GTimeVal\n -> GDate\ngDateNewTimeVal timeVal =\n unsafePerformIO $ alloca $ \\ptr ->\n with timeVal $ \\timeValPtr ->\n do {# call g_date_set_time_val #} (castPtr ptr) $ castPtr timeValPtr\n peek ptr\n\ngDateParse :: String\n -> IO (Maybe GDate)\ngDateParse str =\n alloca $ \\ptr ->\n do withUTFString str $ {# call g_date_set_parse #} $ castPtr ptr\n valid <- liftM toBool $ {# call g_date_valid #} $ castPtr ptr\n if valid\n then liftM Just $ peek ptr\n else return Nothing\n\ngDateAddDays :: GDate\n -> Word\n -> GDate\ngDateAddDays date nDays =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_add_days #} (castPtr ptr) $ fromIntegral nDays\n peek ptr\n\ngDateSubtractDays :: GDate\n -> Word\n -> GDate\ngDateSubtractDays date nDays =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_subtract_days #} (castPtr ptr) $ fromIntegral nDays\n peek ptr\n\ngDateAddMonths :: GDate\n -> Word\n -> GDate\ngDateAddMonths date nMonths =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_add_months #} (castPtr ptr) $ fromIntegral nMonths\n peek ptr\n\ngDateSubtractMonths :: GDate\n -> Word\n -> GDate\ngDateSubtractMonths date nMonths =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_subtract_months #} (castPtr ptr) $ fromIntegral nMonths\n peek ptr\n\ngDateAddYears :: GDate\n -> Word\n -> GDate\ngDateAddYears date nYears =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_add_years #} (castPtr ptr) $ fromIntegral nYears\n peek ptr\n\ngDateSubtractYears :: GDate\n -> Word\n -> GDate\ngDateSubtractYears date nYears =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_subtract_years #} (castPtr ptr) $ fromIntegral nYears\n peek ptr\n\ngDateDaysBetween :: GDate\n -> GDate\n -> Int\ngDateDaysBetween date1 date2 =\n fromIntegral $ unsafePerformIO $ with date1 $ \\ptr1 ->\n with date2 $ \\ptr2 ->\n {# call g_date_days_between #} (castPtr ptr1) $ castPtr ptr2\n\ngDateCompare :: GDate\n -> GDate\n -> Ordering\ngDateCompare date1 date2 =\n let result = fromIntegral $ unsafePerformIO $ with date1 $ \\ptr1 ->\n with date2 $ \\ptr2 ->\n {# call g_date_compare #} (castPtr ptr1) $ castPtr ptr2\n ordering | result < 0 = LT\n | result > 0 = GT\n | otherwise = EQ\n in ordering\n\ninstance Ord GDate where\n compare = gDateCompare\n\ngDateClamp :: GDate\n -> GDate\n -> GDate\n -> GDate\ngDateClamp date minDate maxDate =\n unsafePerformIO $ with date $ \\ptr ->\n with minDate $ \\minPtr ->\n with maxDate $ \\maxPtr ->\n do {# call g_date_clamp #} (castPtr ptr) (castPtr minPtr) $ castPtr maxPtr\n peek ptr\n\ngDateDay :: GDate\n -> GDateDay\ngDateDay date =\n GDateDay $ unsafePerformIO $ with date $ {# call g_date_get_day #} . castPtr\n\ngDateMonth :: GDate\n -> GDateMonth\ngDateMonth date =\n toEnum $ fromIntegral $ unsafePerformIO $ with date $ {# call g_date_get_month #} . castPtr\n\ngDateYear :: GDate\n -> GDateYear\ngDateYear date =\n GDateYear $ unsafePerformIO $ with date $ {# call g_date_get_year #} . castPtr\n\ngDateWeekday :: GDate\n -> GDateWeekday\ngDateWeekday date =\n toEnum $ fromIntegral $ unsafePerformIO $ with date $ {# call g_date_get_weekday #} . castPtr\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK)\n--\n-- Author : Peter Gavin\n--\n-- Created: 19 March 2002\n--\n-- Copyright (C) 2002 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\nmodule System.Glib.GDate (\n GTimeValPart,\n GTimeVal(..),\n gGetCurrentTime,\n gUSleep,\n gTimeValAdd,\n gTimeValFromISO8601,\n gTimeValToISO8601,\n GDate(..),\n GDateDay,\n GDateMonth,\n GDateYear,\n GDateJulianDay,\n GDateWeekday,\n gDateValidJulian,\n gDateValidDMY,\n gDateNewJulian,\n gDateNewDMY,\n gDateSetDay,\n gDateSetMonth,\n gDateSetYear,\n gDateNewTimeVal,\n gDateParse,\n gDateAddDays,\n gDateSubtractDays,\n gDateAddMonths,\n gDateSubtractMonths,\n gDateAddYears,\n gDateSubtractYears,\n gDateDaysBetween,\n gDateCompare,\n gDateClamp,\n gDateDay,\n gDateMonth,\n gDateYear,\n gDateWeekday\n ) where\n\nimport Control.Monad (liftM)\nimport System.Glib.FFI\nimport System.Glib.UTFString\n\ntype GTimeValPart = {# type glong #}\ndata GTimeVal = GTimeVal { gTimeValSec :: GTimeValPart\n , gTimeValUSec :: GTimeValPart }\n deriving (Eq, Ord)\ninstance Storable GTimeVal where\n sizeOf _ = {# sizeof GTimeVal #}\n alignment _ = alignment (undefined :: CString)\n peek ptr =\n do sec <- {# get GTimeVal->tv_sec #} ptr\n uSec <- {# get GTimeVal->tv_usec #} ptr\n return $ GTimeVal sec uSec\n poke ptr (GTimeVal sec uSec) =\n do {# set GTimeVal->tv_sec #} ptr sec\n {# set GTimeVal->tv_usec #} ptr uSec\n\ngGetCurrentTime :: IO GTimeVal\ngGetCurrentTime =\n alloca $ \\ptr ->\n do {# call g_get_current_time #} $ castPtr ptr\n peek ptr\n\ngUSleep :: GTimeValPart\n -> IO ()\ngUSleep microseconds =\n {# call g_usleep #} $ fromIntegral microseconds\n\ngTimeValAdd :: GTimeVal\n -> GTimeValPart\n -> GTimeVal\ngTimeValAdd time microseconds =\n unsafePerformIO $ with time $ \\ptr ->\n do {# call g_time_val_add #} (castPtr ptr) microseconds\n peek ptr\n\ngTimeValFromISO8601 :: String\n -> Maybe GTimeVal\ngTimeValFromISO8601 isoDate =\n unsafePerformIO $ withUTFString isoDate $ \\cISODate ->\n alloca $ \\ptr ->\n do success <- liftM toBool $ {# call g_time_val_from_iso8601 #} cISODate $ castPtr ptr\n if success\n then liftM Just $ peek ptr\n else return Nothing\n\ngTimeValToISO8601 :: GTimeVal\n -> String\ngTimeValToISO8601 time =\n unsafePerformIO $ with time $ \\ptr ->\n {# call g_time_val_to_iso8601 #} (castPtr ptr) >>= readUTFString\n\nnewtype GDateDay = GDateDay {# type GDateDay #}\n deriving (Eq, Ord)\ninstance Bounded GDateDay where\n minBound = GDateDay 1\n maxBound = GDateDay 31\n\n{# enum GDateMonth {underscoreToCase} deriving (Eq, Ord) #}\ninstance Bounded GDateMonth where\n minBound = GDateJanuary\n maxBound = GDateDecember\n\nnewtype GDateYear = GDateYear {# type GDateYear #}\n deriving (Eq, Ord)\ninstance Bounded GDateYear where\n minBound = GDateYear 1\n maxBound = GDateYear (maxBound :: {# type guint16 #})\n\ntype GDateJulianDay = {# type guint32 #}\nnewtype GDate = GDate { gDateJulianDay :: GDateJulianDay }\n deriving (Eq)\ninstance Storable GDate where\n sizeOf _ = {# sizeof GDate #}\n alignment _ = alignment (undefined :: CString)\n peek =\n (liftM (GDate . fromIntegral)) . {# call g_date_get_julian #} . castPtr\n poke ptr val =\n {# call g_date_set_julian #} (castPtr ptr) $ gDateJulianDay val\n\n{# enum GDateWeekday {underscoreToCase} deriving (Eq, Ord) #}\ninstance Bounded GDateWeekday where\n minBound = GDateMonday\n maxBound = GDateSunday\n\ngDateValidJulian :: GDateJulianDay\n -> Bool\ngDateValidJulian =\n toBool . {# call fun g_date_valid_julian #}\n\ngDateValidDMY :: GDateDay\n -> GDateMonth\n -> GDateYear\n -> Bool\ngDateValidDMY (GDateDay day) month (GDateYear year) =\n toBool $ {# call fun g_date_valid_dmy #} day\n (fromIntegral $ fromEnum month)\n year\n\ngDateNewJulian :: GDateJulianDay\n -> Maybe GDate\ngDateNewJulian julian =\n if gDateValidJulian julian\n then Just $ GDate julian\n else Nothing\n\ngDateNewDMY :: GDateDay\n -> GDateMonth\n -> GDateYear\n -> Maybe GDate\ngDateNewDMY day month year =\n if gDateValidDMY day month year\n then Just $ unsafePerformIO $ alloca $ \\ptr ->\n do let GDateDay day' = day\n GDateYear year' = year\n {# call g_date_set_dmy #} (castPtr ptr)\n day'\n (fromIntegral $ fromEnum month)\n year'\n peek ptr\n else Nothing\n\ngDateSetDay :: GDate\n -> GDateDay\n -> Maybe GDate\ngDateSetDay date (GDateDay day) =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_set_day #} (castPtr ptr) day\n valid <- liftM toBool $ {# call g_date_valid #} $ castPtr ptr\n if valid\n then liftM Just $ peek ptr\n else return Nothing\n\ngDateSetMonth :: GDate\n -> GDateMonth\n -> Maybe GDate\ngDateSetMonth date month =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_set_month #} (castPtr ptr) $ fromIntegral $ fromEnum month\n valid <- liftM toBool $ {# call g_date_valid #} $ castPtr ptr\n if valid\n then liftM Just $ peek ptr\n else return Nothing\n\ngDateSetYear :: GDate\n -> GDateYear\n -> Maybe GDate\ngDateSetYear date (GDateYear year) =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_set_year #} (castPtr ptr) year\n valid <- liftM toBool $ {# call g_date_valid #} $ castPtr ptr\n if valid\n then liftM Just $ peek ptr\n else return Nothing\n\ngDateNewTimeVal :: GTimeVal\n -> GDate\ngDateNewTimeVal timeVal =\n unsafePerformIO $ alloca $ \\ptr ->\n with timeVal $ \\timeValPtr ->\n do {# call g_date_set_time_val #} (castPtr ptr) $ castPtr timeValPtr\n peek ptr\n\ngDateParse :: String\n -> IO (Maybe GDate)\ngDateParse str =\n alloca $ \\ptr ->\n do withUTFString str $ {# call g_date_set_parse #} $ castPtr ptr\n valid <- liftM toBool $ {# call g_date_valid #} $ castPtr ptr\n if valid\n then liftM Just $ peek ptr\n else return Nothing\n\ngDateAddDays :: GDate\n -> Word\n -> GDate\ngDateAddDays date nDays =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_add_days #} (castPtr ptr) $ fromIntegral nDays\n peek ptr\n\ngDateSubtractDays :: GDate\n -> Word\n -> GDate\ngDateSubtractDays date nDays =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_subtract_days #} (castPtr ptr) $ fromIntegral nDays\n peek ptr\n\ngDateAddMonths :: GDate\n -> Word\n -> GDate\ngDateAddMonths date nMonths =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_add_months #} (castPtr ptr) $ fromIntegral nMonths\n peek ptr\n\ngDateSubtractMonths :: GDate\n -> Word\n -> GDate\ngDateSubtractMonths date nMonths =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_subtract_months #} (castPtr ptr) $ fromIntegral nMonths\n peek ptr\n\ngDateAddYears :: GDate\n -> Word\n -> GDate\ngDateAddYears date nYears =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_add_years #} (castPtr ptr) $ fromIntegral nYears\n peek ptr\n\ngDateSubtractYears :: GDate\n -> Word\n -> GDate\ngDateSubtractYears date nYears =\n unsafePerformIO $ with date $ \\ptr ->\n do {# call g_date_subtract_years #} (castPtr ptr) $ fromIntegral nYears\n peek ptr\n\ngDateDaysBetween :: GDate\n -> GDate\n -> Int\ngDateDaysBetween date1 date2 =\n fromIntegral $ unsafePerformIO $ with date1 $ \\ptr1 ->\n with date2 $ \\ptr2 ->\n {# call g_date_days_between #} (castPtr ptr1) $ castPtr ptr2\n\ngDateCompare :: GDate\n -> GDate\n -> Ordering\ngDateCompare date1 date2 =\n let result = fromIntegral $ unsafePerformIO $ with date1 $ \\ptr1 ->\n with date2 $ \\ptr2 ->\n {# call g_date_compare #} (castPtr ptr1) $ castPtr ptr2\n ordering | result < 0 = LT\n | result > 0 = GT\n | otherwise = EQ\n in ordering\n\ninstance Ord GDate where\n compare = gDateCompare\n\ngDateClamp :: GDate\n -> GDate\n -> GDate\n -> GDate\ngDateClamp date minDate maxDate =\n unsafePerformIO $ with date $ \\ptr ->\n with minDate $ \\minPtr ->\n with maxDate $ \\maxPtr ->\n do {# call g_date_clamp #} (castPtr ptr) (castPtr minPtr) $ castPtr maxPtr\n peek ptr\n\ngDateDay :: GDate\n -> GDateDay\ngDateDay date =\n GDateDay $ unsafePerformIO $ with date $ {# call g_date_get_day #} . castPtr\n\ngDateMonth :: GDate\n -> GDateMonth\ngDateMonth date =\n toEnum $ fromIntegral $ unsafePerformIO $ with date $ {# call g_date_get_month #} . castPtr\n\ngDateYear :: GDate\n -> GDateYear\ngDateYear date =\n GDateYear $ unsafePerformIO $ with date $ {# call g_date_get_year #} . castPtr\n\ngDateWeekday :: GDate\n -> GDateWeekday\ngDateWeekday date =\n toEnum $ fromIntegral $ unsafePerformIO $ with date $ {# call g_date_get_weekday #} . castPtr\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"a7f3b7d422c60071c2bd802aff5323bca45d4ea5","subject":"Remove spurious ',' which upset haddock","message":"Remove spurious ',' which upset haddock","repos":"vincenthz\/webkit","old_file":"cairo\/Graphics\/Rendering\/Cairo\/Types.chs","new_file":"cairo\/Graphics\/Rendering\/Cairo\/Types.chs","new_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Types\n-- Copyright : (c) Paolo Martini 2005\n-- License : BSD-style (see cairo\/COPYRIGHT)\n--\n-- Maintainer : p.martini@neuralnoise.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Haskell bindings to the cairo types.\n-----------------------------------------------------------------------------\n\n-- #hide\nmodule Graphics.Rendering.Cairo.Types (\n Matrix(Matrix), MatrixPtr\n , Cairo(Cairo), unCairo\n , Surface(Surface), withSurface, mkSurface, manageSurface\n , Pattern(Pattern), unPattern\n , Status(..)\n , Operator(..)\n , Antialias(..)\n , FillRule(..)\n , LineCap(..)\n , LineJoin(..)\n , ScaledFont(..), unScaledFont\n , FontFace(..), unFontFace\n , Glyph, unGlyph\n , TextExtentsPtr\n , TextExtents(..)\n , FontExtentsPtr\n , FontExtents(..)\n , FontSlant(..)\n , FontWeight(..)\n , SubpixelOrder(..)\n , HintStyle(..)\n , HintMetrics(..)\n , FontOptions(..), withFontOptions, mkFontOptions\n , Path(..), unPath\n , Content(..)\n , Format(..)\n , Extend(..)\n , Filter(..)\n\n , cIntConv\n , cFloatConv\n , cFromBool\n , cToBool\n , cToEnum\n , cFromEnum\n , peekFloatConv\n , withFloatConv\n\n ) where\n\n{#import Graphics.Rendering.Cairo.Matrix#}\n\nimport Foreign hiding (rotate)\nimport CForeign\n\nimport Monad (liftM)\n\n{#context lib=\"cairo\" prefix=\"cairo\"#}\n\n-- not visible\n{#pointer *cairo_t as Cairo newtype#}\nunCairo (Cairo x) = x\n\n-- | The medium to draw on.\n{#pointer *surface_t as Surface foreign newtype#}\nwithSurface (Surface x) = withForeignPtr x\n\nmkSurface :: Ptr Surface -> IO Surface\nmkSurface surfacePtr = do\n surfaceForeignPtr <- newForeignPtr_ surfacePtr\n return (Surface surfaceForeignPtr)\n\nmanageSurface :: Surface -> IO ()\nmanageSurface (Surface surfaceForeignPtr) = do\n addForeignPtrFinalizer surfaceDestroy surfaceForeignPtr\n\nforeign import ccall unsafe \"&cairo_surface_destroy\"\n surfaceDestroy :: FinalizerPtr Surface\n\n-- | Patterns can be simple solid colors, various kinds of gradients or\n-- bitmaps. The current pattern for a 'Render' context is used by the 'stroke',\n-- 'fill' and paint operations. These operations composite the current pattern\n-- with the target surface using the currently selected 'Operator'.\n--\n{#pointer *pattern_t as Pattern newtype#}\nunPattern (Pattern x) = x\n\n-- | Cairo status.\n--\n-- * 'Status' is used to indicate errors that can occur when using\n-- Cairo. In some cases it is returned directly by functions. When using\n-- 'Graphics.Rendering.Cairo.Render', the last error, if any, is stored\n-- in the monad and can be retrieved with 'Graphics.Rendering.Cairo.status'.\n--\n{#enum status_t as Status {underscoreToCase} deriving(Eq)#}\n\n-- | Composition operator for all drawing operations.\n--\n{#enum operator_t as Operator {underscoreToCase}#}\n\n-- | Specifies the type of antialiasing to do when rendering text or shapes\n--\n-- ['AntialiasDefault'] Use the default antialiasing for the subsystem\n-- and target device.\n--\n-- ['AntialiasNone'] Use a bilevel alpha mask.\n--\n-- ['AntialiasGray'] Perform single-color antialiasing (using shades of\n-- gray for black text on a white background, for example).\n--\n-- ['AntialiasSubpixel'] Perform antialiasing by taking advantage of\n-- the order of subpixel elements on devices such as LCD panels.\n--\n{#enum antialias_t as Antialias {underscoreToCase}#}\n\n-- | Specify how paths are filled.\n--\n-- * For both fill rules, whether or not a point is included in the fill is\n-- determined by taking a ray from that point to infinity and looking at\n-- intersections with the path. The ray can be in any direction, as long\n-- as it doesn't pass through the end point of a segment or have a tricky\n-- intersection such as intersecting tangent to the path. (Note that\n-- filling is not actually implemented in this way. This is just a\n-- description of the rule that is applied.)\n--\n-- ['FillRuleWinding'] If the path crosses the ray from left-to-right,\n-- counts +1. If the path crosses the ray from right to left, counts -1.\n-- (Left and right are determined from the perspective of looking along\n-- the ray from the starting point.) If the total count is non-zero, the\n-- point will be filled.\n--\n-- ['FillRuleEvenOdd'] Counts the total number of intersections,\n-- without regard to the orientation of the contour. If the total number\n-- of intersections is odd, the point will be filled.\n--\n{#enum fill_rule_t as FillRule {underscoreToCase}#}\n\n-- | Specify line endings.\n--\n-- ['LineCapButt'] Start(stop) the line exactly at the start(end) point.\n--\n-- ['LineCapRound'] Use a round ending, the center of the circle is the\n-- end point.\n--\n-- ['LineCapSquare'] Use squared ending, the center of the square is the\n-- end point\n--\n{#enum line_cap_t as LineCap {underscoreToCase}#}\n\n-- | Specify how lines join.\n--\n{#enum line_join_t as LineJoin {underscoreToCase}#}\n\n{#pointer *scaled_font_t as ScaledFont newtype#}\nunScaledFont (ScaledFont x) = x\n\n{#pointer *font_face_t as FontFace newtype#}\nunFontFace (FontFace x) = x\n\n{#pointer *glyph_t as Glyph newtype#}\nunGlyph (Glyph x) = x\n\n{#pointer *text_extents_t as TextExtentsPtr -> TextExtents#}\n\n-- | Specify the extents of a text.\ndata TextExtents = TextExtents {\n textExtentsXbearing :: Double\n , textExtentsYbearing :: Double\n , textExtentsWidth :: Double\n , textExtentsHeight :: Double\n , textExtentsXadvance :: Double\n , textExtentsYadvance :: Double\n }\n\ninstance Storable TextExtents where\n sizeOf _ = {#sizeof text_extents_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n x_bearing <- {#get text_extents_t->x_bearing#} p\n y_bearing <- {#get text_extents_t->y_bearing#} p\n width <- {#get text_extents_t->width#} p\n height <- {#get text_extents_t->height#} p\n x_advance <- {#get text_extents_t->x_advance#} p\n y_advance <- {#get text_extents_t->y_advance#} p\n return $ TextExtents (cFloatConv x_bearing) (cFloatConv y_bearing)\n (cFloatConv width) (cFloatConv height)\n (cFloatConv x_advance) (cFloatConv y_advance)\n poke p (TextExtents x_bearing y_bearing width height x_advance y_advance) = do\n {#set text_extents_t->x_bearing#} p (cFloatConv x_bearing)\n {#set text_extents_t->y_bearing#} p (cFloatConv y_bearing)\n {#set text_extents_t->width#} p (cFloatConv width)\n {#set text_extents_t->height#} p (cFloatConv height)\n {#set text_extents_t->x_advance#} p (cFloatConv x_advance)\n {#set text_extents_t->y_advance#} p (cFloatConv y_advance)\n return ()\n\n{#pointer *font_extents_t as FontExtentsPtr -> FontExtents#}\n\n-- | Result of querying the font extents.\ndata FontExtents = FontExtents {\n fontExtentsAscent :: Double\n , fontExtentsDescent :: Double\n , fontExtentsHeight :: Double\n , fontExtentsMaxXadvance :: Double\n , fontExtentsMaxYadvance :: Double\n }\n\ninstance Storable FontExtents where\n sizeOf _ = {#sizeof font_extents_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n ascent <- {#get font_extents_t->ascent#} p\n descent <- {#get font_extents_t->descent#} p\n height <- {#get font_extents_t->height#} p\n max_x_advance <- {#get font_extents_t->max_x_advance#} p\n max_y_advance <- {#get font_extents_t->max_y_advance#} p\n return $ FontExtents (cFloatConv ascent) (cFloatConv descent) (cFloatConv height)\n (cFloatConv max_x_advance) (cFloatConv max_y_advance)\n poke p (FontExtents ascent descent height max_x_advance max_y_advance) = do\n {#set font_extents_t->ascent#} p (cFloatConv ascent)\n {#set font_extents_t->descent#} p (cFloatConv descent)\n {#set font_extents_t->height#} p (cFloatConv height)\n {#set font_extents_t->max_x_advance#} p (cFloatConv max_x_advance)\n {#set font_extents_t->max_y_advance#} p (cFloatConv max_y_advance)\n return ()\n\n-- | Specify font slant.\n{#enum font_slant_t as FontSlant {underscoreToCase}#}\n\n-- | Specify font weight.\n{#enum font_weight_t as FontWeight {underscoreToCase}#}\n\n-- | The subpixel order specifies the order of color elements within each pixel\n-- on the display device when rendering with an antialiasing mode of\n-- 'AntialiasSubpixel'.\n--\n-- ['SubpixelOrderDefault'] Use the default subpixel order for for the\n-- target device\n--\n-- ['SubpixelOrderRgb'] Subpixel elements are arranged horizontally\n-- with red at the left\n--\n-- ['SubpixelOrderBgr'] Subpixel elements are arranged horizontally\n-- with blue at the left\n--\n-- ['SubpixelOrderVrgb'] Subpixel elements are arranged vertically\n-- with red at the top\n--\n-- ['SubpixelOrderVbgr'] Subpixel elements are arranged vertically\n-- with blue at the top \n--\n{#enum subpixel_order_t as SubpixelOrder {underscoreToCase}#}\n\n-- | Specifies the type of hinting to do on font outlines.\n--\n-- Hinting is the process of fitting outlines to the pixel grid in order to\n-- improve the appearance of the result. Since hinting outlines involves\n-- distorting them, it also reduces the faithfulness to the original outline\n-- shapes. Not all of the outline hinting styles are supported by all font\n-- backends.\n--\n-- ['HintStyleDefault'] Use the default hint style for for font backend and\n-- target device\n--\n-- ['HintStyleNone'] Do not hint outlines\n--\n-- ['HintStyleSlight'] Hint outlines slightly to improve contrast while\n-- retaining good fidelity to the original shapes.\n--\n-- ['HintStyleMedium'] Hint outlines with medium strength giving a compromise\n-- between fidelity to the original shapes and contrast\n--\n-- ['HintStyleFull'] Hint outlines to maximize contrast\n--\n{#enum hint_style_t as HintStyle {underscoreToCase}#}\n\n-- | Specifies whether to hint font metrics.\n--\n-- Hinting font metrics means quantizing them so that they are integer values\n-- in device space. Doing this improves the consistency of letter and line\n-- spacing, however it also means that text will be laid out differently at\n-- different zoom factors.\n--\n-- ['HintMetricsDefault'] Hint metrics in the default manner for the font\n-- backend and target device\n--\n-- ['HintMetricsOff'] Do not hint font metrics\n--\n-- ['HintMetricsOn'] Hint font metrics\n--\n--\n{#enum hint_metrics_t as HintMetrics {underscoreToCase}#}\n\n-- | Specifies how to render text.\n{#pointer *font_options_t as FontOptions foreign newtype#}\n\nwithFontOptions (FontOptions fptr) = withForeignPtr fptr\n\nmkFontOptions :: Ptr FontOptions -> IO FontOptions\nmkFontOptions fontOptionsPtr = do\n fontOptionsForeignPtr <- newForeignPtr fontOptionsDestroy fontOptionsPtr\n return (FontOptions fontOptionsForeignPtr)\n\nforeign import ccall unsafe \"&cairo_font_options_destroy\"\n fontOptionsDestroy :: FinalizerPtr FontOptions\n\n-- XXX: pathToList :: Path -> [PathData]\n-- \n-- http:\/\/cairographics.org\/manual\/bindings-path.html\n-- \n-- {#enum path_data_type_t as PathDataType {underscoreToCase}#}\n-- \n-- type Point = (Double, Double)\n-- data PathData = PathMoveTo Point\n-- | PathLineTo Point\n-- | PathCurveTo Point Point Point\n-- | PathClose\n\n-- | A Cairo path.\n--\n-- * A path is a sequence of drawing operations that are accumulated until\n-- 'Graphics.Rendering.Cairo.stroke' is called. Using a path is particularly\n-- useful when drawing lines with special join styles and\n-- 'Graphics.Rendering.Cairo.closePath'.\n--\n{#pointer *path_t as Path newtype#}\nunPath (Path x) = x\n\n{#enum content_t as Content {underscoreToCase}#}\n\ndata Format = FormatARGB32\n | FormatRGB24\n | FormatA8\n | FormatA1\n deriving (Enum)\n\n-- | FIXME: We should find out about this.\n{#enum extend_t as Extend {underscoreToCase}#}\n\n-- | Specify how filtering is done.\n{#enum filter_t as Filter {underscoreToCase}#}\n\n-- Marshalling functions\n\ncIntConv :: (Integral a, Integral b) => a -> b\ncIntConv = fromIntegral\n\ncFloatConv :: (RealFloat a, RealFloat b) => a -> b\ncFloatConv = realToFrac\n\ncFromBool :: Num a => Bool -> a\ncFromBool = fromBool\n\ncToBool :: Num a => a -> Bool\ncToBool = toBool\n\ncToEnum :: (Integral i, Enum e) => i -> e\ncToEnum = toEnum . cIntConv\n\ncFromEnum :: (Enum e, Integral i) => e -> i\ncFromEnum = cIntConv . fromEnum\n\npeekFloatConv :: (Storable a, RealFloat a, RealFloat b) => Ptr a -> IO b\npeekFloatConv = liftM cFloatConv . peek\n\nwithFloatConv :: (Storable b, RealFloat a, RealFloat b) => a -> (Ptr b -> IO c) -> IO c\nwithFloatConv = with . cFloatConv\n\nwithArrayFloatConv :: (Storable b, RealFloat a, RealFloat b) => [a] -> (Ptr b -> IO b1) -> IO b1\nwithArrayFloatConv = withArray . map (cFloatConv)\n","old_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Types\n-- Copyright : (c) Paolo Martini 2005\n-- License : BSD-style (see cairo\/COPYRIGHT)\n--\n-- Maintainer : p.martini@neuralnoise.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Haskell bindings to the cairo types.\n-----------------------------------------------------------------------------\n\n-- #hide\nmodule Graphics.Rendering.Cairo.Types (\n Matrix(Matrix), MatrixPtr\n , Cairo(Cairo), unCairo\n , Surface(Surface), withSurface, mkSurface, manageSurface,\n , Pattern(Pattern), unPattern\n , Status(..)\n , Operator(..)\n , Antialias(..)\n , FillRule(..)\n , LineCap(..)\n , LineJoin(..)\n , ScaledFont(..), unScaledFont\n , FontFace(..), unFontFace\n , Glyph, unGlyph\n , TextExtentsPtr\n , TextExtents(..)\n , FontExtentsPtr\n , FontExtents(..)\n , FontSlant(..)\n , FontWeight(..)\n , SubpixelOrder(..)\n , HintStyle(..)\n , HintMetrics(..)\n , FontOptions(..), withFontOptions, mkFontOptions\n , Path(..), unPath\n , Content(..)\n , Format(..)\n , Extend(..)\n , Filter(..)\n\n , cIntConv\n , cFloatConv\n , cFromBool\n , cToBool\n , cToEnum\n , cFromEnum\n , peekFloatConv\n , withFloatConv\n\n ) where\n\n{#import Graphics.Rendering.Cairo.Matrix#}\n\nimport Foreign hiding (rotate)\nimport CForeign\n\nimport Monad (liftM)\n\n{#context lib=\"cairo\" prefix=\"cairo\"#}\n\n-- not visible\n{#pointer *cairo_t as Cairo newtype#}\nunCairo (Cairo x) = x\n\n-- | The medium to draw on.\n{#pointer *surface_t as Surface foreign newtype#}\nwithSurface (Surface x) = withForeignPtr x\n\nmkSurface :: Ptr Surface -> IO Surface\nmkSurface surfacePtr = do\n surfaceForeignPtr <- newForeignPtr_ surfacePtr\n return (Surface surfaceForeignPtr)\n\nmanageSurface :: Surface -> IO ()\nmanageSurface (Surface surfaceForeignPtr) = do\n addForeignPtrFinalizer surfaceDestroy surfaceForeignPtr\n\nforeign import ccall unsafe \"&cairo_surface_destroy\"\n surfaceDestroy :: FinalizerPtr Surface\n\n-- | Patterns can be simple solid colors, various kinds of gradients or\n-- bitmaps. The current pattern for a 'Render' context is used by the 'stroke',\n-- 'fill' and paint operations. These operations composite the current pattern\n-- with the target surface using the currently selected 'Operator'.\n--\n{#pointer *pattern_t as Pattern newtype#}\nunPattern (Pattern x) = x\n\n-- | Cairo status.\n--\n-- * 'Status' is used to indicate errors that can occur when using\n-- Cairo. In some cases it is returned directly by functions. When using\n-- 'Graphics.Rendering.Cairo.Render', the last error, if any, is stored\n-- in the monad and can be retrieved with 'Graphics.Rendering.Cairo.status'.\n--\n{#enum status_t as Status {underscoreToCase} deriving(Eq)#}\n\n-- | Composition operator for all drawing operations.\n--\n{#enum operator_t as Operator {underscoreToCase}#}\n\n-- | Specifies the type of antialiasing to do when rendering text or shapes\n--\n-- ['AntialiasDefault'] Use the default antialiasing for the subsystem\n-- and target device.\n--\n-- ['AntialiasNone'] Use a bilevel alpha mask.\n--\n-- ['AntialiasGray'] Perform single-color antialiasing (using shades of\n-- gray for black text on a white background, for example).\n--\n-- ['AntialiasSubpixel'] Perform antialiasing by taking advantage of\n-- the order of subpixel elements on devices such as LCD panels.\n--\n{#enum antialias_t as Antialias {underscoreToCase}#}\n\n-- | Specify how paths are filled.\n--\n-- * For both fill rules, whether or not a point is included in the fill is\n-- determined by taking a ray from that point to infinity and looking at\n-- intersections with the path. The ray can be in any direction, as long\n-- as it doesn't pass through the end point of a segment or have a tricky\n-- intersection such as intersecting tangent to the path. (Note that\n-- filling is not actually implemented in this way. This is just a\n-- description of the rule that is applied.)\n--\n-- ['FillRuleWinding'] If the path crosses the ray from left-to-right,\n-- counts +1. If the path crosses the ray from right to left, counts -1.\n-- (Left and right are determined from the perspective of looking along\n-- the ray from the starting point.) If the total count is non-zero, the\n-- point will be filled.\n--\n-- ['FillRuleEvenOdd'] Counts the total number of intersections,\n-- without regard to the orientation of the contour. If the total number\n-- of intersections is odd, the point will be filled.\n--\n{#enum fill_rule_t as FillRule {underscoreToCase}#}\n\n-- | Specify line endings.\n--\n-- ['LineCapButt'] Start(stop) the line exactly at the start(end) point.\n--\n-- ['LineCapRound'] Use a round ending, the center of the circle is the\n-- end point.\n--\n-- ['LineCapSquare'] Use squared ending, the center of the square is the\n-- end point\n--\n{#enum line_cap_t as LineCap {underscoreToCase}#}\n\n-- | Specify how lines join.\n--\n{#enum line_join_t as LineJoin {underscoreToCase}#}\n\n{#pointer *scaled_font_t as ScaledFont newtype#}\nunScaledFont (ScaledFont x) = x\n\n{#pointer *font_face_t as FontFace newtype#}\nunFontFace (FontFace x) = x\n\n{#pointer *glyph_t as Glyph newtype#}\nunGlyph (Glyph x) = x\n\n{#pointer *text_extents_t as TextExtentsPtr -> TextExtents#}\n\n-- | Specify the extents of a text.\ndata TextExtents = TextExtents {\n textExtentsXbearing :: Double\n , textExtentsYbearing :: Double\n , textExtentsWidth :: Double\n , textExtentsHeight :: Double\n , textExtentsXadvance :: Double\n , textExtentsYadvance :: Double\n }\n\ninstance Storable TextExtents where\n sizeOf _ = {#sizeof text_extents_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n x_bearing <- {#get text_extents_t->x_bearing#} p\n y_bearing <- {#get text_extents_t->y_bearing#} p\n width <- {#get text_extents_t->width#} p\n height <- {#get text_extents_t->height#} p\n x_advance <- {#get text_extents_t->x_advance#} p\n y_advance <- {#get text_extents_t->y_advance#} p\n return $ TextExtents (cFloatConv x_bearing) (cFloatConv y_bearing)\n (cFloatConv width) (cFloatConv height)\n (cFloatConv x_advance) (cFloatConv y_advance)\n poke p (TextExtents x_bearing y_bearing width height x_advance y_advance) = do\n {#set text_extents_t->x_bearing#} p (cFloatConv x_bearing)\n {#set text_extents_t->y_bearing#} p (cFloatConv y_bearing)\n {#set text_extents_t->width#} p (cFloatConv width)\n {#set text_extents_t->height#} p (cFloatConv height)\n {#set text_extents_t->x_advance#} p (cFloatConv x_advance)\n {#set text_extents_t->y_advance#} p (cFloatConv y_advance)\n return ()\n\n{#pointer *font_extents_t as FontExtentsPtr -> FontExtents#}\n\n-- | Result of querying the font extents.\ndata FontExtents = FontExtents {\n fontExtentsAscent :: Double\n , fontExtentsDescent :: Double\n , fontExtentsHeight :: Double\n , fontExtentsMaxXadvance :: Double\n , fontExtentsMaxYadvance :: Double\n }\n\ninstance Storable FontExtents where\n sizeOf _ = {#sizeof font_extents_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n ascent <- {#get font_extents_t->ascent#} p\n descent <- {#get font_extents_t->descent#} p\n height <- {#get font_extents_t->height#} p\n max_x_advance <- {#get font_extents_t->max_x_advance#} p\n max_y_advance <- {#get font_extents_t->max_y_advance#} p\n return $ FontExtents (cFloatConv ascent) (cFloatConv descent) (cFloatConv height)\n (cFloatConv max_x_advance) (cFloatConv max_y_advance)\n poke p (FontExtents ascent descent height max_x_advance max_y_advance) = do\n {#set font_extents_t->ascent#} p (cFloatConv ascent)\n {#set font_extents_t->descent#} p (cFloatConv descent)\n {#set font_extents_t->height#} p (cFloatConv height)\n {#set font_extents_t->max_x_advance#} p (cFloatConv max_x_advance)\n {#set font_extents_t->max_y_advance#} p (cFloatConv max_y_advance)\n return ()\n\n-- | Specify font slant.\n{#enum font_slant_t as FontSlant {underscoreToCase}#}\n\n-- | Specify font weight.\n{#enum font_weight_t as FontWeight {underscoreToCase}#}\n\n-- | The subpixel order specifies the order of color elements within each pixel\n-- on the display device when rendering with an antialiasing mode of\n-- 'AntialiasSubpixel'.\n--\n-- ['SubpixelOrderDefault'] Use the default subpixel order for for the\n-- target device\n--\n-- ['SubpixelOrderRgb'] Subpixel elements are arranged horizontally\n-- with red at the left\n--\n-- ['SubpixelOrderBgr'] Subpixel elements are arranged horizontally\n-- with blue at the left\n--\n-- ['SubpixelOrderVrgb'] Subpixel elements are arranged vertically\n-- with red at the top\n--\n-- ['SubpixelOrderVbgr'] Subpixel elements are arranged vertically\n-- with blue at the top \n--\n{#enum subpixel_order_t as SubpixelOrder {underscoreToCase}#}\n\n-- | Specifies the type of hinting to do on font outlines.\n--\n-- Hinting is the process of fitting outlines to the pixel grid in order to\n-- improve the appearance of the result. Since hinting outlines involves\n-- distorting them, it also reduces the faithfulness to the original outline\n-- shapes. Not all of the outline hinting styles are supported by all font\n-- backends.\n--\n-- ['HintStyleDefault'] Use the default hint style for for font backend and\n-- target device\n--\n-- ['HintStyleNone'] Do not hint outlines\n--\n-- ['HintStyleSlight'] Hint outlines slightly to improve contrast while\n-- retaining good fidelity to the original shapes.\n--\n-- ['HintStyleMedium'] Hint outlines with medium strength giving a compromise\n-- between fidelity to the original shapes and contrast\n--\n-- ['HintStyleFull'] Hint outlines to maximize contrast\n--\n{#enum hint_style_t as HintStyle {underscoreToCase}#}\n\n-- | Specifies whether to hint font metrics.\n--\n-- Hinting font metrics means quantizing them so that they are integer values\n-- in device space. Doing this improves the consistency of letter and line\n-- spacing, however it also means that text will be laid out differently at\n-- different zoom factors.\n--\n-- ['HintMetricsDefault'] Hint metrics in the default manner for the font\n-- backend and target device\n--\n-- ['HintMetricsOff'] Do not hint font metrics\n--\n-- ['HintMetricsOn'] Hint font metrics\n--\n--\n{#enum hint_metrics_t as HintMetrics {underscoreToCase}#}\n\n-- | Specifies how to render text.\n{#pointer *font_options_t as FontOptions foreign newtype#}\n\nwithFontOptions (FontOptions fptr) = withForeignPtr fptr\n\nmkFontOptions :: Ptr FontOptions -> IO FontOptions\nmkFontOptions fontOptionsPtr = do\n fontOptionsForeignPtr <- newForeignPtr fontOptionsDestroy fontOptionsPtr\n return (FontOptions fontOptionsForeignPtr)\n\nforeign import ccall unsafe \"&cairo_font_options_destroy\"\n fontOptionsDestroy :: FinalizerPtr FontOptions\n\n-- XXX: pathToList :: Path -> [PathData]\n-- \n-- http:\/\/cairographics.org\/manual\/bindings-path.html\n-- \n-- {#enum path_data_type_t as PathDataType {underscoreToCase}#}\n-- \n-- type Point = (Double, Double)\n-- data PathData = PathMoveTo Point\n-- | PathLineTo Point\n-- | PathCurveTo Point Point Point\n-- | PathClose\n\n-- | A Cairo path.\n--\n-- * A path is a sequence of drawing operations that are accumulated until\n-- 'Graphics.Rendering.Cairo.stroke' is called. Using a path is particularly\n-- useful when drawing lines with special join styles and\n-- 'Graphics.Rendering.Cairo.closePath'.\n--\n{#pointer *path_t as Path newtype#}\nunPath (Path x) = x\n\n{#enum content_t as Content {underscoreToCase}#}\n\ndata Format = FormatARGB32\n | FormatRGB24\n | FormatA8\n | FormatA1\n deriving (Enum)\n\n-- | FIXME: We should find out about this.\n{#enum extend_t as Extend {underscoreToCase}#}\n\n-- | Specify how filtering is done.\n{#enum filter_t as Filter {underscoreToCase}#}\n\n-- Marshalling functions\n\ncIntConv :: (Integral a, Integral b) => a -> b\ncIntConv = fromIntegral\n\ncFloatConv :: (RealFloat a, RealFloat b) => a -> b\ncFloatConv = realToFrac\n\ncFromBool :: Num a => Bool -> a\ncFromBool = fromBool\n\ncToBool :: Num a => a -> Bool\ncToBool = toBool\n\ncToEnum :: (Integral i, Enum e) => i -> e\ncToEnum = toEnum . cIntConv\n\ncFromEnum :: (Enum e, Integral i) => e -> i\ncFromEnum = cIntConv . fromEnum\n\npeekFloatConv :: (Storable a, RealFloat a, RealFloat b) => Ptr a -> IO b\npeekFloatConv = liftM cFloatConv . peek\n\nwithFloatConv :: (Storable b, RealFloat a, RealFloat b) => a -> (Ptr b -> IO c) -> IO c\nwithFloatConv = with . cFloatConv\n\nwithArrayFloatConv :: (Storable b, RealFloat a, RealFloat b) => [a] -> (Ptr b -> IO b1) -> IO b1\nwithArrayFloatConv = withArray . map (cFloatConv)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"451cef0c63edbdf3e6189c630519a689a3426f9a","subject":"less weird bytestring to iovec code","message":"less weird bytestring to iovec code\n","repos":"aslatter\/xcb-core","old_file":"Foreign\/IOVec.chs","new_file":"Foreign\/IOVec.chs","new_contents":"-- -*-haskell-*-\n\n{-# LANGUAGE ForeignFunctionInterface, BangPatterns #-}\n\nmodule Foreign.IOVec\n (IOVec()\n ,withByteString\n ,withLazyByteString\n ,withIOVec\n ,writev\n )\n where\n\nimport qualified Data.ByteString as S\nimport qualified Data.ByteString.Internal as S\nimport qualified Data.ByteString.Unsafe as S\nimport qualified Data.ByteString.Lazy as L\n\nimport Foreign\nimport Foreign.C.Types\n\n#include \n\n#c\ntypedef struct iovec hs_iovec;\n#endc\n\n{#pointer *hs_iovec as IOVec newtype#}\n\nwithIOVec :: IOVec -> (Ptr IOVec -> IO a) -> IO a\nwithIOVec (IOVec ptr) f = f ptr\n{-# INLINE withIOVec #-}\n\nwithByteString :: S.ByteString -> (IOVec -> Int -> IO b) -> IO b\nwithByteString b = withLazyByteString (L.fromChunks [b])\n\n-- | This is intented for calling into something like writev.\n-- But I suppose that nothing stops you from calling into\n-- readv and blowing away the passed-in ByteString.\nwithLazyByteString :: L.ByteString -> (IOVec -> Int -> IO b) -> IO b\nwithLazyByteString lbs f =\n let bs = L.toChunks lbs\n num = length bs\n in allocaBytes (num * {#sizeof hs_iovec#}) $\n \\vecAry -> do\n fill vecAry 0 bs\n x <- f (IOVec vecAry) num\n touchAllBS bs\n return x\n\n where fill _vecAry !_off [] = return ()\n fill vecAry !off (b:bs) =\n\n let vec = vecAry `plusPtr` (off * {#sizeof hs_iovec#})\n\n in do\n S.unsafeUseAsCStringLen b $ \\(bsptr,bslen) -> do\n {#set hs_iovec->iov_base#} vec $ castPtr $ bsptr\n {#set hs_iovec->iov_len#} vec $ fromIntegral bslen\n fill vecAry (off+1) bs\n\n-- utility functions\ntouchBS :: S.ByteString -> IO ()\ntouchBS b = case S.toForeignPtr b of (fptr,_,_) -> touchForeignPtr fptr\n\ntouchAllBS :: [S.ByteString] -> IO ()\ntouchAllBS xs = mapM_ touchBS xs\n\n-- | Binding to writev using 'withLazyByteString'. For testing.\nwritev :: CInt -> L.ByteString -> IO CSize\nwritev fd bs = withLazyByteString bs $ \\iov count ->\n c_writev fd iov (fromIntegral count)\n\nforeign import ccall unsafe \"writev\" c_writev :: CInt -> IOVec -> CInt -> IO CSize\n","old_contents":"-- -*-haskell-*-\n\n{-# LANGUAGE ForeignFunctionInterface, BangPatterns #-}\n\nmodule Foreign.IOVec\n (IOVec()\n ,withByteString\n ,withLazyByteString\n ,withIOVec\n ,writev\n )\n where\n\nimport qualified Data.ByteString as S\nimport qualified Data.ByteString.Internal as S\nimport qualified Data.ByteString.Lazy as L\n\nimport Foreign\nimport Foreign.C.Types\n\n#include \n\n#c\ntypedef struct iovec hs_iovec;\n#endc\n\n{#pointer *hs_iovec as IOVec newtype#}\n\nwithIOVec :: IOVec -> (Ptr IOVec -> IO a) -> IO a\nwithIOVec (IOVec ptr) f = f ptr\n{-# INLINE withIOVec #-}\n\nwithByteString :: S.ByteString -> (IOVec -> Int -> IO b) -> IO b\nwithByteString b = withLazyByteString (L.fromChunks [b])\n\n-- | This is intented for calling into something like writev.\n-- But I suppose that nothing stops you from calling into\n-- readv and blowing away the passed-in ByteString.\nwithLazyByteString :: L.ByteString -> (IOVec -> Int -> IO b) -> IO b\nwithLazyByteString lbs f =\n let bs = L.toChunks lbs\n num = length bs\n in allocaBytes (num * {#sizeof hs_iovec#}) $ \\vecAry -> go vecAry 0 bs\n\n where go vecAry !off [] = f (IOVec vecAry) off\n go vecAry !off (b:bs) =\n\n let vec = vecAry `plusPtr` (off * {#sizeof hs_iovec#})\n (fptr, bsOff, bsLen) = S.toForeignPtr b\n\n in withForeignPtr fptr $ \\bsPtr -> do\n {#set hs_iovec->iov_base#} vec $ castPtr $ bsPtr `plusPtr` bsOff\n {#set hs_iovec->iov_len#} vec $ fromIntegral bsLen\n go vecAry (off+1) bs\n\n-- | Binding to writev using 'withLazyByteString'\nwritev :: CInt -> L.ByteString -> IO CSize\nwritev fd bs = withLazyByteString bs $ \\iov count ->\n c_writev fd iov (fromIntegral count)\n\nforeign import ccall unsafe \"writev\" c_writev :: CInt -> IOVec -> CInt -> IO CSize\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"f2de20aff92e3d0d32f447060c1ff85af8810f19","subject":"add takeSocket\/writev primitives","message":"add takeSocket\/writev primitives\n","repos":"aslatter\/xcb-core","old_file":"Graphics\/X11\/Xcb\/Internal.chs","new_file":"Graphics\/X11\/Xcb\/Internal.chs","new_contents":"-- -*-haskell-*-\n\n{-# LANGUAGE\n StandaloneDeriving\n ,GeneralizedNewtypeDeriving\n #-}\n\nmodule Graphics.X11.Xcb.Internal where\n\nimport Control.Applicative\nimport Control.Monad\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\nimport qualified Data.ByteString as S\nimport qualified Data.ByteString.Internal as S\nimport qualified Data.ByteString.Lazy as L\n\n{#import Foreign.IOVec#}\n\n#include \n#include \n\npeekIntConv\n :: (Integral a, Num b, Storable a)\n => Ptr a -> IO b\npeekIntConv ptr = fromIntegral `liftM` peek ptr\n\n{-\n Welcome to my sometimes-dodgy FFI bindings to XCB.\n The idea isn't really to write something to directly\n write X apps with, but to write a foundation for \n something higher-level and safer.\n\n So referential transparency can definetly be abused\n with a lot of the calls in here.\n\n So don't do it.\n -}\n\n{#context lib=\"xcb\" prefix=\"xcb_\"#}\n\nwithConnection :: Connection -> (Ptr Connection -> IO b) -> IO b\n{#pointer *connection_t as Connection foreign newtype#}\n{#pointer *setup_t as Setup newtype#} -- no finalizer, part of the Connection\n\n-- | Returns a connection to the indicated X server, as well\n-- as the screen connected to.\n-- The passed in string may be null, in which case\n-- it will be the same as passing in the DISPLAY environment\n-- variable.\nconnect :: String -> IO (Maybe (Connection, Int))\nconnect display\n = withCString display $ \\displayPtr ->\n alloca $ \\screenPtr -> do\n\n cPtr <- {#call connect as connect_#} displayPtr screenPtr\n screen <- peekIntConv screenPtr\n\n if cPtr == nullPtr then return Nothing else do\n\n c <- mkConnection cPtr\n return $ Just (c, screen)\n\n-- | Parse the host, display and screen from a string.\n-- The same as what we would do if the string were\n-- passed to 'connect'.\nparseDisplay :: String -> IO (Maybe (String, Int, Int))\nparseDisplay display\n = withCString display $ \\displayPtr ->\n alloca $ \\hostStringPtr ->\n alloca $ \\displayNumPtr ->\n alloca $ \\screenPtr -> do\n success <- liftM toBool $\n {#call unsafe parse_display#} displayPtr hostStringPtr displayNumPtr screenPtr\n if not success then return Nothing else do\n\n host <- peek hostStringPtr >>= peekCString\n peek hostStringPtr >>= free\n\n displayNum <- peekIntConv displayNumPtr\n screen <- peekIntConv screenPtr\n\n return $ Just (host, displayNum, screen)\n \n-- | Flush the write buffers.\nflush :: Connection -> IO Bool\nflush c = withConnection c $ \\cPtr ->\n liftM toBool $ {#call flush as flush_#} cPtr\n\n-- | The memory backing this data structure is owned\n-- by the passed in Connection - and will magicaly vanish\n-- if your 'Connection' gets GCd before the return value\n-- of this function. Watch out.\nunsafeGetSetup :: Connection -> IO Setup\nunsafeGetSetup c = withConnection c $ \\cPtr ->\n {#call unsafe get_setup#} cPtr\n\n-- | Length of the setup data in units of four bytes.\nsetupLength :: Setup -> IO Word16\nsetupLength (Setup s) = liftM fromIntegral $ {#get setup_t->length#} s\n\n-- | This ByteString is just as unsafe as the passed in connection\n-- object. Please make a copy.\nunsafeSetupData :: Setup -> IO S.ByteString\nunsafeSetupData s@(Setup sPtr) = do\n len <- liftM (4*) $ setupLength s\n sFPtr <- newForeignPtr_ sPtr\n return $ S.fromForeignPtr (castForeignPtr sFPtr) 0 (fromIntegral len)\n\n-- | Maximum size of a single request.\n-- May not be an asynchronous call, as we'll make a call out\n-- on the big-requests extension to find out if we can use that.\nmaximumRequestLength :: Connection -> IO Word32\nmaximumRequestLength c = withConnection c $ \\cPtr ->\n liftM fromIntegral $ {#call get_maximum_request_length#} cPtr\n\n-- | Asynchronous version of 'maximumRequestLength'. The return\n-- from the server is cached for subsequent callse to 'maximumRequestLength'.\nprefetchMaximumReuestLength :: Connection -> IO ()\nprefetchMaximumReuestLength c = withConnection c $ \\cPtr ->\n {#call prefetch_maximum_request_length#} cPtr\n\n-- | Is the connection in an error state?\nconnectionHasError :: Connection -> IO Bool\nconnectionHasError c = withConnection c $ \\cPtr ->\n liftM toBool $ {#call connection_has_error#} cPtr\n\nnewtype Cookie = Cookie CUInt\n\n-- Working with extensions\n{#pointer *extension_t as Extension newtype#} -- static data, no finalizer\n\n-- :-(\ninstance Storable Extension where\n sizeOf (Extension ex) = sizeOf ex\n alignment (Extension ex) = alignment ex\n peekElemOff ptr off = liftM Extension $ peekElemOff (castPtr ptr) off\n pokeElemOff ptr off (Extension ex) = pokeElemOff (castPtr ptr) off ex\n peekByteOff ptr off = liftM Extension $ peekByteOff ptr off\n pokeByteOff ptr off (Extension ex) = pokeByteOff ptr off ex\n peek ptr = liftM Extension $ peek (castPtr ptr)\n poke ptr (Extension ex) = poke (castPtr ptr) ex\n\n{#pointer *query_extension_reply_t as ExtensionInfo newtype#} -- freed with Connection, no finalizer\n\n-- | May block if the data is not already cached. For internal\n-- use only - make a copy if you need something that will live\n-- longer than the scope of the connection.\nunsafeGetExtensionData :: Connection -> Extension -> IO ExtensionInfo\nunsafeGetExtensionData c ext\n = withConnection c $ \\cPtr ->\n {#call get_extension_data#} cPtr ext\n\nextensionPresent :: ExtensionInfo -> IO Bool\nextensionPresent (ExtensionInfo ext)\n = liftM toBool $ {#get query_extension_reply_t->present#} ext\n\nextensionMajorOpcode :: ExtensionInfo -> IO Word8\nextensionMajorOpcode (ExtensionInfo ext)\n = liftM fromIntegral $ {#get query_extension_reply_t->major_opcode#} ext\n\nextensionFirstEvent :: ExtensionInfo -> IO Word8\nextensionFirstEvent (ExtensionInfo ext)\n = liftM fromIntegral $ {#get query_extension_reply_t->first_event#} ext\n\nextensionFirstError :: ExtensionInfo -> IO Word8\nextensionFirstError (ExtensionInfo ext)\n = liftM fromIntegral $ {#get query_extension_reply_t->first_error#} ext\n\n-- | Non-blocking query for extension data\nprefetchExtension :: Connection -> Extension -> IO ()\nprefetchExtension c ext\n = withConnection c $ \\cPtr ->\n {#call prefetch_extension_data#} cPtr ext\n\nclass HasResponseType a where\n responseType :: a -> IO Int\n\nisBigEvent :: HasResponseType a => a -> IO Bool\nisBigEvent ev = (== 35) `liftM` responseType ev\n\nisError :: HasResponseType a => a -> IO Bool\nisError ev = (== 2) `liftM` responseType ev\n\n-- Events\nwithGenericEvent :: GenericEvent -> (Ptr GenericEvent -> IO b) -> IO b\n{#pointer *generic_event_t as GenericEvent foreign newtype#}\nwithGenericBigEvent :: GenericBigEvent -> (Ptr GenericBigEvent -> IO b) -> IO b\n{#pointer *ge_event_t as GenericBigEvent foreign newtype#}\n\n-- | The XCB documentation seems to imply that this can also return\n-- errors, so be careful.\nwaitForEvent :: Connection -> IO GenericEvent\nwaitForEvent c = withConnection c $ \\cPtr -> do\n evPtr <- {#call wait_for_event#} cPtr\n liftM GenericEvent $ newForeignPtr finalizerFree evPtr\n\ninstance HasResponseType GenericEvent where\n responseType = eventResponseType\n\neventResponseType :: GenericEvent -> IO Int\neventResponseType ev = withGenericEvent ev $ \\evPtr ->\n liftM fromIntegral $ {#get generic_event_t->response_type#} evPtr\n\n-- | The conversion is not checked. \nunsafeToBigEvent :: GenericEvent -> GenericBigEvent\nunsafeToBigEvent (GenericEvent ev) = GenericBigEvent . castForeignPtr $ ev\n\n-- | The conversion is not checked.\nunsafeToError :: GenericEvent -> GenericError\nunsafeToError (GenericEvent ev) = GenericError . castForeignPtr $ ev\n\n-- | In units of four bytes. Extra +1 for the 'full_sequence' field\n-- introduced when XCB decodes from the wire.\nbigEventLength :: GenericBigEvent -> IO Word32\nbigEventLength bge = withGenericBigEvent bge $ \\bgePtr -> do\n lenField <- fromIntegral `liftM` {#get ge_event_t->length#} bgePtr\n return $ 8 + 1 + lenField\n\n-- | Unsafe in that referential transperency may be broken - \n-- the ByteString is aliased to the same memory location as the\n-- the event.\nunsafeEventData :: GenericEvent -> IO S.ByteString\nunsafeEventData ge = do\n isErr <- isError ge\n if isErr then unsafeErrorData (unsafeToError ge) else do\n\n isBig <- isBigEvent ge\n if isBig\n then do\n let bge@(GenericBigEvent bgeFPtr) = unsafeToBigEvent ge\n len <- bigEventLength bge\n return $ S.fromForeignPtr (castForeignPtr bgeFPtr) 0 (4 * fromIntegral len)\n else\n let GenericEvent evFPtr = ge\n in return $ S.fromForeignPtr (castForeignPtr evFPtr) 0 32\n\n-- Errors\nwithGenericError :: GenericError -> (Ptr GenericError -> IO b) -> IO b\n{#pointer *generic_error_t as GenericError foreign newtype#}\n\nrequestCheck :: Connection -> Cookie -> IO (Maybe GenericError)\nrequestCheck c cookie\n = withConnection c $ \\cPtr -> do\n errPtr <- xcb_request_check cPtr cookie\n if errPtr == nullPtr then return Nothing else do\n liftM (Just . GenericError) $ newForeignPtr finalizerFree errPtr\n\nforeign import ccall xcb_request_check :: Ptr Connection -> Cookie -> IO (Ptr GenericError)\n\n-- | The returned ByteString is aliased to the same memory\n-- location as the GenericError.\nunsafeErrorData :: GenericError -> IO S.ByteString\nunsafeErrorData (GenericError errFPtr) =\n return $ S.fromForeignPtr (castForeignPtr errFPtr) 0 32\n\n-- Replies\nwithGenericReply :: GenericReply -> (Ptr GenericReply -> IO b) -> IO b\n{#pointer *generic_reply_t as GenericReply foreign newtype#}\n\n-- | Returns the length of the reply in units of four bytes\nreplyLength :: GenericReply -> IO Word32\nreplyLength rep = withGenericReply rep $ \\repPtr -> do\n lenField <- liftM fromIntegral $ {#get generic_reply_t->length#} repPtr\n return $ lenField + 1 -- for the inserted full_sequence field\n\ninstance HasResponseType GenericReply where\n responseType = replyResponseType\n\nreplyResponseType :: GenericReply -> IO Int\nreplyResponseType rep = withGenericReply rep $ \\repPtr ->\n liftM fromIntegral $ {#get generic_reply_t->response_type#} repPtr\n\n-- | Unchecked conversion\nunsafeReplyToError :: GenericReply -> GenericError\nunsafeReplyToError (GenericReply rep) = GenericError . castForeignPtr $ rep\n\n-- | The returned ByteString is aliased to the same memory\n-- location as the 'GenericReply'\nunsafeReplyData :: GenericReply -> IO S.ByteString\nunsafeReplyData rep@(GenericReply repFPtr) = do\n len <- fromIntegral `liftM` replyLength rep\n return $ S.fromForeignPtr (castForeignPtr repFPtr) 0 (4*len)\n\n-- Sending requests\nwithRequestInfo :: RequestInfo -> (Ptr RequestInfo -> IO b) -> IO b\n{#pointer *protocol_request_t as RequestInfo foreign newtype#}\n\nmkRequestInfo :: (Maybe Extension) -> CUInt -> Bool -> IO RequestInfo\nmkRequestInfo ext opcode isVoid = do\n fptr <- mallocForeignPtrBytes {#sizeof protocol_request_t#}\n withForeignPtr fptr $ \\rptr -> do\n {#set protocol_request_t->ext#} rptr $ maybe (Extension nullPtr) id ext\n {#set protocol_request_t->opcode#} rptr (fromIntegral opcode)\n {#set protocol_request_t->isvoid#} rptr (fromBool isVoid)\n return $ RequestInfo fptr\n \n{#enum send_request_flags_t as RequestFlags {underscoreToCase} deriving(Eq, Show)#}\n\n\n-- |Note: the 'count' field in the request info is always\n-- over-written to the number of chunks in the ByteString\nsendRequest :: Connection -> Int -> L.ByteString -> RequestInfo -> IO Cookie\nsendRequest c flags bytes rInfo\n = withConnection c $ \\cPtr ->\n withRequestInfo rInfo $ \\rPtr ->\n withLazyByteString bytes $ \\vec vecNum ->\n withIOVec vec $ \\vecPtr -> do\n {#set protocol_request_t->count#} rPtr (fromIntegral vecNum)\n liftM (Cookie . fromIntegral) $ {#call send_request#} cPtr (fromIntegral flags) (castPtr vecPtr) rPtr\n\n-- | Return 'Nothing' on failure, or the last request id on success.\n-- This must be called before calling 'writev', as it indicates that you would\n-- like full control of the write end of the connection socket.\ntakeSocket :: Connection\n -> FunPtr (Ptr () -> IO ()) -- ^ Callback to return socket\n -> Ptr () -- ^ Callback argument\n -> Int -- ^ Request flags\n -> IO (Maybe Word64)\ntakeSocket c fn fnArg flags\n = withConnection c $ \\cPtr ->\n alloca $ \\countPtr -> do\n ret <- toBool <$> {#call take_socket#} cPtr fn fnArg (fromIntegral flags) countPtr\n countOpt <- if ret then Just . fromIntegral <$> peek countPtr else return Nothing\n return countOpt\n\n-- | Write raw bytes to the connection socket. The count parameter\n-- indicates the number of requests in this call. It is assumed\n-- that 'takeSocket' has been called prior to calling this. We force the\n-- spine of the lazy bytestring argument before consuming it, so watch\n-- out for that.\nwritev :: Connection -> L.ByteString -> Word64 -> IO Bool\nwritev c bytes reqCount\n = withConnection c $ \\cPtr ->\n withLazyByteString bytes $ \\vec vecNum ->\n withIOVec vec $ \\vecPtr ->\n toBool <$> {#call xcb_writev#} cPtr (castPtr vecPtr) (fromIntegral vecNum) (fromIntegral reqCount)\n\nwaitForReply :: Connection -> Cookie -> IO (Either GenericError GenericReply)\nwaitForReply c (Cookie request) =\n withConnection c $ \\cPtr ->\n alloca $ \\errPtrPtr -> do\n repPtr <- {#call wait_for_reply#} cPtr (fromIntegral request) errPtrPtr\n if repPtr == nullPtr then do\n errPtr <- peek errPtrPtr\n errFPtr <- newForeignPtr finalizerFree errPtr\n return . Left . GenericError $ errFPtr\n else do\n repFPtr <- newForeignPtr finalizerFree $ castPtr repPtr\n return . Right . GenericReply $ repFPtr\n\n\n-- Other\ngenerateId :: Connection -> IO Word32\ngenerateId c = withConnection c $ \\cPtr ->\n liftM fromIntegral $ {#call generate_id#} cPtr\n\n\n-- Internal utils\n\n-- | Create a 'Connection' from a reference.\n-- The connection will be shut down when it goes out of scope.\nmkConnection :: Ptr Connection -> IO Connection\nmkConnection = liftM Connection . newForeignPtr finalizerDisconnect\n\n-- | Creates a connection from an unsafe reference,\n-- with no asociated finalzer.\n-- Only use this if the Haskell code does not own the connection.\nmkConnection_ :: Ptr Connection -> IO Connection\nmkConnection_ = liftM Connection . newForeignPtr_\n\n-- | A finalizer for a Ptr Connection which shuts down the connection\n-- and frees all resources associated with it.\nfinalizerDisconnect :: FinalizerPtr Connection\nfinalizerDisconnect = xcb_disconnect\n\nforeign import ccall \"&xcb_disconnect\" xcb_disconnect :: FunPtr (Ptr Connection -> IO ())\n","old_contents":"-- -*-haskell-*-\n\n{-# LANGUAGE\n StandaloneDeriving\n ,GeneralizedNewtypeDeriving\n #-}\n\nmodule Graphics.X11.Xcb.Internal where\n\nimport Control.Monad\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\nimport qualified Data.ByteString as S\nimport qualified Data.ByteString.Internal as S\nimport qualified Data.ByteString.Lazy as L\n\n{#import Foreign.IOVec#}\n\n#include \n#include \n\npeekIntConv\n :: (Integral a, Num b, Storable a)\n => Ptr a -> IO b\npeekIntConv ptr = fromIntegral `liftM` peek ptr\n\n{-\n Welcome to my sometimes-dodgy FFI bindings to XCB.\n The idea isn't really to write something to directly\n write X apps with, but to write a foundation for \n something higher-level and safer.\n\n So referential transparency can definetly be abused\n with a lot of the calls in here.\n\n So don't do it.\n -}\n\n{#context lib=\"xcb\" prefix=\"xcb_\"#}\n\nwithConnection :: Connection -> (Ptr Connection -> IO b) -> IO b\n{#pointer *connection_t as Connection foreign newtype#}\n{#pointer *setup_t as Setup newtype#} -- no finalizer, part of the Connection\n\n-- | Returns a connection to the indicated X server, as well\n-- as the screen connected to.\n-- The passed in string may be null, in which case\n-- it will be the same as passing in the DISPLAY environment\n-- variable.\nconnect :: String -> IO (Maybe (Connection, Int))\nconnect display\n = withCString display $ \\displayPtr ->\n alloca $ \\screenPtr -> do\n\n cPtr <- {#call connect as connect_#} displayPtr screenPtr\n screen <- peekIntConv screenPtr\n\n if cPtr == nullPtr then return Nothing else do\n\n c <- mkConnection cPtr\n return $ Just (c, screen)\n\n-- | Parse the host, display and screen from a string.\n-- The same as what we would do if the string were\n-- passed to 'connect'.\nparseDisplay :: String -> IO (Maybe (String, Int, Int))\nparseDisplay display\n = withCString display $ \\displayPtr ->\n alloca $ \\hostStringPtr ->\n alloca $ \\displayNumPtr ->\n alloca $ \\screenPtr -> do\n success <- liftM toBool $\n {#call unsafe parse_display#} displayPtr hostStringPtr displayNumPtr screenPtr\n if not success then return Nothing else do\n\n host <- peek hostStringPtr >>= peekCString\n peek hostStringPtr >>= free\n\n displayNum <- peekIntConv displayNumPtr\n screen <- peekIntConv screenPtr\n\n return $ Just (host, displayNum, screen)\n \n-- | Flush the write buffers.\nflush :: Connection -> IO Bool\nflush c = withConnection c $ \\cPtr ->\n liftM toBool $ {#call flush as flush_#} cPtr\n\n-- | The memory backing this data structure is owned\n-- by the passed in Connection - and will magicaly vanish\n-- if your 'Connection' gets GCd before the return value\n-- of this function. Watch out.\nunsafeGetSetup :: Connection -> IO Setup\nunsafeGetSetup c = withConnection c $ \\cPtr ->\n {#call unsafe get_setup#} cPtr\n\n-- | Length of the setup data in units of four bytes.\nsetupLength :: Setup -> IO Word16\nsetupLength (Setup s) = liftM fromIntegral $ {#get setup_t->length#} s\n\n-- | This ByteString is just as unsafe as the passed in connection\n-- object. Please make a copy.\nunsafeSetupData :: Setup -> IO S.ByteString\nunsafeSetupData s@(Setup sPtr) = do\n len <- liftM (4*) $ setupLength s\n sFPtr <- newForeignPtr_ sPtr\n return $ S.fromForeignPtr (castForeignPtr sFPtr) 0 (fromIntegral len)\n\n-- | Maximum size of a single request.\n-- May not be an asynchronous call, as we'll make a call out\n-- on the big-requests extension to find out if we can use that.\nmaximumRequestLength :: Connection -> IO Word32\nmaximumRequestLength c = withConnection c $ \\cPtr ->\n liftM fromIntegral $ {#call get_maximum_request_length#} cPtr\n\n-- | Asynchronous version of 'maximumRequestLength'. The return\n-- from the server is cached for subsequent callse to 'maximumRequestLength'.\nprefetchMaximumReuestLength :: Connection -> IO ()\nprefetchMaximumReuestLength c = withConnection c $ \\cPtr ->\n {#call prefetch_maximum_request_length#} cPtr\n\n-- | Is the connection in an error state?\nconnectionHasError :: Connection -> IO Bool\nconnectionHasError c = withConnection c $ \\cPtr ->\n liftM toBool $ {#call connection_has_error#} cPtr\n\nnewtype Cookie = Cookie CUInt\n\n-- Working with extensions\n{#pointer *extension_t as Extension newtype#} -- static data, no finalizer\n\n-- :-(\ninstance Storable Extension where\n sizeOf (Extension ex) = sizeOf ex\n alignment (Extension ex) = alignment ex\n peekElemOff ptr off = liftM Extension $ peekElemOff (castPtr ptr) off\n pokeElemOff ptr off (Extension ex) = pokeElemOff (castPtr ptr) off ex\n peekByteOff ptr off = liftM Extension $ peekByteOff ptr off\n pokeByteOff ptr off (Extension ex) = pokeByteOff ptr off ex\n peek ptr = liftM Extension $ peek (castPtr ptr)\n poke ptr (Extension ex) = poke (castPtr ptr) ex\n\n{#pointer *query_extension_reply_t as ExtensionInfo newtype#} -- freed with Connection, no finalizer\n\n-- | May block if the data is not already cached. For internal\n-- use only - make a copy if you need something that will live\n-- longer than the scope of the connection.\nunsafeGetExtensionData :: Connection -> Extension -> IO ExtensionInfo\nunsafeGetExtensionData c ext\n = withConnection c $ \\cPtr ->\n {#call get_extension_data#} cPtr ext\n\nextensionPresent :: ExtensionInfo -> IO Bool\nextensionPresent (ExtensionInfo ext)\n = liftM toBool $ {#get query_extension_reply_t->present#} ext\n\nextensionMajorOpcode :: ExtensionInfo -> IO Word8\nextensionMajorOpcode (ExtensionInfo ext)\n = liftM fromIntegral $ {#get query_extension_reply_t->major_opcode#} ext\n\nextensionFirstEvent :: ExtensionInfo -> IO Word8\nextensionFirstEvent (ExtensionInfo ext)\n = liftM fromIntegral $ {#get query_extension_reply_t->first_event#} ext\n\nextensionFirstError :: ExtensionInfo -> IO Word8\nextensionFirstError (ExtensionInfo ext)\n = liftM fromIntegral $ {#get query_extension_reply_t->first_error#} ext\n\n-- | Non-blocking query for extension data\nprefetchExtension :: Connection -> Extension -> IO ()\nprefetchExtension c ext\n = withConnection c $ \\cPtr ->\n {#call prefetch_extension_data#} cPtr ext\n\nclass HasResponseType a where\n responseType :: a -> IO Int\n\nisBigEvent :: HasResponseType a => a -> IO Bool\nisBigEvent ev = (== 35) `liftM` responseType ev\n\nisError :: HasResponseType a => a -> IO Bool\nisError ev = (== 2) `liftM` responseType ev\n\n-- Events\nwithGenericEvent :: GenericEvent -> (Ptr GenericEvent -> IO b) -> IO b\n{#pointer *generic_event_t as GenericEvent foreign newtype#}\nwithGenericBigEvent :: GenericBigEvent -> (Ptr GenericBigEvent -> IO b) -> IO b\n{#pointer *ge_event_t as GenericBigEvent foreign newtype#}\n\n-- | The XCB documentation seems to imply that this can also return\n-- errors, so be careful.\nwaitForEvent :: Connection -> IO GenericEvent\nwaitForEvent c = withConnection c $ \\cPtr -> do\n evPtr <- {#call wait_for_event#} cPtr\n liftM GenericEvent $ newForeignPtr finalizerFree evPtr\n\ninstance HasResponseType GenericEvent where\n responseType = eventResponseType\n\neventResponseType :: GenericEvent -> IO Int\neventResponseType ev = withGenericEvent ev $ \\evPtr ->\n liftM fromIntegral $ {#get generic_event_t->response_type#} evPtr\n\n-- | The conversion is not checked. \nunsafeToBigEvent :: GenericEvent -> GenericBigEvent\nunsafeToBigEvent (GenericEvent ev) = GenericBigEvent . castForeignPtr $ ev\n\n-- | The conversion is not checked.\nunsafeToError :: GenericEvent -> GenericError\nunsafeToError (GenericEvent ev) = GenericError . castForeignPtr $ ev\n\n-- | In units of four bytes. Extra +1 for the 'full_sequence' field\n-- introduced when XCB decodes from the wire.\nbigEventLength :: GenericBigEvent -> IO Word32\nbigEventLength bge = withGenericBigEvent bge $ \\bgePtr -> do\n lenField <- fromIntegral `liftM` {#get ge_event_t->length#} bgePtr\n return $ 8 + 1 + lenField\n\n-- | Unsafe in that referential transperency may be broken - \n-- the ByteString is aliased to the same memory location as the\n-- the event.\nunsafeEventData :: GenericEvent -> IO S.ByteString\nunsafeEventData ge = do\n isErr <- isError ge\n if isErr then unsafeErrorData (unsafeToError ge) else do\n\n isBig <- isBigEvent ge\n if isBig\n then do\n let bge@(GenericBigEvent bgeFPtr) = unsafeToBigEvent ge\n len <- bigEventLength bge\n return $ S.fromForeignPtr (castForeignPtr bgeFPtr) 0 (4 * fromIntegral len)\n else\n let GenericEvent evFPtr = ge\n in return $ S.fromForeignPtr (castForeignPtr evFPtr) 0 32\n\n-- Errors\nwithGenericError :: GenericError -> (Ptr GenericError -> IO b) -> IO b\n{#pointer *generic_error_t as GenericError foreign newtype#}\n\nrequestCheck :: Connection -> Cookie -> IO (Maybe GenericError)\nrequestCheck c cookie\n = withConnection c $ \\cPtr -> do\n errPtr <- xcb_request_check cPtr cookie\n if errPtr == nullPtr then return Nothing else do\n liftM (Just . GenericError) $ newForeignPtr finalizerFree errPtr\n\nforeign import ccall xcb_request_check :: Ptr Connection -> Cookie -> IO (Ptr GenericError)\n\n-- | The returned ByteString is aliased to the same memory\n-- location as the GenericError.\nunsafeErrorData :: GenericError -> IO S.ByteString\nunsafeErrorData (GenericError errFPtr) =\n return $ S.fromForeignPtr (castForeignPtr errFPtr) 0 32\n\n-- Replies\nwithGenericReply :: GenericReply -> (Ptr GenericReply -> IO b) -> IO b\n{#pointer *generic_reply_t as GenericReply foreign newtype#}\n\n-- | Returns the length of the reply in units of four bytes\nreplyLength :: GenericReply -> IO Word32\nreplyLength rep = withGenericReply rep $ \\repPtr -> do\n lenField <- liftM fromIntegral $ {#get generic_reply_t->length#} repPtr\n return $ lenField + 1 -- for the inserted full_sequence field\n\ninstance HasResponseType GenericReply where\n responseType = replyResponseType\n\nreplyResponseType :: GenericReply -> IO Int\nreplyResponseType rep = withGenericReply rep $ \\repPtr ->\n liftM fromIntegral $ {#get generic_reply_t->response_type#} repPtr\n\n-- | Unchecked conversion\nunsafeReplyToError :: GenericReply -> GenericError\nunsafeReplyToError (GenericReply rep) = GenericError . castForeignPtr $ rep\n\n-- | The returned ByteString is aliased to the same memory\n-- location as the 'GenericReply'\nunsafeReplyData :: GenericReply -> IO S.ByteString\nunsafeReplyData rep@(GenericReply repFPtr) = do\n len <- fromIntegral `liftM` replyLength rep\n return $ S.fromForeignPtr (castForeignPtr repFPtr) 0 (4*len)\n\n-- Sending requests\nwithRequestInfo :: RequestInfo -> (Ptr RequestInfo -> IO b) -> IO b\n{#pointer *protocol_request_t as RequestInfo foreign newtype#}\n\nmkRequestInfo :: (Maybe Extension) -> CUInt -> Bool -> IO RequestInfo\nmkRequestInfo ext opcode isVoid = do\n fptr <- mallocForeignPtrBytes {#sizeof protocol_request_t#}\n withForeignPtr fptr $ \\rptr -> do\n {#set protocol_request_t->ext#} rptr $ maybe (Extension nullPtr) id ext\n {#set protocol_request_t->opcode#} rptr (fromIntegral opcode)\n {#set protocol_request_t->isvoid#} rptr (fromBool isVoid)\n return $ RequestInfo fptr\n \n{#enum send_request_flags_t as RequestFlags {underscoreToCase} deriving(Eq, Show)#}\n\n\n-- |Note: the 'count' field in the request info is always\n-- over-written to the number of chunks in the ByteString\nsendRequest :: Connection -> Int -> L.ByteString -> RequestInfo -> IO Cookie\nsendRequest c flags bytes rInfo\n = withConnection c $ \\cPtr ->\n withRequestInfo rInfo $ \\rPtr ->\n withLazyByteString bytes $ \\vec vecNum ->\n withIOVec vec $ \\vecPtr -> do\n {#set protocol_request_t->count#} rPtr (fromIntegral vecNum)\n liftM (Cookie . fromIntegral) $ {#call send_request#} cPtr (fromIntegral flags) (castPtr vecPtr) rPtr\n\nwaitForReply :: Connection -> Cookie -> IO (Either GenericError GenericReply)\nwaitForReply c (Cookie request) =\n withConnection c $ \\cPtr ->\n alloca $ \\errPtrPtr -> do\n repPtr <- {#call wait_for_reply#} cPtr (fromIntegral request) errPtrPtr\n if repPtr == nullPtr then do\n errPtr <- peek errPtrPtr\n errFPtr <- newForeignPtr finalizerFree errPtr\n return . Left . GenericError $ errFPtr\n else do\n repFPtr <- newForeignPtr finalizerFree $ castPtr repPtr\n return . Right . GenericReply $ repFPtr\n\n\n-- Other\ngenerateId :: Connection -> IO Word32\ngenerateId c = withConnection c $ \\cPtr ->\n liftM fromIntegral $ {#call generate_id#} cPtr\n\n\n-- Internal utils\n\n-- | Create a 'Connection' from a reference.\n-- The connection will be shut down when it goes out of scope.\nmkConnection :: Ptr Connection -> IO Connection\nmkConnection = liftM Connection . newForeignPtr finalizerDisconnect\n\n-- | Creates a connection from an unsafe reference,\n-- with no asociated finalzer.\n-- Only use this if the Haskell code does not own the connection.\nmkConnection_ :: Ptr Connection -> IO Connection\nmkConnection_ = liftM Connection . newForeignPtr_\n\n-- | A finalizer for a Ptr Connection which shuts down the connection\n-- and frees all resources associated with it.\nfinalizerDisconnect :: FinalizerPtr Connection\nfinalizerDisconnect = xcb_disconnect\n\nforeign import ccall \"&xcb_disconnect\" xcb_disconnect :: FunPtr (Ptr Connection -> IO ())\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"86bb0bbe651c93616d177b5bcaaeff7e7f9b75b2","subject":"Replace deprecated #import with #include","message":"Replace deprecated #import with #include\n","repos":"AaronFriel\/hyhac,AaronFriel\/hyhac,AaronFriel\/hyhac","old_file":"src\/Database\/HyperDex\/Internal\/Space.chs","new_file":"src\/Database\/HyperDex\/Internal\/Space.chs","new_contents":"module Database.HyperDex.Internal.Space \n ( addSpace, removeSpace\n )\n where\n\n{#import Database.HyperDex.Internal.Client #}\n{#import Database.HyperDex.Internal.ReturnCode #}\nimport Database.HyperDex.Internal.Util\n\n#include \"hyperclient.h\"\n\naddSpace :: Client -> ByteString -> IO ReturnCode\naddSpace c desc = withClientImmediate c $ \\hc -> do\n hyperclientAddSpace hc desc\n\nremoveSpace :: Client -> ByteString -> IO ReturnCode\nremoveSpace c name = withClientImmediate c $ \\hc -> do\n hyperclientRemoveSpace hc name\n\n-- enum hyperclient_returncode\n-- hyperclient_add_space(struct hyperclient* client, const char* description);\nhyperclientAddSpace :: Hyperclient -> ByteString -> IO ReturnCode\nhyperclientAddSpace client d = withCBString d $ \\description -> do\n fmap (toEnum . fromIntegral) $ {#call hyperclient_add_space #} client description\n\n-- enum hyperclient_returncode\n-- hyperclient_rm_space(struct hyperclient* client, const char* space);\nhyperclientRemoveSpace :: Hyperclient -> ByteString -> IO ReturnCode\nhyperclientRemoveSpace client s = withCBString s $ \\space -> do\n fmap (toEnum . fromIntegral) $ {#call hyperclient_rm_space #} client space\n","old_contents":"module Database.HyperDex.Internal.Space \n ( addSpace, removeSpace\n )\n where\n\n{#import Database.HyperDex.Internal.Client #}\n{#import Database.HyperDex.Internal.ReturnCode #}\nimport Database.HyperDex.Internal.Util\n\n#import \"hyperclient.h\"\n\naddSpace :: Client -> ByteString -> IO ReturnCode\naddSpace c desc = withClientImmediate c $ \\hc -> do\n hyperclientAddSpace hc desc\n\nremoveSpace :: Client -> ByteString -> IO ReturnCode\nremoveSpace c name = withClientImmediate c $ \\hc -> do\n hyperclientRemoveSpace hc name\n\n-- enum hyperclient_returncode\n-- hyperclient_add_space(struct hyperclient* client, const char* description);\nhyperclientAddSpace :: Hyperclient -> ByteString -> IO ReturnCode\nhyperclientAddSpace client d = withCBString d $ \\description -> do\n fmap (toEnum . fromIntegral) $ {#call hyperclient_add_space #} client description\n\n-- enum hyperclient_returncode\n-- hyperclient_rm_space(struct hyperclient* client, const char* space);\nhyperclientRemoveSpace :: Hyperclient -> ByteString -> IO ReturnCode\nhyperclientRemoveSpace client s = withCBString s $ \\space -> do\n fmap (toEnum . fromIntegral) $ {#call hyperclient_rm_space #} client space\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"06e6e8349b9f752809d118847eb63696d5f14150","subject":"additional error strings for cuda-3.0","message":"additional error strings for cuda-3.0\n\nIgnore-this: 6c350bc3b9ba31f7acb78a47a58fe594\n\ndarcs-hash:20100413035338-dcabc-1f3b1a688a58fecbcfb12ee4bf2e307fc81fed4e.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Error.chs","new_file":"Foreign\/CUDA\/Driver\/Error.chs","new_contents":"{-# LANGUAGE DeriveDataTypeable #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Error\n-- Copyright : (c) [2009..2010] Trevor L. McDonell\n-- License : BSD\n--\n-- Error handling\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Error\n where\n\n\n-- System\nimport Data.Typeable\nimport Control.Exception.Extensible\n\n#include \n{# context lib=\"cuda\" #}\n\n\n--------------------------------------------------------------------------------\n-- Return Status\n--------------------------------------------------------------------------------\n\n--\n-- Error Codes\n--\n{# enum CUresult as Status\n { underscoreToCase\n , CUDA_SUCCESS as Success\n , CUDA_ERROR_NO_BINARY_FOR_GPU as NoBinaryForGPU }\n with prefix=\"CUDA_ERROR\" deriving (Eq, Show) #}\n\n\n-- |\n-- Return a descriptive error string associated with a particular error code\n--\ndescribe :: Status -> String\ndescribe Success = \"no error\"\ndescribe InvalidValue = \"invalid argument\"\ndescribe OutOfMemory = \"out of memory\"\ndescribe NotInitialized = \"driver not initialised\"\ndescribe Deinitialized = \"driver deinitialised\"\ndescribe NoDevice = \"no CUDA-capable device is available\"\ndescribe InvalidDevice = \"invalid device ordinal\"\ndescribe InvalidImage = \"invalid kernel image\"\ndescribe InvalidContext = \"invalid context handle\"\ndescribe ContextAlreadyCurrent = \"context already current\"\ndescribe MapFailed = \"map failed\"\ndescribe UnmapFailed = \"unmap failed\"\ndescribe ArrayIsMapped = \"array is mapped\"\ndescribe AlreadyMapped = \"already mapped\"\ndescribe NoBinaryForGPU = \"no binary available for this GPU\"\ndescribe AlreadyAcquired = \"resource already acquired\"\ndescribe NotMapped = \"not mapped\"\ndescribe InvalidSource = \"invalid source\"\ndescribe FileNotFound = \"file not found\"\ndescribe InvalidHandle = \"invalid handle\"\ndescribe NotFound = \"not found\"\ndescribe NotReady = \"device not ready\"\ndescribe LaunchFailed = \"unspecified launch failure\"\ndescribe LaunchOutOfResources = \"too many resources requested for launch\"\ndescribe LaunchTimeout = \"the launch timed out and was terminated\"\ndescribe LaunchIncompatibleTexturing = \"launch with incompatible texturing\"\n#if CUDA_VERSION >= 3000\ndescribe NotMappedAsArray = \"mapped resource not available for access as an array\"\ndescribe NotMappedAsPointer = \"mapped resource not available for access as a pointer\"\ndescribe EccUncorrectable = \"uncorrectable ECC error detected\"\ndescribe PointerIs64bit = \"attempt to retrieve a 64-bit pointer via a 32-bit API function\"\ndescribe SizeIs64bit = \"attempt to retrieve 64-bit size via a 32-bit API function\"\n#endif\ndescribe Unknown = \"unknown error\"\n\n\n--------------------------------------------------------------------------------\n-- Exceptions\n--------------------------------------------------------------------------------\n\ndata CUDAException\n = ExitCode Status\n | UserError String\n deriving Typeable\n\ninstance Exception CUDAException\n\ninstance Show CUDAException where\n showsPrec _ (ExitCode s) = showString (\"CUDA Exception: \" ++ describe s)\n showsPrec _ (UserError s) = showString (\"CUDA Exception: \" ++ s)\n\n\n-- |\n-- Raise a CUDAException in the IO Monad\n--\ncudaError :: String -> IO a\ncudaError s = throwIO (UserError s)\n\n\n-- |\n-- Run a CUDA computation\n--\n{-\nrunCUDA f = runEMT $ do\n f `catchWithSrcLoc` \\l e -> lift (handle l e)\n where\n handle :: CallTrace -> CUDAException -> IO ()\n handle l e = putStrLn $ showExceptionWithTrace l e\n-}\n\n--------------------------------------------------------------------------------\n-- Helper Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the results of a function on successful execution, otherwise throw an\n-- exception with an error string associated with the return code\n--\nresultIfOk :: (Status, a) -> IO a\nresultIfOk (status,result) =\n case status of\n Success -> return result\n _ -> throwIO (ExitCode status)\n\n\n-- |\n-- Throw an exception with an error string associated with an unsuccessful\n-- return code, otherwise return unit.\n--\nnothingIfOk :: Status -> IO ()\nnothingIfOk status =\n case status of\n Success -> return ()\n _ -> throwIO (ExitCode status)\n\n","old_contents":"{-# LANGUAGE DeriveDataTypeable #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Error\n-- Copyright : (c) [2009..2010] Trevor L. McDonell\n-- License : BSD\n--\n-- Error handling\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Error\n where\n\n\n-- System\nimport Data.Typeable\nimport Control.Exception.Extensible\n\n#include \n{# context lib=\"cuda\" #}\n\n\n--------------------------------------------------------------------------------\n-- Return Status\n--------------------------------------------------------------------------------\n\n--\n-- Error Codes\n--\n{# enum CUresult as Status\n { underscoreToCase\n , CUDA_SUCCESS as Success\n , CUDA_ERROR_NO_BINARY_FOR_GPU as NoBinaryForGPU }\n with prefix=\"CUDA_ERROR\" deriving (Eq, Show) #}\n\n\n-- |\n-- Return a descriptive error string associated with a particular error code\n--\ndescribe :: Status -> String\ndescribe Success = \"no error\"\ndescribe InvalidValue = \"invalid argument\"\ndescribe OutOfMemory = \"out of memory\"\ndescribe NotInitialized = \"driver not initialised\"\ndescribe Deinitialized = \"driver deinitialised\"\ndescribe NoDevice = \"no CUDA-capable device is available\"\ndescribe InvalidDevice = \"invalid device ordinal\"\ndescribe InvalidImage = \"invalid kernel image\"\ndescribe InvalidContext = \"invalid context handle\"\ndescribe ContextAlreadyCurrent = \"context already current\"\ndescribe MapFailed = \"map failed\"\ndescribe UnmapFailed = \"unmap failed\"\ndescribe ArrayIsMapped = \"array is mapped\"\ndescribe AlreadyMapped = \"already mapped\"\ndescribe NoBinaryForGPU = \"no binary available for this GPU\"\ndescribe AlreadyAcquired = \"resource already acquired\"\ndescribe NotMapped = \"not mapped\"\ndescribe InvalidSource = \"invalid source\"\ndescribe FileNotFound = \"file not found\"\ndescribe InvalidHandle = \"invalid handle\"\ndescribe NotFound = \"not found\"\ndescribe NotReady = \"device not ready\"\ndescribe LaunchFailed = \"unspecified launch failure\"\ndescribe LaunchOutOfResources = \"too many resources requested for launch\"\ndescribe LaunchTimeout = \"the launch timed out and was terminated\"\ndescribe LaunchIncompatibleTexturing = \"launch with incompatible texturing\"\ndescribe Unknown = \"unknown error\"\n\n\n--------------------------------------------------------------------------------\n-- Exceptions\n--------------------------------------------------------------------------------\n\ndata CUDAException\n = ExitCode Status\n | UserError String\n deriving Typeable\n\ninstance Exception CUDAException\n\ninstance Show CUDAException where\n showsPrec _ (ExitCode s) = showString (\"CUDA Exception: \" ++ describe s)\n showsPrec _ (UserError s) = showString (\"CUDA Exception: \" ++ s)\n\n\n-- |\n-- Raise a CUDAException in the IO Monad\n--\ncudaError :: String -> IO a\ncudaError s = throwIO (UserError s)\n\n\n-- |\n-- Run a CUDA computation\n--\n{-\nrunCUDA f = runEMT $ do\n f `catchWithSrcLoc` \\l e -> lift (handle l e)\n where\n handle :: CallTrace -> CUDAException -> IO ()\n handle l e = putStrLn $ showExceptionWithTrace l e\n-}\n\n--------------------------------------------------------------------------------\n-- Helper Functions\n--------------------------------------------------------------------------------\n\n-- |\n-- Return the results of a function on successful execution, otherwise throw an\n-- exception with an error string associated with the return code\n--\nresultIfOk :: (Status, a) -> IO a\nresultIfOk (status,result) =\n case status of\n Success -> return result\n _ -> throwIO (ExitCode status)\n\n\n-- |\n-- Throw an exception with an error string associated with an unsuccessful\n-- return code, otherwise return unit.\n--\nnothingIfOk :: Status -> IO ()\nnothingIfOk status =\n case status of\n Success -> return ()\n _ -> throwIO (ExitCode status)\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"5dc6c16e75a047734375e315df45202df5f81ac7","subject":"CLong -> CLLong","message":"CLong -> CLLong\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/OGRFeature.chs","new_file":"src\/GDAL\/Internal\/OGRFeature.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGRFeature (\n FieldType (..)\n , Field\n , Feature (..)\n , FeatureH\n , FieldDefnH (..)\n , FeatureDefnH (..)\n , Justification (..)\n\n , FeatureDef (..)\n , GeomFieldDef (..)\n , FieldDef (..)\n\n , fieldDef\n , featureToHandle\n , featureFromHandle\n\n , withFeatureH\n , withFieldDefnH\n , fieldDefFromHandle\n , featureDefFromHandle\n#if MULTI_GEOM_FIELDS\n , GeomFieldDefnH (..)\n , withGeomFieldDefnH\n#endif\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\" #}\n\nimport Control.Applicative ((<$>), (<*>), pure)\nimport Control.Monad (liftM, (>=>), (<=<), when)\nimport Control.Monad.Catch (bracket)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Data.ByteString (ByteString)\nimport Data.ByteString.Char8 (packCStringLen)\nimport Data.Int (Int32, Int64)\nimport Data.Monoid (mempty)\nimport Data.Text (Text)\nimport Data.Time.LocalTime (\n LocalTime(..)\n , TimeOfDay(..)\n , ZonedTime(..)\n , getCurrentTimeZone\n , minutesToTimeZone\n , utc\n )\nimport Data.Time ()\nimport Data.Time.Calendar (Day, fromGregorian)\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport qualified Data.Vector as V\n\nimport Foreign.C.Types (\n CInt(..)\n , CLLong(..)\n , CDouble(..)\n , CChar(..)\n , CUChar(..)\n )\nimport Foreign.ForeignPtr (\n ForeignPtr\n , FinalizerPtr\n , withForeignPtr\n )\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (copyBytes)\nimport Foreign.Ptr (Ptr, castPtr)\nimport Foreign.Storable (Storable, sizeOf, peek, peekElemOff)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.Util (\n toEnumC\n , fromEnumC\n , peekEncodedCString\n , useAsEncodedCString\n )\n{#import GDAL.Internal.OSR #}\n{#import GDAL.Internal.CPLError #}\n{#import GDAL.Internal.OGRGeometry #}\n{#import GDAL.Internal.OGRError #}\n\n#include \"gdal.h\"\n#include \"ogr_core.h\"\n#include \"ogr_api.h\"\n#include \"cpl_string.h\"\n\n{#enum FieldType {} omit (OFTMaxType) deriving (Eq,Show,Read,Bounded) #}\n\n{#enum Justification {}\n omit (JustifyUndefined)\n with prefix = \"OJ\"\n add prefix = \"Justify\"\n deriving (Eq,Show,Read,Bounded) #}\n\ndata Field\n = OGRInteger {-# UNPACK #-} !Int32\n | OGRIntegerList {-# UNPACK #-} !(St.Vector Int32)\n | OGRInteger64 {-# UNPACK #-} !Int64\n | OGRInteger64List {-# UNPACK #-} !(St.Vector Int64)\n | OGRReal {-# UNPACK #-} !Double\n | OGRRealList {-# UNPACK #-} !(St.Vector Double)\n | OGRString {-# UNPACK #-} !Text\n | OGRStringList {-# UNPACK #-} !(V.Vector Text)\n | OGRBinary {-# UNPACK #-} !ByteString\n | OGRDateTime {-# UNPACK #-} !ZonedTime\n | OGRDate {-# UNPACK #-} !Day\n | OGRTime {-# UNPACK #-} !TimeOfDay\n deriving (Show)\n\ndata FieldDef\n = FieldDef {\n fldName :: {-# UNPACK #-} !Text\n , fldType :: {-# UNPACK #-} !FieldType\n , fldWidth :: {-# UNPACK #-} !(Maybe Int)\n , fldPrec :: {-# UNPACK #-} !(Maybe Int)\n , fldJust :: {-# UNPACK #-} !(Maybe Justification)\n } deriving (Show, Eq)\n\nfieldDef :: FieldType -> Text -> FieldDef\nfieldDef ftype name = FieldDef name ftype Nothing Nothing Nothing\n\ndata Feature\n = Feature {\n fId :: {-# UNPACK #-} !Int64\n , fFields :: {-# UNPACK #-} !(V.Vector Field)\n , fGeoms :: {-# UNPACK #-} !(V.Vector Geometry)\n } deriving (Show)\n\ndata FeatureDef\n = FeatureDef {\n fdName :: {-# UNPACK #-} !Text\n , fdFields :: {-# UNPACK #-} !(V.Vector FieldDef)\n , fdGeom :: {-# UNPACK #-} !GeomFieldDef\n , fdGeoms :: {-# UNPACK #-} !(V.Vector GeomFieldDef)\n } deriving (Show, Eq)\n\ndata GeomFieldDef\n = GeomFieldDef {\n gfdName :: {-# UNPACK #-} !Text\n , gfdType :: {-# UNPACK #-} !GeometryType\n , gfdSrs :: {-# UNPACK #-} !(Maybe SpatialReference)\n } deriving (Show, Eq)\n\n\n{#pointer FeatureH foreign finalizer OGR_F_Destroy as ^ newtype#}\n{#pointer FieldDefnH newtype#}\n{#pointer FeatureDefnH newtype#}\n\n\n\nwithFieldDefnH :: FieldDef -> (FieldDefnH -> IO a) -> IO a\nwithFieldDefnH FieldDef{..} f =\n useAsEncodedCString fldName $ \\pName ->\n bracket ({#call unsafe OGR_Fld_Create as ^#} pName (fromEnumC fldType))\n ({#call unsafe OGR_Fld_Destroy as ^#}) (\\p -> populate p >> f p)\n where\n populate h = do\n case fldWidth of\n Just w -> {#call unsafe OGR_Fld_SetWidth as ^#} h (fromIntegral w)\n Nothing -> return ()\n case fldPrec of\n Just p -> {#call unsafe OGR_Fld_SetPrecision as ^#} h (fromIntegral p)\n Nothing -> return ()\n case fldJust of\n Just j -> {#call unsafe OGR_Fld_SetJustify as ^#} h (fromEnumC j)\n Nothing -> return ()\n\nfieldDefFromHandle :: FieldDefnH -> IO FieldDef\nfieldDefFromHandle p =\n FieldDef\n <$> getFieldName p\n <*> liftM toEnumC ({#call unsafe OGR_Fld_GetType as ^#} p)\n <*> liftM iToMaybe ({#call unsafe OGR_Fld_GetWidth as ^#} p)\n <*> liftM iToMaybe ({#call unsafe OGR_Fld_GetPrecision as ^#} p)\n <*> liftM jToMaybe ({#call unsafe OGR_Fld_GetJustify as ^#} p)\n where\n iToMaybe = (\\v -> if v==0 then Nothing else Just (fromIntegral v))\n jToMaybe = (\\j -> if j==0 then Nothing else Just (toEnumC j))\n\nfeatureDefFromHandle :: GeomFieldDef -> FeatureDefnH -> IO FeatureDef\nfeatureDefFromHandle gfd p =\n FeatureDef\n <$> ({#call unsafe OGR_FD_GetName as ^#} p >>= peekEncodedCString)\n <*> fieldDefsFromFeatureDefnH p\n <*> pure gfd\n <*> geomFieldDefsFromFeatureDefnH p\n where\n\nfieldDefsFromFeatureDefnH :: FeatureDefnH -> IO (V.Vector FieldDef)\nfieldDefsFromFeatureDefnH p = do\n nFields <- {#call unsafe OGR_FD_GetFieldCount as ^#} p\n V.generateM (fromIntegral nFields) $\n fieldDefFromHandle <=<\n ({#call unsafe OGR_FD_GetFieldDefn as ^#} p . fromIntegral)\n\n\ngeomFieldDefsFromFeatureDefnH :: FeatureDefnH -> IO (V.Vector GeomFieldDef)\n\n#if MULTI_GEOM_FIELDS\n\n{#pointer GeomFieldDefnH newtype#}\n\ngeomFieldDefsFromFeatureDefnH p = do\n nFields <- {#call unsafe OGR_FD_GetGeomFieldCount as ^#} p\n V.generateM (fromIntegral (nFields-1)) $\n gFldDef <=< ( {#call unsafe OGR_FD_GetGeomFieldDefn as ^#} p\n . (+1)\n . fromIntegral\n )\n where\n gFldDef g =\n GeomFieldDef\n <$> ({#call unsafe OGR_GFld_GetNameRef as ^#} g >>= peekEncodedCString)\n <*> liftM toEnumC ({#call unsafe OGR_GFld_GetType as ^#} g)\n <*> ({#call unsafe OGR_GFld_GetSpatialRef as ^#} g >>=\n maybeNewSpatialRefBorrowedHandle)\n\nwithGeomFieldDefnH :: GeomFieldDef -> (GeomFieldDefnH -> IO a) -> IO a\nwithGeomFieldDefnH GeomFieldDef{..} f =\n useAsEncodedCString gfdName $ \\pName ->\n bracket ({#call unsafe OGR_GFld_Create as ^#} pName (fromEnumC gfdType))\n ({#call unsafe OGR_GFld_Destroy as ^#}) (\\p -> populate p >> f p)\n where\n populate = withMaybeSpatialReference gfdSrs .\n {#call unsafe OGR_GFld_SetSpatialRef as ^#}\n#else\n-- | GDAL < 1.11 only supports 1 geometry field and associates it the layer\ngeomFieldDefsFromFeatureDefnH = const (return V.empty)\n#endif\n\n\nfeatureToHandle :: FeatureDef -> Feature -> GDAL s FeatureH\nfeatureToHandle = undefined\n\nfeatureFromHandle :: FeatureDef -> FeatureH -> GDAL s Feature\nfeatureFromHandle = undefined\n\n\ngetFieldBy :: FieldType -> Text -> CInt -> Ptr FeatureH -> IO Field\n\ngetFieldBy OFTInteger _ ix f\n = liftM (OGRInteger . fromIntegral)\n ({#call unsafe OGR_F_GetFieldAsInteger as ^#} f ix)\n\ngetFieldBy OFTIntegerList _ ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsIntegerList as ^#} f ix lenP\n nElems <- peekIntegral lenP\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CInt) (nElems * sizeOf (undefined :: CInt))\n liftM OGRIntegerList (St.unsafeFreeze (Stm.unsafeCast vec))\n\n#if (GDAL_VERSION_MAJOR >= 2)\ngetFieldBy OFTInteger64 _ ix f\n = liftM (OGRInteger64 . fromIntegral)\n ({#call unsafe OGR_F_GetFieldAsInteger64 as ^#} f ix)\n\ngetFieldBy OFTInteger64List _ ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsInteger64List as ^#} f ix lenP\n nElems <- peekIntegral lenP\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CLLong) (nElems * sizeOf (undefined :: CLLong))\n liftM OGRInteger64List (St.unsafeFreeze (Stm.unsafeCast vec))\n#endif\n\ngetFieldBy OFTReal _ ix f\n = liftM (OGRReal . realToFrac)\n ({#call unsafe OGR_F_GetFieldAsDouble as ^#} f ix)\n\ngetFieldBy OFTRealList _ ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsDoubleList as ^#} f ix lenP\n nElems <- peekIntegral lenP\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CDouble) (nElems * sizeOf (undefined :: CDouble))\n liftM OGRRealList (St.unsafeFreeze (Stm.unsafeCast vec))\n\ngetFieldBy OFTString _ ix f = liftM OGRString\n (({#call unsafe OGR_F_GetFieldAsString as ^#} f ix) >>= peekEncodedCString)\n\ngetFieldBy OFTWideString fname ix f = getFieldBy OFTString fname ix f\n\ngetFieldBy OFTStringList _ ix f = liftM OGRStringList $ do\n ptr <- {#call unsafe OGR_F_GetFieldAsStringList as ^#} f ix\n nElems <- liftM fromIntegral ({#call unsafe CSLCount as ^#} ptr)\n V.generateM nElems (peekElemOff ptr >=> peekEncodedCString)\n\ngetFieldBy OFTWideStringList fname ix f = getFieldBy OFTStringList fname ix f\n\ngetFieldBy OFTBinary _ ix f = alloca $ \\lenP -> do\n buf <- liftM castPtr ({#call unsafe OGR_F_GetFieldAsBinary as ^#} f ix lenP)\n nElems <- peekIntegral lenP\n liftM OGRBinary (packCStringLen (buf, nElems))\n\ngetFieldBy OFTDateTime fname ix f\n = liftM OGRDateTime $ alloca $ \\y -> alloca $ \\m -> alloca $ \\d ->\n alloca $ \\h -> alloca $ \\mn -> alloca $ \\s -> alloca $ \\tz -> do\n ret <- {#call unsafe OGR_F_GetFieldAsDateTime as ^#} f ix y m d h mn s tz\n when (ret==0) $ throwBindingException (FieldParseError fname)\n day <- fromGregorian <$> peekIntegral y\n <*> peekIntegral m\n <*> peekIntegral d\n tod <- TimeOfDay <$> peekIntegral h\n <*> peekIntegral mn\n <*> peekIntegral s\n let lt = return . ZonedTime (LocalTime day tod)\n tzV <- peekIntegral tz\n case tzV of\n -- Unknown timezone, assume utc\n 0 -> lt utc\n 1 -> getCurrentTimeZone >>= lt\n 100 -> lt utc\n n -> lt (minutesToTimeZone ((n-100) * 15))\n\ngetFieldBy OFTDate fname ix f\n = liftM (OGRDate . localDay . zonedTimeToLocalTime . unDateTime)\n (getFieldBy OFTDateTime fname ix f)\n\ngetFieldBy OFTTime fname ix f\n = liftM (OGRTime . localTimeOfDay . zonedTimeToLocalTime. unDateTime)\n (getFieldBy OFTDateTime fname ix f)\n\nunDateTime :: Field -> ZonedTime\nunDateTime (OGRDateTime f) = f\nunDateTime _ = error \"GDAL.Internal.OGRFeature.unDateTime\"\n\n\npeekIntegral :: (Storable a, Integral a, Num b) => Ptr a -> IO b\npeekIntegral = liftM fromIntegral . peek\n\ngetFieldName :: FieldDefnH -> IO Text\ngetFieldName =\n {#call unsafe OGR_Fld_GetNameRef as ^#} >=> peekEncodedCString\n\n\ngeometryByName :: Text -> FeatureH -> GDAL s Geometry\ngeometryByName = undefined\n\ngeometryByIndex :: FeatureH -> Int -> GDAL s Geometry\ngeometryByIndex = undefined\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGRFeature (\n FieldType (..)\n , Field\n , Feature (..)\n , FeatureH\n , FieldDefnH (..)\n , FeatureDefnH (..)\n , Justification (..)\n\n , FeatureDef (..)\n , GeomFieldDef (..)\n , FieldDef (..)\n\n , fieldDef\n , featureToHandle\n , featureFromHandle\n\n , withFeatureH\n , withFieldDefnH\n , fieldDefFromHandle\n , featureDefFromHandle\n#if MULTI_GEOM_FIELDS\n , GeomFieldDefnH (..)\n , withGeomFieldDefnH\n#endif\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\" #}\n\nimport Control.Applicative ((<$>), (<*>), pure)\nimport Control.Monad (liftM, (>=>), (<=<), when)\nimport Control.Monad.Catch (bracket)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Data.ByteString (ByteString)\nimport Data.ByteString.Char8 (packCStringLen)\nimport Data.Int (Int32, Int64)\nimport Data.Monoid (mempty)\nimport Data.Text (Text)\nimport Data.Time.LocalTime (\n LocalTime(..)\n , TimeOfDay(..)\n , ZonedTime(..)\n , getCurrentTimeZone\n , minutesToTimeZone\n , utc\n )\nimport Data.Time ()\nimport Data.Time.Calendar (Day, fromGregorian)\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport qualified Data.Vector as V\n\nimport Foreign.C.Types (CInt(..), CLong(..), CDouble(..), CChar(..), CUChar(..))\nimport Foreign.ForeignPtr (\n ForeignPtr\n , FinalizerPtr\n , withForeignPtr\n )\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (copyBytes)\nimport Foreign.Ptr (Ptr, castPtr)\nimport Foreign.Storable (Storable, sizeOf, peek, peekElemOff)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.Util (\n toEnumC\n , fromEnumC\n , peekEncodedCString\n , useAsEncodedCString\n )\n{#import GDAL.Internal.OSR #}\n{#import GDAL.Internal.CPLError #}\n{#import GDAL.Internal.OGRGeometry #}\n{#import GDAL.Internal.OGRError #}\n\n#include \"gdal.h\"\n#include \"ogr_core.h\"\n#include \"ogr_api.h\"\n#include \"cpl_string.h\"\n\n{#enum FieldType {} omit (OFTMaxType) deriving (Eq,Show,Read,Bounded) #}\n\n{#enum Justification {}\n omit (JustifyUndefined)\n with prefix = \"OJ\"\n add prefix = \"Justify\"\n deriving (Eq,Show,Read,Bounded) #}\n\ndata Field\n = OGRInteger {-# UNPACK #-} !Int32\n | OGRIntegerList {-# UNPACK #-} !(St.Vector Int32)\n | OGRInteger64 {-# UNPACK #-} !Int64\n | OGRInteger64List {-# UNPACK #-} !(St.Vector Int64)\n | OGRReal {-# UNPACK #-} !Double\n | OGRRealList {-# UNPACK #-} !(St.Vector Double)\n | OGRString {-# UNPACK #-} !Text\n | OGRStringList {-# UNPACK #-} !(V.Vector Text)\n | OGRBinary {-# UNPACK #-} !ByteString\n | OGRDateTime {-# UNPACK #-} !ZonedTime\n | OGRDate {-# UNPACK #-} !Day\n | OGRTime {-# UNPACK #-} !TimeOfDay\n deriving (Show)\n\ndata FieldDef\n = FieldDef {\n fldName :: {-# UNPACK #-} !Text\n , fldType :: {-# UNPACK #-} !FieldType\n , fldWidth :: {-# UNPACK #-} !(Maybe Int)\n , fldPrec :: {-# UNPACK #-} !(Maybe Int)\n , fldJust :: {-# UNPACK #-} !(Maybe Justification)\n } deriving (Show, Eq)\n\nfieldDef :: FieldType -> Text -> FieldDef\nfieldDef ftype name = FieldDef name ftype Nothing Nothing Nothing\n\ndata Feature\n = Feature {\n fId :: {-# UNPACK #-} !Int64\n , fFields :: {-# UNPACK #-} !(V.Vector Field)\n , fGeoms :: {-# UNPACK #-} !(V.Vector Geometry)\n } deriving (Show)\n\ndata FeatureDef\n = FeatureDef {\n fdName :: {-# UNPACK #-} !Text\n , fdFields :: {-# UNPACK #-} !(V.Vector FieldDef)\n , fdGeom :: {-# UNPACK #-} !GeomFieldDef\n , fdGeoms :: {-# UNPACK #-} !(V.Vector GeomFieldDef)\n } deriving (Show, Eq)\n\ndata GeomFieldDef\n = GeomFieldDef {\n gfdName :: {-# UNPACK #-} !Text\n , gfdType :: {-# UNPACK #-} !GeometryType\n , gfdSrs :: {-# UNPACK #-} !(Maybe SpatialReference)\n } deriving (Show, Eq)\n\n\n{#pointer FeatureH foreign finalizer OGR_F_Destroy as ^ newtype#}\n{#pointer FieldDefnH newtype#}\n{#pointer FeatureDefnH newtype#}\n\n\n\nwithFieldDefnH :: FieldDef -> (FieldDefnH -> IO a) -> IO a\nwithFieldDefnH FieldDef{..} f =\n useAsEncodedCString fldName $ \\pName ->\n bracket ({#call unsafe OGR_Fld_Create as ^#} pName (fromEnumC fldType))\n ({#call unsafe OGR_Fld_Destroy as ^#}) (\\p -> populate p >> f p)\n where\n populate h = do\n case fldWidth of\n Just w -> {#call unsafe OGR_Fld_SetWidth as ^#} h (fromIntegral w)\n Nothing -> return ()\n case fldPrec of\n Just p -> {#call unsafe OGR_Fld_SetPrecision as ^#} h (fromIntegral p)\n Nothing -> return ()\n case fldJust of\n Just j -> {#call unsafe OGR_Fld_SetJustify as ^#} h (fromEnumC j)\n Nothing -> return ()\n\nfieldDefFromHandle :: FieldDefnH -> IO FieldDef\nfieldDefFromHandle p =\n FieldDef\n <$> getFieldName p\n <*> liftM toEnumC ({#call unsafe OGR_Fld_GetType as ^#} p)\n <*> liftM iToMaybe ({#call unsafe OGR_Fld_GetWidth as ^#} p)\n <*> liftM iToMaybe ({#call unsafe OGR_Fld_GetPrecision as ^#} p)\n <*> liftM jToMaybe ({#call unsafe OGR_Fld_GetJustify as ^#} p)\n where\n iToMaybe = (\\v -> if v==0 then Nothing else Just (fromIntegral v))\n jToMaybe = (\\j -> if j==0 then Nothing else Just (toEnumC j))\n\nfeatureDefFromHandle :: GeomFieldDef -> FeatureDefnH -> IO FeatureDef\nfeatureDefFromHandle gfd p =\n FeatureDef\n <$> ({#call unsafe OGR_FD_GetName as ^#} p >>= peekEncodedCString)\n <*> fieldDefsFromFeatureDefnH p\n <*> pure gfd\n <*> geomFieldDefsFromFeatureDefnH p\n where\n\nfieldDefsFromFeatureDefnH :: FeatureDefnH -> IO (V.Vector FieldDef)\nfieldDefsFromFeatureDefnH p = do\n nFields <- {#call unsafe OGR_FD_GetFieldCount as ^#} p\n V.generateM (fromIntegral nFields) $\n fieldDefFromHandle <=<\n ({#call unsafe OGR_FD_GetFieldDefn as ^#} p . fromIntegral)\n\n\ngeomFieldDefsFromFeatureDefnH :: FeatureDefnH -> IO (V.Vector GeomFieldDef)\n\n#if MULTI_GEOM_FIELDS\n\n{#pointer GeomFieldDefnH newtype#}\n\ngeomFieldDefsFromFeatureDefnH p = do\n nFields <- {#call unsafe OGR_FD_GetGeomFieldCount as ^#} p\n V.generateM (fromIntegral (nFields-1)) $\n gFldDef <=< ( {#call unsafe OGR_FD_GetGeomFieldDefn as ^#} p\n . (+1)\n . fromIntegral\n )\n where\n gFldDef g =\n GeomFieldDef\n <$> ({#call unsafe OGR_GFld_GetNameRef as ^#} g >>= peekEncodedCString)\n <*> liftM toEnumC ({#call unsafe OGR_GFld_GetType as ^#} g)\n <*> ({#call unsafe OGR_GFld_GetSpatialRef as ^#} g >>=\n maybeNewSpatialRefBorrowedHandle)\n\nwithGeomFieldDefnH :: GeomFieldDef -> (GeomFieldDefnH -> IO a) -> IO a\nwithGeomFieldDefnH GeomFieldDef{..} f =\n useAsEncodedCString gfdName $ \\pName ->\n bracket ({#call unsafe OGR_GFld_Create as ^#} pName (fromEnumC gfdType))\n ({#call unsafe OGR_GFld_Destroy as ^#}) (\\p -> populate p >> f p)\n where\n populate = withMaybeSpatialReference gfdSrs .\n {#call unsafe OGR_GFld_SetSpatialRef as ^#}\n#else\n-- | GDAL < 1.11 only supports 1 geometry field and associates it the layer\ngeomFieldDefsFromFeatureDefnH = const (return V.empty)\n#endif\n\n\nfeatureToHandle :: FeatureDef -> Feature -> GDAL s FeatureH\nfeatureToHandle = undefined\n\nfeatureFromHandle :: FeatureDef -> FeatureH -> GDAL s Feature\nfeatureFromHandle = undefined\n\n\ngetFieldBy :: FieldType -> Text -> CInt -> Ptr FeatureH -> IO Field\n\ngetFieldBy OFTInteger _ ix f\n = liftM (OGRInteger . fromIntegral)\n ({#call unsafe OGR_F_GetFieldAsInteger as ^#} f ix)\n\ngetFieldBy OFTIntegerList _ ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsIntegerList as ^#} f ix lenP\n nElems <- peekIntegral lenP\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CInt) (nElems * sizeOf (undefined :: CInt))\n liftM OGRIntegerList (St.unsafeFreeze (Stm.unsafeCast vec))\n\n#if (GDAL_VERSION_MAJOR >= 2)\ngetFieldBy OFTInteger64 _ ix f\n = liftM (OGRInteger64 . fromIntegral)\n ({#call unsafe OGR_F_GetFieldAsInteger64 as ^#} f ix)\n\ngetFieldBy OFTInteger64List _ ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsInteger64List as ^#} f ix lenP\n nElems <- peekIntegral lenP\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CLong) (nElems * sizeOf (undefined :: CLong))\n liftM OGRInteger64List (St.unsafeFreeze (Stm.unsafeCast vec))\n#endif\n\ngetFieldBy OFTReal _ ix f\n = liftM (OGRReal . realToFrac)\n ({#call unsafe OGR_F_GetFieldAsDouble as ^#} f ix)\n\ngetFieldBy OFTRealList _ ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsDoubleList as ^#} f ix lenP\n nElems <- peekIntegral lenP\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CDouble) (nElems * sizeOf (undefined :: CDouble))\n liftM OGRRealList (St.unsafeFreeze (Stm.unsafeCast vec))\n\ngetFieldBy OFTString _ ix f = liftM OGRString\n (({#call unsafe OGR_F_GetFieldAsString as ^#} f ix) >>= peekEncodedCString)\n\ngetFieldBy OFTWideString fname ix f = getFieldBy OFTString fname ix f\n\ngetFieldBy OFTStringList _ ix f = liftM OGRStringList $ do\n ptr <- {#call unsafe OGR_F_GetFieldAsStringList as ^#} f ix\n nElems <- liftM fromIntegral ({#call unsafe CSLCount as ^#} ptr)\n V.generateM nElems (peekElemOff ptr >=> peekEncodedCString)\n\ngetFieldBy OFTWideStringList fname ix f = getFieldBy OFTStringList fname ix f\n\ngetFieldBy OFTBinary _ ix f = alloca $ \\lenP -> do\n buf <- liftM castPtr ({#call unsafe OGR_F_GetFieldAsBinary as ^#} f ix lenP)\n nElems <- peekIntegral lenP\n liftM OGRBinary (packCStringLen (buf, nElems))\n\ngetFieldBy OFTDateTime fname ix f\n = liftM OGRDateTime $ alloca $ \\y -> alloca $ \\m -> alloca $ \\d ->\n alloca $ \\h -> alloca $ \\mn -> alloca $ \\s -> alloca $ \\tz -> do\n ret <- {#call unsafe OGR_F_GetFieldAsDateTime as ^#} f ix y m d h mn s tz\n when (ret==0) $ throwBindingException (FieldParseError fname)\n day <- fromGregorian <$> peekIntegral y\n <*> peekIntegral m\n <*> peekIntegral d\n tod <- TimeOfDay <$> peekIntegral h\n <*> peekIntegral mn\n <*> peekIntegral s\n let lt = return . ZonedTime (LocalTime day tod)\n tzV <- peekIntegral tz\n case tzV of\n -- Unknown timezone, assume utc\n 0 -> lt utc\n 1 -> getCurrentTimeZone >>= lt\n 100 -> lt utc\n n -> lt (minutesToTimeZone ((n-100) * 15))\n\ngetFieldBy OFTDate fname ix f\n = liftM (OGRDate . localDay . zonedTimeToLocalTime . unDateTime)\n (getFieldBy OFTDateTime fname ix f)\n\ngetFieldBy OFTTime fname ix f\n = liftM (OGRTime . localTimeOfDay . zonedTimeToLocalTime. unDateTime)\n (getFieldBy OFTDateTime fname ix f)\n\nunDateTime :: Field -> ZonedTime\nunDateTime (OGRDateTime f) = f\nunDateTime _ = error \"GDAL.Internal.OGRFeature.unDateTime\"\n\n\npeekIntegral :: (Storable a, Integral a, Num b) => Ptr a -> IO b\npeekIntegral = liftM fromIntegral . peek\n\ngetFieldName :: FieldDefnH -> IO Text\ngetFieldName =\n {#call unsafe OGR_Fld_GetNameRef as ^#} >=> peekEncodedCString\n\n\ngeometryByName :: Text -> FeatureH -> GDAL s Geometry\ngeometryByName = undefined\n\ngeometryByIndex :: FeatureH -> Int -> GDAL s Geometry\ngeometryByIndex = undefined\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"660d1546c33b59639409fed92ca0a73d8bd410e0","subject":"Transposed the matrix for pointCount to account for a change in OpenCV (somewhere between 2.4.3 and 2.4.5)","message":"Transposed the matrix for pointCount to account for a change in OpenCV\n(somewhere between 2.4.3 and 2.4.5)\n","repos":"aleator\/CV,TomMD\/CV,BeautifulDestinations\/CV,aleator\/CV","old_file":"CV\/Calibration.chs","new_file":"CV\/Calibration.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n#include \"cvWrapLEO.h\"\n-- | This module exposes opencv functions for camera calibration using a chessboard rig. This module follows opencv quite closely and the best documentation\n-- is probably found there. As quick example however, the following program detects and draws chessboard corners from an image.\n--\n-- @\n-- module Main where\n-- import CV.Image\n-- import CV.Calibration\n-- \n-- main = do\n-- Just i <- loadColorImage \\\"chess.png\\\"\n-- let corners = findChessboardCorners (unsafeImageTo8Bit i) (4,5) (FastCheck:defaultFlags)\n-- let y = drawChessboardCorners (unsafeImageTo8Bit i) (4,5) corners\n-- mapM_ print (corners)\n-- saveImage \\\"found_chessboard.png\\\" y\n-- @\nmodule CV.Calibration \n (\n -- * Finding chessboard calibration rig\n FindFlags(..)\n ,defaultFlags\n ,findChessboardCorners\n ,refineChessboardCorners\n -- * Visualization\n ,drawChessboardCorners\n -- * Camera calibration\n ,calibrateCamera2\n -- * Rectification\n ,stereoRectifyUncalibrated\n ,findFundamentalMat\n ,c'CV_FM_7POINT\n ,c'CV_FM_8POINT\n ,c'CV_FM_RANSAC\n ,c'CV_FM_LMEDS\n ) where\n{-#OPTIONS-GHC -fwarn-unused-imports #-}\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.ForeignPtr\nimport Foreign.Storable\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Data.Bits\n\nimport CV.Image \n\nimport System.IO.Unsafe\nimport Utils.Point\nimport Control.Applicative\n\nimport CV.Matrix\nimport CV.Bindings.Calibrate\nimport CV.Bindings.Types\n\n{#import CV.Image#}\n\n#c\nenum FindFlags {\n AdaptiveThresh = CV_CALIB_CB_ADAPTIVE_THRESH\n ,NormalizeImage = CV_CALIB_CB_NORMALIZE_IMAGE\n ,FilterQuads = CV_CALIB_CB_FILTER_QUADS\n ,FastCheck = CV_CALIB_CB_FAST_CHECK\n };\n#endc\n\n-- |\u00a0Flags for the chessboard corner detector. See opencv documentation for cvFindChessboardCorners.\n{#enum FindFlags {}#}\n\nflagsToNum fs = foldl (.|.) 0 $ map (fromIntegral . fromEnum) fs\n\n-- |Default flags for finding corners\ndefaultFlags :: [FindFlags]\ndefaultFlags = [AdaptiveThresh]\n\n-- | Find the inner corners of a chessboard in a given image. \nfindChessboardCorners :: CV.Image.Image RGB D8 -> (Int, Int) -> [FindFlags] -> [(Float,Float)]\nfindChessboardCorners image (w,h) flags =\n unsafePerformIO $ \n with 1 $ \\(c_corner_count::Ptr CInt) -> \n allocaArray len $ \\(c_corners :: Ptr CvPoint )-> \n withGenImage image $ \\c_image -> do\n r <- {#call wrapFindChessBoardCorners#} c_image (fromIntegral w) (fromIntegral h)\n (castPtr c_corners) c_corner_count \n (flagsToNum flags)\n count <- peek c_corner_count\n arr <- peekArray (fromIntegral count) c_corners\n return (map cvPt2Pt arr) \n where len = w*h\n\n-- |Given an estimate of chessboard corners, provide a subpixel estimation of actual corners.\nrefineChessboardCorners :: Image GrayScale D8 -> [(Float,Float)] -> (Int,Int) -> (Int,Int) -> [(Float,Float)]\nrefineChessboardCorners img pts (winW,winH) (zeroW,zeroH) = unsafePerformIO $ do\n with 1 $ \\(c_corner_count::Ptr CInt) -> \n withImage img $ \\c_img ->\n withArray (map mkPt pts) $ \\(c_corners :: Ptr C'CvPoint2D32f ) -> do \n c'wrapFindCornerSubPix c_img c_corners (length pts) winW winH zeroW zeroH tType maxIter epsilon \n map fromPt `fmap` peekArray (length pts) c_corners\n where\n mkPt (x,y) = C'CvPoint2D32f (realToFrac x) (realToFrac y)\n fromPt (C'CvPoint2D32f x y) = (realToFrac x,realToFrac y)\n tType = c'CV_TERMCRIT_ITER\n maxIter = 100\n epsilon = 0.01\n\n-- |\u00a0Draw the found chessboard corners to an image\ndrawChessboardCorners :: CV.Image.Image RGB D8 -> (Int, Int) -> [(Float,Float)] -> CV.Image.Image RGB D8\ndrawChessboardCorners image (w,h) corners =\n unsafePerformIO $ \n withCloneValue image $ \\clone -> \n withArray (map pt2CvPt corners) $ \\(c_corners :: Ptr CvPoint )-> \n withGenImage clone$ \\c_image -> do\n r <- {#call wrapDrawChessBoardCorners#} c_image (fromIntegral w) (fromIntegral h)\n (castPtr c_corners) (fromIntegral $ length corners) \n (found)\n return clone\n where \n len = w*h\n found |\u00a0(w*h) == length corners = 1\n | otherwise = 0 \n \nnewtype CvPoint = CvPt (CFloat,CFloat) deriving (Show)\ncvPt2Pt (CvPt (a,b)) = (realToFrac a , realToFrac b)\npt2CvPt (a,b) = CvPt (realToFrac a , realToFrac b)\n\ninstance Storable CvPoint where\n sizeOf _ = {#sizeof CvPoint #}\n alignment _ = {#alignof CvPoint2D32f #}\n peek p = CvPt <$> ((,) \n <$> {#get CvPoint2D32f->x #} p\n <*> {#get CvPoint2D32f->y #} p)\n poke p (CvPt (hx,hy)) = do\n {#set CvPoint2D32f.x #} p (hx)\n {#set CvPoint2D32f.y #} p (hy)\n\n-- |\u00a0See opencv function cvCalibrateCamera2. This function takes a list of world-screen coordinate pairs acquired with find-chessboard corners\n-- and attempts to find the camera parameters for the system. It returns the fitting error, the camera matrix, list of distortion co-efficients\n-- and rotation and translation vectors for each coordinate pair. \ncalibrateCamera2 ::\n [[((Float, Float, Float), (Float, Float))]]\n -> (Int, Int)\n -> IO (Double, Matrix Float, [[Float]], [[Float]], [[Float]])\ncalibrateCamera2 views (w,h) = do\n let \n pointCounts :: Matrix Int\n pointCounts = fromList (length views,1) (map (length) views)\n m = length views\n totalPts = length (concat views)\n objectPoints :: Matrix Float\n objectPoints = fromList (3,totalPts) $ concat [[x,y,z] | ((x,y,z),_) <- concat views]\n imagePoints :: Matrix Float\n imagePoints = fromList (2,totalPts) $ concat [[x,y] | (_,(x,y)) <- concat views]\n flags = c'CV_CALIB_FIX_K1\n .|. c'CV_CALIB_FIX_K1\n .|. c'CV_CALIB_FIX_K2\n .|. c'CV_CALIB_FIX_K3\n .|. c'CV_CALIB_FIX_K4\n .|. c'CV_CALIB_FIX_K5\n .|. c'CV_CALIB_FIX_K6\n .|. c'CV_CALIB_ZERO_TANGENT_DIST\n\n size = C'CvSize (fromIntegral w) (fromIntegral h)\n cameraMatrix,distCoeffs,rvecs,tvecs :: Matrix Float\n cameraMatrix = emptyMatrix (3,3)\n distCoeffs = emptyMatrix (1,8)\n rvecs = emptyMatrix (m,3)\n tvecs = emptyMatrix (m,3)\n\n err <- with size $\u00a0\\c_size ->\n withMatPtr objectPoints $ \\c_objectPoints ->\n withMatPtr imagePoints $ \\c_imagePoints ->\n withMatPtr pointCounts $ \\c_pointCounts ->\n withMatPtr cameraMatrix $ \\c_cameraMatrix ->\n withMatPtr distCoeffs $ \\c_distCoeffs ->\n withMatPtr rvecs $ \\c_rvecs ->\n withMatPtr tvecs $ \\c_tvecs ->\n c'wrapCalibrateCamera2 c_objectPoints c_imagePoints c_pointCounts c_size \n c_cameraMatrix c_distCoeffs c_rvecs c_tvecs flags\n\n -- print ( objectPoints, imagePoints, pointCounts,cameraMatrix, distCoeffs, rvecs, tvecs )\n return (err, transpose cameraMatrix, toCols distCoeffs, toCols rvecs, toCols tvecs)\n\nstereoRectifyUncalibrated :: Matrix (Float,Float) -> Matrix (Float,Float) -> Matrix Float -> (Int,Int) -> Double\n -> (Matrix Float, Matrix Float)\nstereoRectifyUncalibrated pts1 pts2 fund (w,h) threshold = unsafePerformIO $\n let h1 = emptyMatrix (3,3)\n h2 = emptyMatrix (3,3)\n in withMatPtr pts1 $ \\c_pts1 -> \n withMatPtr pts2 $ \\c_pts2 ->\n withMatPtr fund \u00a0 $ \\c_fund -> \n withMatPtr h1 \u00a0 $ \\c_h1 -> \n withMatPtr h2 \u00a0 $ \\c_h2 -> \n with (C'CvSize (fromIntegral w) (fromIntegral h)) $ \\c_size -> do\n r <- c'wrapStereoRectifyUncalibrated c_pts1 c_pts2 c_fund c_size c_h1 c_h2 (realToFrac threshold)\n return (h1, h2)\n\n\n\nfindFundamentalMat :: Matrix Float -> Matrix Float -> CInt -> Double -> Double\n -> Matrix Float --, Matrix Float)\nfindFundamentalMat pts1 pts2 method p1 p2 = unsafePerformIO $\n let fund = emptyMatrix (3,3)\n in withMatPtr pts1 $ \\c_pts1 -> \n withMatPtr pts2 $ \\c_pts2 ->\n withMatPtr fund \u00a0 $ \\c_fund -> \n do\n r <- c'cvFindFundamentalMat c_pts1 c_pts2 c_fund method (realToFrac p1) (realToFrac p2) nullPtr\n return (fund)\n\n\nstereoCalibrate :: Matrix (Float,Float,Float) -- ^ Object points\n -> Matrix (Float,Float) -- ^ ImagePoints 1\n -> Matrix (Float,Float) -- ^ ImagePoints 2\n -> Matrix (Int) -- ^ point counts\n -> Matrix Float -- ^ camera matrix 1 \n -> Matrix Float -- ^ camera matrix 2 \n -> Matrix Float -- ^ dist coeffs 1\n -> Matrix Float -- ^ dist coeffs 2\n -> (Int,Int) -- ^ image size\n -> C'CvTermCriteria -- ^ stopping condition\n -> CInt -- ^ Flags\n -> (Double, Matrix Float, Matrix Float ,Matrix Float, Matrix Float)\nstereoCalibrate obj im1 im2 counts cam1 cam2 dist1 dist2 (w,h) tc flags = unsafePerformIO $ do \n r <- CV.Matrix.create (3,3)\n e <- CV.Matrix.create (3,3)\n t <- CV.Matrix.create (3,1)\n f <- CV.Matrix.create (3,3)\n \n withMatPtr obj $ \\c_obj ->\n withMatPtr im1 $ \\c_im1 ->\n withMatPtr im2 $ \\c_im2 ->\n withMatPtr counts $ \\c_counts ->\n withMatPtr cam1 $ \\c_cam1 ->\n withMatPtr cam2 $ \\c_cam2 ->\n withMatPtr dist1 $ \\c_dist1 ->\n withMatPtr dist2 $ \\c_dist2 ->\n withMatPtr r $ \\c_r ->\n withMatPtr t $ \\c_t ->\n withMatPtr e $ \\c_e ->\n withMatPtr f $ \\c_f ->\n with tc $ \\c_tc ->\n with (CV.Bindings.Types.C'CvSize (fromIntegral w) (fromIntegral h)) $ \\c_size -> do\n pr <- c'wrapStereoCalibrate \n c_obj \n c_im1 \n c_im2 \n c_counts \n c_cam1 \n c_dist1 \n c_cam2 \n c_dist2 \n c_size\n c_r \n c_t \n c_e \n c_f \n c_tc \n flags\n return (realToFrac pr,r,t,e,f)\n \n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\n#include \"cvWrapLEO.h\"\n-- | This module exposes opencv functions for camera calibration using a chessboard rig. This module follows opencv quite closely and the best documentation\n-- is probably found there. As quick example however, the following program detects and draws chessboard corners from an image.\n--\n-- @\n-- module Main where\n-- import CV.Image\n-- import CV.Calibration\n-- \n-- main = do\n-- Just i <- loadColorImage \\\"chess.png\\\"\n-- let corners = findChessboardCorners (unsafeImageTo8Bit i) (4,5) (FastCheck:defaultFlags)\n-- let y = drawChessboardCorners (unsafeImageTo8Bit i) (4,5) corners\n-- mapM_ print (corners)\n-- saveImage \\\"found_chessboard.png\\\" y\n-- @\nmodule CV.Calibration \n (\n -- * Finding chessboard calibration rig\n FindFlags(..)\n ,defaultFlags\n ,findChessboardCorners\n ,refineChessboardCorners\n -- * Visualization\n ,drawChessboardCorners\n -- * Camera calibration\n ,calibrateCamera2\n -- * Rectification\n ,stereoRectifyUncalibrated\n ,findFundamentalMat\n ,c'CV_FM_7POINT\n ,c'CV_FM_8POINT\n ,c'CV_FM_RANSAC\n ,c'CV_FM_LMEDS\n ) where\n{-#OPTIONS-GHC -fwarn-unused-imports #-}\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.ForeignPtr\nimport Foreign.Storable\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Data.Bits\n\nimport CV.Image \n\nimport System.IO.Unsafe\nimport Utils.Point\nimport Control.Applicative\n\nimport CV.Matrix\nimport CV.Bindings.Calibrate\nimport CV.Bindings.Types\n\n{#import CV.Image#}\n\n#c\nenum FindFlags {\n AdaptiveThresh = CV_CALIB_CB_ADAPTIVE_THRESH\n ,NormalizeImage = CV_CALIB_CB_NORMALIZE_IMAGE\n ,FilterQuads = CV_CALIB_CB_FILTER_QUADS\n ,FastCheck = CV_CALIB_CB_FAST_CHECK\n };\n#endc\n\n-- |\u00a0Flags for the chessboard corner detector. See opencv documentation for cvFindChessboardCorners.\n{#enum FindFlags {}#}\n\nflagsToNum fs = foldl (.|.) 0 $ map (fromIntegral . fromEnum) fs\n\n-- |Default flags for finding corners\ndefaultFlags :: [FindFlags]\ndefaultFlags = [AdaptiveThresh]\n\n-- | Find the inner corners of a chessboard in a given image. \nfindChessboardCorners :: CV.Image.Image RGB D8 -> (Int, Int) -> [FindFlags] -> [(Float,Float)]\nfindChessboardCorners image (w,h) flags =\n unsafePerformIO $ \n with 1 $ \\(c_corner_count::Ptr CInt) -> \n allocaArray len $ \\(c_corners :: Ptr CvPoint )-> \n withGenImage image $ \\c_image -> do\n r <- {#call wrapFindChessBoardCorners#} c_image (fromIntegral w) (fromIntegral h)\n (castPtr c_corners) c_corner_count \n (flagsToNum flags)\n count <- peek c_corner_count\n arr <- peekArray (fromIntegral count) c_corners\n return (map cvPt2Pt arr) \n where len = w*h\n\n-- |Given an estimate of chessboard corners, provide a subpixel estimation of actual corners.\nrefineChessboardCorners :: Image GrayScale D8 -> [(Float,Float)] -> (Int,Int) -> (Int,Int) -> [(Float,Float)]\nrefineChessboardCorners img pts (winW,winH) (zeroW,zeroH) = unsafePerformIO $ do\n with 1 $ \\(c_corner_count::Ptr CInt) -> \n withImage img $ \\c_img ->\n withArray (map mkPt pts) $ \\(c_corners :: Ptr C'CvPoint2D32f ) -> do \n c'wrapFindCornerSubPix c_img c_corners (length pts) winW winH zeroW zeroH tType maxIter epsilon \n map fromPt `fmap` peekArray (length pts) c_corners\n where\n mkPt (x,y) = C'CvPoint2D32f (realToFrac x) (realToFrac y)\n fromPt (C'CvPoint2D32f x y) = (realToFrac x,realToFrac y)\n tType = c'CV_TERMCRIT_ITER\n maxIter = 100\n epsilon = 0.01\n\n-- |\u00a0Draw the found chessboard corners to an image\ndrawChessboardCorners :: CV.Image.Image RGB D8 -> (Int, Int) -> [(Float,Float)] -> CV.Image.Image RGB D8\ndrawChessboardCorners image (w,h) corners =\n unsafePerformIO $ \n withCloneValue image $ \\clone -> \n withArray (map pt2CvPt corners) $ \\(c_corners :: Ptr CvPoint )-> \n withGenImage clone$ \\c_image -> do\n r <- {#call wrapDrawChessBoardCorners#} c_image (fromIntegral w) (fromIntegral h)\n (castPtr c_corners) (fromIntegral $ length corners) \n (found)\n return clone\n where \n len = w*h\n found |\u00a0(w*h) == length corners = 1\n | otherwise = 0 \n \nnewtype CvPoint = CvPt (CFloat,CFloat) deriving (Show)\ncvPt2Pt (CvPt (a,b)) = (realToFrac a , realToFrac b)\npt2CvPt (a,b) = CvPt (realToFrac a , realToFrac b)\n\ninstance Storable CvPoint where\n sizeOf _ = {#sizeof CvPoint #}\n alignment _ = {#alignof CvPoint2D32f #}\n peek p = CvPt <$> ((,) \n <$> {#get CvPoint2D32f->x #} p\n <*> {#get CvPoint2D32f->y #} p)\n poke p (CvPt (hx,hy)) = do\n {#set CvPoint2D32f.x #} p (hx)\n {#set CvPoint2D32f.y #} p (hy)\n\n-- |\u00a0See opencv function cvCalibrateCamera2. This function takes a list of world-screen coordinate pairs acquired with find-chessboard corners\n-- and attempts to find the camera parameters for the system. It returns the fitting error, the camera matrix, list of distortion co-efficients\n-- and rotation and translation vectors for each coordinate pair. \ncalibrateCamera2 ::\n [[((Float, Float, Float), (Float, Float))]]\n -> (Int, Int)\n -> IO (Double, Matrix Float, [[Float]], [[Float]], [[Float]])\ncalibrateCamera2 views (w,h) = do\n let \n pointCounts :: Matrix Int\n pointCounts = fromList (1,length views) (map (length) views)\n m = length views\n totalPts = length (concat views)\n objectPoints :: Matrix Float\n objectPoints = fromList (3,totalPts) $ concat [[x,y,z] | ((x,y,z),_) <- concat views]\n imagePoints :: Matrix Float\n imagePoints = fromList (2,totalPts) $ concat [[x,y] | (_,(x,y)) <- concat views]\n flags = c'CV_CALIB_FIX_K1\n .|. c'CV_CALIB_FIX_K1\n .|. c'CV_CALIB_FIX_K2\n .|. c'CV_CALIB_FIX_K3\n .|. c'CV_CALIB_FIX_K4\n .|. c'CV_CALIB_FIX_K5\n .|. c'CV_CALIB_FIX_K6\n .|. c'CV_CALIB_ZERO_TANGENT_DIST\n\n size = C'CvSize (fromIntegral w) (fromIntegral h)\n cameraMatrix,distCoeffs,rvecs,tvecs :: Matrix Float\n cameraMatrix = emptyMatrix (3,3)\n distCoeffs = emptyMatrix (1,8)\n rvecs = emptyMatrix (m,3)\n tvecs = emptyMatrix (m,3)\n\n err <- with size $\u00a0\\c_size ->\n withMatPtr objectPoints $ \\c_objectPoints ->\n withMatPtr imagePoints $ \\c_imagePoints ->\n withMatPtr pointCounts $ \\c_pointCounts ->\n withMatPtr cameraMatrix $ \\c_cameraMatrix ->\n withMatPtr distCoeffs $ \\c_distCoeffs ->\n withMatPtr rvecs $ \\c_rvecs ->\n withMatPtr tvecs $ \\c_tvecs ->\n c'wrapCalibrateCamera2 c_objectPoints c_imagePoints c_pointCounts c_size \n c_cameraMatrix c_distCoeffs c_rvecs c_tvecs flags\n\n -- print ( objectPoints, imagePoints, pointCounts,cameraMatrix, distCoeffs, rvecs, tvecs )\n return (err, transpose cameraMatrix, toCols distCoeffs, toCols rvecs, toCols tvecs)\n\nstereoRectifyUncalibrated :: Matrix (Float,Float) -> Matrix (Float,Float) -> Matrix Float -> (Int,Int) -> Double\n -> (Matrix Float, Matrix Float)\nstereoRectifyUncalibrated pts1 pts2 fund (w,h) threshold = unsafePerformIO $\n let h1 = emptyMatrix (3,3)\n h2 = emptyMatrix (3,3)\n in withMatPtr pts1 $ \\c_pts1 -> \n withMatPtr pts2 $ \\c_pts2 ->\n withMatPtr fund \u00a0 $ \\c_fund -> \n withMatPtr h1 \u00a0 $ \\c_h1 -> \n withMatPtr h2 \u00a0 $ \\c_h2 -> \n with (C'CvSize (fromIntegral w) (fromIntegral h)) $ \\c_size -> do\n r <- c'wrapStereoRectifyUncalibrated c_pts1 c_pts2 c_fund c_size c_h1 c_h2 (realToFrac threshold)\n return (h1, h2)\n\n\n\nfindFundamentalMat :: Matrix Float -> Matrix Float -> CInt -> Double -> Double\n -> Matrix Float --, Matrix Float)\nfindFundamentalMat pts1 pts2 method p1 p2 = unsafePerformIO $\n let fund = emptyMatrix (3,3)\n in withMatPtr pts1 $ \\c_pts1 -> \n withMatPtr pts2 $ \\c_pts2 ->\n withMatPtr fund \u00a0 $ \\c_fund -> \n do\n r <- c'cvFindFundamentalMat c_pts1 c_pts2 c_fund method (realToFrac p1) (realToFrac p2) nullPtr\n return (fund)\n\n\nstereoCalibrate :: Matrix (Float,Float,Float) -- ^ Object points\n -> Matrix (Float,Float) -- ^ ImagePoints 1\n -> Matrix (Float,Float) -- ^ ImagePoints 2\n -> Matrix (Int) -- ^ point counts\n -> Matrix Float -- ^ camera matrix 1 \n -> Matrix Float -- ^ camera matrix 2 \n -> Matrix Float -- ^ dist coeffs 1\n -> Matrix Float -- ^ dist coeffs 2\n -> (Int,Int) -- ^ image size\n -> C'CvTermCriteria -- ^ stopping condition\n -> CInt -- ^ Flags\n -> (Double, Matrix Float, Matrix Float ,Matrix Float, Matrix Float)\nstereoCalibrate obj im1 im2 counts cam1 cam2 dist1 dist2 (w,h) tc flags = unsafePerformIO $ do \n r <- CV.Matrix.create (3,3)\n e <- CV.Matrix.create (3,3)\n t <- CV.Matrix.create (3,1)\n f <- CV.Matrix.create (3,3)\n \n withMatPtr obj $ \\c_obj ->\n withMatPtr im1 $ \\c_im1 ->\n withMatPtr im2 $ \\c_im2 ->\n withMatPtr counts $ \\c_counts ->\n withMatPtr cam1 $ \\c_cam1 ->\n withMatPtr cam2 $ \\c_cam2 ->\n withMatPtr dist1 $ \\c_dist1 ->\n withMatPtr dist2 $ \\c_dist2 ->\n withMatPtr r $ \\c_r ->\n withMatPtr t $ \\c_t ->\n withMatPtr e $ \\c_e ->\n withMatPtr f $ \\c_f ->\n with tc $ \\c_tc ->\n with (CV.Bindings.Types.C'CvSize (fromIntegral w) (fromIntegral h)) $ \\c_size -> do\n pr <- c'wrapStereoCalibrate \n c_obj \n c_im1 \n c_im2 \n c_counts \n c_cam1 \n c_dist1 \n c_cam2 \n c_dist2 \n c_size\n c_r \n c_t \n c_e \n c_f \n c_tc \n flags\n return (realToFrac pr,r,t,e,f)\n \n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"d45349a7afc72e5fde21de3d80f2504533edca72","subject":"remove obsolete utility","message":"remove obsolete utility\n\nIgnore-this: 759c2e07828e43b1e2ad74c866fbc61d\n\ndarcs-hash:20091217131844-9241b-26756e5abbafaf9c5a33f9dd913b9228f1f33560.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Utils.chs","new_file":"Foreign\/CUDA\/Driver\/Utils.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Utils\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Utility functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Utils\n (\n driverVersion\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n\n-- Friends\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\n\n\n-- |\n-- Return the version number of the installed CUDA driver\n--\ndriverVersion :: IO Int\ndriverVersion = resultIfOk =<< cuDriverGetVersion\n\n{# fun unsafe cuDriverGetVersion\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Utils\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Utility functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Utils\n (\n forceEither, driverVersion\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n\n-- Friends\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\n\n\n-- |\n-- Unwrap an Either construct, throwing an error for non-right values\n--\nforceEither :: Either String a -> a\nforceEither (Left s) = error s\nforceEither (Right r) = r\n\n-- |\n-- Return the version number of the installed CUDA driver\n--\ndriverVersion :: IO Int\ndriverVersion = resultIfOk =<< cuDriverGetVersion\n\n{# fun unsafe cuDriverGetVersion\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"45406224ff23118f8b4678154d4150d9bbbdb002","subject":"Remove fixed TODO.","message":"Remove fixed TODO.\n","repos":"grpc\/grpc-haskell","old_file":"src\/Network\/Grpc\/Core\/Call.chs","new_file":"src\/Network\/Grpc\/Core\/Call.chs","new_contents":"-- Copyright (c) 2016, Google Inc.\n-- All rights reserved.\n--\n-- Redistribution and use in source and binary forms, with or without\n-- modification, are permitted provided that the following conditions are met:\n-- * Redistributions of source code must retain the above copyright\n-- notice, this list of conditions and the following disclaimer.\n-- * Redistributions in binary form must reproduce the above copyright\n-- notice, this list of conditions and the following disclaimer in the\n-- documentation and\/or other materials provided with the distribution.\n-- * Neither the name of Google Inc. nor the\n-- names of its contributors may be used to endorse or promote products\n-- derived from this software without specific prior written permission.\n--\n-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n-- DISCLAIMED. IN NO EVENT SHALL Google Inc. BE LIABLE FOR ANY\n-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n--\n--------------------------------------------------------------------------------\n{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, ExistentialQuantification, RecordWildCards #-}\nmodule Network.Grpc.Core.Call where\n\n\nimport Control.Concurrent\nimport Control.Exception\nimport Control.Monad\n\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Lazy as L\nimport Data.Monoid ((<>), Last(..))\nimport Data.IORef\n\nimport Foreign.C.Types as C\nimport qualified Foreign.Marshal.Alloc as C\nimport qualified Foreign.Marshal.Utils as C\nimport qualified Foreign.Ptr as C\nimport Foreign.Ptr (Ptr)\nimport qualified Foreign.Storable as C\n\n-- transformers\nimport Control.Monad.IO.Class\nimport Control.Monad.Trans.Class\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Reader\n\nimport qualified Network.Grpc.CompletionQueue as CQ\nimport Network.Grpc.Lib.PropagationBits\n{#import Network.Grpc.Lib.ByteBuffer#}\n{#import Network.Grpc.Lib.Metadata#}\n{#import Network.Grpc.Lib.TimeSpec#}\n{#import Network.Grpc.Lib.Core#}\n\n\n#include \n#include \"hs_grpc.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\ndata Deadline\n = AbsoluteDeadline TimeSpec\n | RelativeDeadline Int --seconds\n\ndata ClientContext = ClientContext\n { ccChannel :: Channel\n , ccCQ :: CompletionQueue\n , ccWorker :: CQ.Worker\n }\n\ndata CallOptions = CallOptions\n { coDeadline :: Maybe Deadline\n , coParentContext :: Maybe () -- todo\n , coPropagationMask :: Maybe PropagationMask\n , coMetadata :: [Metadata]\n }\n\ninstance Monoid CallOptions where\n mempty = CallOptions Nothing Nothing Nothing []\n mappend (CallOptions a b c d) (CallOptions a' b' c' d') =\n CallOptions\n (getLast (Last a <> Last a'))\n (getLast (Last b <> Last b'))\n (getLast (Last c <> Last c'))\n (d <> d')\n\nwithAbsoluteDeadline :: TimeSpec -> CallOptions\nwithAbsoluteDeadline deadline =\n mempty { coDeadline = Just (AbsoluteDeadline deadline) }\n\nwithRelativeDeadlineSeconds :: Int -> CallOptions\nwithRelativeDeadlineSeconds seconds =\n mempty { coDeadline = Just (RelativeDeadline seconds) }\n\nwithParentContext :: () -> CallOptions\nwithParentContext ctx =\n mempty { coParentContext = Just ctx }\n\nwithParentContextPropagating :: () -> PropagationMask -> CallOptions\nwithParentContextPropagating ctx prop =\n mempty { coParentContext = Just ctx\n , coPropagationMask = Just prop }\n\nwithMetadata :: [Metadata] -> CallOptions\nwithMetadata md =\n mempty { coMetadata = md }\n\nresolveDeadline :: CallOptions -> IO TimeSpec\nresolveDeadline co =\n case coDeadline co of\n Nothing -> return gprInfFuture\n Just (AbsoluteDeadline deadline) -> return deadline\n Just (RelativeDeadline seconds) ->\n secondsFromNow (fromIntegral seconds)\n\nnewClientContext :: Channel -> IO ClientContext\nnewClientContext chan = do\n cq <- completionQueueCreate reservedPtr\n cqt <- CQ.startCompletionQueueThread cq\n return (ClientContext chan cq cqt)\n\ndestroyClientContext :: ClientContext -> IO ()\ndestroyClientContext (ClientContext _ cq w) = do\n completionQueueShutdown cq\n CQ.waitWorkerTermination w\n\ntype MethodName = B.ByteString\ntype Arg = B.ByteString\n\n-- | Run the IO function once, cache it in the MVar.\nonceMVar :: MVar (Maybe a) -> IO a -> IO a\nonceMVar mvar io = modifyMVar mvar $ \\x ->\n case x of\n Just x' -> return (x, x')\n Nothing -> do\n x' <- io\n return (Just x', x')\n\nreservedPtr :: Ptr ()\nreservedPtr = C.nullPtr\n\ndata UnaryResult a = UnaryResult [Metadata] [Metadata] a deriving Show\n\ncallUnary :: ClientContext -> CallOptions -> MethodName -> Arg -> IO (RpcReply (UnaryResult L.ByteString))\ncallUnary ctx@(ClientContext chan cq _) co method arg = do\n deadline <- resolveDeadline co\n bracket (grpcChannelCreateCall chan C.nullPtr propagateDefaults cq method \"localhost\" deadline) grpcCallDestroy $ \\call0 -> newMVar call0 >>= \\mcall -> do\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n recvStatusOp <- opRecvStatusOnClient crw\n recvMessageOp <- opRecvMessage\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX recvInitialMetadataOp\n , OpX recvMessageOp\n , OpX sendMessageOp\n , OpX recvStatusOp\n ]\n case res of\n RpcOk _ -> do\n (RpcStatus trailMD status statusDetails) <- opRead recvStatusOp\n case status of\n StatusOk -> do\n initMD <- opRead recvInitialMetadataOp\n answ <- opRead recvMessageOp\n let answ' = maybe L.empty id answ\n return (RpcOk (UnaryResult initMD trailMD answ'))\n _ -> return (RpcError (StatusError status statusDetails))\n RpcError err -> return (RpcError err)\n\ncallDownstream :: ClientContext -> CallOptions -> MethodName -> Arg -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallDownstream ctx@(ClientContext chan cq _) co method arg = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall chan C.nullPtr propagateDefaults cq method \"localhost\" deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX sendMessageOp\n ]\n case res of\n RpcOk _ -> do\n return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n\ncallUpstream :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallUpstream ctx@(ClientContext chan cq _) co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall chan C.nullPtr propagateDefaults cq method \"localhost\" deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> do\n return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n\ncallBidi :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallBidi ctx@(ClientContext chan cq _) co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall chan C.nullPtr propagateDefaults cq method \"localhost\" deadline >>= newMVar\n\n crw <- newClientReaderWriter ctx mcall\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n\ndata Client req resp = Client\n { clientCrw :: ClientReaderWriter\n , clientEncoder :: Encoder req\n , clientDecoder :: Decoder resp\n }\n\ntype Decoder a = L.ByteString -> IO (RpcReply a)\ntype Encoder a = a -> IO (RpcReply B.ByteString)\n\ndefaultDecoder :: L.ByteString -> IO (RpcReply L.ByteString)\ndefaultDecoder bs = return (RpcOk bs)\n\ndefaultEncoder :: B.ByteString -> IO (RpcReply B.ByteString)\ndefaultEncoder bs = return (RpcOk bs)\n\ndata ClientReaderWriter = ClientReaderWriter {\n context :: ClientContext,\n callMVar_ :: MVar Call,\n initialMDRef :: !(IORef (Maybe [Metadata])),\n trailingMDRef :: !(IORef (Maybe [Metadata])),\n statusFromServer :: !(IORef (Maybe RpcStatus))\n}\n\nnewClientReaderWriter :: ClientContext -> MVar Call -> IO ClientReaderWriter\nnewClientReaderWriter ctx mcall = do\n initMD <- newIORef Nothing\n trailMD <- newIORef Nothing\n status <- newIORef Nothing\n return (ClientReaderWriter ctx mcall initMD trailMD status)\n\ndata OpX = forall t. OpX (OpT t)\n\ndata OpArray = OpArray { opArrPtr :: !GrpcOpPtr\n , opArrLen :: !CULong\n , opArrFree :: !(IO ())\n }\n\ntoArray :: [OpX] -> IO OpArray\ntoArray ops = do\n aptr <- C.mallocBytes (length ops * {#sizeof grpc_op#})\n let ptrs = iterate (`C.plusPtr` {#sizeof grpc_op#}) aptr\n ops' = concatMap (\\(OpX op) -> opAdd op) ops\n free = C.free aptr >> sequence_ (map (\\(OpX op) -> opFinish op) ops)\n write op p = do\n {#set grpc_op->flags#} p 0\n {#set grpc_op->reserved#} p C.nullPtr\n op p\n zipWithM_ write ops' ptrs\n return $! OpArray aptr (fromIntegral $ length ops) free\n\ncallBatch :: ClientReaderWriter -> [OpX] -> IO (RpcReply ())\ncallBatch crw ops = do\n let ctx = context crw\n CQ.withEvent (ccWorker ctx) $ \\eDesc -> do\n arr <- toArray ops\n callStatus <- withMVar (callMVar_ crw) $ \\call ->\n grpcCallStartBatch call (opArrPtr arr) (opArrLen arr) (CQ.eventTag eDesc) reservedPtr\n -- print (\"callStatus: \" ++ show callStatus)\n case callStatus of\n CallOk -> do\n e <- CQ.interruptibleWaitEvent eDesc\n -- print (\"event: \" ++ show e)\n opArrFree arr -- TODO: We leak if we're interrupted.\n case e of\n QueueOpComplete OpSuccess _ -> return (RpcOk ())\n QueueOpComplete OpError _ -> return (RpcError (Error \"callBatch: op error\"))\n QueueTimeOut -> return (RpcError DeadlineExceeded)\n QueueShutdown -> return (RpcError (Error \"queue shutdown\"))\n _ -> do\n -- print callStatus\n return (RpcError (CallErrorStatus callStatus))\n\ndata OpT out = Op\n { opAdd :: [Ptr GrpcOp -> IO ()]\n , opValue :: IORef out\n , opFinish :: IO ()\n }\n\nopRead :: OpT a -> IO a\nopRead op = readIORef (opValue op)\n\nopRecvInitialMetadata :: ClientReaderWriter -> IO (OpT [Metadata])\nopRecvInitialMetadata crw = do\n arr <- mallocMetadataArray\n value <- newIORef (error \"opRecvInitialMetadata never finished\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvInitialMetadata))\n {#set grpc_op->data.recv_initial_metadata#} p arr\n ]\n finish = do\n mds <- readMetadataArray arr\n writeIORef (initialMDRef crw) (Just mds)\n writeIORef value mds\n freeMetadataArray arr\n return (Op add value finish)\n\nopSendMessage :: B.ByteString -> IO (OpT ())\nopSendMessage bs = do\n bb <- fromByteString bs\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendMessage))\n {#set grpc_op->data.send_message#} p bb\n ]\n finish =\n byteBufferDestroy bb\n return (Op add value finish)\n\nopRecvMessage :: IO (OpT (Maybe L.ByteString))\nopRecvMessage = do\n bbptr <- C.malloc :: IO (Ptr (Ptr CByteBuffer))\n value <- newIORef Nothing\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvMessage))\n {#set grpc_op->data.recv_message#} p bbptr\n ]\n finish = do\n bb <- C.peek bbptr\n C.free bbptr\n writeIORef value =<< if bb \/= C.nullPtr\n then do\n lbs <- toLazyByteString bb\n byteBufferDestroy bb\n return (Just lbs)\n else return Nothing\n return (Op add value finish)\n\nopSendInitialMetadata :: [Metadata] -> IO (OpT ())\nopSendInitialMetadata elems = do\n (mdArrPtr, free) <- mallocMetadata elems\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendInitialMetadata))\n {#set grpc_op->data.send_initial_metadata.count#} p (fromIntegral (length elems))\n {#set grpc_op->data.send_initial_metadata.metadata#} p (C.castPtr mdArrPtr)\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.is_set#} p 0\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.level#} p 0\n ]\n finish = do\n free\n return (Op add value finish)\n\ndata RpcStatus = RpcStatus [Metadata] StatusCode B.ByteString\n deriving Show\n\nopRecvStatusOnClient :: ClientReaderWriter -> IO (OpT RpcStatus)\nopRecvStatusOnClient (ClientReaderWriter{..}) = do\n trailingMetadataArrPtr <- mallocMetadataArray\n statusCodePtr <- C.malloc :: IO (Ptr StatusCodeT)\n ptrPtrStatusStr <- C.new C.nullPtr :: IO (Ptr (Ptr CChar))\n capacityPtr <- C.new 0 :: IO (Ptr SizeT)\n value <- newIORef (error \"opRecvStatusOnClient never ran\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvStatusOnClient))\n {#set grpc_op->data.recv_status_on_client.trailing_metadata#} p trailingMetadataArrPtr\n {#set grpc_op->data.recv_status_on_client.status#} p statusCodePtr\n {#set grpc_op->data.recv_status_on_client.status_details#} p ptrPtrStatusStr\n {#set grpc_op->data.recv_status_on_client.status_details_capacity#} p capacityPtr\n ]\n finish = do\n trailingMd <- readMetadataArray trailingMetadataArrPtr\n statusCode <- fmap toStatusCode (C.peek statusCodePtr)\n statusDetails <- B.packCString =<< C.peek ptrPtrStatusStr\n let status = RpcStatus trailingMd statusCode statusDetails\n writeIORef value status\n writeIORef statusFromServer (Just status)\n free\n free = do\n freeMetadataArray trailingMetadataArrPtr\n C.free statusCodePtr\n C.free ptrPtrStatusStr\n C.free capacityPtr\n return (Op add value finish)\n\nopSendCloseFromClient :: IO (OpT ())\nopSendCloseFromClient = do\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendCloseFromClient))\n ]\n finish =\n return ()\n return (Op add value finish)\n\nclientWaitForInitialMetadata :: ClientReaderWriter -> IO (RpcReply [Metadata])\nclientWaitForInitialMetadata crw@(ClientReaderWriter { .. }) = do\n initMD <- readIORef initialMDRef\n case initMD of\n Just md -> return (RpcOk md)\n Nothing -> do\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n res <- callBatch crw [ OpX recvInitialMetadataOp ]\n case res of\n RpcOk _ -> do\n md <- opRead recvInitialMetadataOp\n writeIORef initialMDRef (Just md)\n return (RpcOk md)\n RpcError err ->\n return (RpcError err)\n\nclientReadInitialMetadata :: ClientReaderWriter -> IO (RpcReply (Maybe [Metadata]))\nclientReadInitialMetadata (ClientReaderWriter {..}) = do\n md <- readIORef initialMDRef\n return (RpcOk md)\n\nclientRead :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nclientRead crw = do\n _ <- clientWaitForInitialMetadata crw\n recvMessage crw\n\nrecvMessage :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nrecvMessage crw = do\n recvMessageOp <- opRecvMessage\n res <- callBatch crw [ OpX recvMessageOp ]\n case res of\n RpcOk _ -> do\n bs <- opRead recvMessageOp\n return (RpcOk bs)\n RpcError err -> do\n putStrLn \"recvMessage: callBatch failed\"\n return (RpcError err)\n\nclientWaitForStatus :: ClientReaderWriter -> IO (RpcReply RpcStatus)\nclientWaitForStatus crw@(ClientReaderWriter{..}) = do\n status <- readIORef statusFromServer\n case status of\n Nothing -> do\n recvStatusOp <- opRecvStatusOnClient crw\n res <- callBatch crw [ OpX recvStatusOp ]\n case res of\n RpcOk _ -> do\n st <- opRead recvStatusOp\n return (RpcOk st)\n RpcError err -> do\n return (RpcError err)\n Just st -> return (RpcOk st)\n\nclientClose :: ClientReaderWriter -> IO ()\nclientClose (ClientReaderWriter{..}) = do\n withMVar callMVar_ $ \\call ->\n grpcCallDestroy call\n\nclientWrite :: ClientReaderWriter -> B.ByteString -> IO (RpcReply ())\nclientWrite crw@(ClientReaderWriter{..}) arg = do\n sendMessageOp <- opSendMessage arg\n callBatch crw [ OpX sendMessageOp ]\n\nclientSendHalfClose :: ClientReaderWriter -> IO (RpcReply ())\nclientSendHalfClose crw@(ClientReaderWriter{..}) = do\n sendCloseOp <- opSendCloseFromClient\n callBatch crw [ OpX sendCloseOp ]\n\nclientCloseCall :: ClientReaderWriter -> IO ()\nclientCloseCall ClientReaderWriter { callMVar_ = callMVar } =\n withMVar callMVar $ \\call ->\n grpcCallDestroy call\n\ntype Rpc req resp a = ReaderT (Client req resp) (ExceptT RpcError IO) a\n\naskCrw :: Rpc req resp ClientReaderWriter\naskCrw = asks clientCrw\n\naskDecoder :: Rpc req resp (Decoder resp)\naskDecoder = asks clientDecoder\n\naskEncoder :: Rpc req resp (Encoder req)\naskEncoder = asks clientEncoder\n\njoinReply :: RpcReply a -> Rpc req resp a\njoinReply (RpcOk a) = return a\njoinReply (RpcError err) = lift (throwE err)\n\nwithNewClient :: RpcReply (Client req resp) -> Rpc req resp a -> IO (RpcReply a)\nwithNewClient r_client m = do\n case r_client of\n RpcOk client -> withClient client m\n RpcError err -> return (RpcError err)\n\nwithClient :: Client req resp -> Rpc req resp a -> IO (RpcReply a)\nwithClient client m = do\n e <- runExceptT (runReaderT m client)\n case e of\n Left err -> return (RpcError err)\n Right a -> return (RpcOk a)\n\ninitialMetadata :: Rpc req resp [Metadata]\ninitialMetadata = do\n crw <- askCrw\n joinReply =<< liftIO (clientWaitForInitialMetadata crw)\n\nwaitForStatus :: Rpc req resp RpcStatus\nwaitForStatus = do\n crw <- askCrw\n joinReply =<< liftIO (clientWaitForStatus crw)\n\nreceiveMessage :: Rpc req resp (Maybe resp)\nreceiveMessage = do\n crw <- askCrw\n msg <- joinReply =<< liftIO (clientRead crw)\n case msg of\n Nothing -> return Nothing\n Just x -> do\n decoder <- askDecoder\n liftM Just (joinReply =<< liftIO (decoder x))\n\nreceiveAllMessages :: Rpc req resp [resp]\nreceiveAllMessages = do\n crw <- askCrw\n decoder <- askDecoder\n let go acc = do\n value <- joinReply =<< liftIO (clientRead crw)\n case value of\n Just x -> do\n y <- joinReply =<< (liftIO (decoder x))\n go (y:acc)\n Nothing -> return (reverse acc)\n go []\n\nsendMessage :: req -> Rpc req resp ()\nsendMessage o = do\n crw <- askCrw\n encoder <- askEncoder\n x <- joinReply =<< liftIO (encoder o)\n joinReply =<< liftIO (clientWrite crw x)\n\nsendHalfClose :: Rpc req resp ()\nsendHalfClose = do\n crw <- askCrw\n joinReply =<< liftIO (clientSendHalfClose crw)\n\ncloseCall :: Rpc req resp ()\ncloseCall = do\n crw <- askCrw\n liftIO (clientClose crw)\n\ndata RpcReply a\n = RpcOk a\n | RpcError RpcError\n deriving Show\n\ndata RpcError\n = DeadlineExceeded\n | Cancelled\n | Error String\n | CallErrorStatus CallError\n | StatusError StatusCode B.ByteString\n deriving Show\n","old_contents":"-- Copyright (c) 2016, Google Inc.\n-- All rights reserved.\n--\n-- Redistribution and use in source and binary forms, with or without\n-- modification, are permitted provided that the following conditions are met:\n-- * Redistributions of source code must retain the above copyright\n-- notice, this list of conditions and the following disclaimer.\n-- * Redistributions in binary form must reproduce the above copyright\n-- notice, this list of conditions and the following disclaimer in the\n-- documentation and\/or other materials provided with the distribution.\n-- * Neither the name of Google Inc. nor the\n-- names of its contributors may be used to endorse or promote products\n-- derived from this software without specific prior written permission.\n--\n-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n-- DISCLAIMED. IN NO EVENT SHALL Google Inc. BE LIABLE FOR ANY\n-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n--\n--------------------------------------------------------------------------------\n{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, ExistentialQuantification, RecordWildCards #-}\nmodule Network.Grpc.Core.Call where\n\n\nimport Control.Concurrent\nimport Control.Exception\nimport Control.Monad\n\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Lazy as L\nimport Data.Monoid ((<>), Last(..))\nimport Data.IORef\n\nimport Foreign.C.Types as C\nimport qualified Foreign.Marshal.Alloc as C\nimport qualified Foreign.Marshal.Utils as C\nimport qualified Foreign.Ptr as C\nimport Foreign.Ptr (Ptr)\nimport qualified Foreign.Storable as C\n\n-- transformers\nimport Control.Monad.IO.Class\nimport Control.Monad.Trans.Class\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Reader\n\nimport qualified Network.Grpc.CompletionQueue as CQ\nimport Network.Grpc.Lib.PropagationBits\n{#import Network.Grpc.Lib.ByteBuffer#}\n{#import Network.Grpc.Lib.Metadata#}\n{#import Network.Grpc.Lib.TimeSpec#}\n{#import Network.Grpc.Lib.Core#}\n\n\n#include \n#include \"hs_grpc.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\ndata Deadline\n = AbsoluteDeadline TimeSpec\n | RelativeDeadline Int --seconds\n\ndata ClientContext = ClientContext\n { ccChannel :: Channel\n , ccCQ :: CompletionQueue\n , ccWorker :: CQ.Worker\n }\n\ndata CallOptions = CallOptions\n { coDeadline :: Maybe Deadline\n , coParentContext :: Maybe () -- todo\n , coPropagationMask :: Maybe PropagationMask\n , coMetadata :: [Metadata] -- todo\n }\n\ninstance Monoid CallOptions where\n mempty = CallOptions Nothing Nothing Nothing []\n mappend (CallOptions a b c d) (CallOptions a' b' c' d') =\n CallOptions\n (getLast (Last a <> Last a'))\n (getLast (Last b <> Last b'))\n (getLast (Last c <> Last c'))\n (d <> d')\n\nwithAbsoluteDeadline :: TimeSpec -> CallOptions\nwithAbsoluteDeadline deadline =\n mempty { coDeadline = Just (AbsoluteDeadline deadline) }\n\nwithRelativeDeadlineSeconds :: Int -> CallOptions\nwithRelativeDeadlineSeconds seconds =\n mempty { coDeadline = Just (RelativeDeadline seconds) }\n\nwithParentContext :: () -> CallOptions\nwithParentContext ctx =\n mempty { coParentContext = Just ctx }\n\nwithParentContextPropagating :: () -> PropagationMask -> CallOptions\nwithParentContextPropagating ctx prop =\n mempty { coParentContext = Just ctx\n , coPropagationMask = Just prop }\n\nwithMetadata :: [Metadata] -> CallOptions\nwithMetadata md =\n mempty { coMetadata = md }\n\nresolveDeadline :: CallOptions -> IO TimeSpec\nresolveDeadline co =\n case coDeadline co of\n Nothing -> return gprInfFuture\n Just (AbsoluteDeadline deadline) -> return deadline\n Just (RelativeDeadline seconds) ->\n secondsFromNow (fromIntegral seconds)\n\nnewClientContext :: Channel -> IO ClientContext\nnewClientContext chan = do\n cq <- completionQueueCreate reservedPtr\n cqt <- CQ.startCompletionQueueThread cq\n return (ClientContext chan cq cqt)\n\ndestroyClientContext :: ClientContext -> IO ()\ndestroyClientContext (ClientContext _ cq w) = do\n completionQueueShutdown cq\n CQ.waitWorkerTermination w\n\ntype MethodName = B.ByteString\ntype Arg = B.ByteString\n\n-- | Run the IO function once, cache it in the MVar.\nonceMVar :: MVar (Maybe a) -> IO a -> IO a\nonceMVar mvar io = modifyMVar mvar $ \\x ->\n case x of\n Just x' -> return (x, x')\n Nothing -> do\n x' <- io\n return (Just x', x')\n\nreservedPtr :: Ptr ()\nreservedPtr = C.nullPtr\n\ndata UnaryResult a = UnaryResult [Metadata] [Metadata] a deriving Show\n\ncallUnary :: ClientContext -> CallOptions -> MethodName -> Arg -> IO (RpcReply (UnaryResult L.ByteString))\ncallUnary ctx@(ClientContext chan cq _) co method arg = do\n deadline <- resolveDeadline co\n bracket (grpcChannelCreateCall chan C.nullPtr propagateDefaults cq method \"localhost\" deadline) grpcCallDestroy $ \\call0 -> newMVar call0 >>= \\mcall -> do\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n recvStatusOp <- opRecvStatusOnClient crw\n recvMessageOp <- opRecvMessage\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX recvInitialMetadataOp\n , OpX recvMessageOp\n , OpX sendMessageOp\n , OpX recvStatusOp\n ]\n case res of\n RpcOk _ -> do\n (RpcStatus trailMD status statusDetails) <- opRead recvStatusOp\n case status of\n StatusOk -> do\n initMD <- opRead recvInitialMetadataOp\n answ <- opRead recvMessageOp\n let answ' = maybe L.empty id answ\n return (RpcOk (UnaryResult initMD trailMD answ'))\n _ -> return (RpcError (StatusError status statusDetails))\n RpcError err -> return (RpcError err)\n\ncallDownstream :: ClientContext -> CallOptions -> MethodName -> Arg -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallDownstream ctx@(ClientContext chan cq _) co method arg = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall chan C.nullPtr propagateDefaults cq method \"localhost\" deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX sendMessageOp\n ]\n case res of\n RpcOk _ -> do\n return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n\ncallUpstream :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallUpstream ctx@(ClientContext chan cq _) co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall chan C.nullPtr propagateDefaults cq method \"localhost\" deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> do\n return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n\ncallBidi :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallBidi ctx@(ClientContext chan cq _) co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall chan C.nullPtr propagateDefaults cq method \"localhost\" deadline >>= newMVar\n\n crw <- newClientReaderWriter ctx mcall\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n\ndata Client req resp = Client\n { clientCrw :: ClientReaderWriter\n , clientEncoder :: Encoder req\n , clientDecoder :: Decoder resp\n }\n\ntype Decoder a = L.ByteString -> IO (RpcReply a)\ntype Encoder a = a -> IO (RpcReply B.ByteString)\n\ndefaultDecoder :: L.ByteString -> IO (RpcReply L.ByteString)\ndefaultDecoder bs = return (RpcOk bs)\n\ndefaultEncoder :: B.ByteString -> IO (RpcReply B.ByteString)\ndefaultEncoder bs = return (RpcOk bs)\n\ndata ClientReaderWriter = ClientReaderWriter {\n context :: ClientContext,\n callMVar_ :: MVar Call,\n initialMDRef :: !(IORef (Maybe [Metadata])),\n trailingMDRef :: !(IORef (Maybe [Metadata])),\n statusFromServer :: !(IORef (Maybe RpcStatus))\n}\n\nnewClientReaderWriter :: ClientContext -> MVar Call -> IO ClientReaderWriter\nnewClientReaderWriter ctx mcall = do\n initMD <- newIORef Nothing\n trailMD <- newIORef Nothing\n status <- newIORef Nothing\n return (ClientReaderWriter ctx mcall initMD trailMD status)\n\ndata OpX = forall t. OpX (OpT t)\n\ndata OpArray = OpArray { opArrPtr :: !GrpcOpPtr\n , opArrLen :: !CULong\n , opArrFree :: !(IO ())\n }\n\ntoArray :: [OpX] -> IO OpArray\ntoArray ops = do\n aptr <- C.mallocBytes (length ops * {#sizeof grpc_op#})\n let ptrs = iterate (`C.plusPtr` {#sizeof grpc_op#}) aptr\n ops' = concatMap (\\(OpX op) -> opAdd op) ops\n free = C.free aptr >> sequence_ (map (\\(OpX op) -> opFinish op) ops)\n write op p = do\n {#set grpc_op->flags#} p 0\n {#set grpc_op->reserved#} p C.nullPtr\n op p\n zipWithM_ write ops' ptrs\n return $! OpArray aptr (fromIntegral $ length ops) free\n\ncallBatch :: ClientReaderWriter -> [OpX] -> IO (RpcReply ())\ncallBatch crw ops = do\n let ctx = context crw\n CQ.withEvent (ccWorker ctx) $ \\eDesc -> do\n arr <- toArray ops\n callStatus <- withMVar (callMVar_ crw) $ \\call ->\n grpcCallStartBatch call (opArrPtr arr) (opArrLen arr) (CQ.eventTag eDesc) reservedPtr\n -- print (\"callStatus: \" ++ show callStatus)\n case callStatus of\n CallOk -> do\n e <- CQ.interruptibleWaitEvent eDesc\n -- print (\"event: \" ++ show e)\n opArrFree arr -- TODO: We leak if we're interrupted.\n case e of\n QueueOpComplete OpSuccess _ -> return (RpcOk ())\n QueueOpComplete OpError _ -> return (RpcError (Error \"callBatch: op error\"))\n QueueTimeOut -> return (RpcError DeadlineExceeded)\n QueueShutdown -> return (RpcError (Error \"queue shutdown\"))\n _ -> do\n -- print callStatus\n return (RpcError (CallErrorStatus callStatus))\n\ndata OpT out = Op\n { opAdd :: [Ptr GrpcOp -> IO ()]\n , opValue :: IORef out\n , opFinish :: IO ()\n }\n\nopRead :: OpT a -> IO a\nopRead op = readIORef (opValue op)\n\nopRecvInitialMetadata :: ClientReaderWriter -> IO (OpT [Metadata])\nopRecvInitialMetadata crw = do\n arr <- mallocMetadataArray\n value <- newIORef (error \"opRecvInitialMetadata never finished\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvInitialMetadata))\n {#set grpc_op->data.recv_initial_metadata#} p arr\n ]\n finish = do\n mds <- readMetadataArray arr\n writeIORef (initialMDRef crw) (Just mds)\n writeIORef value mds\n freeMetadataArray arr\n return (Op add value finish)\n\nopSendMessage :: B.ByteString -> IO (OpT ())\nopSendMessage bs = do\n bb <- fromByteString bs\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendMessage))\n {#set grpc_op->data.send_message#} p bb\n ]\n finish =\n byteBufferDestroy bb\n return (Op add value finish)\n\nopRecvMessage :: IO (OpT (Maybe L.ByteString))\nopRecvMessage = do\n bbptr <- C.malloc :: IO (Ptr (Ptr CByteBuffer))\n value <- newIORef Nothing\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvMessage))\n {#set grpc_op->data.recv_message#} p bbptr\n ]\n finish = do\n bb <- C.peek bbptr\n C.free bbptr\n writeIORef value =<< if bb \/= C.nullPtr\n then do\n lbs <- toLazyByteString bb\n byteBufferDestroy bb\n return (Just lbs)\n else return Nothing\n return (Op add value finish)\n\nopSendInitialMetadata :: [Metadata] -> IO (OpT ())\nopSendInitialMetadata elems = do\n (mdArrPtr, free) <- mallocMetadata elems\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendInitialMetadata))\n {#set grpc_op->data.send_initial_metadata.count#} p (fromIntegral (length elems))\n {#set grpc_op->data.send_initial_metadata.metadata#} p (C.castPtr mdArrPtr)\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.is_set#} p 0\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.level#} p 0\n ]\n finish = do\n free\n return (Op add value finish)\n\ndata RpcStatus = RpcStatus [Metadata] StatusCode B.ByteString\n deriving Show\n\nopRecvStatusOnClient :: ClientReaderWriter -> IO (OpT RpcStatus)\nopRecvStatusOnClient (ClientReaderWriter{..}) = do\n trailingMetadataArrPtr <- mallocMetadataArray\n statusCodePtr <- C.malloc :: IO (Ptr StatusCodeT)\n ptrPtrStatusStr <- C.new C.nullPtr :: IO (Ptr (Ptr CChar))\n capacityPtr <- C.new 0 :: IO (Ptr SizeT)\n value <- newIORef (error \"opRecvStatusOnClient never ran\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvStatusOnClient))\n {#set grpc_op->data.recv_status_on_client.trailing_metadata#} p trailingMetadataArrPtr\n {#set grpc_op->data.recv_status_on_client.status#} p statusCodePtr\n {#set grpc_op->data.recv_status_on_client.status_details#} p ptrPtrStatusStr\n {#set grpc_op->data.recv_status_on_client.status_details_capacity#} p capacityPtr\n ]\n finish = do\n trailingMd <- readMetadataArray trailingMetadataArrPtr\n statusCode <- fmap toStatusCode (C.peek statusCodePtr)\n statusDetails <- B.packCString =<< C.peek ptrPtrStatusStr\n let status = RpcStatus trailingMd statusCode statusDetails\n writeIORef value status\n writeIORef statusFromServer (Just status)\n free\n free = do\n freeMetadataArray trailingMetadataArrPtr\n C.free statusCodePtr\n C.free ptrPtrStatusStr\n C.free capacityPtr\n return (Op add value finish)\n\nopSendCloseFromClient :: IO (OpT ())\nopSendCloseFromClient = do\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendCloseFromClient))\n ]\n finish =\n return ()\n return (Op add value finish)\n\nclientWaitForInitialMetadata :: ClientReaderWriter -> IO (RpcReply [Metadata])\nclientWaitForInitialMetadata crw@(ClientReaderWriter { .. }) = do\n initMD <- readIORef initialMDRef\n case initMD of\n Just md -> return (RpcOk md)\n Nothing -> do\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n res <- callBatch crw [ OpX recvInitialMetadataOp ]\n case res of\n RpcOk _ -> do\n md <- opRead recvInitialMetadataOp\n writeIORef initialMDRef (Just md)\n return (RpcOk md)\n RpcError err ->\n return (RpcError err)\n\nclientReadInitialMetadata :: ClientReaderWriter -> IO (RpcReply (Maybe [Metadata]))\nclientReadInitialMetadata (ClientReaderWriter {..}) = do\n md <- readIORef initialMDRef\n return (RpcOk md)\n\nclientRead :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nclientRead crw = do\n _ <- clientWaitForInitialMetadata crw\n recvMessage crw\n\nrecvMessage :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nrecvMessage crw = do\n recvMessageOp <- opRecvMessage\n res <- callBatch crw [ OpX recvMessageOp ]\n case res of\n RpcOk _ -> do\n bs <- opRead recvMessageOp\n return (RpcOk bs)\n RpcError err -> do\n putStrLn \"recvMessage: callBatch failed\"\n return (RpcError err)\n\nclientWaitForStatus :: ClientReaderWriter -> IO (RpcReply RpcStatus)\nclientWaitForStatus crw@(ClientReaderWriter{..}) = do\n status <- readIORef statusFromServer\n case status of\n Nothing -> do\n recvStatusOp <- opRecvStatusOnClient crw\n res <- callBatch crw [ OpX recvStatusOp ]\n case res of\n RpcOk _ -> do\n st <- opRead recvStatusOp\n return (RpcOk st)\n RpcError err -> do\n return (RpcError err)\n Just st -> return (RpcOk st)\n\nclientClose :: ClientReaderWriter -> IO ()\nclientClose (ClientReaderWriter{..}) = do\n withMVar callMVar_ $ \\call ->\n grpcCallDestroy call\n\nclientWrite :: ClientReaderWriter -> B.ByteString -> IO (RpcReply ())\nclientWrite crw@(ClientReaderWriter{..}) arg = do\n sendMessageOp <- opSendMessage arg\n callBatch crw [ OpX sendMessageOp ]\n\nclientSendHalfClose :: ClientReaderWriter -> IO (RpcReply ())\nclientSendHalfClose crw@(ClientReaderWriter{..}) = do\n sendCloseOp <- opSendCloseFromClient\n callBatch crw [ OpX sendCloseOp ]\n\nclientCloseCall :: ClientReaderWriter -> IO ()\nclientCloseCall ClientReaderWriter { callMVar_ = callMVar } =\n withMVar callMVar $ \\call ->\n grpcCallDestroy call\n\ntype Rpc req resp a = ReaderT (Client req resp) (ExceptT RpcError IO) a\n\naskCrw :: Rpc req resp ClientReaderWriter\naskCrw = asks clientCrw\n\naskDecoder :: Rpc req resp (Decoder resp)\naskDecoder = asks clientDecoder\n\naskEncoder :: Rpc req resp (Encoder req)\naskEncoder = asks clientEncoder\n\njoinReply :: RpcReply a -> Rpc req resp a\njoinReply (RpcOk a) = return a\njoinReply (RpcError err) = lift (throwE err)\n\nwithNewClient :: RpcReply (Client req resp) -> Rpc req resp a -> IO (RpcReply a)\nwithNewClient r_client m = do\n case r_client of\n RpcOk client -> withClient client m\n RpcError err -> return (RpcError err)\n\nwithClient :: Client req resp -> Rpc req resp a -> IO (RpcReply a)\nwithClient client m = do\n e <- runExceptT (runReaderT m client)\n case e of\n Left err -> return (RpcError err)\n Right a -> return (RpcOk a)\n\ninitialMetadata :: Rpc req resp [Metadata]\ninitialMetadata = do\n crw <- askCrw\n joinReply =<< liftIO (clientWaitForInitialMetadata crw)\n\nwaitForStatus :: Rpc req resp RpcStatus\nwaitForStatus = do\n crw <- askCrw\n joinReply =<< liftIO (clientWaitForStatus crw)\n\nreceiveMessage :: Rpc req resp (Maybe resp)\nreceiveMessage = do\n crw <- askCrw\n msg <- joinReply =<< liftIO (clientRead crw)\n case msg of\n Nothing -> return Nothing\n Just x -> do\n decoder <- askDecoder\n liftM Just (joinReply =<< liftIO (decoder x))\n\nreceiveAllMessages :: Rpc req resp [resp]\nreceiveAllMessages = do\n crw <- askCrw\n decoder <- askDecoder\n let go acc = do\n value <- joinReply =<< liftIO (clientRead crw)\n case value of\n Just x -> do\n y <- joinReply =<< (liftIO (decoder x))\n go (y:acc)\n Nothing -> return (reverse acc)\n go []\n\nsendMessage :: req -> Rpc req resp ()\nsendMessage o = do\n crw <- askCrw\n encoder <- askEncoder\n x <- joinReply =<< liftIO (encoder o)\n joinReply =<< liftIO (clientWrite crw x)\n\nsendHalfClose :: Rpc req resp ()\nsendHalfClose = do\n crw <- askCrw\n joinReply =<< liftIO (clientSendHalfClose crw)\n\ncloseCall :: Rpc req resp ()\ncloseCall = do\n crw <- askCrw\n liftIO (clientClose crw)\n\ndata RpcReply a\n = RpcOk a\n | RpcError RpcError\n deriving Show\n\ndata RpcError\n = DeadlineExceeded\n | Cancelled\n | Error String\n | CallErrorStatus CallError\n | StatusError StatusCode B.ByteString\n deriving Show\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"C2hs Haskell"}
{"commit":"c101277f70c7f93e7df9008dd9c39770a4563320","subject":"If a call has already ended, don't allow further receiveMessage.","message":"If a call has already ended, don't allow further receiveMessage.\n","repos":"grpc\/grpc-haskell","old_file":"src\/Network\/Grpc\/Core\/Call.chs","new_file":"src\/Network\/Grpc\/Core\/Call.chs","new_contents":"-- Copyright (c) 2016, Google Inc.\n-- All rights reserved.\n--\n-- Redistribution and use in source and binary forms, with or without\n-- modification, are permitted provided that the following conditions are met:\n-- * Redistributions of source code must retain the above copyright\n-- notice, this list of conditions and the following disclaimer.\n-- * Redistributions in binary form must reproduce the above copyright\n-- notice, this list of conditions and the following disclaimer in the\n-- documentation and\/or other materials provided with the distribution.\n-- * Neither the name of Google Inc. nor the\n-- names of its contributors may be used to endorse or promote products\n-- derived from this software without specific prior written permission.\n--\n-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n-- DISCLAIMED. IN NO EVENT SHALL Google Inc. BE LIABLE FOR ANY\n-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n--\n--------------------------------------------------------------------------------\n{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, ExistentialQuantification, RecordWildCards #-}\nmodule Network.Grpc.Core.Call where\n\n\nimport Control.Concurrent\nimport Control.Exception\nimport Control.Monad\n\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Lazy as L\nimport Data.Monoid ((<>), Last(..))\nimport Data.IORef\n\nimport Foreign.C.Types as C\nimport qualified Foreign.Marshal.Alloc as C\nimport qualified Foreign.Marshal.Utils as C\nimport qualified Foreign.Ptr as C\nimport Foreign.Ptr (Ptr)\nimport qualified Foreign.Storable as C\n\n-- transformers\nimport Control.Monad.IO.Class\nimport Control.Monad.Trans.Class\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Reader\n\nimport qualified Network.Grpc.CompletionQueue as CQ\nimport Network.Grpc.Lib.PropagationBits\n{#import Network.Grpc.Lib.ByteBuffer#}\n{#import Network.Grpc.Lib.Metadata#}\n{#import Network.Grpc.Lib.TimeSpec#}\n{#import Network.Grpc.Lib.Core#}\n\n\n#include \n#include \"hs_grpc.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\ndata Deadline\n = AbsoluteDeadline TimeSpec\n | RelativeDeadline Int --seconds\n\ndata ClientContext = ClientContext\n { ccChannel :: Channel\n , ccCQ :: CompletionQueue\n , ccWorker :: CQ.Worker\n }\n\ndata CallOptions = CallOptions\n { coDeadline :: Maybe Deadline\n , coParentContext :: Maybe () -- todo\n , coPropagationMask :: Maybe PropagationMask\n , coMetadata :: [Metadata]\n }\n\ninstance Monoid CallOptions where\n mempty = CallOptions Nothing Nothing Nothing []\n mappend (CallOptions a b c d) (CallOptions a' b' c' d') =\n CallOptions\n (getLast (Last a <> Last a'))\n (getLast (Last b <> Last b'))\n (getLast (Last c <> Last c'))\n (d <> d')\n\nwithAbsoluteDeadline :: TimeSpec -> CallOptions\nwithAbsoluteDeadline deadline =\n mempty { coDeadline = Just (AbsoluteDeadline deadline) }\n\nwithRelativeDeadlineSeconds :: Int -> CallOptions\nwithRelativeDeadlineSeconds seconds =\n mempty { coDeadline = Just (RelativeDeadline seconds) }\n\nwithParentContext :: () -> CallOptions\nwithParentContext ctx =\n mempty { coParentContext = Just ctx }\n\nwithParentContextPropagating :: () -> PropagationMask -> CallOptions\nwithParentContextPropagating ctx prop =\n mempty { coParentContext = Just ctx\n , coPropagationMask = Just prop }\n\nwithMetadata :: [Metadata] -> CallOptions\nwithMetadata md =\n mempty { coMetadata = md }\n\nresolveDeadline :: CallOptions -> IO TimeSpec\nresolveDeadline co =\n case coDeadline co of\n Nothing -> return gprInfFuture\n Just (AbsoluteDeadline deadline) -> return deadline\n Just (RelativeDeadline seconds) ->\n secondsFromNow (fromIntegral seconds)\n\nnewClientContext :: Channel -> IO ClientContext\nnewClientContext chan = do\n cq <- completionQueueCreate reservedPtr\n cqt <- CQ.startCompletionQueueThread cq\n return (ClientContext chan cq cqt)\n\ndestroyClientContext :: ClientContext -> IO ()\ndestroyClientContext (ClientContext _ cq w) = do\n completionQueueShutdown cq\n CQ.waitWorkerTermination w\n\ntype MethodName = B.ByteString\ntype Arg = B.ByteString\n\n-- | Run the IO function once, cache it in the MVar.\nonceMVar :: MVar (Maybe a) -> IO a -> IO a\nonceMVar mvar io = modifyMVar mvar $ \\x ->\n case x of\n Just x' -> return (x, x')\n Nothing -> do\n x' <- io\n return (Just x', x')\n\nreservedPtr :: Ptr ()\nreservedPtr = C.nullPtr\n\ndata UnaryResult a = UnaryResult [Metadata] [Metadata] a deriving Show\n\ncallUnary :: ClientContext -> CallOptions -> MethodName -> Arg -> IO (RpcReply (UnaryResult L.ByteString))\ncallUnary ctx@(ClientContext chan cq _) co method arg = do\n deadline <- resolveDeadline co\n bracket (grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline) grpcCallDestroy $ \\call0 -> newMVar call0 >>= \\mcall -> do\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n recvStatusOp <- opRecvStatusOnClient crw\n recvMessageOp <- opRecvMessage\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX recvInitialMetadataOp\n , OpX recvMessageOp\n , OpX sendMessageOp\n , OpX recvStatusOp\n ]\n case res of\n RpcOk _ -> do\n (RpcStatus trailMD status statusDetails) <- opRead recvStatusOp\n case status of\n StatusOk -> do\n initMD <- opRead recvInitialMetadataOp\n answ <- opRead recvMessageOp\n let answ' = maybe L.empty id answ\n return (RpcOk (UnaryResult initMD trailMD answ'))\n _ -> return (RpcError (StatusError status statusDetails))\n RpcError err -> return (RpcError err)\n\ncallDownstream :: ClientContext -> CallOptions -> MethodName -> Arg -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallDownstream ctx@(ClientContext chan cq _) co method arg = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX sendMessageOp\n ]\n case res of\n RpcOk _ -> do\n res' <- callBatchStatusOnClient crw\n case res' of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n RpcError err -> return (RpcError err)\n\ncallUpstream :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallUpstream ctx@(ClientContext chan cq _) co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> do\n res' <- callBatchStatusOnClient crw\n case res' of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n RpcError err -> return (RpcError err)\n\ncallBidi :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallBidi ctx@(ClientContext chan cq _) co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n\n crw <- newClientReaderWriter ctx mcall\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> do\n res' <- callBatchStatusOnClient crw\n case res' of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n RpcError err -> return (RpcError err)\n\ndata Client req resp = Client\n { clientCrw :: ClientReaderWriter\n , clientEncoder :: Encoder req\n , clientDecoder :: Decoder resp\n }\n\ntype Decoder a = L.ByteString -> IO (RpcReply a)\ntype Encoder a = a -> IO (RpcReply B.ByteString)\n\ndefaultDecoder :: L.ByteString -> IO (RpcReply L.ByteString)\ndefaultDecoder bs = return (RpcOk bs)\n\ndefaultEncoder :: B.ByteString -> IO (RpcReply B.ByteString)\ndefaultEncoder bs = return (RpcOk bs)\n\ndata ClientReaderWriter = ClientReaderWriter {\n context :: ClientContext,\n callMVar_ :: MVar Call,\n initialMDRef :: !(IORef (Maybe [Metadata])),\n trailingMDRef :: !(IORef (Maybe [Metadata])),\n statusFromServer :: !(MVar RpcStatus),\n statusFromServerTag :: !(MVar CQ.EventDesc)\n}\n\nnewClientReaderWriter :: ClientContext -> MVar Call -> IO ClientReaderWriter\nnewClientReaderWriter ctx mcall = do\n initMD <- newIORef Nothing\n trailMD <- newIORef Nothing\n status <- newEmptyMVar\n statusEvent <- newEmptyMVar\n return (ClientReaderWriter ctx mcall initMD trailMD status statusEvent)\n\ndata OpX = forall t. OpX (OpT t)\n\ndata OpArray = OpArray { opArrPtr :: !GrpcOpPtr\n , opArrLen :: !CULong\n , opArrFinishAndFree :: !(IO ())\n }\n\ntoArray :: [OpX] -> IO OpArray\ntoArray ops = do\n aptr <- C.mallocBytes (length ops * {#sizeof grpc_op#})\n let ptrs = iterate (`C.plusPtr` {#sizeof grpc_op#}) aptr\n ops' = concatMap (\\(OpX op) -> opAdd op) ops\n free = C.free aptr >> sequence_ (map (\\(OpX op) -> opFinish op) ops)\n write op p = do\n {#set grpc_op->flags#} p 0\n {#set grpc_op->reserved#} p C.nullPtr\n op p\n zipWithM_ write ops' ptrs\n return $! OpArray aptr (fromIntegral $ length ops) free\n\ncallBatch :: ClientReaderWriter -> [OpX] -> IO (RpcReply ())\ncallBatch crw ops = do\n let ctx = context crw\n arr <- toArray ops\n let onBatchComplete = opArrFinishAndFree arr\n CQ.withEvent (ccWorker ctx) onBatchComplete $ \\eDesc -> do\n callStatus <- withMVar (callMVar_ crw) $ \\call ->\n grpcCallStartBatch call (opArrPtr arr) (opArrLen arr) (CQ.eventTag eDesc) reservedPtr\n case callStatus of\n CallOk -> do\n e <- CQ.interruptibleWaitEvent eDesc\n case e of\n QueueOpComplete OpSuccess _ -> return (RpcOk ())\n QueueOpComplete OpError _ -> return (RpcError (Error \"callBatch: op error\"))\n QueueTimeOut -> return (RpcError DeadlineExceeded)\n QueueShutdown -> return (RpcError (Error \"queue shutdown\"))\n _ -> do\n return (RpcError (CallErrorStatus callStatus))\n\ncallBatchStatusOnClient :: ClientReaderWriter -> IO (RpcReply ())\ncallBatchStatusOnClient crw@ClientReaderWriter{..} = do\n tag <- tryReadMVar statusFromServerTag\n case tag of\n Just _ -> return (RpcOk ()) -- already did this before\n Nothing -> do\n statusOp <- opRecvStatusOnClient crw\n arr <- toArray [ OpX statusOp ]\n let onBatchComplete = opArrFinishAndFree arr\n eDesc <- CQ.allocateEvent (ccWorker context) onBatchComplete\n putMVar statusFromServerTag eDesc\n callStatus <- withMVar callMVar_ $ \\call ->\n grpcCallStartBatch call (opArrPtr arr) (opArrLen arr) (CQ.eventTag eDesc) reservedPtr\n case callStatus of\n CallOk -> return (RpcOk ())\n _ -> return (RpcError (CallErrorStatus callStatus))\n\ndata OpT out = Op\n { opAdd :: [Ptr GrpcOp -> IO ()]\n , opValue :: IORef out\n , opFinish :: IO ()\n }\n\nopRead :: OpT a -> IO a\nopRead op = readIORef (opValue op)\n\nopRecvInitialMetadata :: ClientReaderWriter -> IO (OpT [Metadata])\nopRecvInitialMetadata crw = do\n arr <- mallocMetadataArray\n value <- newIORef (error \"opRecvInitialMetadata never finished\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvInitialMetadata))\n {#set grpc_op->data.recv_initial_metadata#} p arr\n ]\n finish = do\n mds <- readMetadataArray arr\n writeIORef (initialMDRef crw) (Just mds)\n writeIORef value mds\n freeMetadataArray arr\n return (Op add value finish)\n\nopSendMessage :: B.ByteString -> IO (OpT ())\nopSendMessage bs = do\n bb <- fromByteString bs\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendMessage))\n {#set grpc_op->data.send_message#} p bb\n ]\n finish =\n byteBufferDestroy bb\n return (Op add value finish)\n\nopRecvMessage :: IO (OpT (Maybe L.ByteString))\nopRecvMessage = do\n bbptr <- C.malloc :: IO (Ptr (Ptr CByteBuffer))\n value <- newIORef Nothing\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvMessage))\n {#set grpc_op->data.recv_message#} p bbptr\n ]\n finish = do\n bb <- C.peek bbptr\n C.free bbptr\n writeIORef value =<< if bb \/= C.nullPtr\n then do\n lbs <- toLazyByteString bb\n byteBufferDestroy bb\n return (Just lbs)\n else return Nothing\n return (Op add value finish)\n\nopSendInitialMetadata :: [Metadata] -> IO (OpT ())\nopSendInitialMetadata elems = do\n (mdArrPtr, free) <- mallocMetadata elems\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendInitialMetadata))\n {#set grpc_op->data.send_initial_metadata.count#} p (fromIntegral (length elems))\n {#set grpc_op->data.send_initial_metadata.metadata#} p (C.castPtr mdArrPtr)\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.is_set#} p 0\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.level#} p 0\n ]\n finish = do\n free\n return (Op add value finish)\n\ndata RpcStatus = RpcStatus [Metadata] StatusCode B.ByteString\n deriving Show\n\nopRecvStatusOnClient :: ClientReaderWriter -> IO (OpT RpcStatus)\nopRecvStatusOnClient (ClientReaderWriter{..}) = do\n trailingMetadataArrPtr <- mallocMetadataArray\n statusCodePtr <- C.malloc :: IO (Ptr StatusCodeT)\n ptrPtrStatusStr <- C.new C.nullPtr :: IO (Ptr (Ptr CChar))\n capacityPtr <- C.new 0 :: IO (Ptr SizeT)\n value <- newIORef (error \"opRecvStatusOnClient never ran\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvStatusOnClient))\n {#set grpc_op->data.recv_status_on_client.trailing_metadata#} p trailingMetadataArrPtr\n {#set grpc_op->data.recv_status_on_client.status#} p statusCodePtr\n {#set grpc_op->data.recv_status_on_client.status_details#} p ptrPtrStatusStr\n {#set grpc_op->data.recv_status_on_client.status_details_capacity#} p capacityPtr\n ]\n finish = do\n trailingMd <- readMetadataArray trailingMetadataArrPtr\n statusCode <- fmap toStatusCode (C.peek statusCodePtr)\n statusDetails <- B.packCString =<< C.peek ptrPtrStatusStr\n let status = RpcStatus trailingMd statusCode statusDetails\n writeIORef value status\n putMVar statusFromServer status\n free\n free = do\n freeMetadataArray trailingMetadataArrPtr\n C.free statusCodePtr\n C.free ptrPtrStatusStr\n C.free capacityPtr\n return (Op add value finish)\n\nopSendCloseFromClient :: IO (OpT ())\nopSendCloseFromClient = do\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendCloseFromClient))\n ]\n finish =\n return ()\n return (Op add value finish)\n\nclientWaitForInitialMetadata :: ClientReaderWriter -> IO (RpcReply [Metadata])\nclientWaitForInitialMetadata crw@(ClientReaderWriter { .. }) = do\n initMD <- readIORef initialMDRef\n case initMD of\n Just md -> return (RpcOk md)\n Nothing -> do\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n res <- callBatch crw [ OpX recvInitialMetadataOp ]\n case res of\n RpcOk _ -> do\n md <- opRead recvInitialMetadataOp\n writeIORef initialMDRef (Just md)\n return (RpcOk md)\n RpcError err ->\n return (RpcError err)\n\nclientReadInitialMetadata :: ClientReaderWriter -> IO (RpcReply (Maybe [Metadata]))\nclientReadInitialMetadata (ClientReaderWriter {..}) = do\n md <- readIORef initialMDRef\n return (RpcOk md)\n\nclientRead :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nclientRead crw = do\n _ <- clientWaitForInitialMetadata crw\n recvMessage crw\n\nrecvMessage :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nrecvMessage crw = do\n recvMessageOp <- opRecvMessage\n res <- callBatch crw [ OpX recvMessageOp ]\n case res of\n RpcOk _ -> do\n bs <- opRead recvMessageOp\n return (RpcOk bs)\n RpcError err -> do\n putStrLn \"recvMessage: callBatch failed\"\n return (RpcError err)\n\nclientWaitForStatus :: ClientReaderWriter -> IO (RpcReply RpcStatus)\nclientWaitForStatus ClientReaderWriter{..} = do\n status <- readMVar statusFromServer\n return (RpcOk status)\n\nclientClose :: ClientReaderWriter -> IO ()\nclientClose (ClientReaderWriter{..}) = do\n withMVar callMVar_ $ \\call ->\n grpcCallDestroy call\n\nclientWrite :: ClientReaderWriter -> B.ByteString -> IO (RpcReply ())\nclientWrite crw@(ClientReaderWriter{..}) arg = do\n sendMessageOp <- opSendMessage arg\n callBatch crw [ OpX sendMessageOp ]\n\nclientSendHalfClose :: ClientReaderWriter -> IO (RpcReply ())\nclientSendHalfClose crw@(ClientReaderWriter{..}) = do\n sendCloseOp <- opSendCloseFromClient\n callBatch crw [ OpX sendCloseOp ]\n\nclientCloseCall :: ClientReaderWriter -> IO ()\nclientCloseCall ClientReaderWriter{..} = do\n tag <- tryTakeMVar statusFromServerTag\n case tag of\n Nothing -> return ()\n Just eDesc ->\n CQ.releaseEvent (ccWorker context) eDesc\n withMVar callMVar_ $ \\call ->\n grpcCallDestroy call\n\ntype Rpc req resp a = ReaderT (Client req resp) (ExceptT RpcError IO) a\n\naskCrw :: Rpc req resp ClientReaderWriter\naskCrw = asks clientCrw\n\naskDecoder :: Rpc req resp (Decoder resp)\naskDecoder = asks clientDecoder\n\naskEncoder :: Rpc req resp (Encoder req)\naskEncoder = asks clientEncoder\n\njoinReply :: RpcReply a -> Rpc req resp a\njoinReply (RpcOk a) = return a\njoinReply (RpcError err) = lift (throwE err)\n\nwithNewClient :: RpcReply (Client req resp) -> Rpc req resp a -> IO (RpcReply a)\nwithNewClient r_client m = do\n case r_client of\n RpcOk client -> withClient client m\n RpcError err -> return (RpcError err)\n\nwithClient :: Client req resp -> Rpc req resp a -> IO (RpcReply a)\nwithClient client m = do\n e <- runExceptT (runReaderT m client)\n case e of\n Left err -> return (RpcError err)\n Right a -> return (RpcOk a)\n\nclientRWOp :: (ClientReaderWriter -> IO a) -> Rpc req resp a\nclientRWOp act = do\n crw <- askCrw\n liftIO (act crw)\n\njoinClientRWOp :: (ClientReaderWriter -> IO (RpcReply a)) -> Rpc req resp a\njoinClientRWOp act = do\n x <- clientRWOp act\n joinReply x\n\n\nbranchOnStatus :: Rpc req resp a\n -> Rpc req resp a\n -> (StatusCode -> B.ByteString -> Rpc req resp a)\n -> Rpc req resp a\nbranchOnStatus onProcessing onSuccess onFail = do\n status <- clientRWOp (tryReadMVar . statusFromServer)\n case status of\n Nothing -> onProcessing\n Just (RpcStatus _ code msg)\n | code == StatusOk -> onSuccess\n | otherwise -> onFail code msg\n\nabortIfStatus :: Rpc req resp ()\nabortIfStatus =\n branchOnStatus\n (return ())\n (return ())\n (\\code msg -> lift (throwE (StatusError code msg)))\n\ninitialMetadata :: Rpc req resp [Metadata]\ninitialMetadata = do\n status <- clientRWOp (tryReadMVar . statusFromServer)\n case status of\n Nothing -> joinClientRWOp clientWaitForInitialMetadata\n Just (RpcStatus md statusCode statusDetail) -> do\n case statusCode of\n StatusOk -> return md\n _ -> lift (throwE (StatusError statusCode statusDetail))\n\nwaitForStatus :: Rpc req resp RpcStatus\nwaitForStatus = do\n status <- clientRWOp (tryReadMVar . statusFromServer)\n case status of\n Nothing -> joinClientRWOp clientWaitForStatus\n Just status' -> return status'\n\nreceiveMessage :: Rpc req resp (Maybe resp)\nreceiveMessage = do\n let\n onProcessing = do\n msg <- joinClientRWOp clientRead\n case msg of\n Nothing -> return Nothing\n Just x -> do\n decoder <- askDecoder\n liftM Just (joinReply =<< liftIO (decoder x))\n onSuccess = return Nothing\n onFail code msg = lift (throwE (StatusError code msg))\n branchOnStatus onProcessing onSuccess onFail\n\nreceiveAllMessages :: Rpc req resp [resp]\nreceiveAllMessages = do\n decoder <- askDecoder\n let go acc = do\n value <- joinClientRWOp clientRead\n case value of\n Just x -> do\n y <- joinReply =<< (liftIO (decoder x))\n go (y:acc)\n Nothing -> return (reverse acc)\n go []\n\nsendMessage :: req -> Rpc req resp ()\nsendMessage req = do\n abortIfStatus\n encoder <- askEncoder\n bs <- joinReply =<< liftIO (encoder req)\n joinClientRWOp (\\crw -> clientWrite crw bs)\n\nsendHalfClose :: Rpc req resp ()\nsendHalfClose = do\n abortIfStatus\n joinClientRWOp clientSendHalfClose\n\ncloseCall :: Rpc req resp ()\ncloseCall =\n clientRWOp clientClose\n\ndata RpcReply a\n = RpcOk a\n | RpcError RpcError\n deriving Show\n\ndata RpcError\n = DeadlineExceeded\n | Cancelled\n | Error String\n | CallErrorStatus CallError\n | StatusError StatusCode B.ByteString\n deriving Show\n","old_contents":"-- Copyright (c) 2016, Google Inc.\n-- All rights reserved.\n--\n-- Redistribution and use in source and binary forms, with or without\n-- modification, are permitted provided that the following conditions are met:\n-- * Redistributions of source code must retain the above copyright\n-- notice, this list of conditions and the following disclaimer.\n-- * Redistributions in binary form must reproduce the above copyright\n-- notice, this list of conditions and the following disclaimer in the\n-- documentation and\/or other materials provided with the distribution.\n-- * Neither the name of Google Inc. nor the\n-- names of its contributors may be used to endorse or promote products\n-- derived from this software without specific prior written permission.\n--\n-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n-- DISCLAIMED. IN NO EVENT SHALL Google Inc. BE LIABLE FOR ANY\n-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n--\n--------------------------------------------------------------------------------\n{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, ExistentialQuantification, RecordWildCards #-}\nmodule Network.Grpc.Core.Call where\n\n\nimport Control.Concurrent\nimport Control.Exception\nimport Control.Monad\n\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Lazy as L\nimport Data.Monoid ((<>), Last(..))\nimport Data.IORef\n\nimport Foreign.C.Types as C\nimport qualified Foreign.Marshal.Alloc as C\nimport qualified Foreign.Marshal.Utils as C\nimport qualified Foreign.Ptr as C\nimport Foreign.Ptr (Ptr)\nimport qualified Foreign.Storable as C\n\n-- transformers\nimport Control.Monad.IO.Class\nimport Control.Monad.Trans.Class\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Reader\n\nimport qualified Network.Grpc.CompletionQueue as CQ\nimport Network.Grpc.Lib.PropagationBits\n{#import Network.Grpc.Lib.ByteBuffer#}\n{#import Network.Grpc.Lib.Metadata#}\n{#import Network.Grpc.Lib.TimeSpec#}\n{#import Network.Grpc.Lib.Core#}\n\n\n#include \n#include \"hs_grpc.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\ndata Deadline\n = AbsoluteDeadline TimeSpec\n | RelativeDeadline Int --seconds\n\ndata ClientContext = ClientContext\n { ccChannel :: Channel\n , ccCQ :: CompletionQueue\n , ccWorker :: CQ.Worker\n }\n\ndata CallOptions = CallOptions\n { coDeadline :: Maybe Deadline\n , coParentContext :: Maybe () -- todo\n , coPropagationMask :: Maybe PropagationMask\n , coMetadata :: [Metadata]\n }\n\ninstance Monoid CallOptions where\n mempty = CallOptions Nothing Nothing Nothing []\n mappend (CallOptions a b c d) (CallOptions a' b' c' d') =\n CallOptions\n (getLast (Last a <> Last a'))\n (getLast (Last b <> Last b'))\n (getLast (Last c <> Last c'))\n (d <> d')\n\nwithAbsoluteDeadline :: TimeSpec -> CallOptions\nwithAbsoluteDeadline deadline =\n mempty { coDeadline = Just (AbsoluteDeadline deadline) }\n\nwithRelativeDeadlineSeconds :: Int -> CallOptions\nwithRelativeDeadlineSeconds seconds =\n mempty { coDeadline = Just (RelativeDeadline seconds) }\n\nwithParentContext :: () -> CallOptions\nwithParentContext ctx =\n mempty { coParentContext = Just ctx }\n\nwithParentContextPropagating :: () -> PropagationMask -> CallOptions\nwithParentContextPropagating ctx prop =\n mempty { coParentContext = Just ctx\n , coPropagationMask = Just prop }\n\nwithMetadata :: [Metadata] -> CallOptions\nwithMetadata md =\n mempty { coMetadata = md }\n\nresolveDeadline :: CallOptions -> IO TimeSpec\nresolveDeadline co =\n case coDeadline co of\n Nothing -> return gprInfFuture\n Just (AbsoluteDeadline deadline) -> return deadline\n Just (RelativeDeadline seconds) ->\n secondsFromNow (fromIntegral seconds)\n\nnewClientContext :: Channel -> IO ClientContext\nnewClientContext chan = do\n cq <- completionQueueCreate reservedPtr\n cqt <- CQ.startCompletionQueueThread cq\n return (ClientContext chan cq cqt)\n\ndestroyClientContext :: ClientContext -> IO ()\ndestroyClientContext (ClientContext _ cq w) = do\n completionQueueShutdown cq\n CQ.waitWorkerTermination w\n\ntype MethodName = B.ByteString\ntype Arg = B.ByteString\n\n-- | Run the IO function once, cache it in the MVar.\nonceMVar :: MVar (Maybe a) -> IO a -> IO a\nonceMVar mvar io = modifyMVar mvar $ \\x ->\n case x of\n Just x' -> return (x, x')\n Nothing -> do\n x' <- io\n return (Just x', x')\n\nreservedPtr :: Ptr ()\nreservedPtr = C.nullPtr\n\ndata UnaryResult a = UnaryResult [Metadata] [Metadata] a deriving Show\n\ncallUnary :: ClientContext -> CallOptions -> MethodName -> Arg -> IO (RpcReply (UnaryResult L.ByteString))\ncallUnary ctx@(ClientContext chan cq _) co method arg = do\n deadline <- resolveDeadline co\n bracket (grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline) grpcCallDestroy $ \\call0 -> newMVar call0 >>= \\mcall -> do\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n recvStatusOp <- opRecvStatusOnClient crw\n recvMessageOp <- opRecvMessage\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX recvInitialMetadataOp\n , OpX recvMessageOp\n , OpX sendMessageOp\n , OpX recvStatusOp\n ]\n case res of\n RpcOk _ -> do\n (RpcStatus trailMD status statusDetails) <- opRead recvStatusOp\n case status of\n StatusOk -> do\n initMD <- opRead recvInitialMetadataOp\n answ <- opRead recvMessageOp\n let answ' = maybe L.empty id answ\n return (RpcOk (UnaryResult initMD trailMD answ'))\n _ -> return (RpcError (StatusError status statusDetails))\n RpcError err -> return (RpcError err)\n\ncallDownstream :: ClientContext -> CallOptions -> MethodName -> Arg -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallDownstream ctx@(ClientContext chan cq _) co method arg = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX sendMessageOp\n ]\n case res of\n RpcOk _ -> do\n res' <- callBatchStatusOnClient crw\n case res' of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n RpcError err -> return (RpcError err)\n\ncallUpstream :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallUpstream ctx@(ClientContext chan cq _) co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> do\n res' <- callBatchStatusOnClient crw\n case res' of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n RpcError err -> return (RpcError err)\n\ncallBidi :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallBidi ctx@(ClientContext chan cq _) co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n\n crw <- newClientReaderWriter ctx mcall\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> do\n res' <- callBatchStatusOnClient crw\n case res' of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n RpcError err -> return (RpcError err)\n\ndata Client req resp = Client\n { clientCrw :: ClientReaderWriter\n , clientEncoder :: Encoder req\n , clientDecoder :: Decoder resp\n }\n\ntype Decoder a = L.ByteString -> IO (RpcReply a)\ntype Encoder a = a -> IO (RpcReply B.ByteString)\n\ndefaultDecoder :: L.ByteString -> IO (RpcReply L.ByteString)\ndefaultDecoder bs = return (RpcOk bs)\n\ndefaultEncoder :: B.ByteString -> IO (RpcReply B.ByteString)\ndefaultEncoder bs = return (RpcOk bs)\n\ndata ClientReaderWriter = ClientReaderWriter {\n context :: ClientContext,\n callMVar_ :: MVar Call,\n initialMDRef :: !(IORef (Maybe [Metadata])),\n trailingMDRef :: !(IORef (Maybe [Metadata])),\n statusFromServer :: !(MVar RpcStatus),\n statusFromServerTag :: !(MVar CQ.EventDesc)\n}\n\nnewClientReaderWriter :: ClientContext -> MVar Call -> IO ClientReaderWriter\nnewClientReaderWriter ctx mcall = do\n initMD <- newIORef Nothing\n trailMD <- newIORef Nothing\n status <- newEmptyMVar\n statusEvent <- newEmptyMVar\n return (ClientReaderWriter ctx mcall initMD trailMD status statusEvent)\n\ndata OpX = forall t. OpX (OpT t)\n\ndata OpArray = OpArray { opArrPtr :: !GrpcOpPtr\n , opArrLen :: !CULong\n , opArrFinishAndFree :: !(IO ())\n }\n\ntoArray :: [OpX] -> IO OpArray\ntoArray ops = do\n aptr <- C.mallocBytes (length ops * {#sizeof grpc_op#})\n let ptrs = iterate (`C.plusPtr` {#sizeof grpc_op#}) aptr\n ops' = concatMap (\\(OpX op) -> opAdd op) ops\n free = C.free aptr >> sequence_ (map (\\(OpX op) -> opFinish op) ops)\n write op p = do\n {#set grpc_op->flags#} p 0\n {#set grpc_op->reserved#} p C.nullPtr\n op p\n zipWithM_ write ops' ptrs\n return $! OpArray aptr (fromIntegral $ length ops) free\n\ncallBatch :: ClientReaderWriter -> [OpX] -> IO (RpcReply ())\ncallBatch crw ops = do\n let ctx = context crw\n arr <- toArray ops\n let onBatchComplete = opArrFinishAndFree arr\n CQ.withEvent (ccWorker ctx) onBatchComplete $ \\eDesc -> do\n callStatus <- withMVar (callMVar_ crw) $ \\call ->\n grpcCallStartBatch call (opArrPtr arr) (opArrLen arr) (CQ.eventTag eDesc) reservedPtr\n case callStatus of\n CallOk -> do\n e <- CQ.interruptibleWaitEvent eDesc\n case e of\n QueueOpComplete OpSuccess _ -> return (RpcOk ())\n QueueOpComplete OpError _ -> return (RpcError (Error \"callBatch: op error\"))\n QueueTimeOut -> return (RpcError DeadlineExceeded)\n QueueShutdown -> return (RpcError (Error \"queue shutdown\"))\n _ -> do\n return (RpcError (CallErrorStatus callStatus))\n\ncallBatchStatusOnClient :: ClientReaderWriter -> IO (RpcReply ())\ncallBatchStatusOnClient crw@ClientReaderWriter{..} = do\n tag <- tryReadMVar statusFromServerTag\n case tag of\n Just _ -> return (RpcOk ()) -- already did this before\n Nothing -> do\n statusOp <- opRecvStatusOnClient crw\n arr <- toArray [ OpX statusOp ]\n let onBatchComplete = opArrFinishAndFree arr\n eDesc <- CQ.allocateEvent (ccWorker context) onBatchComplete\n putMVar statusFromServerTag eDesc\n callStatus <- withMVar callMVar_ $ \\call ->\n grpcCallStartBatch call (opArrPtr arr) (opArrLen arr) (CQ.eventTag eDesc) reservedPtr\n case callStatus of\n CallOk -> return (RpcOk ())\n _ -> return (RpcError (CallErrorStatus callStatus))\n\ndata OpT out = Op\n { opAdd :: [Ptr GrpcOp -> IO ()]\n , opValue :: IORef out\n , opFinish :: IO ()\n }\n\nopRead :: OpT a -> IO a\nopRead op = readIORef (opValue op)\n\nopRecvInitialMetadata :: ClientReaderWriter -> IO (OpT [Metadata])\nopRecvInitialMetadata crw = do\n arr <- mallocMetadataArray\n value <- newIORef (error \"opRecvInitialMetadata never finished\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvInitialMetadata))\n {#set grpc_op->data.recv_initial_metadata#} p arr\n ]\n finish = do\n mds <- readMetadataArray arr\n writeIORef (initialMDRef crw) (Just mds)\n writeIORef value mds\n freeMetadataArray arr\n return (Op add value finish)\n\nopSendMessage :: B.ByteString -> IO (OpT ())\nopSendMessage bs = do\n bb <- fromByteString bs\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendMessage))\n {#set grpc_op->data.send_message#} p bb\n ]\n finish =\n byteBufferDestroy bb\n return (Op add value finish)\n\nopRecvMessage :: IO (OpT (Maybe L.ByteString))\nopRecvMessage = do\n bbptr <- C.malloc :: IO (Ptr (Ptr CByteBuffer))\n value <- newIORef Nothing\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvMessage))\n {#set grpc_op->data.recv_message#} p bbptr\n ]\n finish = do\n bb <- C.peek bbptr\n C.free bbptr\n writeIORef value =<< if bb \/= C.nullPtr\n then do\n lbs <- toLazyByteString bb\n byteBufferDestroy bb\n return (Just lbs)\n else return Nothing\n return (Op add value finish)\n\nopSendInitialMetadata :: [Metadata] -> IO (OpT ())\nopSendInitialMetadata elems = do\n (mdArrPtr, free) <- mallocMetadata elems\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendInitialMetadata))\n {#set grpc_op->data.send_initial_metadata.count#} p (fromIntegral (length elems))\n {#set grpc_op->data.send_initial_metadata.metadata#} p (C.castPtr mdArrPtr)\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.is_set#} p 0\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.level#} p 0\n ]\n finish = do\n free\n return (Op add value finish)\n\ndata RpcStatus = RpcStatus [Metadata] StatusCode B.ByteString\n deriving Show\n\nopRecvStatusOnClient :: ClientReaderWriter -> IO (OpT RpcStatus)\nopRecvStatusOnClient (ClientReaderWriter{..}) = do\n trailingMetadataArrPtr <- mallocMetadataArray\n statusCodePtr <- C.malloc :: IO (Ptr StatusCodeT)\n ptrPtrStatusStr <- C.new C.nullPtr :: IO (Ptr (Ptr CChar))\n capacityPtr <- C.new 0 :: IO (Ptr SizeT)\n value <- newIORef (error \"opRecvStatusOnClient never ran\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvStatusOnClient))\n {#set grpc_op->data.recv_status_on_client.trailing_metadata#} p trailingMetadataArrPtr\n {#set grpc_op->data.recv_status_on_client.status#} p statusCodePtr\n {#set grpc_op->data.recv_status_on_client.status_details#} p ptrPtrStatusStr\n {#set grpc_op->data.recv_status_on_client.status_details_capacity#} p capacityPtr\n ]\n finish = do\n trailingMd <- readMetadataArray trailingMetadataArrPtr\n statusCode <- fmap toStatusCode (C.peek statusCodePtr)\n statusDetails <- B.packCString =<< C.peek ptrPtrStatusStr\n let status = RpcStatus trailingMd statusCode statusDetails\n writeIORef value status\n putMVar statusFromServer status\n free\n free = do\n freeMetadataArray trailingMetadataArrPtr\n C.free statusCodePtr\n C.free ptrPtrStatusStr\n C.free capacityPtr\n return (Op add value finish)\n\nopSendCloseFromClient :: IO (OpT ())\nopSendCloseFromClient = do\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendCloseFromClient))\n ]\n finish =\n return ()\n return (Op add value finish)\n\nclientWaitForInitialMetadata :: ClientReaderWriter -> IO (RpcReply [Metadata])\nclientWaitForInitialMetadata crw@(ClientReaderWriter { .. }) = do\n initMD <- readIORef initialMDRef\n case initMD of\n Just md -> return (RpcOk md)\n Nothing -> do\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n res <- callBatch crw [ OpX recvInitialMetadataOp ]\n case res of\n RpcOk _ -> do\n md <- opRead recvInitialMetadataOp\n writeIORef initialMDRef (Just md)\n return (RpcOk md)\n RpcError err ->\n return (RpcError err)\n\nclientReadInitialMetadata :: ClientReaderWriter -> IO (RpcReply (Maybe [Metadata]))\nclientReadInitialMetadata (ClientReaderWriter {..}) = do\n md <- readIORef initialMDRef\n return (RpcOk md)\n\nclientRead :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nclientRead crw = do\n _ <- clientWaitForInitialMetadata crw\n recvMessage crw\n\nrecvMessage :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nrecvMessage crw = do\n recvMessageOp <- opRecvMessage\n res <- callBatch crw [ OpX recvMessageOp ]\n case res of\n RpcOk _ -> do\n bs <- opRead recvMessageOp\n return (RpcOk bs)\n RpcError err -> do\n putStrLn \"recvMessage: callBatch failed\"\n return (RpcError err)\n\nclientWaitForStatus :: ClientReaderWriter -> IO (RpcReply RpcStatus)\nclientWaitForStatus ClientReaderWriter{..} = do\n status <- readMVar statusFromServer\n return (RpcOk status)\n\nclientClose :: ClientReaderWriter -> IO ()\nclientClose (ClientReaderWriter{..}) = do\n withMVar callMVar_ $ \\call ->\n grpcCallDestroy call\n\nclientWrite :: ClientReaderWriter -> B.ByteString -> IO (RpcReply ())\nclientWrite crw@(ClientReaderWriter{..}) arg = do\n sendMessageOp <- opSendMessage arg\n callBatch crw [ OpX sendMessageOp ]\n\nclientSendHalfClose :: ClientReaderWriter -> IO (RpcReply ())\nclientSendHalfClose crw@(ClientReaderWriter{..}) = do\n sendCloseOp <- opSendCloseFromClient\n callBatch crw [ OpX sendCloseOp ]\n\nclientCloseCall :: ClientReaderWriter -> IO ()\nclientCloseCall ClientReaderWriter{..} = do\n tag <- tryTakeMVar statusFromServerTag\n case tag of\n Nothing -> return ()\n Just eDesc ->\n CQ.releaseEvent (ccWorker context) eDesc\n withMVar callMVar_ $ \\call ->\n grpcCallDestroy call\n\ntype Rpc req resp a = ReaderT (Client req resp) (ExceptT RpcError IO) a\n\naskCrw :: Rpc req resp ClientReaderWriter\naskCrw = asks clientCrw\n\naskDecoder :: Rpc req resp (Decoder resp)\naskDecoder = asks clientDecoder\n\naskEncoder :: Rpc req resp (Encoder req)\naskEncoder = asks clientEncoder\n\njoinReply :: RpcReply a -> Rpc req resp a\njoinReply (RpcOk a) = return a\njoinReply (RpcError err) = lift (throwE err)\n\nwithNewClient :: RpcReply (Client req resp) -> Rpc req resp a -> IO (RpcReply a)\nwithNewClient r_client m = do\n case r_client of\n RpcOk client -> withClient client m\n RpcError err -> return (RpcError err)\n\nwithClient :: Client req resp -> Rpc req resp a -> IO (RpcReply a)\nwithClient client m = do\n e <- runExceptT (runReaderT m client)\n case e of\n Left err -> return (RpcError err)\n Right a -> return (RpcOk a)\n\nclientRWOp :: (ClientReaderWriter -> IO a) -> Rpc req resp a\nclientRWOp act = do\n crw <- askCrw\n liftIO (act crw)\n\njoinClientRWOp :: (ClientReaderWriter -> IO (RpcReply a)) -> Rpc req resp a\njoinClientRWOp act = do\n x <- clientRWOp act\n joinReply x\n\nabortIfStatus :: Rpc req resp ()\nabortIfStatus = do\n status <- clientRWOp (tryReadMVar . statusFromServer)\n case status of\n Nothing -> return ()\n Just (RpcStatus _ code msg) ->\n -- call has ended. no further batch ops can be executed.\n -- doesn't have to be an error, could be 200!\n lift (throwE (StatusError code msg))\n\ninitialMetadata :: Rpc req resp [Metadata]\ninitialMetadata = do\n status <- clientRWOp (tryReadMVar . statusFromServer)\n case status of\n Nothing -> joinClientRWOp clientWaitForInitialMetadata\n Just (RpcStatus md statusCode statusDetail) -> do\n case statusCode of\n StatusOk -> return md\n _ -> lift (throwE (StatusError statusCode statusDetail))\n\nwaitForStatus :: Rpc req resp RpcStatus\nwaitForStatus = do\n status <- clientRWOp (tryReadMVar . statusFromServer)\n case status of\n Nothing -> joinClientRWOp clientWaitForStatus\n Just status' -> return status'\n\nreceiveMessage :: Rpc req resp (Maybe resp)\nreceiveMessage = do\n abortIfStatus\n msg <- joinClientRWOp clientRead\n case msg of\n Nothing -> return Nothing\n Just x -> do\n decoder <- askDecoder\n liftM Just (joinReply =<< liftIO (decoder x))\n\nreceiveAllMessages :: Rpc req resp [resp]\nreceiveAllMessages = do\n decoder <- askDecoder\n let go acc = do\n value <- joinClientRWOp clientRead\n case value of\n Just x -> do\n y <- joinReply =<< (liftIO (decoder x))\n go (y:acc)\n Nothing -> return (reverse acc)\n go []\n\nsendMessage :: req -> Rpc req resp ()\nsendMessage req = do\n abortIfStatus\n encoder <- askEncoder\n bs <- joinReply =<< liftIO (encoder req)\n joinClientRWOp (\\crw -> clientWrite crw bs)\n\nsendHalfClose :: Rpc req resp ()\nsendHalfClose = do\n abortIfStatus\n joinClientRWOp clientSendHalfClose\n\ncloseCall :: Rpc req resp ()\ncloseCall =\n clientRWOp clientClose\n\ndata RpcReply a\n = RpcOk a\n | RpcError RpcError\n deriving Show\n\ndata RpcError\n = DeadlineExceeded\n | Cancelled\n | Error String\n | CallErrorStatus CallError\n | StatusError StatusCode B.ByteString\n deriving Show\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"C2hs Haskell"}
{"commit":"5994dd15f04621bef9d93b0e3490a417d91e10e1","subject":"Fix documentation and the fileRead function.","message":"Fix documentation and the fileRead function.","repos":"vincenthz\/webkit","old_file":"gio\/System\/GIO\/File\/File.chs","new_file":"gio\/System\/GIO\/File\/File.chs","new_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to gio -*-haskell-*-\n--\n-- Author : Peter Gavin, Andy Stewart\n-- Created: 13-Oct-2008\n--\n-- Copyright (c) 2008 Peter Gavin\n-- Copyright (c) 2010 Andy Stewart\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GIO, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GIO documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.GIO.File.File (\n-- * Details\n--\n-- | GFile is a high level abstraction for manipulating files on a virtual file system. GFiles are\n-- lightweight, immutable objects that do no I\/O upon creation. It is necessary to understand that\n-- GFile objects do not represent files, merely an identifier for a file. All file content I\/O is\n-- implemented as streaming operations (see GInputStream and GOutputStream).\n-- \n-- To construct a GFile, you can use: 'fileNewForPath' if\n-- you have a URI. 'fileNewForCommandlineArg'\n-- from a utf8 string gotten from 'fileGetParseName'.\n-- \n-- One way to think of a GFile is as an abstraction of a pathname. For normal files the system pathname\n-- is what is stored internally, but as GFiles are extensible it could also be something else that\n-- corresponds to a pathname in a userspace implementation of a filesystem.\n-- \n-- GFiles make up hierarchies of directories and files that correspond to the files on a\n-- filesystem. You can move through the file system with GFile using 'fileGetParent' to get an\n-- identifier for the parent directory, 'fileGetChild' to get a child within a directory,\n-- 'fileResolveRelativePath' to resolve a relative path between two GFiles. There can be multiple\n-- hierarchies, so you may not end up at the same root if you repeatedly call 'fileGetParent' on\n-- two different files.\n-- \n-- All GFiles have a basename (get with 'fileGetBasename'. These names are byte strings that are\n-- used to identify the file on the filesystem (relative to its parent directory) and there is no\n-- guarantees that they have any particular charset encoding or even make any sense at all. If you want\n-- to use filenames in a user interface you should use the display name that you can get by requesting\n-- the GFileAttributeStandardDisplayName attribute with 'fileQueryInfo'. This is guaranteed to\n-- be in utf8 and can be used in a user interface. But always store the real basename or the GFile to\n-- use to actually access the file, because there is no way to go from a display name to the actual\n-- name.\n-- \n-- Using GFile as an identifier has the same weaknesses as using a path in that there may be multiple\n-- aliases for the same file. For instance, hard or soft links may cause two different GFiles to refer\n-- to the same file. Other possible causes for aliases are: case insensitive filesystems, short and\n-- long names on Fat\/NTFS, or bind mounts in Linux. If you want to check if two GFiles point to the\n-- same file you can query for the GFileAttributeIdFile attribute. Note that GFile does some\n-- trivial canonicalization of pathnames passed in, so that trivial differences in the path string used\n-- at creation (duplicated slashes, slash at end of path, \".\" or \"..\" path segments, etc) does not\n-- create different GFiles.\n-- \n-- Many GFile operations have both synchronous and asynchronous versions to suit your\n-- application. Asynchronous versions of synchronous functions simply have _async() appended to their\n-- function names. The asynchronous I\/O functions call a GAsyncReadyCallback which is then used to\n-- finalize the operation, producing a GAsyncResult which is then passed to the function's matching\n-- _finish() operation.\n-- \n-- Some GFile operations do not have synchronous analogs, as they may take a very long time to finish,\n-- and blocking may leave an application unusable. Notable cases include: 'fileMountMountable' to\n-- mount a mountable file. 'fileUnmountMountableWithOperation' to unmount a mountable\n-- file. 'fileEjectMountableWithOperation' to eject a mountable file.\n-- \n-- One notable feature of GFiles are entity tags, or \"etags\" for short. Entity tags are somewhat like a\n-- more abstract version of the traditional mtime, and can be used to quickly determine if the file has\n-- been modified from the version on the file system. See the HTTP 1.1 specification for HTTP Etag\n-- headers, which are a very similar concept.\n\n-- * Types.\n FileProgressCallback,\n FileReadMoreCallback,\n FileClass,\n\n-- * Enums\n File(..),\n FileQueryInfoFlags(..),\n FileCreateFlags(..),\n FileCopyFlags(..),\n FileMonitorFlags(..),\n FilesystemPreviewType(..),\n FileType(..),\n\n-- * Methods\n fileFromPath,\n fileFromURI,\n fileFromCommandlineArg,\n fileFromParseName,\n fileEqual,\n fileBasename,\n filePath,\n#if GLIB_CHECK_VERSION(2,24,0)\n fileHasParent,\n#endif\n fileURI,\n fileParseName,\n fileGetChild,\n fileGetChildForDisplayName,\n fileHasPrefix,\n fileGetRelativePath,\n fileResolveRelativePath,\n fileIsNative,\n fileHasURIScheme,\n fileURIScheme,\n fileRead,\n fileReadAsync,\n fileReadFinish,\n fileAppendTo,\n fileCreate,\n fileReplace,\n fileAppendToAsync,\n fileAppendToFinish,\n fileCreateAsync,\n fileCreateFinish,\n fileReplaceAsync,\n fileReplaceFinish,\n fileQueryInfo,\n fileQueryInfoAsync,\n fileQueryInfoFinish,\n fileQueryExists,\n#if GLIB_CHECK_VERSION(2,18,0)\n fileQueryFileType,\n#endif\n fileQueryFilesystemInfo,\n fileQueryFilesystemInfoAsync,\n fileQueryFilesystemInfoFinish,\n fileQueryDefaultHandler,\n fileFindEnclosingMount,\n fileFindEnclosingMountAsync,\n fileFindEnclosingMountFinish,\n fileEnumerateChildren,\n fileEnumerateChildrenAsync,\n fileEnumerateChildrenFinish,\n fileSetDisplayName,\n fileSetDisplayNameAsync,\n fileSetDisplayNameFinish,\n fileDelete,\n fileTrash,\n fileCopy,\n fileCopyAsync,\n fileCopyFinish,\n fileMove,\n fileMakeDirectory,\n#if GLIB_CHECK_VERSION(2,18,0)\n fileMakeDirectoryWithParents,\n#endif\n fileMakeSymbolicLink,\n fileQuerySettableAttributes,\n fileQueryWritableNamespaces\n ) where\n\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport Data.Typeable\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.UTFString\nimport System.Glib.GObject\n\nimport System.GIO.Base\n{#import System.GIO.Types#}\nimport System.GIO.File.FileAttribute\n\n{# context lib = \"gio\" prefix = \"g\" #}\n\n{# enum GFileQueryInfoFlags as FileQueryInfoFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileQueryInfoFlags\n\n{# enum GFileCreateFlags as FileCreateFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCreateFlags\n\n{# enum GFileCopyFlags as FileCopyFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCopyFlags\n\n{# enum GFileMonitorFlags as FileMonitorFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileMonitorFlags\n\n{# enum GFilesystemPreviewType as FilesystemPreviewType {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\n{# enum GFileType as FileType {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\ntype FileProgressCallback = Offset -> Offset -> IO ()\ntype CFileProgressCallback = {# type goffset #} -> {# type goffset #} -> Ptr () -> IO ()\nforeign import ccall \"wrapper\"\n makeFileProgressCallback :: CFileProgressCallback\n -> IO {# type GFileProgressCallback #}\n\nmarshalFileProgressCallback :: FileProgressCallback -> IO {# type GFileProgressCallback #}\nmarshalFileProgressCallback fileProgressCallback =\n makeFileProgressCallback cFileProgressCallback\n where cFileProgressCallback :: CFileProgressCallback\n cFileProgressCallback cCurrentNumBytes cTotalNumBytes _ = do\n fileProgressCallback (fromIntegral cCurrentNumBytes)\n (fromIntegral cTotalNumBytes)\n\ntype FileReadMoreCallback = BS.ByteString -> IO Bool\n\n-- | Constructs a GFile for a given path. This operation never fails, but the returned object might not\n-- support any I\/O operation if path is malformed.\nfileFromPath :: FilePath -> File\nfileFromPath path =\n unsafePerformIO $ withUTFString path $ \\cPath -> {# call file_new_for_path #} cPath >>= takeGObject\n\n-- | Constructs a GFile for a given URI. This operation never fails, but the returned object might not\n-- support any I\/O operation if uri is malformed or if the uri type is not supported.\nfileFromURI :: String -> File\nfileFromURI uri =\n unsafePerformIO $ withUTFString uri $ \\cURI -> {# call file_new_for_uri #} cURI >>= takeGObject\n\n-- | Creates a GFile with the given argument from the command line. The value of arg can be either a URI,\n-- an absolute path or a relative path resolved relative to the current working directory. This\n-- operation never fails, but the returned object might not support any I\/O operation if arg points to\n-- a malformed path.\nfileFromCommandlineArg :: String -> File\nfileFromCommandlineArg arg =\n unsafePerformIO $ withUTFString arg $ \\cArg -> {# call file_new_for_commandline_arg #} cArg >>= takeGObject\n\n-- | Constructs a GFile with the given 'name (i.e. something given by gFileGetParseName'. This\n-- operation never fails, but the returned object might not support any I\/O operation if the @parseName@\n-- cannot be parsed.\nfileFromParseName :: String -> File\nfileFromParseName parseName =\n unsafePerformIO $ withUTFString parseName $ \\cParseName -> {# call file_parse_name #} cParseName >>= takeGObject\n\n-- | Compare two file descriptors for equality. This test is also used to\n-- implement the '(==)' function, that is, comparing two descriptions\n-- will compare their content, not the pointers to the two structures.\n--\nfileEqual :: (FileClass file1, FileClass file2)\n => file1 -> file2 -> Bool\nfileEqual file1 file2 =\n unsafePerformIO $ liftM toBool $ {# call file_equal #} (toFile file1) (toFile file2)\n\ninstance Eq File where\n (==) = fileEqual\n\n-- | Gets the base name (the last component of the path) for a given GFile.\n-- \n-- If called for the top level of a system (such as the filesystem root or a uri like sftp:\/\/host\/) it\n-- will return a single directory separator (and on Windows, possibly a drive letter).\n-- \n-- The base name is a byte string (*not* UTF-8). It has no defined encoding or rules other than it may\n-- not contain zero bytes. If you want to use filenames in a user interface you should use the display\n-- name that you can get by requesting the GFileAttributeStandardDisplayName attribute with\n-- 'fileQueryInfo'.\n-- \n-- This call does no blocking i\/o.\nfileBasename :: FileClass file => file -> String\nfileBasename file =\n unsafePerformIO $ {# call file_get_basename #} (toFile file) >>= readUTFString\n\n-- | Gets the local pathname for GFile, if one exists.\n-- \n-- This call does no blocking i\/o.\nfilePath :: FileClass file => file -> FilePath\nfilePath file =\n unsafePerformIO $ {# call file_get_path #} (toFile file) >>= readUTFString\n\n-- | Gets the URI for the file.\n-- \n-- This call does no blocking i\/o.\nfileURI :: FileClass file => file -> String\nfileURI file =\n unsafePerformIO $ {# call file_get_uri #} (toFile file) >>= readUTFString\n\n-- | Gets the parse name of the file. A parse name is a UTF-8 string that describes the file such that\n-- one can get the GFile back using 'fileParseName'.\n-- \n-- This is generally used to show the GFile as a nice full-pathname kind of string in a user interface,\n-- like in a location entry.\n-- \n-- For local files with names that can safely be converted to UTF8 the pathname is used, otherwise the\n-- IRI is used (a form of URI that allows UTF8 characters unescaped).\n-- \n-- This call does no blocking i\/o.\nfileParseName :: FileClass file => file -> String\nfileParseName file =\n unsafePerformIO $ {# call file_get_parse_name #} (toFile file) >>= readUTFString\n\n-- | Gets the parent directory for the file. If the file represents the root directory of the file\n-- system, then 'Nothing' will be returned.\n-- \n-- This call does no blocking i\/o.\nfileParent :: FileClass file => file -> Maybe File\nfileParent file =\n unsafePerformIO $ {# call file_get_parent #} (toFile file) >>= maybePeek takeGObject\n\n#if GLIB_CHECK_VERSION(2,24,0)\n-- | Checks if file has a parent, and optionally, if it is parent.\n-- \n-- If parent is 'Nothing' then this function returns 'True' if file has any parent at all. If parent is\n-- non-'Nothing' then 'True' is only returned if file is a child of parent.\nfileHasParent :: FileClass file => file -> Maybe File -> Bool \nfileHasParent file parent = \n unsafePerformIO $ liftM toBool $\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject parent $ \\parentPtr ->\n g_file_has_parent cFile parentPtr\n where _ = {#call file_has_parent #}\n#endif\n\n-- | Gets a child of file with basename equal to name.\n-- \n-- Note that the file with that specific name might not exist, but you can still have a GFile that\n-- points to it. You can use this for instance to create that file.\n-- \n-- This call does no blocking i\/o.\nfileGetChild :: FileClass file => file -> String -> File\nfileGetChild file name =\n unsafePerformIO $\n withUTFString name $ \\cName ->\n {# call file_get_child #} (toFile file) cName >>= takeGObject\n\n-- | Gets the child of file for a given 'name (i.e. a UTF8 version of the name)'. If this function\n-- fails, it returns 'Nothing' and error will be set. This is very useful when constructing a GFile for a\n-- new file and the user entered the filename in the user interface, for instance when you select a\n-- directory and type a filename in the file selector.\n-- \n-- This call does no blocking i\/o.\nfileGetChildForDisplayName :: FileClass file => file -> String -> Maybe File\nfileGetChildForDisplayName file displayName =\n unsafePerformIO $\n withUTFString displayName $ \\cDisplayName ->\n propagateGError ({# call file_get_child_for_display_name #} (toFile file) cDisplayName) >>=\n maybePeek takeGObject\n\n-- | Checks whether file has the prefix specified by prefix. In other word, if the names of inital\n-- elements of files pathname match prefix. Only full pathname elements are matched, so a path like\n-- \/foo is not considered a prefix of \/foobar, only of \/ foo\/bar.\n-- \n-- This call does no i\/o, as it works purely on names. As such it can sometimes return 'False' even if\n-- file is inside a prefix (from a filesystem point of view), because the prefix of file is an alias of\n-- prefix.\nfileHasPrefix :: (FileClass file1, FileClass file2) => file1 -> file2 -> Bool\nfileHasPrefix file1 file2 =\n unsafePerformIO $\n liftM toBool $ {# call file_has_prefix #} (toFile file1) (toFile file2)\n\n-- | Gets the path for descendant relative to parent.\n-- \n-- This call does no blocking i\/o.\nfileGetRelativePath :: (FileClass file1, FileClass file2) => file1 -> file2 -> Maybe FilePath\nfileGetRelativePath file1 file2 =\n unsafePerformIO $\n {# call file_get_relative_path #} (toFile file1) (toFile file2) >>=\n maybePeek readUTFString\n\n-- | Resolves a relative path for file to an absolute path.\n-- \n-- This call does no blocking i\/o.\nfileResolveRelativePath :: FileClass file => file -> FilePath -> Maybe File\nfileResolveRelativePath file relativePath =\n unsafePerformIO $\n withUTFString relativePath $ \\cRelativePath ->\n {# call file_resolve_relative_path #} (toFile file) cRelativePath >>=\n maybePeek takeGObject\n\n-- | Checks to see if a file is native to the platform.\n-- \n-- A native file s one expressed in the platform-native filename format, e.g. \\\"C:\\\\Windows\\\" or\n-- \\\"\/usr\/bin\/\\\". This does not mean the file is local, as it might be on a locally mounted remote\n-- filesystem.\n-- \n-- On some systems non-native files may be available using the native filesystem via a userspace\n-- filesystem (FUSE), in these cases this call will return @False@, but 'fileGetPath' will still\n-- return a native path.\n-- \n-- This call does no blocking i\/o.\nfileIsNative :: FileClass file => file -> Bool\nfileIsNative =\n unsafePerformIO .\n liftM toBool . {# call file_is_native #} . toFile\n\n-- | Checks to see if a 'GFile' has a given URI scheme.\n-- \n-- This call does no blocking i\/o.\nfileHasURIScheme :: FileClass file => file -> String -> Bool\nfileHasURIScheme file uriScheme =\n unsafePerformIO $\n withUTFString uriScheme $ \\cURIScheme ->\n liftM toBool $ {# call file_has_uri_scheme #} (toFile file) cURIScheme\n\n-- | Gets the URI scheme for a GFile. RFC 3986 decodes the scheme as:\n-- \n-- URI = scheme \":\" hier-part [ \"?\" query ] [ \"#\" fragment ]\n-- \n-- Common schemes include \"file\", \"http\", \"ftp\", etc.\n-- \n-- This call does no blocking i\/o.\nfileURIScheme :: FileClass file => file -> String\nfileURIScheme file =\n unsafePerformIO $ {# call file_get_uri_scheme #} (toFile file) >>= readUTFString\n\n-- | Opens a file for reading. The result is a GFileInputStream that can be used to read the contents of\n-- the file.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If the file does not exist, the GIoErrorNotFound error will be returned. If the file is a\n-- directory, the GIoErrorIsDirectory error will be returned. Other errors are possible too, and\n-- depend on what kind of filesystem the file is on.\nfileRead :: FileClass file => file -> Maybe Cancellable -> IO FileInputStream\nfileRead file (Just cancellable) = constructNewGObject mkFileInputStream $\n propagateGError $ {# call file_read #} (toFile file) cancellable\n\n-- | Asynchronously opens file for reading.\n-- \n-- For more details, see 'fileRead' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileReadFinish' to\n-- get the result of the operation.\nfileReadAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReadAsync file ioPriority mbCancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject mbCancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_read_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_read_async #}\n\n-- | Finishes an asynchronous file read operation started with 'fileReadAsync'.\nfileReadFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInputStream\nfileReadFinish file asyncResult =\n propagateGError ({# call file_read_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Gets an output stream for appending data to the file. If the file doesn't already exist it is\n-- created.\n-- \n-- By default files created are generally readable by everyone, but if you pass GFileCreatePrivate\n-- in flags the file will be made readable only to the current user, to the level that is supported on\n-- the target filesystem.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- Some file systems don't allow all file names, and may return an GIoErrorInvalidFilename\n-- error. If the file is a directory the GIoErrorIsDirectory error will be returned. Other errors\n-- are possible too, and depend on what kind of filesystem the file is on.\nfileAppendTo :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileAppendTo file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_append_to cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_append_to #}\n\n-- | Creates a new file and returns an output stream for writing to it. The file must not already exist.\n-- \n-- By default files created are generally readable by everyone, but if you pass GFileCreatePrivate\n-- in flags the file will be made readable only to the current user, to the level that is supported on\n-- the target filesystem.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If a file or directory with this name already exists the GIoErrorExists error will be\n-- returned. Some file systems don't allow all file names, and may return an\n-- GIoErrorInvalidFilename error, and if the name is to long GIoErrorFilenameTooLong will be\n-- returned. Other errors are possible too, and depend on what kind of filesystem the file is on.\nfileCreate :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileCreate file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_create cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_create #}\n\n-- | Returns an output stream for overwriting the file, possibly creating a backup copy of the file\n-- first. If the file doesn't exist, it will be created.\n-- \n-- This will try to replace the file in the safest way possible so that any errors during the writing\n-- will not affect an already existing copy of the file. For instance, for local files it may write to\n-- a temporary file and then atomically rename over the destination when the stream is closed.\n-- \n-- By default files created are generally readable by everyone, but if you pass GFileCreatePrivate\n-- in flags the file will be made readable only to the current user, to the level that is supported on\n-- the target filesystem.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If you pass in a non-'Nothing' etag value, then this value is compared to the current entity tag of the\n-- file, and if they differ an GIoErrorWrongEtag error is returned. This generally means that the\n-- file has been changed since you last read it. You can get the new etag from\n-- 'fileOutputStreamGetEtag' after you've finished writing and closed the GFileOutputStream.\n-- When you load a new file you can use 'fileInputStreamQueryInfo' to get the etag of the file.\n-- \n-- If @makeBackup@ is 'True', this function will attempt to make a backup of the current file before\n-- overwriting it. If this fails a GIoErrorCantCreateBackup error will be returned. If you want to\n-- replace anyway, try again with @makeBackup@ set to 'False'.\n-- \n-- If the file is a directory the GIoErrorIsDirectory error will be returned, and if the file is\n-- some other form of non-regular file then a GIoErrorNotRegularFile error will be returned. Some\n-- file systems don't allow all file names, and may return an GIoErrorInvalidFilename error, and if\n-- the name is to long GIoErrorFilenameTooLong will be returned. Other errors are possible too,\n-- and depend on what kind of filesystem the file is on.\nfileReplace :: FileClass file\n => file\n -> Maybe String\n -> Bool\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileReplace file etag makeBackup flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_replace cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_replace #}\n\n-- | Asynchronously opens file for appending.\n-- \n-- For more details, see 'fileAppendTo' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileAppendToFinish'\n-- to get the result of the operation.\nfileAppendToAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileAppendToAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_append_to_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_append_to_async #}\n\n-- | Finishes an asynchronous file append operation started with 'fileAppendToAsync'.\nfileAppendToFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileAppendToFinish file asyncResult =\n propagateGError ({# call file_append_to_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Asynchronously creates a new file and returns an output stream for writing to it. The file must not\n-- already exist.\n-- \n-- For more details, see 'fileCreate' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileCreateFinish' to\n-- get the result of the operation.\nfileCreateAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileCreateAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_create_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_create_async #}\n\n-- | Finishes an asynchronous file create operation started with 'fileCreateAsync'.\nfileCreateFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileCreateFinish file asyncResult =\n propagateGError ({# call file_create_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Asynchronously overwrites the file, replacing the contents, possibly creating a backup copy of the\n-- file first.\n-- \n-- For more details, see 'fileReplace' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileReplaceFinish'\n-- to get the result of the operation.\nfileReplaceAsync :: FileClass file\n => file\n -> String\n -> Bool\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReplaceAsync file etag makeBackup flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_replace_async cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_replace_async #}\n\n-- | Finishes an asynchronous file replace operation started with 'fileReplaceAsync'.\nfileReplaceFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileReplaceFinish file asyncResult =\n propagateGError ({# call file_replace_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Gets the requested information about specified file. The result is a 'GFileInfo' object that contains\n-- key-value attributes (such as the type or size of the file).\n-- \n-- The attribute value is a string that specifies the file attributes that should be gathered. It is\n-- not an error if it's not possible to read a particular requested attribute from a file - it just\n-- won't be set. attribute should be a comma-separated list of attribute or attribute wildcards. The\n-- wildcard \\\"*\\\" means all attributes, and a wildcard like \\\"standard::*\\\" means all attributes in the\n-- standard namespace. An example attribute query be \\\"standard::*,'user'\\\". The standard attributes\n-- are available as defines, like 'GFileAttributeStandardName'.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error 'GIoErrorCancelled' will be\n-- returned.\n-- \n-- For symlinks, normally the information about the target of the symlink is returned, rather than\n-- information about the symlink itself. However if you pass 'GFileQueryInfoNofollowSymlinks' in\n-- flags the information about the symlink itself will be returned. Also, for symlinks that point to\n-- non-existing files the information about the symlink itself will be returned.\n-- \n-- If the file does not exist, the 'GIoErrorNotFound' error will be returned. Other errors are\n-- possible too, and depend on what kind of filesystem the file is on.\nfileQueryInfo :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryInfo file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_info cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_query_info #}\n\n-- | Asynchronously gets the requested information about specified file. The\n-- result is a 'GFileInfo' object that contains key-value attributes (such as\n-- type or size for the file).\n-- \n-- For more details, see 'fileQueryInfo' which is the synchronous version of\n-- this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileQueryInfoFinish' to get the result of the operation.\nfileQueryInfoAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryInfoAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_info_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_info_async #}\n\n-- | Finishes an asynchronous file info query. See 'fileQueryInfoAsync'.\nfileQueryInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryInfoFinish file asyncResult =\n propagateGError ({#call file_query_info_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Utility function to check if a particular file exists. This is implemented using 'fileQueryInfo'\n-- and as such does blocking I\/O.\n-- \n-- Note that in many cases it is racy to first check for file existence and then execute something\n-- based on the outcome of that, because the file might have been created or removed in between the\n-- operations. The general approach to handling that is to not check, but just do the operation and\n-- handle the errors as they come.\n-- \n-- As an example of race-free checking, take the case of reading a file, and if it doesn't exist,\n-- creating it. There are two racy versions: read it, and on error create it; and: check if it exists,\n-- if not create it. These can both result in two processes creating the file (with perhaps a partially\n-- written file as the result). The correct approach is to always try to create the file with\n-- 'fileCreate' which will either atomically create the file or fail with a GIoErrorExists error.\n-- \n-- However, in many cases an existence check is useful in a user interface, for instance to make a menu\n-- item sensitive\/ insensitive, so that you don't have to fool users that something is possible and\n-- then just show and error dialog. If you do this, you should make sure to also handle the errors that\n-- can happen due to races when you execute the operation.\nfileQueryExists :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Bool\nfileQueryExists file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n liftM toBool $ g_file_query_exists cFile cCancellable\n where _ = {# call file_query_exists #}\n\n#if GLIB_CHECK_VERSION(2,18,0)\n-- | Utility function to inspect the GFileType of a file. This is implemented using 'fileQueryInfo'\n-- and as such does blocking I\/O.\n-- \n-- The primary use case of this method is to check if a file is a regular file, directory, or symlink.\nfileQueryFileType :: FileClass file \n => file \n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileType\nfileQueryFileType file flags cancellable = \n liftM (toEnum . fromIntegral) $\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n (g_file_query_file_type cFile (cFromFlags flags) cCancellable)\n where _ = {# call file_query_file_type #}\n#endif\n\n-- | Similar to 'fileQueryInfo', but obtains information about the filesystem the file is on, rather\n-- than the file itself. For instance the amount of space available and the type of the filesystem.\n-- \n-- The attribute value is a string that specifies the file attributes that should be gathered. It is\n-- not an error if it's not possible to read a particular requested attribute from a file - it just\n-- won't be set. attribute should be a comma-separated list of attribute or attribute wildcards. The\n-- wildcard \"*\" means all attributes, and a wildcard like \"fs:*\" means all attributes in the fs\n-- namespace. The standard namespace for filesystem attributes is \"fs\". Common attributes of interest\n-- are 'FILEAttributeFilesystemSize (The Total Size Of The Filesystem In Bytes)',\n-- 'FILEAttributeFilesystemFree (Number Of Bytes Available)', and GFileAttributeFilesystemType\n-- (type of the filesystem).\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If the file does not exist, the GIoErrorNotFound error will be returned. Other errors are\n-- possible too, and depend on what kind of filesystem the file is on.\nfileQueryFilesystemInfo :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryFilesystemInfo file attributes cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_filesystem_info cFile cAttributes cCancellable) >>=\n takeGObject\n where _ = {# call file_query_filesystem_info #}\n\n-- | Asynchronously gets the requested information about the filesystem that the specified file is\n-- on. The result is a GFileInfo object that contains key-value attributes (such as type or size for\n-- the file).\n-- \n-- For more details, see 'fileQueryFilesystemInfo' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileQueryInfoFinish' to get the result of the operation.\nfileQueryFilesystemInfoAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryFilesystemInfoAsync file attributes ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_filesystem_info_async cFile\n cAttributes\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_filesystem_info_async #}\n\n-- | Finishes an asynchronous filesystem info query. See 'fileQueryFilesystemInfoAsync'.\nfileQueryFilesystemInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryFilesystemInfoFinish file asyncResult =\n propagateGError ({# call file_query_filesystem_info_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\n-- | Returns the GAppInfo that is registered as the default application to handle the file specified by\n-- file.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileQueryDefaultHandler :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO AppInfo\nfileQueryDefaultHandler file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_default_handler cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_query_default_handler #}\n\n-- | Gets a GMount for the GFile.\n-- \n-- If the GFileIface for file does not have a mount (e.g. possibly a remote share), error will be set\n-- to GIoErrorNotFound and 'Nothing' will be returned.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileFindEnclosingMount :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Mount\nfileFindEnclosingMount file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_find_enclosing_mount cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_find_enclosing_mount #}\n\n-- | Asynchronously gets the mount for the file.\n-- \n-- For more details, see 'fileFindEnclosingMount' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileFindEnclosingMountFinish' to get the result of the operation.\nfileFindEnclosingMountAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileFindEnclosingMountAsync file ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_find_enclosing_mount_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_find_enclosing_mount_async #}\n\n-- | Finishes an asynchronous find mount request. See 'fileFindEnclosingMountAsync'.\nfileFindEnclosingMountFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Mount\nfileFindEnclosingMountFinish file asyncResult =\n propagateGError ({# call file_find_enclosing_mount_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\n-- | Gets the requested information about the files in a directory. The result is a 'GFileEnumerator'\n-- object that will give out 'GFileInfo' objects for all the files in the directory.\n-- \n-- The attribute value is a string that specifies the file attributes that should be gathered. It is\n-- not an error if it's not possible to read a particular requested attribute from a file - it just\n-- won't be set. attribute should be a comma-separated list of attribute or attribute wildcards. The\n-- wildcard \\\"*\\\" means all attributes, and a wildcard like \\\"standard::*\\\" means all attributes in the\n-- standard namespace. An example attribute query be \\\"standard::*,'user'\\\". The standard attributes\n-- are available as defines, like 'GFileAttributeStandardName'.\n-- \n-- If cancellable is not @Nothing@, then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error 'GIoErrorCancelled' will be\n-- returned.\n-- \n-- If the file does not exist, the 'GIoErrorNotFound' error will be returned. If the file is not a\n-- directory, the 'GFileErrorNotdir' error will be returned. Other errors are possible too.\nfileEnumerateChildren :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileEnumerator\nfileEnumerateChildren file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_enumerate_children cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_enumerate_children #}\n\n-- | Asynchronously gets the requested information about the files in a directory. The result is a\n-- GFileEnumerator object that will give out GFileInfo objects for all the files in the directory.\n-- \n-- For more details, see 'fileEnumerateChildren' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileEnumerateChildrenFinish' to get the result of the operation.\nfileEnumerateChildrenAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileEnumerateChildrenAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_enumerate_children_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_enumerate_children_async #}\n\n-- | Finishes an async enumerate children operation. See 'fileEnumerateChildrenAsync'.\nfileEnumerateChildrenFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileEnumerator\nfileEnumerateChildrenFinish file asyncResult =\n propagateGError ({# call file_enumerate_children_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\n-- | Renames file to the specified display name.\n-- \n-- The display name is converted from UTF8 to the correct encoding for the target filesystem if\n-- possible and the file is renamed to this.\n-- \n-- If you want to implement a rename operation in the user interface the edit name\n-- (GFileAttributeStandardEditName) should be used as the initial value in the rename widget, and\n-- then the result after editing should be passed to 'fileSetDisplayName'.\n-- \n-- On success the resulting converted filename is returned.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileSetDisplayName :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO File\nfileSetDisplayName file displayName cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_set_display_name cFile cDisplayName cCancellable) >>=\n takeGObject\n where _ = {# call file_set_display_name #}\n\n-- | Asynchronously sets the display name for a given GFile.\n-- \n-- For more details, see 'fileSetDisplayName' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileSetDisplayNameFinish' to get the result of the operation.\nfileSetDisplayNameAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileSetDisplayNameAsync file displayName ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_set_display_name_async cFile\n cDisplayName\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_set_display_name_async #}\n\n-- | Finishes setting a display name started with 'fileSetDisplayNameAsync'.\nfileSetDisplayNameFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO File\nfileSetDisplayNameFinish file asyncResult =\n propagateGError ({# call file_set_display_name_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\n-- | Deletes a file. If the file is a directory, it will only be deleted if it is empty.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileDelete :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileDelete file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_delete cFile cCancellable) >> return ()\n where _ = {# call file_delete #}\n\n-- | Sends file to the \"Trashcan\", if possible. This is similar to deleting it, but the user can recover\n-- it before emptying the trashcan. Not all file systems support trashing, so this call can return the\n-- GIoErrorNotSupported error.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileTrash :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileTrash file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_trash cFile cCancellable) >> return ()\n where _ = {# call file_trash #}\n\n-- | Copies the file source to the location specified by destination. Can not handle recursive copies of\n-- directories.\n-- \n-- If the flag GFileCopyOverwrite is specified an already existing destination file is overwritten.\n-- \n-- If the flag GFileCopyNofollowSymlinks is specified then symlinks will be copied as symlinks,\n-- otherwise the target of the source symlink will be copied.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If @progressCallback@ is not 'Nothing', then the operation can be monitored by setting this to a\n-- GFileProgressCallback function. @progressCallbackData@ will be passed to this function. It is\n-- guaranteed that this callback will be called after all data has been transferred with the total\n-- number of bytes copied during the operation.\n-- \n-- If the source file does not exist then the GIoErrorNotFound error is returned, independent on\n-- the status of the destination.\n-- \n-- If GFileCopyOverwrite is not specified and the target exists, then the error GIoErrorExists is\n-- returned.\n-- \n-- If trying to overwrite a file over a directory the GIoErrorIsDirectory error is returned. If\n-- trying to overwrite a directory with a directory the GIoErrorWouldMerge error is returned.\n-- \n-- If the source is a directory and the target does not exist, or GFileCopyOverwrite is specified\n-- and the target is a file, then the GIoErrorWouldRecurse error is returned.\n-- \n-- If you are interested in copying the GFile object itself (not the on-disk file), see 'fileDup'.\nfileCopy :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileCopy source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_copy cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n when (cProgressCallback \/= nullFunPtr) $\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_copy #}\n\n-- | Copies the file source to the location specified by destination asynchronously. For details of the\n-- behaviour, see 'fileCopy'.\n-- \n-- If @progressCallback@ is not 'Nothing', then that function that will be called just like in 'fileCopy',\n-- however the callback will run in the main loop, not in the thread that is doing the I\/O operation.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileCopyFinish' to\n-- get the result of the operation.\nfileCopyAsync :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Int\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> AsyncReadyCallback\n -> IO ()\nfileCopyAsync source destination flags ioPriority cancellable progressCallback callback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n cCallback <- marshalAsyncReadyCallback $ \\sourceObject res -> do\n when (cProgressCallback \/= nullFunPtr) $\n freeHaskellFunPtr cProgressCallback\n callback sourceObject res\n g_file_copy_async cSource\n cDestination\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cProgressCallback\n nullPtr\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_copy_async #}\n\n-- | Finishes copying the file started with 'fileCopyAsync'.\nfileCopyFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Bool\nfileCopyFinish file asyncResult =\n liftM toBool $ propagateGError ({# call file_copy_finish #} (toFile file) asyncResult)\n\n-- | Tries to move the file or directory source to the location specified by destination. If native move\n-- operations are supported then this is used, otherwise a copy + delete fallback is used. The native\n-- implementation may support moving directories (for instance on moves inside the same filesystem),\n-- but the fallback code does not.\n-- \n-- If the flag GFileCopyOverwrite is specified an already existing destination file is overwritten.\n-- \n-- If the flag GFileCopyNofollowSymlinks is specified then symlinks will be copied as symlinks,\n-- otherwise the target of the source symlink will be copied.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If @progressCallback@ is not 'Nothing', then the operation can be monitored by setting this to a\n-- GFileProgressCallback function. @progressCallbackData@ will be passed to this function. It is\n-- guaranteed that this callback will be called after all data has been transferred with the total\n-- number of bytes copied during the operation.\n-- \n-- If the source file does not exist then the GIoErrorNotFound error is returned, independent on\n-- the status of the destination.\n-- \n-- If GFileCopyOverwrite is not specified and the target exists, then the error GIoErrorExists is\n-- returned.\n-- \n-- If trying to overwrite a file over a directory the GIoErrorIsDirectory error is returned. If\n-- trying to overwrite a directory with a directory the GIoErrorWouldMerge error is returned.\n-- \n-- If the source is a directory and the target does not exist, or GFileCopyOverwrite is specified\n-- and the target is a file, then the GIoErrorWouldRecurse error may be returned (if the native\n-- move operation isn't available).\nfileMove :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileMove source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_move cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n when (cProgressCallback \/= nullFunPtr) $\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_move #}\n\n-- | Creates a directory. Note that this will only create a child directory of the immediate parent\n-- directory of the path or URI given by the GFile. To recursively create directories, see\n-- 'fileMakeDirectoryWithParents'. This function will fail if the parent directory does not\n-- exist, setting error to GIoErrorNotFound. If the file system doesn't support creating\n-- directories, this function will fail, setting error to GIoErrorNotSupported.\n-- \n-- For a local GFile the newly created directory will have the default (current) ownership and\n-- permissions of the current process.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileMakeDirectory :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectory file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory cFile cCancellable\n return ()\n where _ = {# call file_make_directory #}\n\n#if GLIB_CHECK_VERSION(2,18,0)\n-- | Creates a directory and any parent directories that may not exist similar to 'mkdir -p'. If the file\n-- system does not support creating directories, this function will fail, setting error to\n-- GIoErrorNotSupported.\n-- \n-- For a local GFile the newly created directories will have the default (current) ownership and\n-- permissions of the current process.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileMakeDirectoryWithParents :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectoryWithParents file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory_with_parents cFile cCancellable\n return ()\n where _ = {# call file_make_directory_with_parents #}\n#endif\n\n-- | Creates a symbolic link.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileMakeSymbolicLink :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO ()\nfileMakeSymbolicLink file symlinkValue cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString symlinkValue $ \\cSymlinkValue ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_symbolic_link cFile cSymlinkValue cCancellable\n return ()\n where _ = {# call file_make_symbolic_link #}\n\n{# pointer *FileAttributeInfoList newtype #}\ntakeFileAttributeInfoList :: Ptr FileAttributeInfoList\n -> IO [FileAttributeInfo]\ntakeFileAttributeInfoList ptr =\n do cInfos <- liftM castPtr $ {# get FileAttributeInfoList->infos #} ptr\n cNInfos <- {# get FileAttributeInfoList->n_infos #} ptr\n infos <- peekArray (fromIntegral cNInfos) cInfos\n g_file_attribute_info_list_unref ptr\n return infos\n where _ = {# call file_attribute_info_list_unref #}\n\n-- | Obtain the list of settable attributes for the file.\n-- \n-- Returns the type and full attribute name of all the attributes that can be set on this file. This\n-- doesn't mean setting it will always succeed though, you might get an access failure, or some\n-- specific file may not support a specific attribute.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileQuerySettableAttributes :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO [FileAttributeInfo]\nfileQuerySettableAttributes file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n ptr <- propagateGError $ g_file_query_settable_attributes cFile cCancellable\n infos <- takeFileAttributeInfoList ptr\n return infos\n where _ = {# call file_query_settable_attributes #}\n\n-- | Obtain the list of attribute namespaces where new attributes can be created by a user. An example of\n-- this is extended attributes (in the \"xattr\" namespace).\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileQueryWritableNamespaces :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO [FileAttributeInfo]\nfileQueryWritableNamespaces file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n ptr <- propagateGError $ g_file_query_writable_namespaces cFile cCancellable\n infos <- takeFileAttributeInfoList ptr\n return infos\n where _ = {# call file_query_writable_namespaces #}\n\n","old_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to gio -*-haskell-*-\n--\n-- Author : Peter Gavin, Andy Stewart\n-- Created: 13-Oct-2008\n--\n-- Copyright (c) 2008 Peter Gavin\n-- Copyright (c) 2010 Andy Stewart\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GIO, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GIO documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.GIO.File.File (\n-- * Details\n--\n-- | GFile is a high level abstraction for manipulating files on a virtual file system. GFiles are\n-- lightweight, immutable objects that do no I\/O upon creation. It is necessary to understand that\n-- GFile objects do not represent files, merely an identifier for a file. All file content I\/O is\n-- implemented as streaming operations (see GInputStream and GOutputStream).\n-- \n-- To construct a GFile, you can use: 'fileNewForPath' if\n-- you have a URI. 'fileNewForCommandlineArg'\n-- from a utf8 string gotten from 'fileGetParseName'.\n-- \n-- One way to think of a GFile is as an abstraction of a pathname. For normal files the system pathname\n-- is what is stored internally, but as GFiles are extensible it could also be something else that\n-- corresponds to a pathname in a userspace implementation of a filesystem.\n-- \n-- GFiles make up hierarchies of directories and files that correspond to the files on a\n-- filesystem. You can move through the file system with GFile using 'fileGetParent' to get an\n-- identifier for the parent directory, 'fileGetChild' to get a child within a directory,\n-- 'fileResolveRelativePath' to resolve a relative path between two GFiles. There can be multiple\n-- hierarchies, so you may not end up at the same root if you repeatedly call 'fileGetParent' on\n-- two different files.\n-- \n-- All GFiles have a basename (get with 'fileGetBasename'. These names are byte strings that are\n-- used to identify the file on the filesystem (relative to its parent directory) and there is no\n-- guarantees that they have any particular charset encoding or even make any sense at all. If you want\n-- to use filenames in a user interface you should use the display name that you can get by requesting\n-- the GFileAttributeStandardDisplayName attribute with 'fileQueryInfo'. This is guaranteed to\n-- be in utf8 and can be used in a user interface. But always store the real basename or the GFile to\n-- use to actually access the file, because there is no way to go from a display name to the actual\n-- name.\n-- \n-- Using GFile as an identifier has the same weaknesses as using a path in that there may be multiple\n-- aliases for the same file. For instance, hard or soft links may cause two different GFiles to refer\n-- to the same file. Other possible causes for aliases are: case insensitive filesystems, short and\n-- long names on Fat\/NTFS, or bind mounts in Linux. If you want to check if two GFiles point to the\n-- same file you can query for the GFileAttributeIdFile attribute. Note that GFile does some\n-- trivial canonicalization of pathnames passed in, so that trivial differences in the path string used\n-- at creation (duplicated slashes, slash at end of path, \".\" or \"..\" path segments, etc) does not\n-- create different GFiles.\n-- \n-- Many GFile operations have both synchronous and asynchronous versions to suit your\n-- application. Asynchronous versions of synchronous functions simply have _async() appended to their\n-- function names. The asynchronous I\/O functions call a GAsyncReadyCallback which is then used to\n-- finalize the operation, producing a GAsyncResult which is then passed to the function's matching\n-- _finish() operation.\n-- \n-- Some GFile operations do not have synchronous analogs, as they may take a very long time to finish,\n-- and blocking may leave an application unusable. Notable cases include: 'fileMountMountable' to\n-- mount a mountable file. 'fileUnmountMountableWithOperation' to unmount a mountable\n-- file. 'fileEjectMountableWithOperation' to eject a mountable file.\n-- \n-- One notable feature of GFiles are entity tags, or \"etags\" for short. Entity tags are somewhat like a\n-- more abstract version of the traditional mtime, and can be used to quickly determine if the file has\n-- been modified from the version on the file system. See the HTTP 1.1 specification for HTTP Etag\n-- headers, which are a very similar concept.\n\n-- * Types.\n FileProgressCallback,\n FileReadMoreCallback,\n FileClass,\n\n-- * Enums\n File(..),\n FileQueryInfoFlags(..),\n FileCreateFlags(..),\n FileCopyFlags(..),\n FileMonitorFlags(..),\n FilesystemPreviewType(..),\n FileType(..),\n\n-- * Methods\n fileFromPath,\n fileFromURI,\n fileFromCommandlineArg,\n fileFromParseName,\n fileEqual,\n fileBasename,\n filePath,\n#if GLIB_CHECK_VERSION(2,24,0)\n fileHasParent,\n#endif\n fileURI,\n fileParseName,\n fileGetChild,\n fileGetChildForDisplayName,\n fileHasPrefix,\n fileGetRelativePath,\n fileResolveRelativePath,\n fileIsNative,\n fileHasURIScheme,\n fileURIScheme,\n fileRead,\n fileReadAsync,\n fileReadFinish,\n fileAppendTo,\n fileCreate,\n fileReplace,\n fileAppendToAsync,\n fileAppendToFinish,\n fileCreateAsync,\n fileCreateFinish,\n fileReplaceAsync,\n fileReplaceFinish,\n fileQueryInfo,\n fileQueryInfoAsync,\n fileQueryInfoFinish,\n fileQueryExists,\n#if GLIB_CHECK_VERSION(2,18,0)\n fileQueryFileType,\n#endif\n fileQueryFilesystemInfo,\n fileQueryFilesystemInfoAsync,\n fileQueryFilesystemInfoFinish,\n fileQueryDefaultHandler,\n fileFindEnclosingMount,\n fileFindEnclosingMountAsync,\n fileFindEnclosingMountFinish,\n fileEnumerateChildren,\n fileEnumerateChildrenAsync,\n fileEnumerateChildrenFinish,\n fileSetDisplayName,\n fileSetDisplayNameAsync,\n fileSetDisplayNameFinish,\n fileDelete,\n fileTrash,\n fileCopy,\n fileCopyAsync,\n fileCopyFinish,\n fileMove,\n fileMakeDirectory,\n#if GLIB_CHECK_VERSION(2,18,0)\n fileMakeDirectoryWithParents,\n#endif\n fileMakeSymbolicLink,\n fileQuerySettableAttributes,\n fileQueryWritableNamespaces\n ) where\n\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport Data.Typeable\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.UTFString\nimport System.Glib.GObject\n\nimport System.GIO.Base\n{#import System.GIO.Types#}\nimport System.GIO.File.FileAttribute\n\n{# context lib = \"gio\" prefix = \"g\" #}\n\n{# enum GFileQueryInfoFlags as FileQueryInfoFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileQueryInfoFlags\n\n{# enum GFileCreateFlags as FileCreateFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCreateFlags\n\n{# enum GFileCopyFlags as FileCopyFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCopyFlags\n\n{# enum GFileMonitorFlags as FileMonitorFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileMonitorFlags\n\n{# enum GFilesystemPreviewType as FilesystemPreviewType {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\n{# enum GFileType as FileType {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\ntype FileProgressCallback = Offset -> Offset -> IO ()\ntype CFileProgressCallback = {# type goffset #} -> {# type goffset #} -> Ptr () -> IO ()\nforeign import ccall \"wrapper\"\n makeFileProgressCallback :: CFileProgressCallback\n -> IO {# type GFileProgressCallback #}\n\nmarshalFileProgressCallback :: FileProgressCallback -> IO {# type GFileProgressCallback #}\nmarshalFileProgressCallback fileProgressCallback =\n makeFileProgressCallback cFileProgressCallback\n where cFileProgressCallback :: CFileProgressCallback\n cFileProgressCallback cCurrentNumBytes cTotalNumBytes _ = do\n fileProgressCallback (fromIntegral cCurrentNumBytes)\n (fromIntegral cTotalNumBytes)\n\ntype FileReadMoreCallback = BS.ByteString -> IO Bool\n\n-- | Constructs a GFile for a given path. This operation never fails, but the returned object might not\n-- support any I\/O operation if path is malformed.\nfileFromPath :: FilePath -> File\nfileFromPath path =\n unsafePerformIO $ withUTFString path $ \\cPath -> {# call file_new_for_path #} cPath >>= takeGObject\n\n-- | Constructs a GFile for a given URI. This operation never fails, but the returned object might not\n-- support any I\/O operation if uri is malformed or if the uri type is not supported.\nfileFromURI :: String -> File\nfileFromURI uri =\n unsafePerformIO $ withUTFString uri $ \\cURI -> {# call file_new_for_uri #} cURI >>= takeGObject\n\n-- | Creates a GFile with the given argument from the command line. The value of arg can be either a URI,\n-- an absolute path or a relative path resolved relative to the current working directory. This\n-- operation never fails, but the returned object might not support any I\/O operation if arg points to\n-- a malformed path.\nfileFromCommandlineArg :: String -> File\nfileFromCommandlineArg arg =\n unsafePerformIO $ withUTFString arg $ \\cArg -> {# call file_new_for_commandline_arg #} cArg >>= takeGObject\n\n-- | Constructs a GFile with the given 'name (i.e. something given by gFileGetParseName'. This\n-- operation never fails, but the returned object might not support any I\/O operation if the @parseName@\n-- cannot be parsed.\nfileFromParseName :: String -> File\nfileFromParseName parseName =\n unsafePerformIO $ withUTFString parseName $ \\cParseName -> {# call file_parse_name #} cParseName >>= takeGObject\n\n-- | Compare two file descriptors for equality. This test is also used to\n-- implement the '(==)' function, that is, comparing two descriptions\n-- will compare their content, not the pointers to the two structures.\n--\nfileEqual :: (FileClass file1, FileClass file2)\n => file1 -> file2 -> Bool\nfileEqual file1 file2 =\n unsafePerformIO $ liftM toBool $ {# call file_equal #} (toFile file1) (toFile file2)\n\ninstance Eq File where\n (==) = fileEqual\n\n-- | Gets the base name (the last component of the path) for a given GFile.\n-- \n-- If called for the top level of a system (such as the filesystem root or a uri like sftp:\/\/host\/) it\n-- will return a single directory separator (and on Windows, possibly a drive letter).\n-- \n-- The base name is a byte string (*not* UTF-8). It has no defined encoding or rules other than it may\n-- not contain zero bytes. If you want to use filenames in a user interface you should use the display\n-- name that you can get by requesting the GFileAttributeStandardDisplayName attribute with\n-- 'fileQueryInfo'.\n-- \n-- This call does no blocking i\/o.\nfileBasename :: FileClass file => file -> String\nfileBasename file =\n unsafePerformIO $ {# call file_get_basename #} (toFile file) >>= readUTFString\n\n-- | Gets the local pathname for GFile, if one exists.\n-- \n-- This call does no blocking i\/o.\nfilePath :: FileClass file => file -> FilePath\nfilePath file =\n unsafePerformIO $ {# call file_get_path #} (toFile file) >>= readUTFString\n\n-- | Gets the URI for the file.\n-- \n-- This call does no blocking i\/o.\nfileURI :: FileClass file => file -> String\nfileURI file =\n unsafePerformIO $ {# call file_get_uri #} (toFile file) >>= readUTFString\n\n-- | Gets the parse name of the file. A parse name is a UTF-8 string that describes the file such that\n-- one can get the GFile back using 'fileParseName'.\n-- \n-- This is generally used to show the GFile as a nice full-pathname kind of string in a user interface,\n-- like in a location entry.\n-- \n-- For local files with names that can safely be converted to UTF8 the pathname is used, otherwise the\n-- IRI is used (a form of URI that allows UTF8 characters unescaped).\n-- \n-- This call does no blocking i\/o.\nfileParseName :: FileClass file => file -> String\nfileParseName file =\n unsafePerformIO $ {# call file_get_parse_name #} (toFile file) >>= readUTFString\n\n-- | Gets the parent directory for the file. If the file represents the root directory of the file\n-- system, then 'Nothing' will be returned.\n-- \n-- This call does no blocking i\/o.\nfileParent :: FileClass file => file -> Maybe File\nfileParent file =\n unsafePerformIO $ {# call file_get_parent #} (toFile file) >>= maybePeek takeGObject\n\n#if GLIB_CHECK_VERSION(2,24,0)\n-- | Checks if file has a parent, and optionally, if it is parent.\n-- \n-- If parent is 'Nothing' then this function returns 'True' if file has any parent at all. If parent is\n-- non-'Nothing' then 'True' is only returned if file is a child of parent.\nfileHasParent :: FileClass file => file -> Maybe File -> Bool \nfileHasParent file parent = \n unsafePerformIO $ liftM toBool $\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject parent $ \\parentPtr ->\n g_file_has_parent cFile parentPtr\n where _ = {#call file_has_parent #}\n#endif\n\n-- | Gets a child of file with basename equal to name.\n-- \n-- Note that the file with that specific name might not exist, but you can still have a GFile that\n-- points to it. You can use this for instance to create that file.\n-- \n-- This call does no blocking i\/o.\nfileGetChild :: FileClass file => file -> String -> File\nfileGetChild file name =\n unsafePerformIO $\n withUTFString name $ \\cName ->\n {# call file_get_child #} (toFile file) cName >>= takeGObject\n\n-- | Gets the child of file for a given 'name (i.e. a UTF8 version of the name)'. If this function\n-- fails, it returns 'Nothing' and error will be set. This is very useful when constructing a GFile for a\n-- new file and the user entered the filename in the user interface, for instance when you select a\n-- directory and type a filename in the file selector.\n-- \n-- This call does no blocking i\/o.\nfileGetChildForDisplayName :: FileClass file => file -> String -> Maybe File\nfileGetChildForDisplayName file displayName =\n unsafePerformIO $\n withUTFString displayName $ \\cDisplayName ->\n propagateGError ({# call file_get_child_for_display_name #} (toFile file) cDisplayName) >>=\n maybePeek takeGObject\n\n-- | Checks whether file has the prefix specified by prefix. In other word, if the names of inital\n-- elements of files pathname match prefix. Only full pathname elements are matched, so a path like\n-- \/foo is not considered a prefix of \/foobar, only of \/ foo\/bar.\n-- \n-- This call does no i\/o, as it works purely on names. As such it can sometimes return 'False' even if\n-- file is inside a prefix (from a filesystem point of view), because the prefix of file is an alias of\n-- prefix.\nfileHasPrefix :: (FileClass file1, FileClass file2) => file1 -> file2 -> Bool\nfileHasPrefix file1 file2 =\n unsafePerformIO $\n liftM toBool $ {# call file_has_prefix #} (toFile file1) (toFile file2)\n\n-- | Gets the path for descendant relative to parent.\n-- \n-- This call does no blocking i\/o.\nfileGetRelativePath :: (FileClass file1, FileClass file2) => file1 -> file2 -> Maybe FilePath\nfileGetRelativePath file1 file2 =\n unsafePerformIO $\n {# call file_get_relative_path #} (toFile file1) (toFile file2) >>=\n maybePeek readUTFString\n\n-- | Resolves a relative path for file to an absolute path.\n-- \n-- This call does no blocking i\/o.\nfileResolveRelativePath :: FileClass file => file -> FilePath -> Maybe File\nfileResolveRelativePath file relativePath =\n unsafePerformIO $\n withUTFString relativePath $ \\cRelativePath ->\n {# call file_resolve_relative_path #} (toFile file) cRelativePath >>=\n maybePeek takeGObject\n\n-- | Checks to see if a file is native to the platform.\n-- \n-- A native file s one expressed in the platform-native filename format, e.g. \"C:\\Windows\" or\n-- \"\/usr\/bin\/\". This does not mean the file is local, as it might be on a locally mounted remote\n-- filesystem.\n-- \n-- On some systems non-native files may be available using the native filesystem via a userspace\n-- filesystem (FUSE), in these cases this call will return 'False', but 'fileGetPath' will still\n-- return a native path.\n-- \n-- This call does no blocking i\/o.\nfileIsNative :: FileClass file => file -> Bool\nfileIsNative =\n unsafePerformIO .\n liftM toBool . {# call file_is_native #} . toFile\n\n-- | Checks to see if a GFile has a given URI scheme.\n-- \n-- This call does no blocking i\/o.\nfileHasURIScheme :: FileClass file => file -> String -> Bool\nfileHasURIScheme file uriScheme =\n unsafePerformIO $\n withUTFString uriScheme $ \\cURIScheme ->\n liftM toBool $ {# call file_has_uri_scheme #} (toFile file) cURIScheme\n\n-- | Gets the URI scheme for a GFile. RFC 3986 decodes the scheme as:\n-- \n-- URI = scheme \":\" hier-part [ \"?\" query ] [ \"#\" fragment ]\n-- \n-- Common schemes include \"file\", \"http\", \"ftp\", etc.\n-- \n-- This call does no blocking i\/o.\nfileURIScheme :: FileClass file => file -> String\nfileURIScheme file =\n unsafePerformIO $ {# call file_get_uri_scheme #} (toFile file) >>= readUTFString\n\n-- | Opens a file for reading. The result is a GFileInputStream that can be used to read the contents of\n-- the file.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If the file does not exist, the GIoErrorNotFound error will be returned. If the file is a\n-- directory, the GIoErrorIsDirectory error will be returned. Other errors are possible too, and\n-- depend on what kind of filesystem the file is on.\nfileRead :: FileClass file => file -> Maybe Cancellable -> IO FileInputStream\nfileRead file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_read cFile cCancellable) >>= takeGObject\n where _ = {# call file_read #}\n\n-- | Asynchronously opens file for reading.\n-- \n-- For more details, see 'fileRead' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileReadFinish' to\n-- get the result of the operation.\nfileReadAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReadAsync file ioPriority mbCancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject mbCancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_read_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_read_async #}\n\n-- | Finishes an asynchronous file read operation started with 'fileReadAsync'.\nfileReadFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInputStream\nfileReadFinish file asyncResult =\n propagateGError ({# call file_read_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Gets an output stream for appending data to the file. If the file doesn't already exist it is\n-- created.\n-- \n-- By default files created are generally readable by everyone, but if you pass GFileCreatePrivate\n-- in flags the file will be made readable only to the current user, to the level that is supported on\n-- the target filesystem.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- Some file systems don't allow all file names, and may return an GIoErrorInvalidFilename\n-- error. If the file is a directory the GIoErrorIsDirectory error will be returned. Other errors\n-- are possible too, and depend on what kind of filesystem the file is on.\nfileAppendTo :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileAppendTo file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_append_to cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_append_to #}\n\n-- | Creates a new file and returns an output stream for writing to it. The file must not already exist.\n-- \n-- By default files created are generally readable by everyone, but if you pass GFileCreatePrivate\n-- in flags the file will be made readable only to the current user, to the level that is supported on\n-- the target filesystem.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If a file or directory with this name already exists the GIoErrorExists error will be\n-- returned. Some file systems don't allow all file names, and may return an\n-- GIoErrorInvalidFilename error, and if the name is to long GIoErrorFilenameTooLong will be\n-- returned. Other errors are possible too, and depend on what kind of filesystem the file is on.\nfileCreate :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileCreate file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_create cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_create #}\n\n-- | Returns an output stream for overwriting the file, possibly creating a backup copy of the file\n-- first. If the file doesn't exist, it will be created.\n-- \n-- This will try to replace the file in the safest way possible so that any errors during the writing\n-- will not affect an already existing copy of the file. For instance, for local files it may write to\n-- a temporary file and then atomically rename over the destination when the stream is closed.\n-- \n-- By default files created are generally readable by everyone, but if you pass GFileCreatePrivate\n-- in flags the file will be made readable only to the current user, to the level that is supported on\n-- the target filesystem.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If you pass in a non-'Nothing' etag value, then this value is compared to the current entity tag of the\n-- file, and if they differ an GIoErrorWrongEtag error is returned. This generally means that the\n-- file has been changed since you last read it. You can get the new etag from\n-- 'fileOutputStreamGetEtag' after you've finished writing and closed the GFileOutputStream.\n-- When you load a new file you can use 'fileInputStreamQueryInfo' to get the etag of the file.\n-- \n-- If @makeBackup@ is 'True', this function will attempt to make a backup of the current file before\n-- overwriting it. If this fails a GIoErrorCantCreateBackup error will be returned. If you want to\n-- replace anyway, try again with @makeBackup@ set to 'False'.\n-- \n-- If the file is a directory the GIoErrorIsDirectory error will be returned, and if the file is\n-- some other form of non-regular file then a GIoErrorNotRegularFile error will be returned. Some\n-- file systems don't allow all file names, and may return an GIoErrorInvalidFilename error, and if\n-- the name is to long GIoErrorFilenameTooLong will be returned. Other errors are possible too,\n-- and depend on what kind of filesystem the file is on.\nfileReplace :: FileClass file\n => file\n -> Maybe String\n -> Bool\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileReplace file etag makeBackup flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_replace cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_replace #}\n\n-- | Asynchronously opens file for appending.\n-- \n-- For more details, see 'fileAppendTo' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileAppendToFinish'\n-- to get the result of the operation.\nfileAppendToAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileAppendToAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_append_to_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_append_to_async #}\n\n-- | Finishes an asynchronous file append operation started with 'fileAppendToAsync'.\nfileAppendToFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileAppendToFinish file asyncResult =\n propagateGError ({# call file_append_to_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Asynchronously creates a new file and returns an output stream for writing to it. The file must not\n-- already exist.\n-- \n-- For more details, see 'fileCreate' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileCreateFinish' to\n-- get the result of the operation.\nfileCreateAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileCreateAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_create_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_create_async #}\n\n-- | Finishes an asynchronous file create operation started with 'fileCreateAsync'.\nfileCreateFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileCreateFinish file asyncResult =\n propagateGError ({# call file_create_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Asynchronously overwrites the file, replacing the contents, possibly creating a backup copy of the\n-- file first.\n-- \n-- For more details, see 'fileReplace' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileReplaceFinish'\n-- to get the result of the operation.\nfileReplaceAsync :: FileClass file\n => file\n -> String\n -> Bool\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReplaceAsync file etag makeBackup flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_replace_async cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_replace_async #}\n\n-- | Finishes an asynchronous file replace operation started with 'fileReplaceAsync'.\nfileReplaceFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileReplaceFinish file asyncResult =\n propagateGError ({# call file_replace_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Gets the requested information about specified file. The result is a GFileInfo object that contains\n-- key-value attributes (such as the type or size of the file).\n-- \n-- The attribute value is a string that specifies the file attributes that should be gathered. It is\n-- not an error if it's not possible to read a particular requested attribute from a file - it just\n-- won't be set. attribute should be a comma-separated list of attribute or attribute wildcards. The\n-- wildcard \"*\" means all attributes, and a wildcard like \"standard::*\" means all attributes in the\n-- standard namespace. An example attribute query be \"standard::*,'user'\". The standard attributes\n-- are available as defines, like GFileAttributeStandardName.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- For symlinks, normally the information about the target of the symlink is returned, rather than\n-- information about the symlink itself. However if you pass GFileQueryInfoNofollowSymlinks in\n-- flags the information about the symlink itself will be returned. Also, for symlinks that point to\n-- non-existing files the information about the symlink itself will be returned.\n-- \n-- If the file does not exist, the GIoErrorNotFound error will be returned. Other errors are\n-- possible too, and depend on what kind of filesystem the file is on.\nfileQueryInfo :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryInfo file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_info cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_query_info #}\n\n-- | Asynchronously gets the requested information about specified file. The result is a GFileInfo object\n-- that contains key-value attributes (such as type or size for the file).\n-- \n-- For more details, see 'fileQueryInfo' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileQueryInfoFinish' to get the result of the operation.\nfileQueryInfoAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryInfoAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_info_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_info_async #}\n\n-- | Finishes an asynchronous file info query. See 'fileQueryInfoAsync'.\nfileQueryInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryInfoFinish file asyncResult =\n propagateGError ({#call file_query_info_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Utility function to check if a particular file exists. This is implemented using 'fileQueryInfo'\n-- and as such does blocking I\/O.\n-- \n-- Note that in many cases it is racy to first check for file existence and then execute something\n-- based on the outcome of that, because the file might have been created or removed in between the\n-- operations. The general approach to handling that is to not check, but just do the operation and\n-- handle the errors as they come.\n-- \n-- As an example of race-free checking, take the case of reading a file, and if it doesn't exist,\n-- creating it. There are two racy versions: read it, and on error create it; and: check if it exists,\n-- if not create it. These can both result in two processes creating the file (with perhaps a partially\n-- written file as the result). The correct approach is to always try to create the file with\n-- 'fileCreate' which will either atomically create the file or fail with a GIoErrorExists error.\n-- \n-- However, in many cases an existence check is useful in a user interface, for instance to make a menu\n-- item sensitive\/ insensitive, so that you don't have to fool users that something is possible and\n-- then just show and error dialog. If you do this, you should make sure to also handle the errors that\n-- can happen due to races when you execute the operation.\nfileQueryExists :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Bool\nfileQueryExists file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n liftM toBool $ g_file_query_exists cFile cCancellable\n where _ = {# call file_query_exists #}\n\n#if GLIB_CHECK_VERSION(2,18,0)\n-- | Utility function to inspect the GFileType of a file. This is implemented using 'fileQueryInfo'\n-- and as such does blocking I\/O.\n-- \n-- The primary use case of this method is to check if a file is a regular file, directory, or symlink.\nfileQueryFileType :: FileClass file \n => file \n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileType\nfileQueryFileType file flags cancellable = \n liftM (toEnum . fromIntegral) $\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n (g_file_query_file_type cFile (cFromFlags flags) cCancellable)\n where _ = {# call file_query_file_type #}\n#endif\n\n-- | Similar to 'fileQueryInfo', but obtains information about the filesystem the file is on, rather\n-- than the file itself. For instance the amount of space available and the type of the filesystem.\n-- \n-- The attribute value is a string that specifies the file attributes that should be gathered. It is\n-- not an error if it's not possible to read a particular requested attribute from a file - it just\n-- won't be set. attribute should be a comma-separated list of attribute or attribute wildcards. The\n-- wildcard \"*\" means all attributes, and a wildcard like \"fs:*\" means all attributes in the fs\n-- namespace. The standard namespace for filesystem attributes is \"fs\". Common attributes of interest\n-- are 'FILEAttributeFilesystemSize (The Total Size Of The Filesystem In Bytes)',\n-- 'FILEAttributeFilesystemFree (Number Of Bytes Available)', and GFileAttributeFilesystemType\n-- (type of the filesystem).\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If the file does not exist, the GIoErrorNotFound error will be returned. Other errors are\n-- possible too, and depend on what kind of filesystem the file is on.\nfileQueryFilesystemInfo :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryFilesystemInfo file attributes cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_filesystem_info cFile cAttributes cCancellable) >>=\n takeGObject\n where _ = {# call file_query_filesystem_info #}\n\n-- | Asynchronously gets the requested information about the filesystem that the specified file is\n-- on. The result is a GFileInfo object that contains key-value attributes (such as type or size for\n-- the file).\n-- \n-- For more details, see 'fileQueryFilesystemInfo' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileQueryInfoFinish' to get the result of the operation.\nfileQueryFilesystemInfoAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryFilesystemInfoAsync file attributes ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_filesystem_info_async cFile\n cAttributes\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_filesystem_info_async #}\n\n-- | Finishes an asynchronous filesystem info query. See 'fileQueryFilesystemInfoAsync'.\nfileQueryFilesystemInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryFilesystemInfoFinish file asyncResult =\n propagateGError ({# call file_query_filesystem_info_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\n-- | Returns the GAppInfo that is registered as the default application to handle the file specified by\n-- file.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileQueryDefaultHandler :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO AppInfo\nfileQueryDefaultHandler file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_default_handler cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_query_default_handler #}\n\n-- | Gets a GMount for the GFile.\n-- \n-- If the GFileIface for file does not have a mount (e.g. possibly a remote share), error will be set\n-- to GIoErrorNotFound and 'Nothing' will be returned.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileFindEnclosingMount :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Mount\nfileFindEnclosingMount file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_find_enclosing_mount cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_find_enclosing_mount #}\n\n-- | Asynchronously gets the mount for the file.\n-- \n-- For more details, see 'fileFindEnclosingMount' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileFindEnclosingMountFinish' to get the result of the operation.\nfileFindEnclosingMountAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileFindEnclosingMountAsync file ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_find_enclosing_mount_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_find_enclosing_mount_async #}\n\n-- | Finishes an asynchronous find mount request. See 'fileFindEnclosingMountAsync'.\nfileFindEnclosingMountFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Mount\nfileFindEnclosingMountFinish file asyncResult =\n propagateGError ({# call file_find_enclosing_mount_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\n-- | Gets the requested information about the files in a directory. The result is a GFileEnumerator\n-- object that will give out GFileInfo objects for all the files in the directory.\n-- \n-- The attribute value is a string that specifies the file attributes that should be gathered. It is\n-- not an error if it's not possible to read a particular requested attribute from a file - it just\n-- won't be set. attribute should be a comma-separated list of attribute or attribute wildcards. The\n-- wildcard \"*\" means all attributes, and a wildcard like \"standard::*\" means all attributes in the\n-- standard namespace. An example attribute query be \"standard::*,'user'\". The standard attributes\n-- are available as defines, like GFileAttributeStandardName.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If the file does not exist, the GIoErrorNotFound error will be returned. If the file is not a\n-- directory, the GFileErrorNotdir error will be returned. Other errors are possible too.\nfileEnumerateChildren :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileEnumerator\nfileEnumerateChildren file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_enumerate_children cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_enumerate_children #}\n\n-- | Asynchronously gets the requested information about the files in a directory. The result is a\n-- GFileEnumerator object that will give out GFileInfo objects for all the files in the directory.\n-- \n-- For more details, see 'fileEnumerateChildren' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileEnumerateChildrenFinish' to get the result of the operation.\nfileEnumerateChildrenAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileEnumerateChildrenAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_enumerate_children_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_enumerate_children_async #}\n\n-- | Finishes an async enumerate children operation. See 'fileEnumerateChildrenAsync'.\nfileEnumerateChildrenFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileEnumerator\nfileEnumerateChildrenFinish file asyncResult =\n propagateGError ({# call file_enumerate_children_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\n-- | Renames file to the specified display name.\n-- \n-- The display name is converted from UTF8 to the correct encoding for the target filesystem if\n-- possible and the file is renamed to this.\n-- \n-- If you want to implement a rename operation in the user interface the edit name\n-- (GFileAttributeStandardEditName) should be used as the initial value in the rename widget, and\n-- then the result after editing should be passed to 'fileSetDisplayName'.\n-- \n-- On success the resulting converted filename is returned.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileSetDisplayName :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO File\nfileSetDisplayName file displayName cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_set_display_name cFile cDisplayName cCancellable) >>=\n takeGObject\n where _ = {# call file_set_display_name #}\n\n-- | Asynchronously sets the display name for a given GFile.\n-- \n-- For more details, see 'fileSetDisplayName' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileSetDisplayNameFinish' to get the result of the operation.\nfileSetDisplayNameAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileSetDisplayNameAsync file displayName ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_set_display_name_async cFile\n cDisplayName\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_set_display_name_async #}\n\n-- | Finishes setting a display name started with 'fileSetDisplayNameAsync'.\nfileSetDisplayNameFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO File\nfileSetDisplayNameFinish file asyncResult =\n propagateGError ({# call file_set_display_name_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\n-- | Deletes a file. If the file is a directory, it will only be deleted if it is empty.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileDelete :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileDelete file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_delete cFile cCancellable) >> return ()\n where _ = {# call file_delete #}\n\n-- | Sends file to the \"Trashcan\", if possible. This is similar to deleting it, but the user can recover\n-- it before emptying the trashcan. Not all file systems support trashing, so this call can return the\n-- GIoErrorNotSupported error.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileTrash :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileTrash file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_trash cFile cCancellable) >> return ()\n where _ = {# call file_trash #}\n\n-- | Copies the file source to the location specified by destination. Can not handle recursive copies of\n-- directories.\n-- \n-- If the flag GFileCopyOverwrite is specified an already existing destination file is overwritten.\n-- \n-- If the flag GFileCopyNofollowSymlinks is specified then symlinks will be copied as symlinks,\n-- otherwise the target of the source symlink will be copied.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If @progressCallback@ is not 'Nothing', then the operation can be monitored by setting this to a\n-- GFileProgressCallback function. @progressCallbackData@ will be passed to this function. It is\n-- guaranteed that this callback will be called after all data has been transferred with the total\n-- number of bytes copied during the operation.\n-- \n-- If the source file does not exist then the GIoErrorNotFound error is returned, independent on\n-- the status of the destination.\n-- \n-- If GFileCopyOverwrite is not specified and the target exists, then the error GIoErrorExists is\n-- returned.\n-- \n-- If trying to overwrite a file over a directory the GIoErrorIsDirectory error is returned. If\n-- trying to overwrite a directory with a directory the GIoErrorWouldMerge error is returned.\n-- \n-- If the source is a directory and the target does not exist, or GFileCopyOverwrite is specified\n-- and the target is a file, then the GIoErrorWouldRecurse error is returned.\n-- \n-- If you are interested in copying the GFile object itself (not the on-disk file), see 'fileDup'.\nfileCopy :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileCopy source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_copy cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n when (cProgressCallback \/= nullFunPtr) $\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_copy #}\n\n-- | Copies the file source to the location specified by destination asynchronously. For details of the\n-- behaviour, see 'fileCopy'.\n-- \n-- If @progressCallback@ is not 'Nothing', then that function that will be called just like in 'fileCopy',\n-- however the callback will run in the main loop, not in the thread that is doing the I\/O operation.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileCopyFinish' to\n-- get the result of the operation.\nfileCopyAsync :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Int\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> AsyncReadyCallback\n -> IO ()\nfileCopyAsync source destination flags ioPriority cancellable progressCallback callback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n cCallback <- marshalAsyncReadyCallback $ \\sourceObject res -> do\n when (cProgressCallback \/= nullFunPtr) $\n freeHaskellFunPtr cProgressCallback\n callback sourceObject res\n g_file_copy_async cSource\n cDestination\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cProgressCallback\n nullPtr\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_copy_async #}\n\n-- | Finishes copying the file started with 'fileCopyAsync'.\nfileCopyFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Bool\nfileCopyFinish file asyncResult =\n liftM toBool $ propagateGError ({# call file_copy_finish #} (toFile file) asyncResult)\n\n-- | Tries to move the file or directory source to the location specified by destination. If native move\n-- operations are supported then this is used, otherwise a copy + delete fallback is used. The native\n-- implementation may support moving directories (for instance on moves inside the same filesystem),\n-- but the fallback code does not.\n-- \n-- If the flag GFileCopyOverwrite is specified an already existing destination file is overwritten.\n-- \n-- If the flag GFileCopyNofollowSymlinks is specified then symlinks will be copied as symlinks,\n-- otherwise the target of the source symlink will be copied.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If @progressCallback@ is not 'Nothing', then the operation can be monitored by setting this to a\n-- GFileProgressCallback function. @progressCallbackData@ will be passed to this function. It is\n-- guaranteed that this callback will be called after all data has been transferred with the total\n-- number of bytes copied during the operation.\n-- \n-- If the source file does not exist then the GIoErrorNotFound error is returned, independent on\n-- the status of the destination.\n-- \n-- If GFileCopyOverwrite is not specified and the target exists, then the error GIoErrorExists is\n-- returned.\n-- \n-- If trying to overwrite a file over a directory the GIoErrorIsDirectory error is returned. If\n-- trying to overwrite a directory with a directory the GIoErrorWouldMerge error is returned.\n-- \n-- If the source is a directory and the target does not exist, or GFileCopyOverwrite is specified\n-- and the target is a file, then the GIoErrorWouldRecurse error may be returned (if the native\n-- move operation isn't available).\nfileMove :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileMove source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_move cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n when (cProgressCallback \/= nullFunPtr) $\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_move #}\n\n-- | Creates a directory. Note that this will only create a child directory of the immediate parent\n-- directory of the path or URI given by the GFile. To recursively create directories, see\n-- 'fileMakeDirectoryWithParents'. This function will fail if the parent directory does not\n-- exist, setting error to GIoErrorNotFound. If the file system doesn't support creating\n-- directories, this function will fail, setting error to GIoErrorNotSupported.\n-- \n-- For a local GFile the newly created directory will have the default (current) ownership and\n-- permissions of the current process.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileMakeDirectory :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectory file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory cFile cCancellable\n return ()\n where _ = {# call file_make_directory #}\n\n#if GLIB_CHECK_VERSION(2,18,0)\n-- | Creates a directory and any parent directories that may not exist similar to 'mkdir -p'. If the file\n-- system does not support creating directories, this function will fail, setting error to\n-- GIoErrorNotSupported.\n-- \n-- For a local GFile the newly created directories will have the default (current) ownership and\n-- permissions of the current process.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileMakeDirectoryWithParents :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectoryWithParents file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory_with_parents cFile cCancellable\n return ()\n where _ = {# call file_make_directory_with_parents #}\n#endif\n\n-- | Creates a symbolic link.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileMakeSymbolicLink :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO ()\nfileMakeSymbolicLink file symlinkValue cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString symlinkValue $ \\cSymlinkValue ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_symbolic_link cFile cSymlinkValue cCancellable\n return ()\n where _ = {# call file_make_symbolic_link #}\n\n{# pointer *FileAttributeInfoList newtype #}\ntakeFileAttributeInfoList :: Ptr FileAttributeInfoList\n -> IO [FileAttributeInfo]\ntakeFileAttributeInfoList ptr =\n do cInfos <- liftM castPtr $ {# get FileAttributeInfoList->infos #} ptr\n cNInfos <- {# get FileAttributeInfoList->n_infos #} ptr\n infos <- peekArray (fromIntegral cNInfos) cInfos\n g_file_attribute_info_list_unref ptr\n return infos\n where _ = {# call file_attribute_info_list_unref #}\n\n-- | Obtain the list of settable attributes for the file.\n-- \n-- Returns the type and full attribute name of all the attributes that can be set on this file. This\n-- doesn't mean setting it will always succeed though, you might get an access failure, or some\n-- specific file may not support a specific attribute.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileQuerySettableAttributes :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO [FileAttributeInfo]\nfileQuerySettableAttributes file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n ptr <- propagateGError $ g_file_query_settable_attributes cFile cCancellable\n infos <- takeFileAttributeInfoList ptr\n return infos\n where _ = {# call file_query_settable_attributes #}\n\n-- | Obtain the list of attribute namespaces where new attributes can be created by a user. An example of\n-- this is extended attributes (in the \"xattr\" namespace).\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileQueryWritableNamespaces :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO [FileAttributeInfo]\nfileQueryWritableNamespaces file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n ptr <- propagateGError $ g_file_query_writable_namespaces cFile cCancellable\n infos <- takeFileAttributeInfoList ptr\n return infos\n where _ = {# call file_query_writable_namespaces #}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"e0132ee945d3e2b576f9d95b0c9a1c7d1fb17e8f","subject":"Fix Andy's compilation problem.","message":"Fix Andy's compilation problem.\n","repos":"gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"gio\/System\/GIO\/File\/File.chs","new_file":"gio\/System\/GIO\/File\/File.chs","new_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to gio -*-haskell-*-\n--\n-- Author : Peter Gavin, Andy Stewart\n-- Created: 13-Oct-2008\n--\n-- Copyright (c) 2008 Peter Gavin\n-- Copyright (c) 2010 Andy Stewart\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GIO, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GIO documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.GIO.File.File (\n-- * Details\n--\n-- | GFile is a high level abstraction for manipulating files on a virtual file system. GFiles are\n-- lightweight, immutable objects that do no I\/O upon creation. It is necessary to understand that\n-- GFile objects do not represent files, merely an identifier for a file. All file content I\/O is\n-- implemented as streaming operations (see GInputStream and GOutputStream).\n-- \n-- To construct a GFile, you can use: 'fileNewForPath' if\n-- you have a URI. 'fileNewForCommandlineArg'\n-- from a utf8 string gotten from 'fileGetParseName'.\n-- \n-- One way to think of a GFile is as an abstraction of a pathname. For normal files the system pathname\n-- is what is stored internally, but as GFiles are extensible it could also be something else that\n-- corresponds to a pathname in a userspace implementation of a filesystem.\n-- \n-- GFiles make up hierarchies of directories and files that correspond to the files on a\n-- filesystem. You can move through the file system with GFile using 'fileGetParent' to get an\n-- identifier for the parent directory, 'fileGetChild' to get a child within a directory,\n-- 'fileResolveRelativePath' to resolve a relative path between two GFiles. There can be multiple\n-- hierarchies, so you may not end up at the same root if you repeatedly call 'fileGetParent' on\n-- two different files.\n-- \n-- All GFiles have a basename (get with 'fileGetBasename'. These names are byte strings that are\n-- used to identify the file on the filesystem (relative to its parent directory) and there is no\n-- guarantees that they have any particular charset encoding or even make any sense at all. If you want\n-- to use filenames in a user interface you should use the display name that you can get by requesting\n-- the GFileAttributeStandardDisplayName attribute with 'fileQueryInfo'. This is guaranteed to\n-- be in utf8 and can be used in a user interface. But always store the real basename or the GFile to\n-- use to actually access the file, because there is no way to go from a display name to the actual\n-- name.\n-- \n-- Using GFile as an identifier has the same weaknesses as using a path in that there may be multiple\n-- aliases for the same file. For instance, hard or soft links may cause two different GFiles to refer\n-- to the same file. Other possible causes for aliases are: case insensitive filesystems, short and\n-- long names on Fat\/NTFS, or bind mounts in Linux. If you want to check if two GFiles point to the\n-- same file you can query for the GFileAttributeIdFile attribute. Note that GFile does some\n-- trivial canonicalization of pathnames passed in, so that trivial differences in the path string used\n-- at creation (duplicated slashes, slash at end of path, \".\" or \"..\" path segments, etc) does not\n-- create different GFiles.\n-- \n-- Many GFile operations have both synchronous and asynchronous versions to suit your\n-- application. Asynchronous versions of synchronous functions simply have _async() appended to their\n-- function names. The asynchronous I\/O functions call a GAsyncReadyCallback which is then used to\n-- finalize the operation, producing a GAsyncResult which is then passed to the function's matching\n-- _finish() operation.\n-- \n-- Some GFile operations do not have synchronous analogs, as they may take a very long time to finish,\n-- and blocking may leave an application unusable. Notable cases include: 'fileMountMountable' to\n-- mount a mountable file. 'fileUnmountMountableWithOperation' to unmount a mountable\n-- file. 'fileEjectMountableWithOperation' to eject a mountable file.\n-- \n-- One notable feature of GFiles are entity tags, or \"etags\" for short. Entity tags are somewhat like a\n-- more abstract version of the traditional mtime, and can be used to quickly determine if the file has\n-- been modified from the version on the file system. See the HTTP 1.1 specification for HTTP Etag\n-- headers, which are a very similar concept.\n\n-- * Types.\n FileProgressCallback,\n FileReadMoreCallback,\n FileClass,\n\n-- * Enums\n File(..),\n FileQueryInfoFlags(..),\n FileCreateFlags(..),\n FileCopyFlags(..),\n FileMonitorFlags(..),\n FilesystemPreviewType(..),\n FileType(..),\n\n-- * Methods\n fileFromPath,\n fileFromURI,\n fileFromCommandlineArg,\n fileFromParseName,\n fileEqual,\n fileBasename,\n filePath,\n#if GLIB_CHECK_VERSION(2,24,0)\n fileHasParent,\n#endif\n fileURI,\n fileParseName,\n fileGetChild,\n fileGetChildForDisplayName,\n fileHasPrefix,\n fileGetRelativePath,\n fileResolveRelativePath,\n fileIsNative,\n fileHasURIScheme,\n fileURIScheme,\n fileRead,\n fileReadAsync,\n fileReadFinish,\n fileAppendTo,\n fileCreate,\n fileReplace,\n fileAppendToAsync,\n fileAppendToFinish,\n fileCreateAsync,\n fileCreateFinish,\n fileReplaceAsync,\n fileReplaceFinish,\n fileQueryInfo,\n fileQueryInfoAsync,\n fileQueryInfoFinish,\n fileQueryExists,\n#if GLIB_CHECK_VERSION(2,18,0)\n fileQueryFileType,\n#endif\n fileQueryFilesystemInfo,\n fileQueryFilesystemInfoAsync,\n fileQueryFilesystemInfoFinish,\n fileQueryDefaultHandler,\n fileFindEnclosingMount,\n fileFindEnclosingMountAsync,\n fileFindEnclosingMountFinish,\n fileEnumerateChildren,\n fileEnumerateChildrenAsync,\n fileEnumerateChildrenFinish,\n fileSetDisplayName,\n fileSetDisplayNameAsync,\n fileSetDisplayNameFinish,\n fileDelete,\n fileTrash,\n fileCopy,\n fileCopyAsync,\n fileCopyFinish,\n fileMove,\n fileMakeDirectory,\n#if GLIB_CHECK_VERSION(2,18,0)\n fileMakeDirectoryWithParents,\n#endif\n fileMakeSymbolicLink,\n fileQuerySettableAttributes,\n fileQueryWritableNamespaces\n ) where\n\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport Data.Typeable\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.UTFString\nimport System.Glib.GObject\n\n{#import System.GIO.Base#}\n{#import System.GIO.Types#}\nimport System.GIO.File.FileAttribute\n\n{# context lib = \"gio\" prefix = \"g\" #}\n\n{# enum GFileQueryInfoFlags as FileQueryInfoFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileQueryInfoFlags\n\n{# enum GFileCreateFlags as FileCreateFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCreateFlags\n\n{# enum GFileCopyFlags as FileCopyFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCopyFlags\n\n{# enum GFileMonitorFlags as FileMonitorFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileMonitorFlags\n\n{# enum GFilesystemPreviewType as FilesystemPreviewType {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\n{# enum GFileType as FileType {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\ntype FileProgressCallback = Offset -> Offset -> IO ()\ntype CFileProgressCallback = {# type goffset #} -> {# type goffset #} -> Ptr () -> IO ()\nforeign import ccall \"wrapper\"\n makeFileProgressCallback :: CFileProgressCallback\n -> IO {# type GFileProgressCallback #}\n\nmarshalFileProgressCallback :: FileProgressCallback -> IO {# type GFileProgressCallback #}\nmarshalFileProgressCallback fileProgressCallback =\n makeFileProgressCallback cFileProgressCallback\n where cFileProgressCallback :: CFileProgressCallback\n cFileProgressCallback cCurrentNumBytes cTotalNumBytes _ = do\n fileProgressCallback (fromIntegral cCurrentNumBytes)\n (fromIntegral cTotalNumBytes)\n\ntype FileReadMoreCallback = BS.ByteString -> IO Bool\n\n-- | Constructs a GFile for a given path. This operation never fails, but the returned object might not\n-- support any I\/O operation if path is malformed.\nfileFromPath :: FilePath -> File\nfileFromPath path =\n unsafePerformIO $ withUTFString path $ \\cPath -> {# call file_new_for_path #} cPath >>= takeGObject\n\n-- | Constructs a GFile for a given URI. This operation never fails, but the returned object might not\n-- support any I\/O operation if uri is malformed or if the uri type is not supported.\nfileFromURI :: String -> File\nfileFromURI uri =\n unsafePerformIO $ withUTFString uri $ \\cURI -> {# call file_new_for_uri #} cURI >>= takeGObject\n\n-- | Creates a GFile with the given argument from the command line. The value of arg can be either a URI,\n-- an absolute path or a relative path resolved relative to the current working directory. This\n-- operation never fails, but the returned object might not support any I\/O operation if arg points to\n-- a malformed path.\nfileFromCommandlineArg :: String -> File\nfileFromCommandlineArg arg =\n unsafePerformIO $ withUTFString arg $ \\cArg -> {# call file_new_for_commandline_arg #} cArg >>= takeGObject\n\n-- | Constructs a GFile with the given 'name (i.e. something given by gFileGetParseName'. This\n-- operation never fails, but the returned object might not support any I\/O operation if the @parseName@\n-- cannot be parsed.\nfileFromParseName :: String -> File\nfileFromParseName parseName =\n unsafePerformIO $ withUTFString parseName $ \\cParseName -> {# call file_parse_name #} cParseName >>= takeGObject\n\n-- | Compare two file descriptors for equality. This test is also used to\n-- implement the '(==)' function, that is, comparing two descriptions\n-- will compare their content, not the pointers to the two structures.\n--\nfileEqual :: (FileClass file1, FileClass file2)\n => file1 -> file2 -> Bool\nfileEqual file1 file2 =\n unsafePerformIO $ liftM toBool $ {# call file_equal #} (toFile file1) (toFile file2)\n\ninstance Eq File where\n (==) = fileEqual\n\n-- | Gets the base name (the last component of the path) for a given GFile.\n-- \n-- If called for the top level of a system (such as the filesystem root or a uri like sftp:\/\/host\/) it\n-- will return a single directory separator (and on Windows, possibly a drive letter).\n-- \n-- The base name is a byte string (*not* UTF-8). It has no defined encoding or rules other than it may\n-- not contain zero bytes. If you want to use filenames in a user interface you should use the display\n-- name that you can get by requesting the GFileAttributeStandardDisplayName attribute with\n-- 'fileQueryInfo'.\n-- \n-- This call does no blocking i\/o.\nfileBasename :: FileClass file => file -> String\nfileBasename file =\n unsafePerformIO $ {# call file_get_basename #} (toFile file) >>= readUTFString\n\n-- | Gets the local pathname for GFile, if one exists.\n-- \n-- This call does no blocking i\/o.\nfilePath :: FileClass file => file -> FilePath\nfilePath file =\n unsafePerformIO $ {# call file_get_path #} (toFile file) >>= readUTFString\n\n-- | Gets the URI for the file.\n-- \n-- This call does no blocking i\/o.\nfileURI :: FileClass file => file -> String\nfileURI file =\n unsafePerformIO $ {# call file_get_uri #} (toFile file) >>= readUTFString\n\n-- | Gets the parse name of the file. A parse name is a UTF-8 string that describes the file such that\n-- one can get the GFile back using 'fileParseName'.\n-- \n-- This is generally used to show the GFile as a nice full-pathname kind of string in a user interface,\n-- like in a location entry.\n-- \n-- For local files with names that can safely be converted to UTF8 the pathname is used, otherwise the\n-- IRI is used (a form of URI that allows UTF8 characters unescaped).\n-- \n-- This call does no blocking i\/o.\nfileParseName :: FileClass file => file -> String\nfileParseName file =\n unsafePerformIO $ {# call file_get_parse_name #} (toFile file) >>= readUTFString\n\n-- | Gets the parent directory for the file. If the file represents the root directory of the file\n-- system, then 'Nothing' will be returned.\n-- \n-- This call does no blocking i\/o.\nfileParent :: FileClass file => file -> Maybe File\nfileParent file =\n unsafePerformIO $ {# call file_get_parent #} (toFile file) >>= maybePeek takeGObject\n\n#if GLIB_CHECK_VERSION(2,24,0)\n-- | Checks if file has a parent, and optionally, if it is parent.\n-- \n-- If parent is 'Nothing' then this function returns 'True' if file has any parent at all. If parent is\n-- non-'Nothing' then 'True' is only returned if file is a child of parent.\nfileHasParent :: FileClass file => file -> Maybe File -> Bool \nfileHasParent file parent = \n unsafePerformIO $ liftM toBool $\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject parent $ \\parentPtr ->\n g_file_has_parent cFile parentPtr\n where _ = {#call file_has_parent #}\n#endif\n\n-- | Gets a child of file with basename equal to name.\n-- \n-- Note that the file with that specific name might not exist, but you can still have a GFile that\n-- points to it. You can use this for instance to create that file.\n-- \n-- This call does no blocking i\/o.\nfileGetChild :: FileClass file => file -> String -> File\nfileGetChild file name =\n unsafePerformIO $\n withUTFString name $ \\cName ->\n {# call file_get_child #} (toFile file) cName >>= takeGObject\n\n-- | Gets the child of file for a given 'name (i.e. a UTF8 version of the name)'. If this function\n-- fails, it returns 'Nothing' and error will be set. This is very useful when constructing a GFile for a\n-- new file and the user entered the filename in the user interface, for instance when you select a\n-- directory and type a filename in the file selector.\n-- \n-- This call does no blocking i\/o.\nfileGetChildForDisplayName :: FileClass file => file -> String -> Maybe File\nfileGetChildForDisplayName file displayName =\n unsafePerformIO $\n withUTFString displayName $ \\cDisplayName ->\n propagateGError ({# call file_get_child_for_display_name #} (toFile file) cDisplayName) >>=\n maybePeek takeGObject\n\n-- | Checks whether file has the prefix specified by prefix. In other word, if the names of inital\n-- elements of files pathname match prefix. Only full pathname elements are matched, so a path like\n-- \/foo is not considered a prefix of \/foobar, only of \/ foo\/bar.\n-- \n-- This call does no i\/o, as it works purely on names. As such it can sometimes return 'False' even if\n-- file is inside a prefix (from a filesystem point of view), because the prefix of file is an alias of\n-- prefix.\nfileHasPrefix :: (FileClass file1, FileClass file2) => file1 -> file2 -> Bool\nfileHasPrefix file1 file2 =\n unsafePerformIO $\n liftM toBool $ {# call file_has_prefix #} (toFile file1) (toFile file2)\n\n-- | Gets the path for descendant relative to parent.\n-- \n-- This call does no blocking i\/o.\nfileGetRelativePath :: (FileClass file1, FileClass file2) => file1 -> file2 -> Maybe FilePath\nfileGetRelativePath file1 file2 =\n unsafePerformIO $\n {# call file_get_relative_path #} (toFile file1) (toFile file2) >>=\n maybePeek readUTFString\n\n-- | Resolves a relative path for file to an absolute path.\n-- \n-- This call does no blocking i\/o.\nfileResolveRelativePath :: FileClass file => file -> FilePath -> Maybe File\nfileResolveRelativePath file relativePath =\n unsafePerformIO $\n withUTFString relativePath $ \\cRelativePath ->\n {# call file_resolve_relative_path #} (toFile file) cRelativePath >>=\n maybePeek takeGObject\n\n-- | Checks to see if a file is native to the platform.\n-- \n-- A native file s one expressed in the platform-native filename format, e.g. \\\"C:\\\\Windows\\\" or\n-- \\\"\/usr\/bin\/\\\". This does not mean the file is local, as it might be on a locally mounted remote\n-- filesystem.\n-- \n-- On some systems non-native files may be available using the native filesystem via a userspace\n-- filesystem (FUSE), in these cases this call will return @False@, but 'fileGetPath' will still\n-- return a native path.\n-- \n-- This call does no blocking i\/o.\nfileIsNative :: FileClass file => file -> Bool\nfileIsNative =\n unsafePerformIO .\n liftM toBool . {# call file_is_native #} . toFile\n\n-- | Checks to see if a 'GFile' has a given URI scheme.\n-- \n-- This call does no blocking i\/o.\nfileHasURIScheme :: FileClass file => file -> String -> Bool\nfileHasURIScheme file uriScheme =\n unsafePerformIO $\n withUTFString uriScheme $ \\cURIScheme ->\n liftM toBool $ {# call file_has_uri_scheme #} (toFile file) cURIScheme\n\n-- | Gets the URI scheme for a GFile. RFC 3986 decodes the scheme as:\n-- \n-- URI = scheme \":\" hier-part [ \"?\" query ] [ \"#\" fragment ]\n-- \n-- Common schemes include \"file\", \"http\", \"ftp\", etc.\n-- \n-- This call does no blocking i\/o.\nfileURIScheme :: FileClass file => file -> String\nfileURIScheme file =\n unsafePerformIO $ {# call file_get_uri_scheme #} (toFile file) >>= readUTFString\n\n-- | Opens a file for reading. The result is a GFileInputStream that can be used to read the contents of\n-- the file.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If the file does not exist, the GIoErrorNotFound error will be returned. If the file is a\n-- directory, the GIoErrorIsDirectory error will be returned. Other errors are possible too, and\n-- depend on what kind of filesystem the file is on.\nfileRead :: FileClass file => file -> Maybe Cancellable -> IO FileInputStream\nfileRead file (Just cancellable) = constructNewGObject mkFileInputStream $\n propagateGError $ {# call file_read #} (toFile file) cancellable\n\n-- | Asynchronously opens file for reading.\n-- \n-- For more details, see 'fileRead' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileReadFinish' to\n-- get the result of the operation.\nfileReadAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReadAsync file ioPriority mbCancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject mbCancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_read_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_read_async #}\n\n-- | Finishes an asynchronous file read operation started with 'fileReadAsync'.\nfileReadFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInputStream\nfileReadFinish file asyncResult =\n propagateGError ({# call file_read_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Gets an output stream for appending data to the file. If the file doesn't already exist it is\n-- created.\n-- \n-- By default files created are generally readable by everyone, but if you pass GFileCreatePrivate\n-- in flags the file will be made readable only to the current user, to the level that is supported on\n-- the target filesystem.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- Some file systems don't allow all file names, and may return an GIoErrorInvalidFilename\n-- error. If the file is a directory the GIoErrorIsDirectory error will be returned. Other errors\n-- are possible too, and depend on what kind of filesystem the file is on.\nfileAppendTo :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileAppendTo file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_append_to cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_append_to #}\n\n-- | Creates a new file and returns an output stream for writing to it. The file must not already exist.\n-- \n-- By default files created are generally readable by everyone, but if you pass GFileCreatePrivate\n-- in flags the file will be made readable only to the current user, to the level that is supported on\n-- the target filesystem.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If a file or directory with this name already exists the GIoErrorExists error will be\n-- returned. Some file systems don't allow all file names, and may return an\n-- GIoErrorInvalidFilename error, and if the name is to long GIoErrorFilenameTooLong will be\n-- returned. Other errors are possible too, and depend on what kind of filesystem the file is on.\nfileCreate :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileCreate file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_create cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_create #}\n\n-- | Returns an output stream for overwriting the file, possibly creating a backup copy of the file\n-- first. If the file doesn't exist, it will be created.\n-- \n-- This will try to replace the file in the safest way possible so that any errors during the writing\n-- will not affect an already existing copy of the file. For instance, for local files it may write to\n-- a temporary file and then atomically rename over the destination when the stream is closed.\n-- \n-- By default files created are generally readable by everyone, but if you pass GFileCreatePrivate\n-- in flags the file will be made readable only to the current user, to the level that is supported on\n-- the target filesystem.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If you pass in a non-'Nothing' etag value, then this value is compared to the current entity tag of the\n-- file, and if they differ an GIoErrorWrongEtag error is returned. This generally means that the\n-- file has been changed since you last read it. You can get the new etag from\n-- 'fileOutputStreamGetEtag' after you've finished writing and closed the GFileOutputStream.\n-- When you load a new file you can use 'fileInputStreamQueryInfo' to get the etag of the file.\n-- \n-- If @makeBackup@ is 'True', this function will attempt to make a backup of the current file before\n-- overwriting it. If this fails a GIoErrorCantCreateBackup error will be returned. If you want to\n-- replace anyway, try again with @makeBackup@ set to 'False'.\n-- \n-- If the file is a directory the GIoErrorIsDirectory error will be returned, and if the file is\n-- some other form of non-regular file then a GIoErrorNotRegularFile error will be returned. Some\n-- file systems don't allow all file names, and may return an GIoErrorInvalidFilename error, and if\n-- the name is to long GIoErrorFilenameTooLong will be returned. Other errors are possible too,\n-- and depend on what kind of filesystem the file is on.\nfileReplace :: FileClass file\n => file\n -> Maybe String\n -> Bool\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileReplace file etag makeBackup flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_replace cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_replace #}\n\n-- | Asynchronously opens file for appending.\n-- \n-- For more details, see 'fileAppendTo' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileAppendToFinish'\n-- to get the result of the operation.\nfileAppendToAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileAppendToAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_append_to_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_append_to_async #}\n\n-- | Finishes an asynchronous file append operation started with 'fileAppendToAsync'.\nfileAppendToFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileAppendToFinish file asyncResult =\n propagateGError ({# call file_append_to_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Asynchronously creates a new file and returns an output stream for writing to it. The file must not\n-- already exist.\n-- \n-- For more details, see 'fileCreate' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileCreateFinish' to\n-- get the result of the operation.\nfileCreateAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileCreateAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_create_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_create_async #}\n\n-- | Finishes an asynchronous file create operation started with 'fileCreateAsync'.\nfileCreateFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileCreateFinish file asyncResult =\n propagateGError ({# call file_create_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Asynchronously overwrites the file, replacing the contents, possibly creating a backup copy of the\n-- file first.\n-- \n-- For more details, see 'fileReplace' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileReplaceFinish'\n-- to get the result of the operation.\nfileReplaceAsync :: FileClass file\n => file\n -> String\n -> Bool\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReplaceAsync file etag makeBackup flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_replace_async cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_replace_async #}\n\n-- | Finishes an asynchronous file replace operation started with 'fileReplaceAsync'.\nfileReplaceFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileReplaceFinish file asyncResult =\n propagateGError ({# call file_replace_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Gets the requested information about specified file. The result is a 'GFileInfo' object that contains\n-- key-value attributes (such as the type or size of the file).\n-- \n-- The attribute value is a string that specifies the file attributes that should be gathered. It is\n-- not an error if it's not possible to read a particular requested attribute from a file - it just\n-- won't be set. attribute should be a comma-separated list of attribute or attribute wildcards. The\n-- wildcard \\\"*\\\" means all attributes, and a wildcard like \\\"standard::*\\\" means all attributes in the\n-- standard namespace. An example attribute query be \\\"standard::*,'user'\\\". The standard attributes\n-- are available as defines, like 'GFileAttributeStandardName'.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error 'GIoErrorCancelled' will be\n-- returned.\n-- \n-- For symlinks, normally the information about the target of the symlink is returned, rather than\n-- information about the symlink itself. However if you pass 'GFileQueryInfoNofollowSymlinks' in\n-- flags the information about the symlink itself will be returned. Also, for symlinks that point to\n-- non-existing files the information about the symlink itself will be returned.\n-- \n-- If the file does not exist, the 'GIoErrorNotFound' error will be returned. Other errors are\n-- possible too, and depend on what kind of filesystem the file is on.\nfileQueryInfo :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryInfo file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_info cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_query_info #}\n\n-- | Asynchronously gets the requested information about specified file. The\n-- result is a 'GFileInfo' object that contains key-value attributes (such as\n-- type or size for the file).\n-- \n-- For more details, see 'fileQueryInfo' which is the synchronous version of\n-- this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileQueryInfoFinish' to get the result of the operation.\nfileQueryInfoAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryInfoAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_info_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_info_async #}\n\n-- | Finishes an asynchronous file info query. See 'fileQueryInfoAsync'.\nfileQueryInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryInfoFinish file asyncResult =\n propagateGError ({#call file_query_info_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Utility function to check if a particular file exists. This is implemented using 'fileQueryInfo'\n-- and as such does blocking I\/O.\n-- \n-- Note that in many cases it is racy to first check for file existence and then execute something\n-- based on the outcome of that, because the file might have been created or removed in between the\n-- operations. The general approach to handling that is to not check, but just do the operation and\n-- handle the errors as they come.\n-- \n-- As an example of race-free checking, take the case of reading a file, and if it doesn't exist,\n-- creating it. There are two racy versions: read it, and on error create it; and: check if it exists,\n-- if not create it. These can both result in two processes creating the file (with perhaps a partially\n-- written file as the result). The correct approach is to always try to create the file with\n-- 'fileCreate' which will either atomically create the file or fail with a GIoErrorExists error.\n-- \n-- However, in many cases an existence check is useful in a user interface, for instance to make a menu\n-- item sensitive\/ insensitive, so that you don't have to fool users that something is possible and\n-- then just show and error dialog. If you do this, you should make sure to also handle the errors that\n-- can happen due to races when you execute the operation.\nfileQueryExists :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Bool\nfileQueryExists file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n liftM toBool $ g_file_query_exists cFile cCancellable\n where _ = {# call file_query_exists #}\n\n#if GLIB_CHECK_VERSION(2,18,0)\n-- | Utility function to inspect the GFileType of a file. This is implemented using 'fileQueryInfo'\n-- and as such does blocking I\/O.\n-- \n-- The primary use case of this method is to check if a file is a regular file, directory, or symlink.\nfileQueryFileType :: FileClass file \n => file \n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileType\nfileQueryFileType file flags cancellable = \n liftM (toEnum . fromIntegral) $\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n (g_file_query_file_type cFile (cFromFlags flags) cCancellable)\n where _ = {# call file_query_file_type #}\n#endif\n\n-- | Similar to 'fileQueryInfo', but obtains information about the filesystem the file is on, rather\n-- than the file itself. For instance the amount of space available and the type of the filesystem.\n-- \n-- The attribute value is a string that specifies the file attributes that should be gathered. It is\n-- not an error if it's not possible to read a particular requested attribute from a file - it just\n-- won't be set. attribute should be a comma-separated list of attribute or attribute wildcards. The\n-- wildcard \"*\" means all attributes, and a wildcard like \"fs:*\" means all attributes in the fs\n-- namespace. The standard namespace for filesystem attributes is \"fs\". Common attributes of interest\n-- are 'FILEAttributeFilesystemSize (The Total Size Of The Filesystem In Bytes)',\n-- 'FILEAttributeFilesystemFree (Number Of Bytes Available)', and GFileAttributeFilesystemType\n-- (type of the filesystem).\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If the file does not exist, the GIoErrorNotFound error will be returned. Other errors are\n-- possible too, and depend on what kind of filesystem the file is on.\nfileQueryFilesystemInfo :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryFilesystemInfo file attributes cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_filesystem_info cFile cAttributes cCancellable) >>=\n takeGObject\n where _ = {# call file_query_filesystem_info #}\n\n-- | Asynchronously gets the requested information about the filesystem that the specified file is\n-- on. The result is a GFileInfo object that contains key-value attributes (such as type or size for\n-- the file).\n-- \n-- For more details, see 'fileQueryFilesystemInfo' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileQueryInfoFinish' to get the result of the operation.\nfileQueryFilesystemInfoAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryFilesystemInfoAsync file attributes ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_filesystem_info_async cFile\n cAttributes\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_filesystem_info_async #}\n\n-- | Finishes an asynchronous filesystem info query. See 'fileQueryFilesystemInfoAsync'.\nfileQueryFilesystemInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryFilesystemInfoFinish file asyncResult =\n propagateGError ({# call file_query_filesystem_info_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\n-- | Returns the GAppInfo that is registered as the default application to handle the file specified by\n-- file.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileQueryDefaultHandler :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO AppInfo\nfileQueryDefaultHandler file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_default_handler cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_query_default_handler #}\n\n-- | Gets a GMount for the GFile.\n-- \n-- If the GFileIface for file does not have a mount (e.g. possibly a remote share), error will be set\n-- to GIoErrorNotFound and 'Nothing' will be returned.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileFindEnclosingMount :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Mount\nfileFindEnclosingMount file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_find_enclosing_mount cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_find_enclosing_mount #}\n\n-- | Asynchronously gets the mount for the file.\n-- \n-- For more details, see 'fileFindEnclosingMount' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileFindEnclosingMountFinish' to get the result of the operation.\nfileFindEnclosingMountAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileFindEnclosingMountAsync file ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_find_enclosing_mount_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_find_enclosing_mount_async #}\n\n-- | Finishes an asynchronous find mount request. See 'fileFindEnclosingMountAsync'.\nfileFindEnclosingMountFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Mount\nfileFindEnclosingMountFinish file asyncResult =\n propagateGError ({# call file_find_enclosing_mount_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\n-- | Gets the requested information about the files in a directory. The result is a 'GFileEnumerator'\n-- object that will give out 'GFileInfo' objects for all the files in the directory.\n-- \n-- The attribute value is a string that specifies the file attributes that should be gathered. It is\n-- not an error if it's not possible to read a particular requested attribute from a file - it just\n-- won't be set. attribute should be a comma-separated list of attribute or attribute wildcards. The\n-- wildcard \\\"*\\\" means all attributes, and a wildcard like \\\"standard::*\\\" means all attributes in the\n-- standard namespace. An example attribute query be \\\"standard::*,'user'\\\". The standard attributes\n-- are available as defines, like 'GFileAttributeStandardName'.\n-- \n-- If cancellable is not @Nothing@, then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error 'GIoErrorCancelled' will be\n-- returned.\n-- \n-- If the file does not exist, the 'GIoErrorNotFound' error will be returned. If the file is not a\n-- directory, the 'GFileErrorNotdir' error will be returned. Other errors are possible too.\nfileEnumerateChildren :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileEnumerator\nfileEnumerateChildren file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_enumerate_children cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_enumerate_children #}\n\n-- | Asynchronously gets the requested information about the files in a directory. The result is a\n-- GFileEnumerator object that will give out GFileInfo objects for all the files in the directory.\n-- \n-- For more details, see 'fileEnumerateChildren' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileEnumerateChildrenFinish' to get the result of the operation.\nfileEnumerateChildrenAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileEnumerateChildrenAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_enumerate_children_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_enumerate_children_async #}\n\n-- | Finishes an async enumerate children operation. See 'fileEnumerateChildrenAsync'.\nfileEnumerateChildrenFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileEnumerator\nfileEnumerateChildrenFinish file asyncResult =\n propagateGError ({# call file_enumerate_children_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\n-- | Renames file to the specified display name.\n-- \n-- The display name is converted from UTF8 to the correct encoding for the target filesystem if\n-- possible and the file is renamed to this.\n-- \n-- If you want to implement a rename operation in the user interface the edit name\n-- (GFileAttributeStandardEditName) should be used as the initial value in the rename widget, and\n-- then the result after editing should be passed to 'fileSetDisplayName'.\n-- \n-- On success the resulting converted filename is returned.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileSetDisplayName :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO File\nfileSetDisplayName file displayName cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_set_display_name cFile cDisplayName cCancellable) >>=\n takeGObject\n where _ = {# call file_set_display_name #}\n\n-- | Asynchronously sets the display name for a given GFile.\n-- \n-- For more details, see 'fileSetDisplayName' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileSetDisplayNameFinish' to get the result of the operation.\nfileSetDisplayNameAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileSetDisplayNameAsync file displayName ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_set_display_name_async cFile\n cDisplayName\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_set_display_name_async #}\n\n-- | Finishes setting a display name started with 'fileSetDisplayNameAsync'.\nfileSetDisplayNameFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO File\nfileSetDisplayNameFinish file asyncResult =\n propagateGError ({# call file_set_display_name_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\n-- | Deletes a file. If the file is a directory, it will only be deleted if it is empty.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileDelete :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileDelete file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_delete cFile cCancellable) >> return ()\n where _ = {# call file_delete #}\n\n-- | Sends file to the \"Trashcan\", if possible. This is similar to deleting it, but the user can recover\n-- it before emptying the trashcan. Not all file systems support trashing, so this call can return the\n-- GIoErrorNotSupported error.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileTrash :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileTrash file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_trash cFile cCancellable) >> return ()\n where _ = {# call file_trash #}\n\n-- | Copies the file source to the location specified by destination. Can not handle recursive copies of\n-- directories.\n-- \n-- If the flag GFileCopyOverwrite is specified an already existing destination file is overwritten.\n-- \n-- If the flag GFileCopyNofollowSymlinks is specified then symlinks will be copied as symlinks,\n-- otherwise the target of the source symlink will be copied.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If @progressCallback@ is not 'Nothing', then the operation can be monitored by setting this to a\n-- GFileProgressCallback function. @progressCallbackData@ will be passed to this function. It is\n-- guaranteed that this callback will be called after all data has been transferred with the total\n-- number of bytes copied during the operation.\n-- \n-- If the source file does not exist then the GIoErrorNotFound error is returned, independent on\n-- the status of the destination.\n-- \n-- If GFileCopyOverwrite is not specified and the target exists, then the error GIoErrorExists is\n-- returned.\n-- \n-- If trying to overwrite a file over a directory the GIoErrorIsDirectory error is returned. If\n-- trying to overwrite a directory with a directory the GIoErrorWouldMerge error is returned.\n-- \n-- If the source is a directory and the target does not exist, or GFileCopyOverwrite is specified\n-- and the target is a file, then the GIoErrorWouldRecurse error is returned.\n-- \n-- If you are interested in copying the GFile object itself (not the on-disk file), see 'fileDup'.\nfileCopy :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileCopy source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_copy cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n when (cProgressCallback \/= nullFunPtr) $\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_copy #}\n\n-- | Copies the file source to the location specified by destination asynchronously. For details of the\n-- behaviour, see 'fileCopy'.\n-- \n-- If @progressCallback@ is not 'Nothing', then that function that will be called just like in 'fileCopy',\n-- however the callback will run in the main loop, not in the thread that is doing the I\/O operation.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileCopyFinish' to\n-- get the result of the operation.\nfileCopyAsync :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Int\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> AsyncReadyCallback\n -> IO ()\nfileCopyAsync source destination flags ioPriority cancellable progressCallback callback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n cCallback <- marshalAsyncReadyCallback $ \\sourceObject res -> do\n when (cProgressCallback \/= nullFunPtr) $\n freeHaskellFunPtr cProgressCallback\n callback sourceObject res\n g_file_copy_async cSource\n cDestination\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cProgressCallback\n nullPtr\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_copy_async #}\n\n-- | Finishes copying the file started with 'fileCopyAsync'.\nfileCopyFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Bool\nfileCopyFinish file asyncResult =\n liftM toBool $ propagateGError ({# call file_copy_finish #} (toFile file) asyncResult)\n\n-- | Tries to move the file or directory source to the location specified by destination. If native move\n-- operations are supported then this is used, otherwise a copy + delete fallback is used. The native\n-- implementation may support moving directories (for instance on moves inside the same filesystem),\n-- but the fallback code does not.\n-- \n-- If the flag GFileCopyOverwrite is specified an already existing destination file is overwritten.\n-- \n-- If the flag GFileCopyNofollowSymlinks is specified then symlinks will be copied as symlinks,\n-- otherwise the target of the source symlink will be copied.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If @progressCallback@ is not 'Nothing', then the operation can be monitored by setting this to a\n-- GFileProgressCallback function. @progressCallbackData@ will be passed to this function. It is\n-- guaranteed that this callback will be called after all data has been transferred with the total\n-- number of bytes copied during the operation.\n-- \n-- If the source file does not exist then the GIoErrorNotFound error is returned, independent on\n-- the status of the destination.\n-- \n-- If GFileCopyOverwrite is not specified and the target exists, then the error GIoErrorExists is\n-- returned.\n-- \n-- If trying to overwrite a file over a directory the GIoErrorIsDirectory error is returned. If\n-- trying to overwrite a directory with a directory the GIoErrorWouldMerge error is returned.\n-- \n-- If the source is a directory and the target does not exist, or GFileCopyOverwrite is specified\n-- and the target is a file, then the GIoErrorWouldRecurse error may be returned (if the native\n-- move operation isn't available).\nfileMove :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileMove source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_move cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n when (cProgressCallback \/= nullFunPtr) $\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_move #}\n\n-- | Creates a directory. Note that this will only create a child directory of the immediate parent\n-- directory of the path or URI given by the GFile. To recursively create directories, see\n-- 'fileMakeDirectoryWithParents'. This function will fail if the parent directory does not\n-- exist, setting error to GIoErrorNotFound. If the file system doesn't support creating\n-- directories, this function will fail, setting error to GIoErrorNotSupported.\n-- \n-- For a local GFile the newly created directory will have the default (current) ownership and\n-- permissions of the current process.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileMakeDirectory :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectory file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory cFile cCancellable\n return ()\n where _ = {# call file_make_directory #}\n\n#if GLIB_CHECK_VERSION(2,18,0)\n-- | Creates a directory and any parent directories that may not exist similar to 'mkdir -p'. If the file\n-- system does not support creating directories, this function will fail, setting error to\n-- GIoErrorNotSupported.\n-- \n-- For a local GFile the newly created directories will have the default (current) ownership and\n-- permissions of the current process.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileMakeDirectoryWithParents :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectoryWithParents file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory_with_parents cFile cCancellable\n return ()\n where _ = {# call file_make_directory_with_parents #}\n#endif\n\n-- | Creates a symbolic link.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileMakeSymbolicLink :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO ()\nfileMakeSymbolicLink file symlinkValue cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString symlinkValue $ \\cSymlinkValue ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_symbolic_link cFile cSymlinkValue cCancellable\n return ()\n where _ = {# call file_make_symbolic_link #}\n\n{# pointer *FileAttributeInfoList newtype #}\ntakeFileAttributeInfoList :: Ptr FileAttributeInfoList\n -> IO [FileAttributeInfo]\ntakeFileAttributeInfoList ptr =\n do cInfos <- liftM castPtr $ {# get FileAttributeInfoList->infos #} ptr\n cNInfos <- {# get FileAttributeInfoList->n_infos #} ptr\n infos <- peekArray (fromIntegral cNInfos) cInfos\n g_file_attribute_info_list_unref ptr\n return infos\n where _ = {# call file_attribute_info_list_unref #}\n\n-- | Obtain the list of settable attributes for the file.\n-- \n-- Returns the type and full attribute name of all the attributes that can be set on this file. This\n-- doesn't mean setting it will always succeed though, you might get an access failure, or some\n-- specific file may not support a specific attribute.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileQuerySettableAttributes :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO [FileAttributeInfo]\nfileQuerySettableAttributes file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n ptr <- propagateGError $ g_file_query_settable_attributes cFile cCancellable\n infos <- takeFileAttributeInfoList ptr\n return infos\n where _ = {# call file_query_settable_attributes #}\n\n-- | Obtain the list of attribute namespaces where new attributes can be created by a user. An example of\n-- this is extended attributes (in the \"xattr\" namespace).\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileQueryWritableNamespaces :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO [FileAttributeInfo]\nfileQueryWritableNamespaces file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n ptr <- propagateGError $ g_file_query_writable_namespaces cFile cCancellable\n infos <- takeFileAttributeInfoList ptr\n return infos\n where _ = {# call file_query_writable_namespaces #}\n\n","old_contents":"{-# LANGUAGE CPP, DeriveDataTypeable #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to gio -*-haskell-*-\n--\n-- Author : Peter Gavin, Andy Stewart\n-- Created: 13-Oct-2008\n--\n-- Copyright (c) 2008 Peter Gavin\n-- Copyright (c) 2010 Andy Stewart\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GIO, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GIO documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.GIO.File.File (\n-- * Details\n--\n-- | GFile is a high level abstraction for manipulating files on a virtual file system. GFiles are\n-- lightweight, immutable objects that do no I\/O upon creation. It is necessary to understand that\n-- GFile objects do not represent files, merely an identifier for a file. All file content I\/O is\n-- implemented as streaming operations (see GInputStream and GOutputStream).\n-- \n-- To construct a GFile, you can use: 'fileNewForPath' if\n-- you have a URI. 'fileNewForCommandlineArg'\n-- from a utf8 string gotten from 'fileGetParseName'.\n-- \n-- One way to think of a GFile is as an abstraction of a pathname. For normal files the system pathname\n-- is what is stored internally, but as GFiles are extensible it could also be something else that\n-- corresponds to a pathname in a userspace implementation of a filesystem.\n-- \n-- GFiles make up hierarchies of directories and files that correspond to the files on a\n-- filesystem. You can move through the file system with GFile using 'fileGetParent' to get an\n-- identifier for the parent directory, 'fileGetChild' to get a child within a directory,\n-- 'fileResolveRelativePath' to resolve a relative path between two GFiles. There can be multiple\n-- hierarchies, so you may not end up at the same root if you repeatedly call 'fileGetParent' on\n-- two different files.\n-- \n-- All GFiles have a basename (get with 'fileGetBasename'. These names are byte strings that are\n-- used to identify the file on the filesystem (relative to its parent directory) and there is no\n-- guarantees that they have any particular charset encoding or even make any sense at all. If you want\n-- to use filenames in a user interface you should use the display name that you can get by requesting\n-- the GFileAttributeStandardDisplayName attribute with 'fileQueryInfo'. This is guaranteed to\n-- be in utf8 and can be used in a user interface. But always store the real basename or the GFile to\n-- use to actually access the file, because there is no way to go from a display name to the actual\n-- name.\n-- \n-- Using GFile as an identifier has the same weaknesses as using a path in that there may be multiple\n-- aliases for the same file. For instance, hard or soft links may cause two different GFiles to refer\n-- to the same file. Other possible causes for aliases are: case insensitive filesystems, short and\n-- long names on Fat\/NTFS, or bind mounts in Linux. If you want to check if two GFiles point to the\n-- same file you can query for the GFileAttributeIdFile attribute. Note that GFile does some\n-- trivial canonicalization of pathnames passed in, so that trivial differences in the path string used\n-- at creation (duplicated slashes, slash at end of path, \".\" or \"..\" path segments, etc) does not\n-- create different GFiles.\n-- \n-- Many GFile operations have both synchronous and asynchronous versions to suit your\n-- application. Asynchronous versions of synchronous functions simply have _async() appended to their\n-- function names. The asynchronous I\/O functions call a GAsyncReadyCallback which is then used to\n-- finalize the operation, producing a GAsyncResult which is then passed to the function's matching\n-- _finish() operation.\n-- \n-- Some GFile operations do not have synchronous analogs, as they may take a very long time to finish,\n-- and blocking may leave an application unusable. Notable cases include: 'fileMountMountable' to\n-- mount a mountable file. 'fileUnmountMountableWithOperation' to unmount a mountable\n-- file. 'fileEjectMountableWithOperation' to eject a mountable file.\n-- \n-- One notable feature of GFiles are entity tags, or \"etags\" for short. Entity tags are somewhat like a\n-- more abstract version of the traditional mtime, and can be used to quickly determine if the file has\n-- been modified from the version on the file system. See the HTTP 1.1 specification for HTTP Etag\n-- headers, which are a very similar concept.\n\n-- * Types.\n FileProgressCallback,\n FileReadMoreCallback,\n FileClass,\n\n-- * Enums\n File(..),\n FileQueryInfoFlags(..),\n FileCreateFlags(..),\n FileCopyFlags(..),\n FileMonitorFlags(..),\n FilesystemPreviewType(..),\n FileType(..),\n\n-- * Methods\n fileFromPath,\n fileFromURI,\n fileFromCommandlineArg,\n fileFromParseName,\n fileEqual,\n fileBasename,\n filePath,\n#if GLIB_CHECK_VERSION(2,24,0)\n fileHasParent,\n#endif\n fileURI,\n fileParseName,\n fileGetChild,\n fileGetChildForDisplayName,\n fileHasPrefix,\n fileGetRelativePath,\n fileResolveRelativePath,\n fileIsNative,\n fileHasURIScheme,\n fileURIScheme,\n fileRead,\n fileReadAsync,\n fileReadFinish,\n fileAppendTo,\n fileCreate,\n fileReplace,\n fileAppendToAsync,\n fileAppendToFinish,\n fileCreateAsync,\n fileCreateFinish,\n fileReplaceAsync,\n fileReplaceFinish,\n fileQueryInfo,\n fileQueryInfoAsync,\n fileQueryInfoFinish,\n fileQueryExists,\n#if GLIB_CHECK_VERSION(2,18,0)\n fileQueryFileType,\n#endif\n fileQueryFilesystemInfo,\n fileQueryFilesystemInfoAsync,\n fileQueryFilesystemInfoFinish,\n fileQueryDefaultHandler,\n fileFindEnclosingMount,\n fileFindEnclosingMountAsync,\n fileFindEnclosingMountFinish,\n fileEnumerateChildren,\n fileEnumerateChildrenAsync,\n fileEnumerateChildrenFinish,\n fileSetDisplayName,\n fileSetDisplayNameAsync,\n fileSetDisplayNameFinish,\n fileDelete,\n fileTrash,\n fileCopy,\n fileCopyAsync,\n fileCopyFinish,\n fileMove,\n fileMakeDirectory,\n#if GLIB_CHECK_VERSION(2,18,0)\n fileMakeDirectoryWithParents,\n#endif\n fileMakeSymbolicLink,\n fileQuerySettableAttributes,\n fileQueryWritableNamespaces\n ) where\n\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport Data.Typeable\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.UTFString\nimport System.Glib.GObject\n\nimport System.GIO.Base\n{#import System.GIO.Types#}\nimport System.GIO.File.FileAttribute\n\n{# context lib = \"gio\" prefix = \"g\" #}\n\n{# enum GFileQueryInfoFlags as FileQueryInfoFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileQueryInfoFlags\n\n{# enum GFileCreateFlags as FileCreateFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCreateFlags\n\n{# enum GFileCopyFlags as FileCopyFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCopyFlags\n\n{# enum GFileMonitorFlags as FileMonitorFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileMonitorFlags\n\n{# enum GFilesystemPreviewType as FilesystemPreviewType {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\n{# enum GFileType as FileType {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\ntype FileProgressCallback = Offset -> Offset -> IO ()\ntype CFileProgressCallback = {# type goffset #} -> {# type goffset #} -> Ptr () -> IO ()\nforeign import ccall \"wrapper\"\n makeFileProgressCallback :: CFileProgressCallback\n -> IO {# type GFileProgressCallback #}\n\nmarshalFileProgressCallback :: FileProgressCallback -> IO {# type GFileProgressCallback #}\nmarshalFileProgressCallback fileProgressCallback =\n makeFileProgressCallback cFileProgressCallback\n where cFileProgressCallback :: CFileProgressCallback\n cFileProgressCallback cCurrentNumBytes cTotalNumBytes _ = do\n fileProgressCallback (fromIntegral cCurrentNumBytes)\n (fromIntegral cTotalNumBytes)\n\ntype FileReadMoreCallback = BS.ByteString -> IO Bool\n\n-- | Constructs a GFile for a given path. This operation never fails, but the returned object might not\n-- support any I\/O operation if path is malformed.\nfileFromPath :: FilePath -> File\nfileFromPath path =\n unsafePerformIO $ withUTFString path $ \\cPath -> {# call file_new_for_path #} cPath >>= takeGObject\n\n-- | Constructs a GFile for a given URI. This operation never fails, but the returned object might not\n-- support any I\/O operation if uri is malformed or if the uri type is not supported.\nfileFromURI :: String -> File\nfileFromURI uri =\n unsafePerformIO $ withUTFString uri $ \\cURI -> {# call file_new_for_uri #} cURI >>= takeGObject\n\n-- | Creates a GFile with the given argument from the command line. The value of arg can be either a URI,\n-- an absolute path or a relative path resolved relative to the current working directory. This\n-- operation never fails, but the returned object might not support any I\/O operation if arg points to\n-- a malformed path.\nfileFromCommandlineArg :: String -> File\nfileFromCommandlineArg arg =\n unsafePerformIO $ withUTFString arg $ \\cArg -> {# call file_new_for_commandline_arg #} cArg >>= takeGObject\n\n-- | Constructs a GFile with the given 'name (i.e. something given by gFileGetParseName'. This\n-- operation never fails, but the returned object might not support any I\/O operation if the @parseName@\n-- cannot be parsed.\nfileFromParseName :: String -> File\nfileFromParseName parseName =\n unsafePerformIO $ withUTFString parseName $ \\cParseName -> {# call file_parse_name #} cParseName >>= takeGObject\n\n-- | Compare two file descriptors for equality. This test is also used to\n-- implement the '(==)' function, that is, comparing two descriptions\n-- will compare their content, not the pointers to the two structures.\n--\nfileEqual :: (FileClass file1, FileClass file2)\n => file1 -> file2 -> Bool\nfileEqual file1 file2 =\n unsafePerformIO $ liftM toBool $ {# call file_equal #} (toFile file1) (toFile file2)\n\ninstance Eq File where\n (==) = fileEqual\n\n-- | Gets the base name (the last component of the path) for a given GFile.\n-- \n-- If called for the top level of a system (such as the filesystem root or a uri like sftp:\/\/host\/) it\n-- will return a single directory separator (and on Windows, possibly a drive letter).\n-- \n-- The base name is a byte string (*not* UTF-8). It has no defined encoding or rules other than it may\n-- not contain zero bytes. If you want to use filenames in a user interface you should use the display\n-- name that you can get by requesting the GFileAttributeStandardDisplayName attribute with\n-- 'fileQueryInfo'.\n-- \n-- This call does no blocking i\/o.\nfileBasename :: FileClass file => file -> String\nfileBasename file =\n unsafePerformIO $ {# call file_get_basename #} (toFile file) >>= readUTFString\n\n-- | Gets the local pathname for GFile, if one exists.\n-- \n-- This call does no blocking i\/o.\nfilePath :: FileClass file => file -> FilePath\nfilePath file =\n unsafePerformIO $ {# call file_get_path #} (toFile file) >>= readUTFString\n\n-- | Gets the URI for the file.\n-- \n-- This call does no blocking i\/o.\nfileURI :: FileClass file => file -> String\nfileURI file =\n unsafePerformIO $ {# call file_get_uri #} (toFile file) >>= readUTFString\n\n-- | Gets the parse name of the file. A parse name is a UTF-8 string that describes the file such that\n-- one can get the GFile back using 'fileParseName'.\n-- \n-- This is generally used to show the GFile as a nice full-pathname kind of string in a user interface,\n-- like in a location entry.\n-- \n-- For local files with names that can safely be converted to UTF8 the pathname is used, otherwise the\n-- IRI is used (a form of URI that allows UTF8 characters unescaped).\n-- \n-- This call does no blocking i\/o.\nfileParseName :: FileClass file => file -> String\nfileParseName file =\n unsafePerformIO $ {# call file_get_parse_name #} (toFile file) >>= readUTFString\n\n-- | Gets the parent directory for the file. If the file represents the root directory of the file\n-- system, then 'Nothing' will be returned.\n-- \n-- This call does no blocking i\/o.\nfileParent :: FileClass file => file -> Maybe File\nfileParent file =\n unsafePerformIO $ {# call file_get_parent #} (toFile file) >>= maybePeek takeGObject\n\n#if GLIB_CHECK_VERSION(2,24,0)\n-- | Checks if file has a parent, and optionally, if it is parent.\n-- \n-- If parent is 'Nothing' then this function returns 'True' if file has any parent at all. If parent is\n-- non-'Nothing' then 'True' is only returned if file is a child of parent.\nfileHasParent :: FileClass file => file -> Maybe File -> Bool \nfileHasParent file parent = \n unsafePerformIO $ liftM toBool $\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject parent $ \\parentPtr ->\n g_file_has_parent cFile parentPtr\n where _ = {#call file_has_parent #}\n#endif\n\n-- | Gets a child of file with basename equal to name.\n-- \n-- Note that the file with that specific name might not exist, but you can still have a GFile that\n-- points to it. You can use this for instance to create that file.\n-- \n-- This call does no blocking i\/o.\nfileGetChild :: FileClass file => file -> String -> File\nfileGetChild file name =\n unsafePerformIO $\n withUTFString name $ \\cName ->\n {# call file_get_child #} (toFile file) cName >>= takeGObject\n\n-- | Gets the child of file for a given 'name (i.e. a UTF8 version of the name)'. If this function\n-- fails, it returns 'Nothing' and error will be set. This is very useful when constructing a GFile for a\n-- new file and the user entered the filename in the user interface, for instance when you select a\n-- directory and type a filename in the file selector.\n-- \n-- This call does no blocking i\/o.\nfileGetChildForDisplayName :: FileClass file => file -> String -> Maybe File\nfileGetChildForDisplayName file displayName =\n unsafePerformIO $\n withUTFString displayName $ \\cDisplayName ->\n propagateGError ({# call file_get_child_for_display_name #} (toFile file) cDisplayName) >>=\n maybePeek takeGObject\n\n-- | Checks whether file has the prefix specified by prefix. In other word, if the names of inital\n-- elements of files pathname match prefix. Only full pathname elements are matched, so a path like\n-- \/foo is not considered a prefix of \/foobar, only of \/ foo\/bar.\n-- \n-- This call does no i\/o, as it works purely on names. As such it can sometimes return 'False' even if\n-- file is inside a prefix (from a filesystem point of view), because the prefix of file is an alias of\n-- prefix.\nfileHasPrefix :: (FileClass file1, FileClass file2) => file1 -> file2 -> Bool\nfileHasPrefix file1 file2 =\n unsafePerformIO $\n liftM toBool $ {# call file_has_prefix #} (toFile file1) (toFile file2)\n\n-- | Gets the path for descendant relative to parent.\n-- \n-- This call does no blocking i\/o.\nfileGetRelativePath :: (FileClass file1, FileClass file2) => file1 -> file2 -> Maybe FilePath\nfileGetRelativePath file1 file2 =\n unsafePerformIO $\n {# call file_get_relative_path #} (toFile file1) (toFile file2) >>=\n maybePeek readUTFString\n\n-- | Resolves a relative path for file to an absolute path.\n-- \n-- This call does no blocking i\/o.\nfileResolveRelativePath :: FileClass file => file -> FilePath -> Maybe File\nfileResolveRelativePath file relativePath =\n unsafePerformIO $\n withUTFString relativePath $ \\cRelativePath ->\n {# call file_resolve_relative_path #} (toFile file) cRelativePath >>=\n maybePeek takeGObject\n\n-- | Checks to see if a file is native to the platform.\n-- \n-- A native file s one expressed in the platform-native filename format, e.g. \\\"C:\\\\Windows\\\" or\n-- \\\"\/usr\/bin\/\\\". This does not mean the file is local, as it might be on a locally mounted remote\n-- filesystem.\n-- \n-- On some systems non-native files may be available using the native filesystem via a userspace\n-- filesystem (FUSE), in these cases this call will return @False@, but 'fileGetPath' will still\n-- return a native path.\n-- \n-- This call does no blocking i\/o.\nfileIsNative :: FileClass file => file -> Bool\nfileIsNative =\n unsafePerformIO .\n liftM toBool . {# call file_is_native #} . toFile\n\n-- | Checks to see if a 'GFile' has a given URI scheme.\n-- \n-- This call does no blocking i\/o.\nfileHasURIScheme :: FileClass file => file -> String -> Bool\nfileHasURIScheme file uriScheme =\n unsafePerformIO $\n withUTFString uriScheme $ \\cURIScheme ->\n liftM toBool $ {# call file_has_uri_scheme #} (toFile file) cURIScheme\n\n-- | Gets the URI scheme for a GFile. RFC 3986 decodes the scheme as:\n-- \n-- URI = scheme \":\" hier-part [ \"?\" query ] [ \"#\" fragment ]\n-- \n-- Common schemes include \"file\", \"http\", \"ftp\", etc.\n-- \n-- This call does no blocking i\/o.\nfileURIScheme :: FileClass file => file -> String\nfileURIScheme file =\n unsafePerformIO $ {# call file_get_uri_scheme #} (toFile file) >>= readUTFString\n\n-- | Opens a file for reading. The result is a GFileInputStream that can be used to read the contents of\n-- the file.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If the file does not exist, the GIoErrorNotFound error will be returned. If the file is a\n-- directory, the GIoErrorIsDirectory error will be returned. Other errors are possible too, and\n-- depend on what kind of filesystem the file is on.\nfileRead :: FileClass file => file -> Maybe Cancellable -> IO FileInputStream\nfileRead file (Just cancellable) = constructNewGObject mkFileInputStream $\n propagateGError $ {# call file_read #} (toFile file) cancellable\n\n-- | Asynchronously opens file for reading.\n-- \n-- For more details, see 'fileRead' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileReadFinish' to\n-- get the result of the operation.\nfileReadAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReadAsync file ioPriority mbCancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject mbCancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_read_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_read_async #}\n\n-- | Finishes an asynchronous file read operation started with 'fileReadAsync'.\nfileReadFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInputStream\nfileReadFinish file asyncResult =\n propagateGError ({# call file_read_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Gets an output stream for appending data to the file. If the file doesn't already exist it is\n-- created.\n-- \n-- By default files created are generally readable by everyone, but if you pass GFileCreatePrivate\n-- in flags the file will be made readable only to the current user, to the level that is supported on\n-- the target filesystem.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- Some file systems don't allow all file names, and may return an GIoErrorInvalidFilename\n-- error. If the file is a directory the GIoErrorIsDirectory error will be returned. Other errors\n-- are possible too, and depend on what kind of filesystem the file is on.\nfileAppendTo :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileAppendTo file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_append_to cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_append_to #}\n\n-- | Creates a new file and returns an output stream for writing to it. The file must not already exist.\n-- \n-- By default files created are generally readable by everyone, but if you pass GFileCreatePrivate\n-- in flags the file will be made readable only to the current user, to the level that is supported on\n-- the target filesystem.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If a file or directory with this name already exists the GIoErrorExists error will be\n-- returned. Some file systems don't allow all file names, and may return an\n-- GIoErrorInvalidFilename error, and if the name is to long GIoErrorFilenameTooLong will be\n-- returned. Other errors are possible too, and depend on what kind of filesystem the file is on.\nfileCreate :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileCreate file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_create cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_create #}\n\n-- | Returns an output stream for overwriting the file, possibly creating a backup copy of the file\n-- first. If the file doesn't exist, it will be created.\n-- \n-- This will try to replace the file in the safest way possible so that any errors during the writing\n-- will not affect an already existing copy of the file. For instance, for local files it may write to\n-- a temporary file and then atomically rename over the destination when the stream is closed.\n-- \n-- By default files created are generally readable by everyone, but if you pass GFileCreatePrivate\n-- in flags the file will be made readable only to the current user, to the level that is supported on\n-- the target filesystem.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If you pass in a non-'Nothing' etag value, then this value is compared to the current entity tag of the\n-- file, and if they differ an GIoErrorWrongEtag error is returned. This generally means that the\n-- file has been changed since you last read it. You can get the new etag from\n-- 'fileOutputStreamGetEtag' after you've finished writing and closed the GFileOutputStream.\n-- When you load a new file you can use 'fileInputStreamQueryInfo' to get the etag of the file.\n-- \n-- If @makeBackup@ is 'True', this function will attempt to make a backup of the current file before\n-- overwriting it. If this fails a GIoErrorCantCreateBackup error will be returned. If you want to\n-- replace anyway, try again with @makeBackup@ set to 'False'.\n-- \n-- If the file is a directory the GIoErrorIsDirectory error will be returned, and if the file is\n-- some other form of non-regular file then a GIoErrorNotRegularFile error will be returned. Some\n-- file systems don't allow all file names, and may return an GIoErrorInvalidFilename error, and if\n-- the name is to long GIoErrorFilenameTooLong will be returned. Other errors are possible too,\n-- and depend on what kind of filesystem the file is on.\nfileReplace :: FileClass file\n => file\n -> Maybe String\n -> Bool\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileReplace file etag makeBackup flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_replace cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_replace #}\n\n-- | Asynchronously opens file for appending.\n-- \n-- For more details, see 'fileAppendTo' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileAppendToFinish'\n-- to get the result of the operation.\nfileAppendToAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileAppendToAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_append_to_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_append_to_async #}\n\n-- | Finishes an asynchronous file append operation started with 'fileAppendToAsync'.\nfileAppendToFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileAppendToFinish file asyncResult =\n propagateGError ({# call file_append_to_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Asynchronously creates a new file and returns an output stream for writing to it. The file must not\n-- already exist.\n-- \n-- For more details, see 'fileCreate' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileCreateFinish' to\n-- get the result of the operation.\nfileCreateAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileCreateAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_create_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_create_async #}\n\n-- | Finishes an asynchronous file create operation started with 'fileCreateAsync'.\nfileCreateFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileCreateFinish file asyncResult =\n propagateGError ({# call file_create_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Asynchronously overwrites the file, replacing the contents, possibly creating a backup copy of the\n-- file first.\n-- \n-- For more details, see 'fileReplace' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileReplaceFinish'\n-- to get the result of the operation.\nfileReplaceAsync :: FileClass file\n => file\n -> String\n -> Bool\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReplaceAsync file etag makeBackup flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_replace_async cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_replace_async #}\n\n-- | Finishes an asynchronous file replace operation started with 'fileReplaceAsync'.\nfileReplaceFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileReplaceFinish file asyncResult =\n propagateGError ({# call file_replace_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Gets the requested information about specified file. The result is a 'GFileInfo' object that contains\n-- key-value attributes (such as the type or size of the file).\n-- \n-- The attribute value is a string that specifies the file attributes that should be gathered. It is\n-- not an error if it's not possible to read a particular requested attribute from a file - it just\n-- won't be set. attribute should be a comma-separated list of attribute or attribute wildcards. The\n-- wildcard \\\"*\\\" means all attributes, and a wildcard like \\\"standard::*\\\" means all attributes in the\n-- standard namespace. An example attribute query be \\\"standard::*,'user'\\\". The standard attributes\n-- are available as defines, like 'GFileAttributeStandardName'.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error 'GIoErrorCancelled' will be\n-- returned.\n-- \n-- For symlinks, normally the information about the target of the symlink is returned, rather than\n-- information about the symlink itself. However if you pass 'GFileQueryInfoNofollowSymlinks' in\n-- flags the information about the symlink itself will be returned. Also, for symlinks that point to\n-- non-existing files the information about the symlink itself will be returned.\n-- \n-- If the file does not exist, the 'GIoErrorNotFound' error will be returned. Other errors are\n-- possible too, and depend on what kind of filesystem the file is on.\nfileQueryInfo :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryInfo file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_info cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_query_info #}\n\n-- | Asynchronously gets the requested information about specified file. The\n-- result is a 'GFileInfo' object that contains key-value attributes (such as\n-- type or size for the file).\n-- \n-- For more details, see 'fileQueryInfo' which is the synchronous version of\n-- this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileQueryInfoFinish' to get the result of the operation.\nfileQueryInfoAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryInfoAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_info_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_info_async #}\n\n-- | Finishes an asynchronous file info query. See 'fileQueryInfoAsync'.\nfileQueryInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryInfoFinish file asyncResult =\n propagateGError ({#call file_query_info_finish #} (toFile file) asyncResult) >>= takeGObject\n\n-- | Utility function to check if a particular file exists. This is implemented using 'fileQueryInfo'\n-- and as such does blocking I\/O.\n-- \n-- Note that in many cases it is racy to first check for file existence and then execute something\n-- based on the outcome of that, because the file might have been created or removed in between the\n-- operations. The general approach to handling that is to not check, but just do the operation and\n-- handle the errors as they come.\n-- \n-- As an example of race-free checking, take the case of reading a file, and if it doesn't exist,\n-- creating it. There are two racy versions: read it, and on error create it; and: check if it exists,\n-- if not create it. These can both result in two processes creating the file (with perhaps a partially\n-- written file as the result). The correct approach is to always try to create the file with\n-- 'fileCreate' which will either atomically create the file or fail with a GIoErrorExists error.\n-- \n-- However, in many cases an existence check is useful in a user interface, for instance to make a menu\n-- item sensitive\/ insensitive, so that you don't have to fool users that something is possible and\n-- then just show and error dialog. If you do this, you should make sure to also handle the errors that\n-- can happen due to races when you execute the operation.\nfileQueryExists :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Bool\nfileQueryExists file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n liftM toBool $ g_file_query_exists cFile cCancellable\n where _ = {# call file_query_exists #}\n\n#if GLIB_CHECK_VERSION(2,18,0)\n-- | Utility function to inspect the GFileType of a file. This is implemented using 'fileQueryInfo'\n-- and as such does blocking I\/O.\n-- \n-- The primary use case of this method is to check if a file is a regular file, directory, or symlink.\nfileQueryFileType :: FileClass file \n => file \n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileType\nfileQueryFileType file flags cancellable = \n liftM (toEnum . fromIntegral) $\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n (g_file_query_file_type cFile (cFromFlags flags) cCancellable)\n where _ = {# call file_query_file_type #}\n#endif\n\n-- | Similar to 'fileQueryInfo', but obtains information about the filesystem the file is on, rather\n-- than the file itself. For instance the amount of space available and the type of the filesystem.\n-- \n-- The attribute value is a string that specifies the file attributes that should be gathered. It is\n-- not an error if it's not possible to read a particular requested attribute from a file - it just\n-- won't be set. attribute should be a comma-separated list of attribute or attribute wildcards. The\n-- wildcard \"*\" means all attributes, and a wildcard like \"fs:*\" means all attributes in the fs\n-- namespace. The standard namespace for filesystem attributes is \"fs\". Common attributes of interest\n-- are 'FILEAttributeFilesystemSize (The Total Size Of The Filesystem In Bytes)',\n-- 'FILEAttributeFilesystemFree (Number Of Bytes Available)', and GFileAttributeFilesystemType\n-- (type of the filesystem).\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If the file does not exist, the GIoErrorNotFound error will be returned. Other errors are\n-- possible too, and depend on what kind of filesystem the file is on.\nfileQueryFilesystemInfo :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryFilesystemInfo file attributes cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_filesystem_info cFile cAttributes cCancellable) >>=\n takeGObject\n where _ = {# call file_query_filesystem_info #}\n\n-- | Asynchronously gets the requested information about the filesystem that the specified file is\n-- on. The result is a GFileInfo object that contains key-value attributes (such as type or size for\n-- the file).\n-- \n-- For more details, see 'fileQueryFilesystemInfo' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileQueryInfoFinish' to get the result of the operation.\nfileQueryFilesystemInfoAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryFilesystemInfoAsync file attributes ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_filesystem_info_async cFile\n cAttributes\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_filesystem_info_async #}\n\n-- | Finishes an asynchronous filesystem info query. See 'fileQueryFilesystemInfoAsync'.\nfileQueryFilesystemInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryFilesystemInfoFinish file asyncResult =\n propagateGError ({# call file_query_filesystem_info_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\n-- | Returns the GAppInfo that is registered as the default application to handle the file specified by\n-- file.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileQueryDefaultHandler :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO AppInfo\nfileQueryDefaultHandler file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_default_handler cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_query_default_handler #}\n\n-- | Gets a GMount for the GFile.\n-- \n-- If the GFileIface for file does not have a mount (e.g. possibly a remote share), error will be set\n-- to GIoErrorNotFound and 'Nothing' will be returned.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileFindEnclosingMount :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Mount\nfileFindEnclosingMount file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_find_enclosing_mount cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_find_enclosing_mount #}\n\n-- | Asynchronously gets the mount for the file.\n-- \n-- For more details, see 'fileFindEnclosingMount' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileFindEnclosingMountFinish' to get the result of the operation.\nfileFindEnclosingMountAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileFindEnclosingMountAsync file ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_find_enclosing_mount_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_find_enclosing_mount_async #}\n\n-- | Finishes an asynchronous find mount request. See 'fileFindEnclosingMountAsync'.\nfileFindEnclosingMountFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Mount\nfileFindEnclosingMountFinish file asyncResult =\n propagateGError ({# call file_find_enclosing_mount_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\n-- | Gets the requested information about the files in a directory. The result is a 'GFileEnumerator'\n-- object that will give out 'GFileInfo' objects for all the files in the directory.\n-- \n-- The attribute value is a string that specifies the file attributes that should be gathered. It is\n-- not an error if it's not possible to read a particular requested attribute from a file - it just\n-- won't be set. attribute should be a comma-separated list of attribute or attribute wildcards. The\n-- wildcard \\\"*\\\" means all attributes, and a wildcard like \\\"standard::*\\\" means all attributes in the\n-- standard namespace. An example attribute query be \\\"standard::*,'user'\\\". The standard attributes\n-- are available as defines, like 'GFileAttributeStandardName'.\n-- \n-- If cancellable is not @Nothing@, then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error 'GIoErrorCancelled' will be\n-- returned.\n-- \n-- If the file does not exist, the 'GIoErrorNotFound' error will be returned. If the file is not a\n-- directory, the 'GFileErrorNotdir' error will be returned. Other errors are possible too.\nfileEnumerateChildren :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileEnumerator\nfileEnumerateChildren file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_enumerate_children cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_enumerate_children #}\n\n-- | Asynchronously gets the requested information about the files in a directory. The result is a\n-- GFileEnumerator object that will give out GFileInfo objects for all the files in the directory.\n-- \n-- For more details, see 'fileEnumerateChildren' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileEnumerateChildrenFinish' to get the result of the operation.\nfileEnumerateChildrenAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileEnumerateChildrenAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_enumerate_children_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_enumerate_children_async #}\n\n-- | Finishes an async enumerate children operation. See 'fileEnumerateChildrenAsync'.\nfileEnumerateChildrenFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileEnumerator\nfileEnumerateChildrenFinish file asyncResult =\n propagateGError ({# call file_enumerate_children_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\n-- | Renames file to the specified display name.\n-- \n-- The display name is converted from UTF8 to the correct encoding for the target filesystem if\n-- possible and the file is renamed to this.\n-- \n-- If you want to implement a rename operation in the user interface the edit name\n-- (GFileAttributeStandardEditName) should be used as the initial value in the rename widget, and\n-- then the result after editing should be passed to 'fileSetDisplayName'.\n-- \n-- On success the resulting converted filename is returned.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileSetDisplayName :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO File\nfileSetDisplayName file displayName cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_set_display_name cFile cDisplayName cCancellable) >>=\n takeGObject\n where _ = {# call file_set_display_name #}\n\n-- | Asynchronously sets the display name for a given GFile.\n-- \n-- For more details, see 'fileSetDisplayName' which is the synchronous version of this call.\n-- \n-- When the operation is finished, callback will be called. You can then call\n-- 'fileSetDisplayNameFinish' to get the result of the operation.\nfileSetDisplayNameAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileSetDisplayNameAsync file displayName ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_set_display_name_async cFile\n cDisplayName\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_set_display_name_async #}\n\n-- | Finishes setting a display name started with 'fileSetDisplayNameAsync'.\nfileSetDisplayNameFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO File\nfileSetDisplayNameFinish file asyncResult =\n propagateGError ({# call file_set_display_name_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\n-- | Deletes a file. If the file is a directory, it will only be deleted if it is empty.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileDelete :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileDelete file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_delete cFile cCancellable) >> return ()\n where _ = {# call file_delete #}\n\n-- | Sends file to the \"Trashcan\", if possible. This is similar to deleting it, but the user can recover\n-- it before emptying the trashcan. Not all file systems support trashing, so this call can return the\n-- GIoErrorNotSupported error.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileTrash :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileTrash file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_trash cFile cCancellable) >> return ()\n where _ = {# call file_trash #}\n\n-- | Copies the file source to the location specified by destination. Can not handle recursive copies of\n-- directories.\n-- \n-- If the flag GFileCopyOverwrite is specified an already existing destination file is overwritten.\n-- \n-- If the flag GFileCopyNofollowSymlinks is specified then symlinks will be copied as symlinks,\n-- otherwise the target of the source symlink will be copied.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If @progressCallback@ is not 'Nothing', then the operation can be monitored by setting this to a\n-- GFileProgressCallback function. @progressCallbackData@ will be passed to this function. It is\n-- guaranteed that this callback will be called after all data has been transferred with the total\n-- number of bytes copied during the operation.\n-- \n-- If the source file does not exist then the GIoErrorNotFound error is returned, independent on\n-- the status of the destination.\n-- \n-- If GFileCopyOverwrite is not specified and the target exists, then the error GIoErrorExists is\n-- returned.\n-- \n-- If trying to overwrite a file over a directory the GIoErrorIsDirectory error is returned. If\n-- trying to overwrite a directory with a directory the GIoErrorWouldMerge error is returned.\n-- \n-- If the source is a directory and the target does not exist, or GFileCopyOverwrite is specified\n-- and the target is a file, then the GIoErrorWouldRecurse error is returned.\n-- \n-- If you are interested in copying the GFile object itself (not the on-disk file), see 'fileDup'.\nfileCopy :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileCopy source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_copy cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n when (cProgressCallback \/= nullFunPtr) $\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_copy #}\n\n-- | Copies the file source to the location specified by destination asynchronously. For details of the\n-- behaviour, see 'fileCopy'.\n-- \n-- If @progressCallback@ is not 'Nothing', then that function that will be called just like in 'fileCopy',\n-- however the callback will run in the main loop, not in the thread that is doing the I\/O operation.\n-- \n-- When the operation is finished, callback will be called. You can then call 'fileCopyFinish' to\n-- get the result of the operation.\nfileCopyAsync :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Int\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> AsyncReadyCallback\n -> IO ()\nfileCopyAsync source destination flags ioPriority cancellable progressCallback callback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n cCallback <- marshalAsyncReadyCallback $ \\sourceObject res -> do\n when (cProgressCallback \/= nullFunPtr) $\n freeHaskellFunPtr cProgressCallback\n callback sourceObject res\n g_file_copy_async cSource\n cDestination\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cProgressCallback\n nullPtr\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_copy_async #}\n\n-- | Finishes copying the file started with 'fileCopyAsync'.\nfileCopyFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Bool\nfileCopyFinish file asyncResult =\n liftM toBool $ propagateGError ({# call file_copy_finish #} (toFile file) asyncResult)\n\n-- | Tries to move the file or directory source to the location specified by destination. If native move\n-- operations are supported then this is used, otherwise a copy + delete fallback is used. The native\n-- implementation may support moving directories (for instance on moves inside the same filesystem),\n-- but the fallback code does not.\n-- \n-- If the flag GFileCopyOverwrite is specified an already existing destination file is overwritten.\n-- \n-- If the flag GFileCopyNofollowSymlinks is specified then symlinks will be copied as symlinks,\n-- otherwise the target of the source symlink will be copied.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\n-- \n-- If @progressCallback@ is not 'Nothing', then the operation can be monitored by setting this to a\n-- GFileProgressCallback function. @progressCallbackData@ will be passed to this function. It is\n-- guaranteed that this callback will be called after all data has been transferred with the total\n-- number of bytes copied during the operation.\n-- \n-- If the source file does not exist then the GIoErrorNotFound error is returned, independent on\n-- the status of the destination.\n-- \n-- If GFileCopyOverwrite is not specified and the target exists, then the error GIoErrorExists is\n-- returned.\n-- \n-- If trying to overwrite a file over a directory the GIoErrorIsDirectory error is returned. If\n-- trying to overwrite a directory with a directory the GIoErrorWouldMerge error is returned.\n-- \n-- If the source is a directory and the target does not exist, or GFileCopyOverwrite is specified\n-- and the target is a file, then the GIoErrorWouldRecurse error may be returned (if the native\n-- move operation isn't available).\nfileMove :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileMove source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_move cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n when (cProgressCallback \/= nullFunPtr) $\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_move #}\n\n-- | Creates a directory. Note that this will only create a child directory of the immediate parent\n-- directory of the path or URI given by the GFile. To recursively create directories, see\n-- 'fileMakeDirectoryWithParents'. This function will fail if the parent directory does not\n-- exist, setting error to GIoErrorNotFound. If the file system doesn't support creating\n-- directories, this function will fail, setting error to GIoErrorNotSupported.\n-- \n-- For a local GFile the newly created directory will have the default (current) ownership and\n-- permissions of the current process.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileMakeDirectory :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectory file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory cFile cCancellable\n return ()\n where _ = {# call file_make_directory #}\n\n#if GLIB_CHECK_VERSION(2,18,0)\n-- | Creates a directory and any parent directories that may not exist similar to 'mkdir -p'. If the file\n-- system does not support creating directories, this function will fail, setting error to\n-- GIoErrorNotSupported.\n-- \n-- For a local GFile the newly created directories will have the default (current) ownership and\n-- permissions of the current process.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileMakeDirectoryWithParents :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectoryWithParents file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory_with_parents cFile cCancellable\n return ()\n where _ = {# call file_make_directory_with_parents #}\n#endif\n\n-- | Creates a symbolic link.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileMakeSymbolicLink :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO ()\nfileMakeSymbolicLink file symlinkValue cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString symlinkValue $ \\cSymlinkValue ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_symbolic_link cFile cSymlinkValue cCancellable\n return ()\n where _ = {# call file_make_symbolic_link #}\n\n{# pointer *FileAttributeInfoList newtype #}\ntakeFileAttributeInfoList :: Ptr FileAttributeInfoList\n -> IO [FileAttributeInfo]\ntakeFileAttributeInfoList ptr =\n do cInfos <- liftM castPtr $ {# get FileAttributeInfoList->infos #} ptr\n cNInfos <- {# get FileAttributeInfoList->n_infos #} ptr\n infos <- peekArray (fromIntegral cNInfos) cInfos\n g_file_attribute_info_list_unref ptr\n return infos\n where _ = {# call file_attribute_info_list_unref #}\n\n-- | Obtain the list of settable attributes for the file.\n-- \n-- Returns the type and full attribute name of all the attributes that can be set on this file. This\n-- doesn't mean setting it will always succeed though, you might get an access failure, or some\n-- specific file may not support a specific attribute.\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileQuerySettableAttributes :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO [FileAttributeInfo]\nfileQuerySettableAttributes file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n ptr <- propagateGError $ g_file_query_settable_attributes cFile cCancellable\n infos <- takeFileAttributeInfoList ptr\n return infos\n where _ = {# call file_query_settable_attributes #}\n\n-- | Obtain the list of attribute namespaces where new attributes can be created by a user. An example of\n-- this is extended attributes (in the \"xattr\" namespace).\n-- \n-- If cancellable is not 'Nothing', then the operation can be cancelled by triggering the cancellable object\n-- from another thread. If the operation was cancelled, the error GIoErrorCancelled will be\n-- returned.\nfileQueryWritableNamespaces :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO [FileAttributeInfo]\nfileQueryWritableNamespaces file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n ptr <- propagateGError $ g_file_query_writable_namespaces cFile cCancellable\n infos <- takeFileAttributeInfoList ptr\n return infos\n where _ = {# call file_query_writable_namespaces #}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"ee7cdb7fb2508328ede995e21197dc401a894c06","subject":"safe prececende for GComplex constructor as for Comples","message":"safe prececende for GComplex constructor as for Comples\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/OSGeo\/GDAL\/Internal.chs","new_file":"src\/OSGeo\/GDAL\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nmodule OSGeo.GDAL.Internal (\n HasDataset\n , HasBand\n , HasWritebaleBand\n , HasDatatype\n , Datatype (..)\n , GDALException\n , isGDALException\n , Geotransform (..)\n , IOVector\n , DriverOptions\n , MajorObject\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Driver\n , ColorTable\n , RasterAttributeTable\n , GComplex (..)\n\n , setQuietErrorHandler\n , unDataset\n , unBand\n\n , withAllDriversRegistered\n , registerAllDrivers\n , destroyDriverManager\n , driverByName\n , create\n , create'\n , createMem\n , flushCache\n , openReadOnly\n , openReadWrite\n , createCopy\n\n , datatypeSize\n , datatypeByName\n , datatypeUnion\n , datatypeIsComplex\n\n , datasetProjection\n , setDatasetProjection\n , datasetGeotransform\n , setDatasetGeotransform\n , datasetBandCount\n\n , withBand\n , bandDatatype\n , bandBlockSize\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , readBand\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception (bracket, throw, Exception(..), SomeException,\n finally)\nimport Control.Monad (liftM, foldM)\n\nimport Data.Int (Int16, Int32)\nimport qualified Data.Complex as Complex\nimport Data.Maybe (isJust)\nimport Data.Typeable (Typeable, typeOf)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector, unsafeFromForeignPtr0, unsafeToForeignPtr0)\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (ForeignPtr, withForeignPtr, newForeignPtr\n ,mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport OSGeo.Util\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\ndata GDALException = GDALException Error String\n deriving (Show, Typeable)\n\ninstance Exception GDALException\n\nisGDALException :: SomeException -> Bool\nisGDALException e = isJust (fromException e :: Maybe GDALException)\n\n{# enum CPLErr as Error {upcaseFirstLetter} deriving (Eq,Show) #}\n\n\ntype ErrorHandler = CInt -> CInt -> CString -> IO ()\n\nforeign import ccall \"cpl_error.h &CPLQuietErrorHandler\"\n c_quietErrorHandler :: FunPtr ErrorHandler\n\nforeign import ccall \"cpl_error.h CPLSetErrorHandler\"\n c_setErrorHandler :: FunPtr ErrorHandler -> IO (FunPtr ErrorHandler)\n\nsetQuietErrorHandler :: IO ()\nsetQuietErrorHandler = setErrorHandler c_quietErrorHandler\n\nsetErrorHandler :: FunPtr ErrorHandler -> IO ()\nsetErrorHandler h = c_setErrorHandler h >>= (\\_->return ())\n\n\nthrowIfError :: String -> IO CInt -> IO ()\nthrowIfError msg act = do\n e <- liftM toEnumC act\n case e of\n CE_None -> return ()\n e' -> throw $ GDALException e' msg\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\ninstance Show Datatype where\n show = getDatatypeName\n\n{# fun pure unsafe GDALGetDataTypeSize as datatypeSize\n { fromEnumC `Datatype' } -> `Int' #}\n\n{# fun pure unsafe GDALDataTypeIsComplex as datatypeIsComplex\n { fromEnumC `Datatype' } -> `Bool' #}\n\n{# fun pure unsafe GDALGetDataTypeName as getDatatypeName\n { fromEnumC `Datatype' } -> `String' #}\n\n{# fun pure unsafe GDALGetDataTypeByName as datatypeByName\n { `String' } -> `Datatype' toEnumC #}\n\n{# fun pure unsafe GDALDataTypeUnion as datatypeUnion\n { fromEnumC `Datatype', fromEnumC `Datatype' } -> `Datatype' toEnumC #}\n\n\n{# enum GDALAccess as Access {upcaseFirstLetter} deriving (Eq, Show) #}\n\n{# enum GDALRWFlag as RwFlag {upcaseFirstLetter} deriving (Eq, Show) #}\n\n{#pointer GDALMajorObjectH as MajorObject newtype#}\n{#pointer GDALDatasetH as Dataset foreign newtype nocode#}\n\ndata ReadOnly\ndata ReadWrite\nnewtype (Dataset a t) = Dataset (ForeignPtr (Dataset a t), Mutex)\n\nunDataset (Dataset (d, _)) = d\n\ntype RODataset = Dataset ReadOnly\ntype RWDataset = Dataset ReadWrite\nwithDataset, withDataset' :: (Dataset a t) -> (Ptr (Dataset a t) -> IO b) -> IO b\nwithDataset ds@(Dataset (_, m)) fun = withMutex m $ withDataset' ds fun\n\nwithDataset' (Dataset (fptr,_)) = withForeignPtr fptr\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band a t) = Band (Ptr ((Band a t)))\n\nunBand (Band b) = b\n\ntype ROBand = Band ReadOnly\ntype RWBand = Band ReadWrite\n\n\n{#pointer GDALDriverH as Driver newtype#}\n{#pointer GDALColorTableH as ColorTable newtype#}\n{#pointer GDALRasterAttributeTableH as RasterAttributeTable newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\nwithAllDriversRegistered act\n = registerAllDrivers >> finally act destroyDriverManager\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `Driver' id #}\n\ndriverByName :: String -> IO Driver\ndriverByName s = do\n driver@(Driver ptr) <- c_driverByName s\n if ptr==nullPtr\n then throw $ GDALException CE_Failure \"failed to load driver\"\n else return driver\n\ntype DriverOptions = [(String,String)]\n\nclass ( HasDatatype t\n , a ~ ReadWrite\n , d ~ Dataset,\n HasWritebaleBand Band ReadWrite t)\n => HasDataset d a t where\n create :: String -> String -> Int -> Int -> Int -> DriverOptions\n -> IO (d a t)\n create drv path nx ny bands options = do\n d <- driverByName drv\n create' d path nx ny bands (datatype (undefined :: t)) options\n\ncreate' :: Driver -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO (Dataset ReadWrite t)\ncreate' drv path nx ny bands dtype options = withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC dtype\n withOptionList options $ \\opts ->\n create_ drv path' nx' ny' bands' dtype' opts >>= newDatasetHandle\n\nwithOptionList ::\n [(String, String)] -> (Ptr CString -> IO c) -> IO c\nwithOptionList opts = bracket (toOptionList opts) freeOptionList\n where toOptionList = foldM folder nullPtr\n folder acc (k,v) = withCString k $ \\k' -> withCString v $ \\v' ->\n {#call unsafe CSLSetNameValue as ^#} acc k' v'\n freeOptionList = {#call unsafe CSLDestroy as ^#} . castPtr\n\ninstance HasDataset Dataset ReadWrite Word8 where\ninstance HasDataset Dataset ReadWrite Int16 where\ninstance HasDataset Dataset ReadWrite Int32 where\ninstance HasDataset Dataset ReadWrite Word16 where\ninstance HasDataset Dataset ReadWrite Word32 where\ninstance HasDataset Dataset ReadWrite Float where\ninstance HasDataset Dataset ReadWrite Double where\ninstance HasDataset Dataset ReadWrite (GComplex Int16) where\ninstance HasDataset Dataset ReadWrite (GComplex Int32) where\ninstance HasDataset Dataset ReadWrite (GComplex Float) where\ninstance HasDataset Dataset ReadWrite (GComplex Double) where\n\n\nforeign import ccall safe \"gdal.h GDALCreate\" create_\n :: Driver\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset t))\n\nopenReadOnly :: String -> IO (RODataset t)\nopenReadOnly p = withCString p openIt\n where openIt p' = open_ p' (fromEnumC GA_ReadOnly) >>= newDatasetHandle\n\nopenReadWrite :: String -> IO (RWDataset t)\nopenReadWrite p = withCString p openIt\n where openIt p' = open_ p' (fromEnumC GA_Update) >>= newDatasetHandle\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset a t))\n\n\ncreateCopy' ::\n Driver -> String -> (Dataset a t) -> Bool -> DriverOptions\n -> ProgressFun -> IO (RWDataset t)\ncreateCopy' driver path dataset strict options progressFun\n = withCString path $ \\p ->\n withDataset dataset $ \\ds ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n createCopy_ driver p ds s o pFunc (castPtr nullPtr)\n >>= newDatasetHandle\n\n\ncreateCopy ::\n String -> String -> (Dataset a t) -> Bool -> DriverOptions\n -> IO (RWDataset t)\ncreateCopy driver path dataset strict options = do\n d <- driverByName driver\n createCopy' d path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" createCopy_\n :: Driver\n -> Ptr CChar\n -> Ptr (Dataset a t)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset t))\n\n\nwithProgressFun :: forall c.\n ProgressFun -> (FunPtr ProgressFun -> IO c) -> IO c\nwithProgressFun = withCCallback wrapProgressFun\n\nwithCCallback :: forall c t a.\n (t -> IO (FunPtr a)) -> t -> (FunPtr a -> IO c) -> IO c\nwithCCallback w f = bracket (w f) freeHaskellFunPtr\n\ntype ProgressFun = CDouble -> Ptr CChar -> Ptr () -> IO CInt\n\nforeign import ccall \"wrapper\"\n wrapProgressFun :: ProgressFun -> IO (FunPtr ProgressFun)\n\n\nnewDatasetHandle :: Ptr (Dataset a t) -> IO (Dataset a t)\nnewDatasetHandle p =\n if p==nullPtr\n then throw $ GDALException CE_Failure \"Could not create dataset\"\n else do fp <- newForeignPtr closeDataset p\n mutex <- newMutex\n return $ Dataset (fp, mutex)\n\nforeign import ccall \"gdal.h &GDALClose\"\n closeDataset :: FunPtr (Ptr (Dataset a t) -> IO ())\n\ncreateMem:: HasDataset d a t\n => Int -> Int -> Int -> DriverOptions -> IO (d a t)\ncreateMem = create \"MEM\" \"\"\n\nflushCache :: forall a t. Dataset a t -> IO ()\nflushCache d = withDataset d flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: Ptr (Dataset a t) -> IO ()\n\n\ndatasetProjection :: Dataset a t -> IO String\ndatasetProjection d = withDataset d $ \\d' -> do\n p <- getProjection_ d'\n peekCString p\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset a t) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset t) -> String -> IO ()\nsetDatasetProjection d p = throwIfError \"could not set projection\" f\n where f = withDataset d $ \\d' -> withCString p $ \\p' -> setProjection' d' p'\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset a t) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset a t -> IO Geotransform\ndatasetGeotransform ds = withDataset' ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n throwIfError \"could not get geotransform\" $ getGeoTransform dPtr a\n Geotransform <$> liftM realToFrac (peekElemOff a 0)\n <*> liftM realToFrac (peekElemOff a 1)\n <*> liftM realToFrac (peekElemOff a 2)\n <*> liftM realToFrac (peekElemOff a 3)\n <*> liftM realToFrac (peekElemOff a 4)\n <*> liftM realToFrac (peekElemOff a 5)\n\nforeign import ccall unsafe \"gdal.h GDALGetGeoTransform\" getGeoTransform\n :: Ptr (Dataset a t) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset t) -> Geotransform -> IO ()\nsetDatasetGeotransform ds gt = withDataset ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n let (Geotransform g0 g1 g2 g3 g4 g5) = gt\n pokeElemOff a 0 (realToFrac g0)\n pokeElemOff a 1 (realToFrac g1)\n pokeElemOff a 2 (realToFrac g2)\n pokeElemOff a 3 (realToFrac g3)\n pokeElemOff a 4 (realToFrac g4)\n pokeElemOff a 5 (realToFrac g5)\n throwIfError \"could not set geotransform\" $ setGeoTransform dPtr a\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset a t) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset a t -> IO (Int)\ndatasetBandCount d = liftM fromIntegral $ withDataset d bandCount_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset a t) -> IO CInt\n\nwithBand :: Dataset a t -> Int -> (Band a t -> IO b) -> IO b\nwithBand ds band f = withDataset ds $ \\dPtr -> do\n rBand@(Band p) <- getRasterBand dPtr (fromIntegral band)\n if p == nullPtr\n then throw $\n GDALException CE_Failure (\"could not get band #\" ++ show band)\n else f rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset a t) -> CInt -> IO ((Band a t))\n\n\nbandDatatype :: (Band a t) -> Datatype\nbandDatatype band = toEnumC . getDatatype_ $ band\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band a t) -> CInt\n\n\nbandBlockSize :: (Band a t) -> (Int,Int)\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n -- unsafePerformIO is safe here since the block size cant change once\n -- a dataset is created\n getBlockSize_ band xPtr yPtr\n liftA2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nforeign import ccall unsafe \"gdal.h GDALGetBlockSize\" getBlockSize_\n :: (Band a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band a t) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band a t) -> (Int, Int)\nbandSize band\n = (fromIntegral . getXSize_ $ band, fromIntegral . getYSize_ $ band)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getXSize_\n :: (Band a t) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getYSize_\n :: (Band a t) -> CInt\n\n\nbandNodataValue :: (Band a t) -> IO (Maybe Double)\nbandNodataValue b = alloca $ \\p -> do\n value <- liftM realToFrac $ getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: (Band a t) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: (RWBand t) -> Double -> IO ()\nsetBandNodataValue b v = throwIfError \"could not set nodata\" $\n setNodata_ b (realToFrac v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand t) -> CDouble -> IO CInt\n\n\nfillBand :: (RWBand t) -> Double -> Double -> IO ()\nfillBand b r i = throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand t) -> CDouble -> CDouble -> IO CInt\n\n\n\n\ndata GComplex a = (:+) !a !a deriving (Eq, Show, Typeable)\ninfix 6 :+\n\nclass IsGComplex a where\n type ComplexType a :: *\n toComplex :: GComplex a -> Complex.Complex (ComplexType a)\n fromComplex :: Complex.Complex (ComplexType a) -> GComplex a\n\n toComplex (r :+ i) = (toUnit r) Complex.:+ (toUnit i)\n fromComplex (r Complex.:+ i) = (fromUnit r) :+ (fromUnit i)\n\n toUnit :: a -> ComplexType a\n fromUnit :: ComplexType a -> a\n\ninstance IsGComplex Int16 where\n type ComplexType Int16 = Float\n toUnit = fromIntegral\n fromUnit = round\n\ninstance IsGComplex Int32 where\n type ComplexType Int32 = Double\n toUnit = fromIntegral\n fromUnit = round\n\ninstance IsGComplex Float where\n type ComplexType Float = Float\n toUnit = id\n fromUnit = id\n\ninstance IsGComplex Double where\n type ComplexType Double = Double\n toUnit = id\n fromUnit = id\n\n\ninstance Storable a => Storable (GComplex a) where\n sizeOf _ = sizeOf (undefined :: a) * 2\n alignment _ = alignment (undefined :: a)\n \n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Double) -> IO (GComplex Double) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Float) -> IO (GComplex Float) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Int16) -> IO (GComplex Int16) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Int32) -> IO (GComplex Int32) #-}\n peek p = (:+) <$> peekElemOff (castPtr p) 0 <*> peekElemOff (castPtr p) 1\n\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Float) -> GComplex Float -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Double) -> GComplex Double -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Int16) -> GComplex Int16 -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Int32) -> GComplex Int32 -> IO () #-}\n poke p (r :+ i)\n = pokeElemOff (castPtr p) 0 r >> pokeElemOff (castPtr p) 1 i\n\n\n\nreadBand :: forall a b t. HasDatatype a\n => (Band b t)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector a)\nreadBand band xoff yoff sx sy bx by pxs lns = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (undefined :: a))\n withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\n adviseRead_\n band\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (fromIntegral bx)\n (fromIntegral by)\n dtype\n (castPtr nullPtr)\n throwIfError \"could not read band\" $\n rasterIO_\n band\n (fromEnumC GF_Read) \n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n dtype\n (fromIntegral pxs)\n (fromIntegral lns)\n return $ unsafeFromForeignPtr0 fp (bx * by)\n\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand :: forall a t. HasDatatype a\n => (RWBand t)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBand band xoff yoff sx sy bx by pxs lns vec = do\n let nElems = bx * by\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw $ GDALException CE_Failure \"vector of wrong size\"\n else withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not write band\" $\n rasterIO_\n band\n (fromEnumC GF_Write) \n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (datatype (undefined :: a)))\n (fromIntegral pxs)\n (fromIntegral lns)\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\n\ntype IOVector a = IO (Vector a)\n\nclass (HasDatatype t, b ~ Band)\n => HasBand b a t where\n readBandBlock :: b a t -> Int -> Int -> IOVector t\n readBandBlock b x y\n = if not $ isValidDatatype b (undefined :: Vector t)\n then throw $ GDALException CE_Failure \"wrong band type\"\n else do\n f <- mallocForeignPtrArray (bandBlockLen b)\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ unsafeFromForeignPtr0 f (bandBlockLen b)\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nclass (HasBand b a t, a ~ ReadWrite) => HasWritebaleBand b a t where\n writeBandBlock :: b a t -> Int -> Int -> Vector t -> IO ()\n writeBandBlock b x y vec = do\n let nElems = bandBlockLen b\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw $ GDALException CE_Failure \"wrongly sized vector\"\n else if not $ isValidDatatype b vec\n then throw $ GDALException CE_Failure \"wrongly typed vector\"\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y)\n (castPtr ptr)\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: (RWBand t) -> CInt -> CInt -> Ptr () -> IO CInt\n\n\n\ninstance forall a. HasBand Band a Word8 where\ninstance forall a. HasBand Band a Word16 where\ninstance forall a. HasBand Band a Word32 where\ninstance forall a. HasBand Band a Int16 where\ninstance forall a. HasBand Band a Int32 where\ninstance forall a. HasBand Band a Float where\ninstance forall a. HasBand Band a Double where\ninstance forall a. HasBand Band a (GComplex Int16) where\ninstance forall a. HasBand Band a (GComplex Int32) where\ninstance forall a. HasBand Band a (GComplex Float) where\ninstance forall a. HasBand Band a (GComplex Double) where\n\ninstance HasWritebaleBand Band ReadWrite Word8\ninstance HasWritebaleBand Band ReadWrite Word16\ninstance HasWritebaleBand Band ReadWrite Word32\ninstance HasWritebaleBand Band ReadWrite Int16\ninstance HasWritebaleBand Band ReadWrite Int32\ninstance HasWritebaleBand Band ReadWrite Float\ninstance HasWritebaleBand Band ReadWrite Double\ninstance HasWritebaleBand Band ReadWrite (GComplex Int16) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Int32) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Float) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Double) where\n\nclass (Storable a, Typeable a) => HasDatatype a where\n datatype :: a -> Datatype\n\ninstance HasDatatype Word8 where datatype _ = GDT_Byte\ninstance HasDatatype Word16 where datatype _ = GDT_UInt16\ninstance HasDatatype Word32 where datatype _ = GDT_UInt32\ninstance HasDatatype Int16 where datatype _ = GDT_Int16\ninstance HasDatatype Int32 where datatype _ = GDT_Int32\ninstance HasDatatype Float where datatype _ = GDT_Float32\ninstance HasDatatype Double where datatype _ = GDT_Float64\ninstance HasDatatype (GComplex Int16) where datatype _ = GDT_CInt16\ninstance HasDatatype (GComplex Int32) where datatype _ = GDT_CInt32\ninstance HasDatatype (GComplex Float) where datatype _ = GDT_CFloat32\ninstance HasDatatype (GComplex Double) where datatype _ = GDT_CFloat64\n\nisValidDatatype :: forall a t v. Typeable v\n => Band a t -> v -> Bool\nisValidDatatype b v = typeOfBand b == typeOf v\n where\n typeOfBand = typeOfdatatype . bandDatatype\n typeOfdatatype dt =\n case dt of\n GDT_Byte -> typeOf (undefined :: Vector Word8)\n GDT_UInt16 -> typeOf (undefined :: Vector Word16)\n GDT_UInt32 -> typeOf (undefined :: Vector Word32)\n GDT_Int16 -> typeOf (undefined :: Vector Int16)\n GDT_Int32 -> typeOf (undefined :: Vector Int32)\n GDT_Float32 -> typeOf (undefined :: Vector Float)\n GDT_Float64 -> typeOf (undefined :: Vector Double)\n GDT_CInt16 -> typeOf (undefined :: Vector (GComplex Int16))\n GDT_CInt32 -> typeOf (undefined :: Vector (GComplex Int32))\n GDT_CFloat32 -> typeOf (undefined :: Vector (GComplex Float))\n GDT_CFloat64 -> typeOf (undefined :: Vector (GComplex Double))\n _ -> typeOf (undefined :: Bool) -- will never match a vector\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n\nmodule OSGeo.GDAL.Internal (\n HasDataset\n , HasBand\n , HasWritebaleBand\n , HasDatatype\n , Datatype (..)\n , GDALException\n , isGDALException\n , Geotransform (..)\n , IOVector\n , DriverOptions\n , MajorObject\n , Dataset\n , ReadWrite\n , ReadOnly\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , Driver\n , ColorTable\n , RasterAttributeTable\n , GComplex (..)\n\n , setQuietErrorHandler\n , unDataset\n , unBand\n\n , withAllDriversRegistered\n , registerAllDrivers\n , destroyDriverManager\n , driverByName\n , create\n , create'\n , createMem\n , flushCache\n , openReadOnly\n , openReadWrite\n , createCopy\n\n , datatypeSize\n , datatypeByName\n , datatypeUnion\n , datatypeIsComplex\n\n , datasetProjection\n , setDatasetProjection\n , datasetGeotransform\n , setDatasetGeotransform\n , datasetBandCount\n\n , withBand\n , bandDatatype\n , bandBlockSize\n , bandBlockLen\n , bandSize\n , bandNodataValue\n , setBandNodataValue\n , readBand\n , readBandBlock\n , writeBand\n , writeBandBlock\n , fillBand\n\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Exception (bracket, throw, Exception(..), SomeException,\n finally)\nimport Control.Monad (liftM, foldM)\n\nimport Data.Int (Int16, Int32)\nimport qualified Data.Complex as Complex\nimport Data.Maybe (isJust)\nimport Data.Typeable (Typeable, typeOf)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector, unsafeFromForeignPtr0, unsafeToForeignPtr0)\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (ForeignPtr, withForeignPtr, newForeignPtr\n ,mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport OSGeo.Util\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n\ndata GDALException = GDALException Error String\n deriving (Show, Typeable)\n\ninstance Exception GDALException\n\nisGDALException :: SomeException -> Bool\nisGDALException e = isJust (fromException e :: Maybe GDALException)\n\n{# enum CPLErr as Error {upcaseFirstLetter} deriving (Eq,Show) #}\n\n\ntype ErrorHandler = CInt -> CInt -> CString -> IO ()\n\nforeign import ccall \"cpl_error.h &CPLQuietErrorHandler\"\n c_quietErrorHandler :: FunPtr ErrorHandler\n\nforeign import ccall \"cpl_error.h CPLSetErrorHandler\"\n c_setErrorHandler :: FunPtr ErrorHandler -> IO (FunPtr ErrorHandler)\n\nsetQuietErrorHandler :: IO ()\nsetQuietErrorHandler = setErrorHandler c_quietErrorHandler\n\nsetErrorHandler :: FunPtr ErrorHandler -> IO ()\nsetErrorHandler h = c_setErrorHandler h >>= (\\_->return ())\n\n\nthrowIfError :: String -> IO CInt -> IO ()\nthrowIfError msg act = do\n e <- liftM toEnumC act\n case e of\n CE_None -> return ()\n e' -> throw $ GDALException e' msg\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\ninstance Show Datatype where\n show = getDatatypeName\n\n{# fun pure unsafe GDALGetDataTypeSize as datatypeSize\n { fromEnumC `Datatype' } -> `Int' #}\n\n{# fun pure unsafe GDALDataTypeIsComplex as datatypeIsComplex\n { fromEnumC `Datatype' } -> `Bool' #}\n\n{# fun pure unsafe GDALGetDataTypeName as getDatatypeName\n { fromEnumC `Datatype' } -> `String' #}\n\n{# fun pure unsafe GDALGetDataTypeByName as datatypeByName\n { `String' } -> `Datatype' toEnumC #}\n\n{# fun pure unsafe GDALDataTypeUnion as datatypeUnion\n { fromEnumC `Datatype', fromEnumC `Datatype' } -> `Datatype' toEnumC #}\n\n\n{# enum GDALAccess as Access {upcaseFirstLetter} deriving (Eq, Show) #}\n\n{# enum GDALRWFlag as RwFlag {upcaseFirstLetter} deriving (Eq, Show) #}\n\n{#pointer GDALMajorObjectH as MajorObject newtype#}\n{#pointer GDALDatasetH as Dataset foreign newtype nocode#}\n\ndata ReadOnly\ndata ReadWrite\nnewtype (Dataset a t) = Dataset (ForeignPtr (Dataset a t), Mutex)\n\nunDataset (Dataset (d, _)) = d\n\ntype RODataset = Dataset ReadOnly\ntype RWDataset = Dataset ReadWrite\nwithDataset, withDataset' :: (Dataset a t) -> (Ptr (Dataset a t) -> IO b) -> IO b\nwithDataset ds@(Dataset (_, m)) fun = withMutex m $ withDataset' ds fun\n\nwithDataset' (Dataset (fptr,_)) = withForeignPtr fptr\n\n{#pointer GDALRasterBandH as Band newtype nocode#}\nnewtype (Band a t) = Band (Ptr ((Band a t)))\n\nunBand (Band b) = b\n\ntype ROBand = Band ReadOnly\ntype RWBand = Band ReadWrite\n\n\n{#pointer GDALDriverH as Driver newtype#}\n{#pointer GDALColorTableH as ColorTable newtype#}\n{#pointer GDALRasterAttributeTableH as RasterAttributeTable newtype#}\n\n{#fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{#fun GDALDestroyDriverManager as destroyDriverManager {} -> `()'#}\n\nwithAllDriversRegistered act\n = registerAllDrivers >> finally act destroyDriverManager\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `Driver' id #}\n\ndriverByName :: String -> IO Driver\ndriverByName s = do\n driver@(Driver ptr) <- c_driverByName s\n if ptr==nullPtr\n then throw $ GDALException CE_Failure \"failed to load driver\"\n else return driver\n\ntype DriverOptions = [(String,String)]\n\nclass ( HasDatatype t\n , a ~ ReadWrite\n , d ~ Dataset,\n HasWritebaleBand Band ReadWrite t)\n => HasDataset d a t where\n create :: String -> String -> Int -> Int -> Int -> DriverOptions\n -> IO (d a t)\n create drv path nx ny bands options = do\n d <- driverByName drv\n create' d path nx ny bands (datatype (undefined :: t)) options\n\ncreate' :: Driver -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO (Dataset ReadWrite t)\ncreate' drv path nx ny bands dtype options = withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC dtype\n withOptionList options $ \\opts ->\n create_ drv path' nx' ny' bands' dtype' opts >>= newDatasetHandle\n\nwithOptionList ::\n [(String, String)] -> (Ptr CString -> IO c) -> IO c\nwithOptionList opts = bracket (toOptionList opts) freeOptionList\n where toOptionList = foldM folder nullPtr\n folder acc (k,v) = withCString k $ \\k' -> withCString v $ \\v' ->\n {#call unsafe CSLSetNameValue as ^#} acc k' v'\n freeOptionList = {#call unsafe CSLDestroy as ^#} . castPtr\n\ninstance HasDataset Dataset ReadWrite Word8 where\ninstance HasDataset Dataset ReadWrite Int16 where\ninstance HasDataset Dataset ReadWrite Int32 where\ninstance HasDataset Dataset ReadWrite Word16 where\ninstance HasDataset Dataset ReadWrite Word32 where\ninstance HasDataset Dataset ReadWrite Float where\ninstance HasDataset Dataset ReadWrite Double where\ninstance HasDataset Dataset ReadWrite (GComplex Int16) where\ninstance HasDataset Dataset ReadWrite (GComplex Int32) where\ninstance HasDataset Dataset ReadWrite (GComplex Float) where\ninstance HasDataset Dataset ReadWrite (GComplex Double) where\n\n\nforeign import ccall safe \"gdal.h GDALCreate\" create_\n :: Driver\n -> CString\n -> CInt\n -> CInt\n -> CInt\n -> CInt\n -> Ptr CString\n -> IO (Ptr (RWDataset t))\n\nopenReadOnly :: String -> IO (RODataset t)\nopenReadOnly p = withCString p openIt\n where openIt p' = open_ p' (fromEnumC GA_ReadOnly) >>= newDatasetHandle\n\nopenReadWrite :: String -> IO (RWDataset t)\nopenReadWrite p = withCString p openIt\n where openIt p' = open_ p' (fromEnumC GA_Update) >>= newDatasetHandle\n\nforeign import ccall safe \"gdal.h GDALOpen\" open_\n :: CString -> CInt -> IO (Ptr (Dataset a t))\n\n\ncreateCopy' ::\n Driver -> String -> (Dataset a t) -> Bool -> DriverOptions\n -> ProgressFun -> IO (RWDataset t)\ncreateCopy' driver path dataset strict options progressFun\n = withCString path $ \\p ->\n withDataset dataset $ \\ds ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n withOptionList options $ \\o ->\n createCopy_ driver p ds s o pFunc (castPtr nullPtr)\n >>= newDatasetHandle\n\n\ncreateCopy ::\n String -> String -> (Dataset a t) -> Bool -> DriverOptions\n -> IO (RWDataset t)\ncreateCopy driver path dataset strict options = do\n d <- driverByName driver\n createCopy' d path dataset strict options (\\_ _ _ -> return 1)\n\nforeign import ccall safe \"gdal.h GDALCreateCopy\" createCopy_\n :: Driver\n -> Ptr CChar\n -> Ptr (Dataset a t)\n -> CInt\n -> Ptr CString\n -> FunPtr ProgressFun\n -> Ptr ()\n -> IO (Ptr (RWDataset t))\n\n\nwithProgressFun :: forall c.\n ProgressFun -> (FunPtr ProgressFun -> IO c) -> IO c\nwithProgressFun = withCCallback wrapProgressFun\n\nwithCCallback :: forall c t a.\n (t -> IO (FunPtr a)) -> t -> (FunPtr a -> IO c) -> IO c\nwithCCallback w f = bracket (w f) freeHaskellFunPtr\n\ntype ProgressFun = CDouble -> Ptr CChar -> Ptr () -> IO CInt\n\nforeign import ccall \"wrapper\"\n wrapProgressFun :: ProgressFun -> IO (FunPtr ProgressFun)\n\n\nnewDatasetHandle :: Ptr (Dataset a t) -> IO (Dataset a t)\nnewDatasetHandle p =\n if p==nullPtr\n then throw $ GDALException CE_Failure \"Could not create dataset\"\n else do fp <- newForeignPtr closeDataset p\n mutex <- newMutex\n return $ Dataset (fp, mutex)\n\nforeign import ccall \"gdal.h &GDALClose\"\n closeDataset :: FunPtr (Ptr (Dataset a t) -> IO ())\n\ncreateMem:: HasDataset d a t\n => Int -> Int -> Int -> DriverOptions -> IO (d a t)\ncreateMem = create \"MEM\" \"\"\n\nflushCache :: forall a t. Dataset a t -> IO ()\nflushCache d = withDataset d flushCache'\n\nforeign import ccall safe \"gdal.h GDALFlushCache\" flushCache'\n :: Ptr (Dataset a t) -> IO ()\n\n\ndatasetProjection :: Dataset a t -> IO String\ndatasetProjection d = withDataset d $ \\d' -> do\n p <- getProjection_ d'\n peekCString p\n\nforeign import ccall unsafe \"gdal.h GDALGetProjectionRef\" getProjection_\n :: Ptr (Dataset a t) -> IO (Ptr CChar)\n\n\nsetDatasetProjection :: (RWDataset t) -> String -> IO ()\nsetDatasetProjection d p = throwIfError \"could not set projection\" f\n where f = withDataset d $ \\d' -> withCString p $ \\p' -> setProjection' d' p'\n\nforeign import ccall unsafe \"gdal.h GDALSetProjection\" setProjection'\n :: Ptr (Dataset a t) -> Ptr CChar -> IO CInt\n\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset a t -> IO Geotransform\ndatasetGeotransform ds = withDataset' ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n throwIfError \"could not get geotransform\" $ getGeoTransform dPtr a\n Geotransform <$> liftM realToFrac (peekElemOff a 0)\n <*> liftM realToFrac (peekElemOff a 1)\n <*> liftM realToFrac (peekElemOff a 2)\n <*> liftM realToFrac (peekElemOff a 3)\n <*> liftM realToFrac (peekElemOff a 4)\n <*> liftM realToFrac (peekElemOff a 5)\n\nforeign import ccall unsafe \"gdal.h GDALGetGeoTransform\" getGeoTransform\n :: Ptr (Dataset a t) -> Ptr CDouble -> IO CInt\n\nsetDatasetGeotransform :: (RWDataset t) -> Geotransform -> IO ()\nsetDatasetGeotransform ds gt = withDataset ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n let (Geotransform g0 g1 g2 g3 g4 g5) = gt\n pokeElemOff a 0 (realToFrac g0)\n pokeElemOff a 1 (realToFrac g1)\n pokeElemOff a 2 (realToFrac g2)\n pokeElemOff a 3 (realToFrac g3)\n pokeElemOff a 4 (realToFrac g4)\n pokeElemOff a 5 (realToFrac g5)\n throwIfError \"could not set geotransform\" $ setGeoTransform dPtr a\n\nforeign import ccall unsafe \"gdal.h GDALSetGeoTransform\" setGeoTransform\n :: Ptr (Dataset a t) -> Ptr CDouble -> IO CInt\n\ndatasetBandCount :: Dataset a t -> IO (Int)\ndatasetBandCount d = liftM fromIntegral $ withDataset d bandCount_\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterCount\" bandCount_\n :: Ptr (Dataset a t) -> IO CInt\n\nwithBand :: Dataset a t -> Int -> (Band a t -> IO b) -> IO b\nwithBand ds band f = withDataset ds $ \\dPtr -> do\n rBand@(Band p) <- getRasterBand dPtr (fromIntegral band)\n if p == nullPtr\n then throw $\n GDALException CE_Failure (\"could not get band #\" ++ show band)\n else f rBand\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBand\" getRasterBand\n :: Ptr (Dataset a t) -> CInt -> IO ((Band a t))\n\n\nbandDatatype :: (Band a t) -> Datatype\nbandDatatype band = toEnumC . getDatatype_ $ band\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterDataType\" getDatatype_\n :: (Band a t) -> CInt\n\n\nbandBlockSize :: (Band a t) -> (Int,Int)\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n -- unsafePerformIO is safe here since the block size cant change once\n -- a dataset is created\n getBlockSize_ band xPtr yPtr\n liftA2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nforeign import ccall unsafe \"gdal.h GDALGetBlockSize\" getBlockSize_\n :: (Band a t) -> Ptr CInt -> Ptr CInt -> IO ()\n\n\nbandBlockLen :: (Band a t) -> Int\nbandBlockLen = uncurry (*) . bandBlockSize\n\nbandSize :: (Band a t) -> (Int, Int)\nbandSize band\n = (fromIntegral . getXSize_ $ band, fromIntegral . getYSize_ $ band)\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandXSize\" getXSize_\n :: (Band a t) -> CInt\n\nforeign import ccall unsafe \"gdal.h GDALGetRasterBandYSize\" getYSize_\n :: (Band a t) -> CInt\n\n\nbandNodataValue :: (Band a t) -> IO (Maybe Double)\nbandNodataValue b = alloca $ \\p -> do\n value <- liftM realToFrac $ getNodata_ b p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just value else Nothing)\n \nforeign import ccall unsafe \"gdal.h GDALGetRasterNoDataValue\" getNodata_\n :: (Band a t) -> Ptr CInt -> IO CDouble\n \n\nsetBandNodataValue :: (RWBand t) -> Double -> IO ()\nsetBandNodataValue b v = throwIfError \"could not set nodata\" $\n setNodata_ b (realToFrac v)\n\nforeign import ccall safe \"gdal.h GDALSetRasterNoDataValue\" setNodata_\n :: (RWBand t) -> CDouble -> IO CInt\n\n\nfillBand :: (RWBand t) -> Double -> Double -> IO ()\nfillBand b r i = throwIfError \"could not fill band\" $\n fillRaster_ b (realToFrac r) (realToFrac i)\n\nforeign import ccall safe \"gdal.h GDALFillRaster\" fillRaster_\n :: (RWBand t) -> CDouble -> CDouble -> IO CInt\n\n\n\n\ndata GComplex a = (:+) !a !a deriving (Eq, Show, Typeable)\n\nclass IsGComplex a where\n type ComplexType a :: *\n toComplex :: GComplex a -> Complex.Complex (ComplexType a)\n fromComplex :: Complex.Complex (ComplexType a) -> GComplex a\n\n toComplex (r :+ i) = (toUnit r) Complex.:+ (toUnit i)\n fromComplex (r Complex.:+ i) = (fromUnit r) :+ (fromUnit i)\n\n toUnit :: a -> ComplexType a\n fromUnit :: ComplexType a -> a\n\ninstance IsGComplex Int16 where\n type ComplexType Int16 = Float\n toUnit = fromIntegral\n fromUnit = round\n\ninstance IsGComplex Int32 where\n type ComplexType Int32 = Double\n toUnit = fromIntegral\n fromUnit = round\n\ninstance IsGComplex Float where\n type ComplexType Float = Float\n toUnit = id\n fromUnit = id\n\ninstance IsGComplex Double where\n type ComplexType Double = Double\n toUnit = id\n fromUnit = id\n\n\ninstance Storable a => Storable (GComplex a) where\n sizeOf _ = sizeOf (undefined :: a) * 2\n alignment _ = alignment (undefined :: a)\n \n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Double) -> IO (GComplex Double) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Float) -> IO (GComplex Float) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Int16) -> IO (GComplex Int16) #-}\n {-# SPECIALIZE INLINE peek ::\n Ptr (GComplex Int32) -> IO (GComplex Int32) #-}\n peek p = (:+) <$> peekElemOff (castPtr p) 0 <*> peekElemOff (castPtr p) 1\n\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Float) -> GComplex Float -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Double) -> GComplex Double -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Int16) -> GComplex Int16 -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (GComplex Int32) -> GComplex Int32 -> IO () #-}\n poke p (r :+ i)\n = pokeElemOff (castPtr p) 0 r >> pokeElemOff (castPtr p) 1 i\n\n\n\nreadBand :: forall a b t. HasDatatype a\n => (Band b t)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Vector a)\nreadBand band xoff yoff sx sy bx by pxs lns = do\n fp <- mallocForeignPtrArray (bx * by)\n let dtype = fromEnumC (datatype (undefined :: a))\n withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not advise read\" $\n adviseRead_\n band\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (fromIntegral bx)\n (fromIntegral by)\n dtype\n (castPtr nullPtr)\n throwIfError \"could not read band\" $\n rasterIO_\n band\n (fromEnumC GF_Read) \n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n dtype\n (fromIntegral pxs)\n (fromIntegral lns)\n return $ unsafeFromForeignPtr0 fp (bx * by)\n\nforeign import ccall safe \"gdal.h GDALRasterAdviseRead\" adviseRead_\n :: (Band a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt\n -> Ptr (Ptr CChar) -> IO CInt\n\n \nwriteBand :: forall a t. HasDatatype a\n => (RWBand t)\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> IO ()\nwriteBand band xoff yoff sx sy bx by pxs lns vec = do\n let nElems = bx * by\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw $ GDALException CE_Failure \"vector of wrong size\"\n else withForeignPtr fp $ \\ptr -> do\n throwIfError \"could not write band\" $\n rasterIO_\n band\n (fromEnumC GF_Write) \n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (datatype (undefined :: a)))\n (fromIntegral pxs)\n (fromIntegral lns)\n\nforeign import ccall safe \"gdal.h GDALRasterIO\" rasterIO_\n :: (Band a t) -> CInt -> CInt -> CInt -> CInt -> CInt -> Ptr () -> CInt -> CInt\n -> CInt -> CInt -> CInt -> IO CInt\n\n\ntype IOVector a = IO (Vector a)\n\nclass (HasDatatype t, b ~ Band)\n => HasBand b a t where\n readBandBlock :: b a t -> Int -> Int -> IOVector t\n readBandBlock b x y\n = if not $ isValidDatatype b (undefined :: Vector t)\n then throw $ GDALException CE_Failure \"wrong band type\"\n else do\n f <- mallocForeignPtrArray (bandBlockLen b)\n withForeignPtr f $ \\ptr ->\n throwIfError \"could not read block\" $\n readBlock_ b (fromIntegral x) (fromIntegral y) (castPtr ptr)\n return $ unsafeFromForeignPtr0 f (bandBlockLen b)\n\nforeign import ccall safe \"gdal.h GDALReadBlock\" readBlock_\n :: (Band a t) -> CInt -> CInt -> Ptr () -> IO CInt\n\nclass (HasBand b a t, a ~ ReadWrite) => HasWritebaleBand b a t where\n writeBandBlock :: b a t -> Int -> Int -> Vector t -> IO ()\n writeBandBlock b x y vec = do\n let nElems = bandBlockLen b\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then throw $ GDALException CE_Failure \"wrongly sized vector\"\n else if not $ isValidDatatype b vec\n then throw $ GDALException CE_Failure \"wrongly typed vector\"\n else withForeignPtr fp $ \\ptr ->\n throwIfError \"could not write block\" $\n writeBlock_ b (fromIntegral x) (fromIntegral y)\n (castPtr ptr)\n\nforeign import ccall safe \"gdal.h GDALWriteBlock\" writeBlock_\n :: (RWBand t) -> CInt -> CInt -> Ptr () -> IO CInt\n\n\n\ninstance forall a. HasBand Band a Word8 where\ninstance forall a. HasBand Band a Word16 where\ninstance forall a. HasBand Band a Word32 where\ninstance forall a. HasBand Band a Int16 where\ninstance forall a. HasBand Band a Int32 where\ninstance forall a. HasBand Band a Float where\ninstance forall a. HasBand Band a Double where\ninstance forall a. HasBand Band a (GComplex Int16) where\ninstance forall a. HasBand Band a (GComplex Int32) where\ninstance forall a. HasBand Band a (GComplex Float) where\ninstance forall a. HasBand Band a (GComplex Double) where\n\ninstance HasWritebaleBand Band ReadWrite Word8\ninstance HasWritebaleBand Band ReadWrite Word16\ninstance HasWritebaleBand Band ReadWrite Word32\ninstance HasWritebaleBand Band ReadWrite Int16\ninstance HasWritebaleBand Band ReadWrite Int32\ninstance HasWritebaleBand Band ReadWrite Float\ninstance HasWritebaleBand Band ReadWrite Double\ninstance HasWritebaleBand Band ReadWrite (GComplex Int16) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Int32) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Float) where\ninstance HasWritebaleBand Band ReadWrite (GComplex Double) where\n\nclass (Storable a, Typeable a) => HasDatatype a where\n datatype :: a -> Datatype\n\ninstance HasDatatype Word8 where datatype _ = GDT_Byte\ninstance HasDatatype Word16 where datatype _ = GDT_UInt16\ninstance HasDatatype Word32 where datatype _ = GDT_UInt32\ninstance HasDatatype Int16 where datatype _ = GDT_Int16\ninstance HasDatatype Int32 where datatype _ = GDT_Int32\ninstance HasDatatype Float where datatype _ = GDT_Float32\ninstance HasDatatype Double where datatype _ = GDT_Float64\ninstance HasDatatype (GComplex Int16) where datatype _ = GDT_CInt16\ninstance HasDatatype (GComplex Int32) where datatype _ = GDT_CInt32\ninstance HasDatatype (GComplex Float) where datatype _ = GDT_CFloat32\ninstance HasDatatype (GComplex Double) where datatype _ = GDT_CFloat64\n\nisValidDatatype :: forall a t v. Typeable v\n => Band a t -> v -> Bool\nisValidDatatype b v = typeOfBand b == typeOf v\n where\n typeOfBand = typeOfdatatype . bandDatatype\n typeOfdatatype dt =\n case dt of\n GDT_Byte -> typeOf (undefined :: Vector Word8)\n GDT_UInt16 -> typeOf (undefined :: Vector Word16)\n GDT_UInt32 -> typeOf (undefined :: Vector Word32)\n GDT_Int16 -> typeOf (undefined :: Vector Int16)\n GDT_Int32 -> typeOf (undefined :: Vector Int32)\n GDT_Float32 -> typeOf (undefined :: Vector Float)\n GDT_Float64 -> typeOf (undefined :: Vector Double)\n GDT_CInt16 -> typeOf (undefined :: Vector (GComplex Int16))\n GDT_CInt32 -> typeOf (undefined :: Vector (GComplex Int32))\n GDT_CFloat32 -> typeOf (undefined :: Vector (GComplex Float))\n GDT_CFloat64 -> typeOf (undefined :: Vector (GComplex Double))\n _ -> typeOf (undefined :: Bool) -- will never match a vector\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"dea59deb87102e2d2a67f89ab6b067c9063c9832","subject":"Store HostPtr objects as standard, rather than foreign, pointers.","message":"Store HostPtr objects as standard, rather than foreign, pointers.\n\nIgnore-this: 15142cd94fa723bcc3e39e1794c1c5a5\n\ndarcs-hash:20091221101240-dcabc-460e331b18bb75a32417ad95e9b259898f3a9424.gz\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Marshal.chs","new_file":"Foreign\/CUDA\/Driver\/Marshal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Marshal\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Memory management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Marshal\n (\n DevicePtr, HostPtr, AllocFlag(..), withHostPtr,\n malloc, free, mallocHost, freeHost,\n peekArray, peekArrayAsync, pokeArray, pokeArrayAsync, memset,\n getDevicePtr\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Stream (Stream(..))\n\n-- System\nimport Foreign hiding (peekArray, pokeArray, malloc, free)\nimport Foreign.C\nimport Control.Monad (liftM)\nimport Unsafe.Coerce\n\n#c\ntypedef enum CUmemhostalloc_option_enum {\n CU_MEMHOSTALLOC_OPTION_PORTABLE = CU_MEMHOSTALLOC_PORTABLE,\n CU_MEMHOSTALLOC_OPTION_DEVICE_MAPPED = CU_MEMHOSTALLOC_DEVICEMAP,\n CU_MEMHOSTALLOC_OPTION_WRITE_COMBINED = CU_MEMHOSTALLOC_WRITECOMBINED\n} CUmemhostalloc_option;\n#endc\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A reference to memory allocated on the device\n--\nnewtype DevicePtr a = DevicePtr { useDevicePtr :: {# type CUdeviceptr #}}\n\ninstance Storable (DevicePtr a) where\n sizeOf _ = sizeOf (undefined :: {# type CUdeviceptr #})\n alignment _ = alignment (undefined :: {# type CUdeviceptr #})\n peek p = DevicePtr `fmap` peek (castPtr p)\n poke p v = poke (castPtr p) (useDevicePtr v)\n\n\n-- |\n-- A reference to memory on the host that is page-locked and directly-accessible\n-- from the device. Since the memory can be accessed directly, it can be read or\n-- written at a much higher bandwidth than pageable memory from the traditional\n-- malloc.\n--\n-- The driver automatically accelerates calls to functions such as `memcpy'\n-- which reference page-locked memory.\n--\nnewtype HostPtr a = HostPtr { useHostPtr :: Ptr a }\n\n-- |\n-- Unwrap a host pointer and execute a computation using the base pointer object\n--\nwithHostPtr :: HostPtr a -> (Ptr a -> IO b) -> IO b\nwithHostPtr p f = f (useHostPtr p)\n\n-- |\n-- Options for host allocation\n--\n{# enum CUmemhostalloc_option as AllocFlag\n { underscoreToCase }\n with prefix=\"CU_MEMHOSTALLOC_OPTION\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------------------\n-- Host Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a section of linear memory on the host which is page-locked and\n-- directly accessible from the device. The storage is sufficient to hold the\n-- given number of elements of a storable type.\n--\n-- Note that since the amount of pageable memory is thusly reduced, overall\n-- system performance may suffer. This is best used sparingly to allocate\n-- staging areas for data exchange.\n--\nmallocHost :: Storable a => [AllocFlag] -> Int -> IO (HostPtr a)\nmallocHost flags = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (HostPtr a')\n doMalloc x n = resultIfOk =<< cuMemHostAlloc (n * sizeOf x) flags\n\n{# fun unsafe cuMemHostAlloc\n { alloca'- `HostPtr a' peekHP*\n , `Int'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n peekHP p = (HostPtr . castPtr) `fmap` peek p\n\n\n-- |\n-- Free a section of page-locked host memory\n--\nfreeHost :: HostPtr a -> IO ()\nfreeHost p = nothingIfOk =<< cuMemFreeHost p\n\n{# fun unsafe cuMemFreeHost\n { useHP `HostPtr a' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n--------------------------------------------------------------------------------\n-- Device Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a section of linear memory on the device, and return a reference to\n-- it. The memory is sufficient to hold the given number of elements of storable\n-- type. It is suitably aligned for any type, and is not cleared.\n--\nmalloc :: Storable a => Int -> IO (DevicePtr a)\nmalloc = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')\n doMalloc x n = resultIfOk =<< cuMemAlloc (n * sizeOf x)\n\n{# fun unsafe cuMemAlloc\n { alloca- `DevicePtr a' dptr*\n , `Int' } -> `Status' cToEnum #}\n where dptr = liftM DevicePtr . peek\n\n-- |\n-- Release a section of device memory\n--\nfree :: DevicePtr a -> IO ()\nfree dp = nothingIfOk =<< cuMemFree dp\n\n{# fun unsafe cuMemFree\n { useDevicePtr `DevicePtr a' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Transfer\n--------------------------------------------------------------------------------\n\n-- |\n-- Copy a number of elements from the device to host memory. This is a\n-- synchronous operation\n--\npeekArray :: Storable a => Int -> DevicePtr a -> Ptr a -> IO ()\npeekArray n dptr hptr = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ = nothingIfOk =<< cuMemcpyDtoH hptr dptr (n * sizeOf x)\n\n{# fun unsafe cuMemcpyDtoH\n { castPtr `Ptr a'\n , useDevicePtr `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy memory from the device asynchronously, possibly associated with a\n-- particular stream. The destination host memory must be page-locked (allocated\n-- by mallocHost)\n--\npeekArrayAsync :: Storable a => Int -> DevicePtr a -> Ptr a -> Maybe Stream -> IO ()\npeekArrayAsync n dptr hptr mst = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ =\n nothingIfOk =<< case mst of\n Nothing -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) (Stream nullPtr)\n Just st -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) st\n\n{# fun unsafe cuMemcpyDtoHAsync\n { castPtr `Ptr a'\n , useDevicePtr `DevicePtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a number of elements onto the device. This is a synchronous operation\n--\npokeArray :: Storable a => Int -> Ptr a -> DevicePtr a -> IO ()\npokeArray n hptr dptr = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPoke x _ = nothingIfOk =<< cuMemcpyHtoD dptr hptr (n * sizeOf x)\n\n{# fun unsafe cuMemcpyHtoD\n { useDevicePtr `DevicePtr a'\n , castPtr `Ptr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy memory onto the device asynchronously, possibly associated with a\n-- particular stream. The source host memory must be page-locked (allocated by\n-- mallocHost)\n--\npokeArrayAsync :: Storable a => Int -> Ptr a -> DevicePtr a -> Maybe Stream -> IO ()\npokeArrayAsync n hptr dptr mst = dopoke undefined dptr\n where\n dopoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n dopoke x _ =\n nothingIfOk =<< case mst of\n Nothing -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) (Stream nullPtr)\n Just st -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) st\n\n{# fun unsafe cuMemcpyHtoDAsync\n { useDevicePtr `DevicePtr a'\n , castPtr `Ptr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Utility\n--------------------------------------------------------------------------------\n\n-- |\n-- Set a number of data elements to the specified value, which may be either 8-,\n-- 16-, or 32-bits wide.\n--\nmemset :: Storable a => DevicePtr a -> Int -> a -> IO ()\nmemset dptr n val = case sizeOf val of\n 1 -> nothingIfOk =<< cuMemsetD8 dptr val n\n 2 -> nothingIfOk =<< cuMemsetD16 dptr val n\n 4 -> nothingIfOk =<< cuMemsetD32 dptr val n\n _ -> cudaError \"can only memset 8-, 16-, and 32-bit values\"\n\n--\n-- We use unsafe coerce below to reinterpret the bits of the value to memset as,\n-- into the integer type required by the setting functions.\n--\n{# fun unsafe cuMemsetD8\n { useDevicePtr `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuMemsetD16\n { useDevicePtr `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuMemsetD32\n { useDevicePtr `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the device pointer associated with a mapped, pinned host buffer, which\n-- was allocated with the 'DeviceMapped' option by 'mallocHost'.\n--\n-- Currently, no options are supported and this must be empty.\n--\ngetDevicePtr :: [AllocFlag] -> HostPtr a -> IO (DevicePtr a)\ngetDevicePtr flags hp = resultIfOk =<< cuMemHostGetDevicePointer hp flags\n\n{# fun unsafe cuMemHostGetDevicePointer\n { alloca'- `DevicePtr a' peekDP*\n , useHP `HostPtr a'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n useHP = castPtr . useHostPtr\n peekDP = liftM DevicePtr . peek\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Marshal\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Memory management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Marshal\n (\n DevicePtr, HostPtr, AllocFlag(..), withHostPtr,\n malloc, free, mallocHost, freeHost,\n peekArray, peekArrayAsync, pokeArray, pokeArrayAsync, memset,\n getDevicePtr\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Stream (Stream(..))\n\n-- System\nimport Foreign hiding (peekArray, pokeArray, malloc, free)\nimport Foreign.C\nimport Control.Monad (liftM)\nimport Unsafe.Coerce\n\n#c\ntypedef enum CUmemhostalloc_option_enum {\n CU_MEMHOSTALLOC_OPTION_PORTABLE = CU_MEMHOSTALLOC_PORTABLE,\n CU_MEMHOSTALLOC_OPTION_DEVICE_MAPPED = CU_MEMHOSTALLOC_DEVICEMAP,\n CU_MEMHOSTALLOC_OPTION_WRITE_COMBINED = CU_MEMHOSTALLOC_WRITECOMBINED\n} CUmemhostalloc_option;\n#endc\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A reference to memory allocated on the device\n--\nnewtype DevicePtr a = DevicePtr { useDevicePtr :: {# type CUdeviceptr #}}\n\ninstance Storable (DevicePtr a) where\n sizeOf _ = sizeOf (undefined :: {# type CUdeviceptr #})\n alignment _ = alignment (undefined :: {# type CUdeviceptr #})\n peek p = DevicePtr `fmap` peek (castPtr p)\n poke p v = poke (castPtr p) (useDevicePtr v)\n\n\n-- |\n-- A reference to memory on the host that is page-locked and directly-accessible\n-- from the device. Since the memory can be accessed directly, it can be read or\n-- written at a much higher bandwidth than pageable memory from the traditional\n-- malloc.\n--\n-- The driver automatically accelerates calls to functions such as `memcpy'\n-- which reference page-locked memory.\n--\nnewtype HostPtr a = HostPtr (ForeignPtr a)\n\nwithHostPtr :: HostPtr a -> (Ptr a -> IO b) -> IO b\nwithHostPtr (HostPtr hptr) = withForeignPtr hptr\n\nnewHostPtr :: IO (HostPtr a)\nnewHostPtr = HostPtr `fmap` mallocForeignPtrBytes (sizeOf (undefined :: Ptr ()))\n\n-- |\n-- Options for host allocation\n--\n{# enum CUmemhostalloc_option as AllocFlag\n { underscoreToCase }\n with prefix=\"CU_MEMHOSTALLOC_OPTION\" deriving (Eq, Show) #}\n\n--------------------------------------------------------------------------------\n-- Host Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a section of linear memory on the host which is page-locked and\n-- directly accessible from the device. The storage is sufficient to hold the\n-- given number of elements of a storable type.\n--\n-- Note that since the amount of pageable memory is thusly reduced, overall\n-- system performance may suffer. This is best used sparingly to allocate\n-- staging areas for data exchange.\n--\nmallocHost :: Storable a => [AllocFlag] -> Int -> IO (HostPtr a)\nmallocHost flags = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (HostPtr a')\n doMalloc x n =\n newHostPtr >>= \\hp -> withHostPtr hp $ \\p ->\n cuMemHostAlloc p (n * sizeOf x) flags >>= nothingIfOk >>\n return hp\n\n{# fun unsafe cuMemHostAlloc\n { with'* `Ptr a'\n , `Int'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where with' = with . castPtr\n\n\n-- |\n-- Free a section of page-locked host memory\n--\nfreeHost :: HostPtr a -> IO ()\nfreeHost hp = withHostPtr hp $ \\p -> (nothingIfOk =<< cuMemFreeHost p)\n\n{# fun unsafe cuMemFreeHost\n { castPtr `Ptr a' } -> `Status' cToEnum #}\n\n--------------------------------------------------------------------------------\n-- Device Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a section of linear memory on the device, and return a reference to\n-- it. The memory is sufficient to hold the given number of elements of storable\n-- type. It is suitably aligned for any type, and is not cleared.\n--\nmalloc :: Storable a => Int -> IO (DevicePtr a)\nmalloc = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')\n doMalloc x n = resultIfOk =<< cuMemAlloc (n * sizeOf x)\n\n{# fun unsafe cuMemAlloc\n { alloca- `DevicePtr a' dptr*\n , `Int' } -> `Status' cToEnum #}\n where dptr = liftM DevicePtr . peek\n\n-- |\n-- Release a section of device memory\n--\nfree :: DevicePtr a -> IO ()\nfree dp = nothingIfOk =<< cuMemFree dp\n\n{# fun unsafe cuMemFree\n { useDevicePtr `DevicePtr a' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Transfer\n--------------------------------------------------------------------------------\n\n-- |\n-- Copy a number of elements from the device to host memory. This is a\n-- synchronous operation\n--\npeekArray :: Storable a => Int -> DevicePtr a -> Ptr a -> IO ()\npeekArray n dptr hptr = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ = nothingIfOk =<< cuMemcpyDtoH hptr dptr (n * sizeOf x)\n\n{# fun unsafe cuMemcpyDtoH\n { castPtr `Ptr a'\n , useDevicePtr `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy memory from the device asynchronously, possibly associated with a\n-- particular stream. The destination host memory must be page-locked (allocated\n-- by mallocHost)\n--\npeekArrayAsync :: Storable a => Int -> DevicePtr a -> Ptr a -> Maybe Stream -> IO ()\npeekArrayAsync n dptr hptr mst = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ =\n nothingIfOk =<< case mst of\n Nothing -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) (Stream nullPtr)\n Just st -> cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) st\n\n{# fun unsafe cuMemcpyDtoHAsync\n { castPtr `Ptr a'\n , useDevicePtr `DevicePtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a number of elements onto the device. This is a synchronous operation\n--\npokeArray :: Storable a => Int -> Ptr a -> DevicePtr a -> IO ()\npokeArray n hptr dptr = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPoke x _ = nothingIfOk =<< cuMemcpyHtoD dptr hptr (n * sizeOf x)\n\n{# fun unsafe cuMemcpyHtoD\n { useDevicePtr `DevicePtr a'\n , castPtr `Ptr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy memory onto the device asynchronously, possibly associated with a\n-- particular stream. The source host memory must be page-locked (allocated by\n-- mallocHost)\n--\npokeArrayAsync :: Storable a => Int -> Ptr a -> DevicePtr a -> Maybe Stream -> IO ()\npokeArrayAsync n hptr dptr mst = dopoke undefined dptr\n where\n dopoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n dopoke x _ =\n nothingIfOk =<< case mst of\n Nothing -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) (Stream nullPtr)\n Just st -> cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) st\n\n{# fun unsafe cuMemcpyHtoDAsync\n { useDevicePtr `DevicePtr a'\n , castPtr `Ptr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Utility\n--------------------------------------------------------------------------------\n\n-- |\n-- Set a number of data elements to the specified value, which may be either 8-,\n-- 16-, or 32-bits wide.\n--\nmemset :: Storable a => DevicePtr a -> Int -> a -> IO ()\nmemset dptr n val = case sizeOf val of\n 1 -> nothingIfOk =<< cuMemsetD8 dptr val n\n 2 -> nothingIfOk =<< cuMemsetD16 dptr val n\n 4 -> nothingIfOk =<< cuMemsetD32 dptr val n\n _ -> cudaError \"can only memset 8-, 16-, and 32-bit values\"\n\n--\n-- We use unsafe coerce below to reinterpret the bits of the value to memset as,\n-- into the integer type required by the setting functions.\n--\n{# fun unsafe cuMemsetD8\n { useDevicePtr `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuMemsetD16\n { useDevicePtr `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuMemsetD32\n { useDevicePtr `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the device pointer associated with a mapped, pinned host buffer, which\n-- was allocated with the DEVICE_MAPPED option.\n--\n-- Currently, no options are supported and this must be empty.\n--\ngetDevicePtr :: [AllocFlag] -> HostPtr a -> IO (DevicePtr a)\ngetDevicePtr flags hptr = withHostPtr hptr $ \\hp -> (resultIfOk =<< cuMemHostGetDevicePointer hp flags)\n\n{# fun unsafe cuMemHostGetDevicePointer\n { alloca- `DevicePtr a' dptr*\n , castPtr `Ptr a'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where dptr = liftM DevicePtr . peek\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"b19e7bc9554330a2a335d67ca0f8badad09d269f","subject":"texture reads can perform sRGB -> linear conversion","message":"texture reads can perform sRGB -> linear conversion\n\nunknown which version this was introduced\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Texture.chs","new_file":"Foreign\/CUDA\/Driver\/Texture.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# OPTIONS_HADDOCK prune #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Texture\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Texture management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Texture (\n\n -- * Texture Reference Management\n Texture(..), Format(..), AddressMode(..), FilterMode(..), ReadMode(..),\n create, destroy,\n bind, bind2D,\n getAddressMode, getFilterMode, getFormat,\n setAddressMode, setFilterMode, setFormat, setReadMode,\n\n -- Internal\n peekTex\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Ptr\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Marshal\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n#if CUDA_VERSION >= 3020\n{-# DEPRECATED create, destroy \"as of CUDA version 3.2\" #-}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A texture reference\n--\nnewtype Texture = Texture { useTexture :: {# type CUtexref #}}\n deriving (Eq, Show)\n\ninstance Storable Texture where\n sizeOf _ = sizeOf (undefined :: {# type CUtexref #})\n alignment _ = alignment (undefined :: {# type CUtexref #})\n peek p = Texture `fmap` peek (castPtr p)\n poke p t = poke (castPtr p) (useTexture t)\n\n-- |\n-- Texture reference addressing modes\n--\n{# enum CUaddress_mode as AddressMode\n { underscoreToCase }\n with prefix=\"CU_TR_ADDRESS_MODE\" deriving (Eq, Show) #}\n\n-- |\n-- Texture reference filtering mode\n--\n{# enum CUfilter_mode as FilterMode\n { underscoreToCase }\n with prefix=\"CU_TR_FILTER_MODE\" deriving (Eq, Show) #}\n\n-- |\n-- Texture read mode options\n--\n#c\ntypedef enum CUtexture_flag_enum {\n CU_TEXTURE_FLAG_READ_AS_INTEGER = CU_TRSF_READ_AS_INTEGER,\n CU_TEXTURE_FLAG_NORMALIZED_COORDINATES = CU_TRSF_NORMALIZED_COORDINATES,\n CU_TEXTURE_FLAG_SRGB = CU_TRSF_SRGB\n} CUtexture_flag;\n#endc\n\n{# enum CUtexture_flag as ReadMode\n { underscoreToCase\n , CU_TEXTURE_FLAG_SRGB as SRGB }\n with prefix=\"CU_TEXTURE_FLAG\" deriving (Eq, Show) #}\n\n-- |\n-- Texture data formats\n--\n{# enum CUarray_format as Format\n { underscoreToCase\n , UNSIGNED_INT8 as Word8\n , UNSIGNED_INT16 as Word16\n , UNSIGNED_INT32 as Word32\n , SIGNED_INT8 as Int8\n , SIGNED_INT16 as Int16\n , SIGNED_INT32 as Int32 }\n with prefix=\"CU_AD_FORMAT\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Texture management\n--------------------------------------------------------------------------------\n\n-- |\n-- Create a new texture reference. Once created, the application must call\n-- 'setPtr' to associate the reference with allocated memory. Other texture\n-- reference functions are used to specify the format and interpretation to be\n-- used when the memory is read through this reference.\n--\n{-# INLINEABLE create #-}\ncreate :: IO Texture\ncreate = resultIfOk =<< cuTexRefCreate\n\n{-# INLINE cuTexRefCreate #-}\n{# fun unsafe cuTexRefCreate\n { alloca- `Texture' peekTex* } -> `Status' cToEnum #}\n\n\n-- |\n-- Destroy a texture reference\n--\n{-# INLINEABLE destroy #-}\ndestroy :: Texture -> IO ()\ndestroy !tex = nothingIfOk =<< cuTexRefDestroy tex\n\n{-# INLINE cuTexRefDestroy #-}\n{# fun unsafe cuTexRefDestroy\n { useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |\n-- Bind a linear array address of the given size (bytes) as a texture\n-- reference. Any previously bound references are unbound.\n--\n{-# INLINEABLE bind #-}\nbind :: Texture -> DevicePtr a -> Int64 -> IO ()\nbind !tex !dptr !bytes = nothingIfOk =<< cuTexRefSetAddress tex dptr bytes\n\n{-# INLINE cuTexRefSetAddress #-}\n{# fun unsafe cuTexRefSetAddress\n { alloca- `Int'\n , useTexture `Texture'\n , useDeviceHandle `DevicePtr a'\n , `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Bind a linear address range to the given texture reference as a\n-- two-dimensional arena. Any previously bound reference is unbound. Note that\n-- calls to 'setFormat' can not follow a call to 'bind2D' for the same texture\n-- reference.\n--\n{-# INLINEABLE bind2D #-}\nbind2D :: Texture -> Format -> Int -> DevicePtr a -> (Int,Int) -> Int64 -> IO ()\nbind2D !tex !fmt !chn !dptr (!width,!height) !pitch =\n nothingIfOk =<< cuTexRefSetAddress2DSimple tex fmt chn dptr width height pitch\n\n{-# INLINE cuTexRefSetAddress2DSimple #-}\n{# fun unsafe cuTexRefSetAddress2DSimple\n { useTexture `Texture'\n , cFromEnum `Format'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Get the addressing mode used by a texture reference, corresponding to the\n-- given dimension (currently the only supported dimension values are 0 or 1).\n--\n{-# INLINEABLE getAddressMode #-}\ngetAddressMode :: Texture -> Int -> IO AddressMode\ngetAddressMode !tex !dim = resultIfOk =<< cuTexRefGetAddressMode tex dim\n\n{-# INLINE cuTexRefGetAddressMode #-}\n{# fun unsafe cuTexRefGetAddressMode\n { alloca- `AddressMode' peekEnum*\n , useTexture `Texture'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Get the filtering mode used by a texture reference\n--\n{-# INLINEABLE getFilterMode #-}\ngetFilterMode :: Texture -> IO FilterMode\ngetFilterMode !tex = resultIfOk =<< cuTexRefGetFilterMode tex\n\n{-# INLINE cuTexRefGetFilterMode #-}\n{# fun unsafe cuTexRefGetFilterMode\n { alloca- `FilterMode' peekEnum*\n , useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |\n-- Get the data format and number of channel components of the bound texture\n--\n{-# INLINEABLE getFormat #-}\ngetFormat :: Texture -> IO (Format, Int)\ngetFormat !tex = do\n (!status,!fmt,!dim) <- cuTexRefGetFormat tex\n resultIfOk (status,(fmt,dim))\n\n{-# INLINE cuTexRefGetFormat #-}\n{# fun unsafe cuTexRefGetFormat\n { alloca- `Format' peekEnum*\n , alloca- `Int' peekIntConv*\n , useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the addressing mode for the given dimension of a texture reference\n--\n{-# INLINEABLE setAddressMode #-}\nsetAddressMode :: Texture -> Int -> AddressMode -> IO ()\nsetAddressMode !tex !dim !mode = nothingIfOk =<< cuTexRefSetAddressMode tex dim mode\n\n{-# INLINE cuTexRefSetAddressMode #-}\n{# fun unsafe cuTexRefSetAddressMode\n { useTexture `Texture'\n , `Int'\n , cFromEnum `AddressMode' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the filtering mode to be used when reading memory through a texture\n-- reference\n--\n{-# INLINEABLE setFilterMode #-}\nsetFilterMode :: Texture -> FilterMode -> IO ()\nsetFilterMode !tex !mode = nothingIfOk =<< cuTexRefSetFilterMode tex mode\n\n{-# INLINE cuTexRefSetFilterMode #-}\n{# fun unsafe cuTexRefSetFilterMode\n { useTexture `Texture'\n , cFromEnum `FilterMode' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify additional characteristics for reading and indexing the texture\n-- reference\n--\n{-# INLINEABLE setReadMode #-}\nsetReadMode :: Texture -> ReadMode -> IO ()\nsetReadMode !tex !mode = nothingIfOk =<< cuTexRefSetFlags tex mode\n\n{-# INLINE cuTexRefSetFlags #-}\n{# fun unsafe cuTexRefSetFlags\n { useTexture `Texture'\n , cFromEnum `ReadMode' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the format of the data and number of packed components per element to\n-- be read by the texture reference\n--\n{-# INLINEABLE setFormat #-}\nsetFormat :: Texture -> Format -> Int -> IO ()\nsetFormat !tex !fmt !chn = nothingIfOk =<< cuTexRefSetFormat tex fmt chn\n\n{-# INLINE cuTexRefSetFormat #-}\n{# fun unsafe cuTexRefSetFormat\n { useTexture `Texture'\n , cFromEnum `Format'\n , `Int' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE peekTex #-}\npeekTex :: Ptr {# type CUtexref #} -> IO Texture\npeekTex = liftM Texture . peek\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# OPTIONS_HADDOCK prune #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Texture\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Texture management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Texture (\n\n -- * Texture Reference Management\n Texture(..), Format(..), AddressMode(..), FilterMode(..), ReadMode(..),\n create, destroy,\n bind, bind2D,\n getAddressMode, getFilterMode, getFormat,\n setAddressMode, setFilterMode, setFormat, setReadMode,\n\n -- Internal\n peekTex\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Ptr\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Marshal\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n#if CUDA_VERSION >= 3020\n{-# DEPRECATED create, destroy \"as of CUDA version 3.2\" #-}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A texture reference\n--\nnewtype Texture = Texture { useTexture :: {# type CUtexref #}}\n deriving (Eq, Show)\n\ninstance Storable Texture where\n sizeOf _ = sizeOf (undefined :: {# type CUtexref #})\n alignment _ = alignment (undefined :: {# type CUtexref #})\n peek p = Texture `fmap` peek (castPtr p)\n poke p t = poke (castPtr p) (useTexture t)\n\n-- |\n-- Texture reference addressing modes\n--\n{# enum CUaddress_mode as AddressMode\n { underscoreToCase }\n with prefix=\"CU_TR_ADDRESS_MODE\" deriving (Eq, Show) #}\n\n-- |\n-- Texture reference filtering mode\n--\n{# enum CUfilter_mode as FilterMode\n { underscoreToCase }\n with prefix=\"CU_TR_FILTER_MODE\" deriving (Eq, Show) #}\n\n-- |\n-- Texture read mode options\n--\n#c\ntypedef enum CUtexture_flag_enum {\n CU_TEXTURE_FLAG_READ_AS_INTEGER = CU_TRSF_READ_AS_INTEGER,\n CU_TEXTURE_FLAG_NORMALIZED_COORDINATES = CU_TRSF_NORMALIZED_COORDINATES\n} CUtexture_flag;\n#endc\n\n{# enum CUtexture_flag as ReadMode\n { underscoreToCase }\n with prefix=\"CU_TEXTURE_FLAG\" deriving (Eq, Show) #}\n\n-- |\n-- Texture data formats\n--\n{# enum CUarray_format as Format\n { underscoreToCase\n , UNSIGNED_INT8 as Word8\n , UNSIGNED_INT16 as Word16\n , UNSIGNED_INT32 as Word32\n , SIGNED_INT8 as Int8\n , SIGNED_INT16 as Int16\n , SIGNED_INT32 as Int32 }\n with prefix=\"CU_AD_FORMAT\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Texture management\n--------------------------------------------------------------------------------\n\n-- |\n-- Create a new texture reference. Once created, the application must call\n-- 'setPtr' to associate the reference with allocated memory. Other texture\n-- reference functions are used to specify the format and interpretation to be\n-- used when the memory is read through this reference.\n--\n{-# INLINEABLE create #-}\ncreate :: IO Texture\ncreate = resultIfOk =<< cuTexRefCreate\n\n{-# INLINE cuTexRefCreate #-}\n{# fun unsafe cuTexRefCreate\n { alloca- `Texture' peekTex* } -> `Status' cToEnum #}\n\n\n-- |\n-- Destroy a texture reference\n--\n{-# INLINEABLE destroy #-}\ndestroy :: Texture -> IO ()\ndestroy !tex = nothingIfOk =<< cuTexRefDestroy tex\n\n{-# INLINE cuTexRefDestroy #-}\n{# fun unsafe cuTexRefDestroy\n { useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |\n-- Bind a linear array address of the given size (bytes) as a texture\n-- reference. Any previously bound references are unbound.\n--\n{-# INLINEABLE bind #-}\nbind :: Texture -> DevicePtr a -> Int64 -> IO ()\nbind !tex !dptr !bytes = nothingIfOk =<< cuTexRefSetAddress tex dptr bytes\n\n{-# INLINE cuTexRefSetAddress #-}\n{# fun unsafe cuTexRefSetAddress\n { alloca- `Int'\n , useTexture `Texture'\n , useDeviceHandle `DevicePtr a'\n , `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Bind a linear address range to the given texture reference as a\n-- two-dimensional arena. Any previously bound reference is unbound. Note that\n-- calls to 'setFormat' can not follow a call to 'bind2D' for the same texture\n-- reference.\n--\n{-# INLINEABLE bind2D #-}\nbind2D :: Texture -> Format -> Int -> DevicePtr a -> (Int,Int) -> Int64 -> IO ()\nbind2D !tex !fmt !chn !dptr (!width,!height) !pitch =\n nothingIfOk =<< cuTexRefSetAddress2DSimple tex fmt chn dptr width height pitch\n\n{-# INLINE cuTexRefSetAddress2DSimple #-}\n{# fun unsafe cuTexRefSetAddress2DSimple\n { useTexture `Texture'\n , cFromEnum `Format'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Get the addressing mode used by a texture reference, corresponding to the\n-- given dimension (currently the only supported dimension values are 0 or 1).\n--\n{-# INLINEABLE getAddressMode #-}\ngetAddressMode :: Texture -> Int -> IO AddressMode\ngetAddressMode !tex !dim = resultIfOk =<< cuTexRefGetAddressMode tex dim\n\n{-# INLINE cuTexRefGetAddressMode #-}\n{# fun unsafe cuTexRefGetAddressMode\n { alloca- `AddressMode' peekEnum*\n , useTexture `Texture'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Get the filtering mode used by a texture reference\n--\n{-# INLINEABLE getFilterMode #-}\ngetFilterMode :: Texture -> IO FilterMode\ngetFilterMode !tex = resultIfOk =<< cuTexRefGetFilterMode tex\n\n{-# INLINE cuTexRefGetFilterMode #-}\n{# fun unsafe cuTexRefGetFilterMode\n { alloca- `FilterMode' peekEnum*\n , useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |\n-- Get the data format and number of channel components of the bound texture\n--\n{-# INLINEABLE getFormat #-}\ngetFormat :: Texture -> IO (Format, Int)\ngetFormat !tex = do\n (!status,!fmt,!dim) <- cuTexRefGetFormat tex\n resultIfOk (status,(fmt,dim))\n\n{-# INLINE cuTexRefGetFormat #-}\n{# fun unsafe cuTexRefGetFormat\n { alloca- `Format' peekEnum*\n , alloca- `Int' peekIntConv*\n , useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the addressing mode for the given dimension of a texture reference\n--\n{-# INLINEABLE setAddressMode #-}\nsetAddressMode :: Texture -> Int -> AddressMode -> IO ()\nsetAddressMode !tex !dim !mode = nothingIfOk =<< cuTexRefSetAddressMode tex dim mode\n\n{-# INLINE cuTexRefSetAddressMode #-}\n{# fun unsafe cuTexRefSetAddressMode\n { useTexture `Texture'\n , `Int'\n , cFromEnum `AddressMode' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the filtering mode to be used when reading memory through a texture\n-- reference\n--\n{-# INLINEABLE setFilterMode #-}\nsetFilterMode :: Texture -> FilterMode -> IO ()\nsetFilterMode !tex !mode = nothingIfOk =<< cuTexRefSetFilterMode tex mode\n\n{-# INLINE cuTexRefSetFilterMode #-}\n{# fun unsafe cuTexRefSetFilterMode\n { useTexture `Texture'\n , cFromEnum `FilterMode' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify additional characteristics for reading and indexing the texture\n-- reference\n--\n{-# INLINEABLE setReadMode #-}\nsetReadMode :: Texture -> ReadMode -> IO ()\nsetReadMode !tex !mode = nothingIfOk =<< cuTexRefSetFlags tex mode\n\n{-# INLINE cuTexRefSetFlags #-}\n{# fun unsafe cuTexRefSetFlags\n { useTexture `Texture'\n , cFromEnum `ReadMode' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the format of the data and number of packed components per element to\n-- be read by the texture reference\n--\n{-# INLINEABLE setFormat #-}\nsetFormat :: Texture -> Format -> Int -> IO ()\nsetFormat !tex !fmt !chn = nothingIfOk =<< cuTexRefSetFormat tex fmt chn\n\n{-# INLINE cuTexRefSetFormat #-}\n{# fun unsafe cuTexRefSetFormat\n { useTexture `Texture'\n , cFromEnum `Format'\n , `Int' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE peekTex #-}\npeekTex :: Ptr {# type CUtexref #} -> IO Texture\npeekTex = liftM Texture . peek\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"7ae7bc4ecee1e22fbc7f77b0b57f0b88095f5221","subject":"Foreign: do not use the `unsafe' keyword for foreign imports","message":"Foreign: do not use the `unsafe' keyword for foreign imports\n\nAccording to http:\/\/blog.ezyang.com\/2010\/07\/safety-first-ffi-and-threading,\nGHC is not able to preempt `unsafe' imports, and it therefore plays\nbadly with threading.\n","repos":"joachifm\/hxine,joachifm\/hxine","old_file":"Xine\/Foreign.chs","new_file":"Xine\/Foreign.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\n-- |\n-- Module : Xine.Foreign\n-- Copyright : (c) Joachim Fasting 2010\n-- License : LGPL (see COPYING)\n-- Maintainer : Joachim Fasting \n-- Stability : unstable\n-- Portability : not portable\n--\n-- A simple binding to xine-lib. Low-level bindings.\n-- Made for xine-lib version 1.1.18.1\n\nmodule Xine.Foreign (\n -- * Version information\n xine_get_version_string, xine_get_version, xine_check_version,\n -- * Global engine handling\n Engine, AudioPort, VideoPort, VisualType(..),\n xine_new, xine_init, xine_open_audio_driver, xine_open_video_driver,\n xine_close_audio_driver, xine_close_video_driver, xine_exit,\n -- * Stream handling\n Stream, StreamParam(..), Speed(..), NormalSpeed(..), Zoom(..),\n AspectRatio(..), MRL, EngineParam(..), Affection(..), TrickMode(..),\n xine_stream_new, xine_stream_master_slave, xine_open, xine_play,\n xine_dispose, xine_eject,\n xine_trick_mode, xine_stop, xine_close, xine_engine_set_param,\n xine_engine_get_param, xine_set_param, xine_get_param,\n -- * Information retrieval\n EngineStatus(..), XineError(..),\n xine_get_error, xine_get_status,\n xine_get_audio_lang, xine_get_spu_lang,\n xine_get_pos_length,\n InfoType(..), MetaType(..),\n xine_get_stream_info, xine_get_meta_info\n ) where\n\nimport Control.Monad (liftM)\nimport Data.Bits\nimport Foreign\nimport Foreign.C\n\n#include \n\n-- Define the name of the dynamic library that has to be loaded before any of\n-- the external C functions may be invoked.\n-- The prefix declaration allows us to refer to identifiers while omitting the\n-- prefix. Prefix matching is case insensitive and any underscore characters\n-- between the prefix and the stem of the identifiers are also removed.\n{#context lib=\"xine\" prefix=\"xine\"#}\n\n-- Opaque types used for structures that are never dereferenced on the\n-- Haskell side.\n{#pointer *xine_t as Engine foreign newtype#}\n{#pointer *xine_audio_port_t as AudioPort foreign newtype#}\n{#pointer *xine_video_port_t as VideoPort foreign newtype#}\n{#pointer *xine_stream_t as Stream foreign newtype#}\n\n-- XXX: just a hack. We really want to be able to pass\n-- custom structs to functions. See 'withData', 'xine_open_audio_driver'.\nnewtype Data = Data (Ptr Data)\n\n-- | Media Resource Locator.\n-- Describes the media to read from. Valid MRLs may be plain file names or\n-- one of the following:\n--\n-- * Filesystem:\n--\n-- file:\\\n--\n-- fifo:\\\n--\n-- stdin:\\\/\n--\n-- * CD and DVD:\n--\n-- dvd:\\\/[device_name][\\\/title[.part]]\n--\n-- dvd:\\\/DVD_image_file[\\\/title[.part]]\n--\n-- dvd:\\\/DVD_directory[\\\/title[.part]]\n--\n-- vcd:\\\/\\\/[CD_image_or_device_name][\\@[letter]number]\n--\n-- vcdo:\\\/\\\/track_number\n--\n-- cdda:\\\/[device][\\\/track_number]\n--\n-- * Video devices:\n--\n-- v4l:\\\/\\\/[tuner_device\\\/frequency\n--\n-- v4l2:\\\/\\\/tuner_device\n--\n-- dvb:\\\/\\\/channel_number\n--\n-- dvb:\\\/\\\/channel_name\n--\n-- dvbc:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvbs:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvbt:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvba:\\\/\\\/channel_name:tuning_parameters\n--\n-- pvr:\\\/tmp_files_path!saved_files_path!max_page_age\n--\n-- * Network:\n--\n-- http:\\\/\\\/host\n--\n-- tcp:\\\/\\\/host[:port]\n--\n-- udp:\\\/\\\/host[:port[?iface=interface]]\n--\n-- rtp:\\\/\\\/host[:port[?iface=interface]]\n--\n-- smb:\\\/\\\/\n--\n-- mms:\\\/\\\/host\n--\n-- pnm:\\\/\\\/host\n--\n-- rtsp:\\\/\\\/host\ntype MRL = String\n\n------------------------------------------------------------------------------\n-- Marshalling\n------------------------------------------------------------------------------\n\ncint2bool :: CInt -> Bool\ncint2bool = (\/= 0)\n{-# INLINE cint2bool #-}\n\nint2cint :: Int -> CInt\nint2cint = fromIntegral\n{-# INLINE int2cint #-}\n\ncint2int :: CInt -> Int\ncint2int = fromIntegral\n{-# INLINE cint2int #-}\n\ncuint2int :: CUInt -> Int\ncuint2int = fromIntegral\n{-# INLINE cuint2int #-}\n\ncint2enum :: Enum a => CInt -> a\ncint2enum = toEnum . cint2int\n{-# INLINE cint2enum #-}\n\nenum2cint :: Enum a => a -> CInt\nenum2cint = int2cint . fromEnum\n{-# INLINE enum2cint #-}\n\npeekInt :: Ptr CInt -> IO Int\npeekInt = liftM cint2int . peek\n{-# INLINE peekInt #-}\n\n-- For pointers which may be NULL.\nmaybeForeignPtr_ c x | x == nullPtr = return Nothing\n | otherwise = (Just . c) `liftM` newForeignPtr_ x\n\npeekEngine = liftM Engine . newForeignPtr_\n{-# INLINE peekEngine #-}\n\npeekAudioPort = maybeForeignPtr_ AudioPort\n{-# INLINE peekAudioPort #-}\n\npeekVideoPort = maybeForeignPtr_ VideoPort\n{-# INLINE peekVideoPort #-}\n\npeekStream = maybeForeignPtr_ Stream\n{-# INLINE peekStream #-}\n\n-- XXX: just a temporary hack until we can actually support\n-- passing a custom struct to functions which support it.\nwithData f = f nullPtr\n\n-- Handle strings which may be NULL.\nwithMaybeString :: Maybe String -> (CString -> IO a) -> IO a\nwithMaybeString Nothing f = f nullPtr\nwithMaybeString (Just s) f = withCString s f\n\n------------------------------------------------------------------------------\n-- Version information\n------------------------------------------------------------------------------\n\n-- | Get xine-lib version string.\n--\n-- Header declaration:\n--\n-- const char *xine_get_version_string (void)\n{#fun pure xine_get_version_string {} -> `String' peekCString*#}\n\n-- | Get version as a triple: major, minor, sub\n--\n-- Header declaration:\n--\n-- void xine_get_version (int *major, int *minor, int *sub)\n{#fun pure xine_get_version\n {alloca- `Int' peekInt*,\n alloca- `Int' peekInt*,\n alloca- `Int' peekInt*} -> `()'#}\n\n-- | Compare given version to xine-lib version (major, minor, sub).\n--\n-- Header declaration:\n--\n-- int xine_check_version (int major, int minor, int sub)\n--\n-- returns 1 if compatible, 0 otherwise.\n{#fun pure xine_check_version\n {int2cint `Int',\n int2cint `Int',\n int2cint `Int'} -> `Bool' cint2bool#}\n\n------------------------------------------------------------------------------\n-- Global engine handling\n------------------------------------------------------------------------------\n\n-- | Valid visual types\n{#enum define VisualType {XINE_VISUAL_TYPE_NONE as None\n ,XINE_VISUAL_TYPE_X11 as X11\n ,XINE_VISUAL_TYPE_X11_2 as X11_2\n ,XINE_VISUAL_TYPE_AA as AA\n ,XINE_VISUAL_TYPE_FB as FB\n ,XINE_VISUAL_TYPE_GTK as GTK\n ,XINE_VISUAL_TYPE_DFB as DFB\n ,XINE_VISUAL_TYPE_PM as PM\n ,XINE_VISUAL_TYPE_DIRECTX as DirectX\n ,XINE_VISUAL_TYPE_CACA as CACA\n ,XINE_VISUAL_TYPE_MACOSX as MacOSX\n ,XINE_VISUAL_TYPE_XCB as XCB\n ,XINE_VISUAL_TYPE_RAW as Raw\n }#}\n\n-- | Pre-init the Xine engine.\n--\n-- Header declaration:\n--\n-- xine_t *xine_new (void)\n{#fun xine_new {} -> `Engine' peekEngine*#}\n\n-- | Post-init the Xine engine.\n--\n-- Header declaration:\n--\n-- void xine_init (xine_t *self)\n{#fun xine_init {withEngine* `Engine'} -> `()'#}\n\n-- | Initialise audio driver.\n--\n-- Header declaration:\n--\n-- xine_audio_port_t *xine_open_audio_driver (xine_t *self, const char *id,\n-- void *data)\n--\n-- id: identifier of the driver, may be NULL for auto-detection\n--\n-- data: special data struct for ui\/driver communication\n--\n-- May return NULL if the driver failed to load.\n{#fun xine_open_audio_driver\n {withEngine* `Engine'\n ,withMaybeString* `(Maybe String)'\n ,withData- `Data'} -> `(Maybe AudioPort)' peekAudioPort*#}\n\n-- | Initialise video driver.\n--\n-- Header declaration:\n--\n-- xine_video_port_t *xine_open_video_driver (xine_t *self, const char *id,\n-- int visual, void *data)\n--\n-- id: identifier of the driver, may be NULL for auto-detection\n--\n-- data: special data struct for ui\/driver communication\n--\n-- visual : video driver flavor selector\n--\n-- May return NULL if the driver failed to load.\n{#fun xine_open_video_driver\n {withEngine* `Engine'\n ,withMaybeString* `(Maybe String)'\n ,enum2cint `VisualType'\n ,withData- `Data'} -> `(Maybe VideoPort)' peekVideoPort*#}\n\n-- | Close audio port.\n--\n-- Header declaration:\n--\n-- void xine_close_audio_driver (xine_t *self, xine_audio_port_t *driver)\n{#fun xine_close_audio_driver\n {withEngine* `Engine'\n ,withAudioPort* `AudioPort'} -> `()'#}\n\n-- | Close video port.\n--\n-- Header declaration:\n--\n-- void xine_close_video_driver (xine_t *self, xine_video_port_t *driver)\n{#fun xine_close_video_driver\n {withEngine* `Engine'\n ,withVideoPort* `VideoPort'} -> `()'#}\n\n-- | Free all resources, close all plugins, close engine.\n--\n-- Header declaration:\n--\n-- void xine_exit (xine_t *self)\n{#fun xine_exit {withEngine* `Engine'} -> `()'#}\n\n------------------------------------------------------------------------------\n-- Stream handling\n------------------------------------------------------------------------------\n\n-- | Engine parameter enumeration.\n{#enum define EngineParam\n {XINE_ENGINE_PARAM_VERBOSITY as EngineVerbosity}#}\n\n-- | Stream parameter enumeration.\n{#enum define StreamParam\n {XINE_PARAM_SPEED as Speed\n ,XINE_PARAM_AV_OFFSET as AvOffset\n ,XINE_PARAM_AUDIO_CHANNEL_LOGICAL as AudioChannelLogical\n ,XINE_PARAM_SPU_CHANNEL as SpuChannel\n ,XINE_PARAM_AUDIO_VOLUME as AudioVolume\n ,XINE_PARAM_AUDIO_MUTE as AudioMute\n ,XINE_PARAM_AUDIO_COMPR_LEVEL as AudioComprLevel\n ,XINE_PARAM_AUDIO_REPORT_LEVEL as AudioReportLevel\n ,XINE_PARAM_VERBOSITY as Verbosity\n ,XINE_PARAM_SPU_OFFSET as SpuOffset\n ,XINE_PARAM_IGNORE_VIDEO as IgnoreVideo\n ,XINE_PARAM_IGNORE_AUDIO as IgnoreAudio\n ,XINE_PARAM_BROADCASTER_PORT as BroadcasterPort\n ,XINE_PARAM_METRONOM_PREBUFFER as MetronomPrebuffer\n ,XINE_PARAM_EQ_30HZ as Eq30Hz\n ,XINE_PARAM_EQ_60HZ as Eq60Hz\n ,XINE_PARAM_EQ_125HZ as Eq125Hz\n ,XINE_PARAM_EQ_500HZ as Eq500Hz\n ,XINE_PARAM_EQ_1000HZ as Eq1000Hz\n ,XINE_PARAM_EQ_2000HZ as Eq2000Hz\n ,XINE_PARAM_EQ_4000HZ as Eq4000Hz\n ,XINE_PARAM_EQ_8000HZ as Eq8000Hz\n ,XINE_PARAM_EQ_16000HZ as Eq16000Hz\n ,XINE_PARAM_AUDIO_CLOSE_DEVICE as AudioCloseDevice\n ,XINE_PARAM_AUDIO_AMP_MUTE as AmpMute\n ,XINE_PARAM_FINE_SPEED as FineSpeed\n ,XINE_PARAM_EARLY_FINISHED_EVENT as EarlyFinishedEvent\n ,XINE_PARAM_GAPLESS_SWITCH as GaplessSwitch\n ,XINE_PARAM_DELAY_FINISHED_EVENT as DelayFinishedEvent\n ,XINE_PARAM_VO_DEINTERLACE as Deinterlace\n ,XINE_PARAM_VO_ASPECT_RATIO as AspectRatio\n ,XINE_PARAM_VO_HUE as Hue\n ,XINE_PARAM_VO_SATURATION as Saturation\n ,XINE_PARAM_VO_CONTRAST as Contrast\n ,XINE_PARAM_VO_BRIGHTNESS as Brightness\n ,XINE_PARAM_VO_ZOOM_X as ZoomX\n ,XINE_PARAM_VO_ZOOM_Y as ZoomY\n ,XINE_PARAM_VO_PAN_SCAN as PanScan\n ,XINE_PARAM_VO_TVMODE as TvMode\n ,XINE_PARAM_VO_WINDOW_WIDTH as WindowWidth\n ,XINE_PARAM_VO_WINDOW_HEIGHT as WindowHeight\n ,XINE_PARAM_VO_CROP_LEFT as CropLeft\n ,XINE_PARAM_VO_CROP_RIGHT as CropRight\n ,XINE_PARAM_VO_CROP_TOP as CropTop\n ,XINE_PARAM_VO_CROP_BOTTOM as CropBottom\n }#}\n\n-- | Values for XINE_PARAM_SPEED parameter.\n{#enum define Speed\n {XINE_SPEED_PAUSE as Pause\n ,XINE_SPEED_SLOW_4 as Slow4\n ,XINE_SPEED_SLOW_2 as Slow2\n ,XINE_SPEED_NORMAL as Normal\n ,XINE_SPEED_FAST_2 as Fast2\n ,XINE_SPEED_FAST_4 as Fast4\n }#}\n\nderiving instance Eq Speed\n\n-- | Value for XINE_PARAM_FINE_SPEED\n{#enum define NormalSpeed\n {XINE_FINE_SPEED_NORMAL as NormalSpeed}#}\n\n-- | Values for XINE_PARAM_VO_ZOOM_\n{#enum define Zoom\n {XINE_VO_ZOOM_STEP as ZoomStep\n ,XINE_VO_ZOOM_MAX as ZoomMax\n ,XINE_VO_ZOOM_MIN as ZoomMin}#}\n\n-- | Values for XINE_PARAM_VO_ASPECT_RATIO\n{#enum define AspectRatio\n {XINE_VO_ASPECT_AUTO as AspectAuto\n ,XINE_VO_ASPECT_SQUARE as AspectSquare\n ,XINE_VO_ASPECT_4_3 as Aspect43\n ,XINE_VO_ASPECT_ANAMORPHIC as AspectAnamorphic\n ,XINE_VO_ASPECT_DVB as AspectDvb\n ,XINE_VO_ASPECT_NUM_RATIOS as AspectNumRatios\n }#}\n\n-- | Create a new stream for media playback.\n--\n-- Header declaration:\n--\n-- xine_stream_t *xine_stream_new (xine_t *self,\n-- xine_audio_port *ao, xine_video_port_t *vo)\n--\n-- Returns xine_stream_t* if OK, NULL on error (use 'xine_get_error' for\n-- details).\n{#fun xine_stream_new\n {withEngine* `Engine'\n ,withAudioPort* `AudioPort'\n ,withVideoPort* `VideoPort'} -> `(Maybe Stream)' peekStream*#}\n\n-- | Make one stream the slave of another.\n-- Certain operations on the master stream are also applied to the slave\n-- stream.\n--\n-- Header declaration:\n--\n-- int xine_stream_master_slave (xine_stream_t *master, xine_stream_t *slave,\n-- int affection)\n--\n-- returns 1 on success, 0 on failure.\n{#fun xine_stream_master_slave\n {withStream* `Stream'\n ,withStream* `Stream'\n ,combineAffection `[Affection]'} -> `Int' cint2int#}\n\n-- | The affection determines which actions on the master stream\n-- are also to be applied to the slave stream. See 'xine_stream_master_slave'.\n{#enum define Affection\n {XINE_MASTER_SLAVE_PLAY as AffectionPlay\n ,XINE_MASTER_SLAVE_STOP as AffectionStop\n ,XINE_MASTER_SLAVE_SPEED as AffectionSpeed}#}\n\n-- | Affections can be ORed together.\ncombineAffection :: [Affection] -> CInt\ncombineAffection [] = enum2cint AffectionSpeed\ncombineAffection xs = foldr1 (.&.) (map enum2cint xs)\n\n-- | Open a stream.\n--\n-- Header declaration:\n--\n-- int xine_open (xine_stream_t *stream, const char *mrl)\n--\n-- Returns 1 if OK, 0 on error (use 'xine_get_error' for details).\n{#fun xine_open\n {withStream* `Stream'\n ,withCAString* `MRL'} -> `Int' cint2int#}\n\n-- | Play a stream from a given position.\n--\n-- Header declaration:\n--\n-- int xine_play (xine_stream_t *stream, int start_pos, int start_time)\n--\n-- Returns 1 if OK, 0 on error (use 'xine_get_error' for details).\n{#fun xine_play\n {withStream* `Stream'\n ,int2cint `Int'\n ,int2cint `Int'} -> `Int' cint2int#}\n\n-- | Set xine to a trick mode for fast forward, backwards playback,\n-- low latency seeking.\n--\n-- Header declaration:\n--\n-- int xine_trick_mode (xine_stream_t *stream, int mode, int value)\n--\n-- Returns 1 if OK, 0 on error (use 'xine_get_error' for details).\n{#fun xine_trick_mode\n {withStream* `Stream'\n ,enum2cint `TrickMode'\n ,int2cint `Int'} -> `Int' cint2int#}\n\n{#enum define TrickMode\n {XINE_TRICK_MODE_OFF as TrickOff\n ,XINE_TRICK_MODE_SEEK_TO_POSITION as TrickSeekToPosition\n ,XINE_TRICK_MODE_SEEK_TO_TIME as TrickSeekToTime\n ,XINE_TRICK_MODE_FAST_FORWARD as TrickFastForward\n ,XINE_TRICK_MODE_FAST_REWIND as TrickRewind}#}\n\n-- | Stop stream playback.\n-- The stream stays valid for new 'xine_open' or 'xine_play'.\n--\n-- Header declaration:\n--\n-- void xine_stop (xine_stream *stream)\n{#fun xine_stop {withStream* `Stream'} -> `()'#}\n\n-- | Free all stream-related resources.\n-- The stream stays valid for new 'xine_open'.\n--\n-- Header declaration:\n--\n-- void xine_close (xine_stream_t *stream)\n{#fun xine_close {withStream* `Stream'} -> `()'#}\n\n-- | Ask current input plugin to eject media.\n--\n-- Header declaration:\n--\n-- int xine_eject (xine_stream_t *stream)\n{#fun xine_eject {withStream* `Stream'} -> `Int' cint2int#}\n\n-- | Stop playback, dispose all stream-related resources.\n-- The stream is no longer valid after this.\n--\n-- Header declaration:\n--\n-- void xine_dispose (xine_stream_t *stream)\n{#fun xine_dispose {withStream* `Stream'} -> `()'#}\n\n-- | Set engine parameter.\n--\n-- Header declaration:\n--\n-- void xine_engine_set_param (xine_t *self, int param, int value)\n{#fun xine_engine_set_param\n {withEngine* `Engine'\n ,enum2cint `EngineParam'\n ,int2cint `Int'} -> `()'#}\n\n-- | Get engine parameter.\n--\n-- Header declaration:\n--\n-- int xine_engine_get_param(xine_t *self, int param)\n{#fun xine_engine_get_param\n {withEngine* `Engine'\n ,enum2cint `EngineParam'} -> `Int' cint2int#}\n\n-- | Set stream parameter.\n--\n-- Header declaration:\n--\n-- void xine_set_param (xine_stream_t *stream, int param, int value)\n{#fun xine_set_param\n `(Enum a)' =>\n {withStream* `Stream'\n ,enum2cint `StreamParam'\n ,enum2cint `a'} -> `()'#}\n\n-- | Get stream parameter.\n--\n-- Header declaration:\n--\n-- int xine_get_param (xine_stream_t *stream, int param)\n{#fun xine_get_param\n `(Enum a)' =>\n {withStream* `Stream'\n ,enum2cint `StreamParam'} -> `a' cint2enum#}\n\n------------------------------------------------------------------------------\n-- Information retrieval\n------------------------------------------------------------------------------\n\n-- | Engine status codes.\n{#enum define EngineStatus\n {XINE_STATUS_IDLE as Idle\n ,XINE_STATUS_STOP as Stopped\n ,XINE_STATUS_PLAY as Playing\n ,XINE_STATUS_QUIT as Quitting}#}\n\nderiving instance Eq EngineStatus\nderiving instance Show EngineStatus\n\n-- | Xine error codes.\n{#enum define XineError\n {XINE_ERROR_NONE as NoError\n ,XINE_ERROR_NO_INPUT_PLUGIN as NoInputPlugin\n ,XINE_ERROR_NO_DEMUX_PLUGIN as NoDemuxPlugin\n ,XINE_ERROR_MALFORMED_MRL as MalformedMrl\n ,XINE_ERROR_INPUT_FAILED as InputFailed}#}\n\nderiving instance Eq XineError\nderiving instance Show XineError\n\n-- | Return last error.\n--\n-- Header declaration:\n--\n-- int xine_get_error (xine_stream_t *stream)\n{#fun xine_get_error\n {withStream* `Stream'} -> `XineError' cint2enum#}\n\n-- | Get current xine engine status.\n--\n-- int xine_get_status (xine_stream_t *stream)\n{#fun xine_get_status\n {withStream* `Stream'} -> `EngineStatus' cint2enum#}\n\n-- | Find the audio language of the given channel (use -1 for\n-- current channel).\n--\n-- Header declaration:\n--\n-- int xine_get_audio_lang (xine_stream_t *stream, int channel,\n-- char *lang)\n--\n-- lang must point to a buffer of at least XINE_LANG_MAX bytes.\n--\n-- Returns 1 on success, 0 on failure.\n{#fun xine_get_audio_lang\n {withStream* `Stream'\n ,int2cint `Int'\n ,allocLangBuf- `String' peekCString*} -> `Int' cint2int#}\n\n-- XXX: read the constant XINE_LANG_MAX\nallocLangBuf = allocaArray0 32\n\n-- | Find the spu language of the given channel (use -1 for\n-- current channel).\n--\n-- Header declaration:\n--\n-- int xine_get_spu_lang (xine_stream_t *stream, int channel,\n-- char *lang)\n--\n-- lang must point to a buffer of at least XINE_LANG_MAX bytes.\n--\n-- Returns 1 on success, 0 on failure.\n{#fun xine_get_spu_lang\n {withStream* `Stream'\n ,int2cint `Int'\n ,allocLangBuf- `String' peekCString*} -> `Int' cint2int#}\n\n-- | Get position\\\/length information.\n--\n-- Header declaration:\n--\n-- int xine_get_pos_length (xine_stream_t *stream, int *pos_stream,\n-- int *pos_time, int *length_time)\n--\n-- Returns 1 on success, 0 on failure.\n{#fun xine_get_pos_length\n {withStream* `Stream'\n ,alloca- `Int' peekInt*\n ,alloca- `Int' peekInt*\n ,alloca- `Int' peekInt*} -> `Int' cint2int#}\n\n-- | Get information about the stream.\n--\n-- Header declaration:\n--\n-- int32_t xine_get_stream_info (xine_stream_t *stream, int info)\n{#fun xine_get_stream_info\n {withStream* `Stream'\n ,enum2cint `InfoType'} -> `Int' cuint2int#}\n\n-- | Get meta information about the stream.\n--\n-- Header declaration:\n--\n-- const char *xine_get_meta_info (xine_stream_t *stream, int info)\n{#fun xine_get_meta_info\n {withStream* `Stream'\n ,enum2cint `MetaType'} -> `String' peekCString*#}\n\n{#enum define InfoType\n {XINE_STREAM_INFO_BITRATE as InfoBitrate\n ,XINE_STREAM_INFO_SEEKABLE as InfoSeekable\n ,XINE_STREAM_INFO_VIDEO_WIDTH as InfoVideoWidth\n ,XINE_STREAM_INFO_VIDEO_HEIGHT as InfoVideoHeight\n ,XINE_STREAM_INFO_VIDEO_RATIO as InfoVideoRatio\n ,XINE_STREAM_INFO_VIDEO_CHANNELS as InfoVideoChannels\n ,XINE_STREAM_INFO_VIDEO_STREAMS as InfoVideoStreams\n ,XINE_STREAM_INFO_VIDEO_BITRATE as InfoVideoBitrate\n ,XINE_STREAM_INFO_VIDEO_FOURCC as InfoVideoFourCC\n ,XINE_STREAM_INFO_VIDEO_HANDLED as InfoVideoHandled\n ,XINE_STREAM_INFO_FRAME_DURATION as InfoFrameDuration\n ,XINE_STREAM_INFO_AUDIO_CHANNELS as InfoAudioChannels\n ,XINE_STREAM_INFO_AUDIO_BITS as InfoAudioBits\n ,XINE_STREAM_INFO_AUDIO_SAMPLERATE as InfoAudioSamplerate\n ,XINE_STREAM_INFO_AUDIO_BITRATE as InfoAudioBitrate\n ,XINE_STREAM_INFO_AUDIO_FOURCC as InfoAudioFourCC\n ,XINE_STREAM_INFO_AUDIO_HANDLED as InfoAudioHandled\n ,XINE_STREAM_INFO_HAS_CHAPTERS as InfoHasChapters\n ,XINE_STREAM_INFO_HAS_VIDEO as InfoHasVideo\n ,XINE_STREAM_INFO_HAS_AUDIO as InfoHasAudio\n ,XINE_STREAM_INFO_IGNORE_VIDEO as InfoIgnoreVideo\n ,XINE_STREAM_INFO_IGNORE_AUDIO as InfoIgnoreAudio\n ,XINE_STREAM_INFO_IGNORE_SPU as InfoIgnoreSpu\n ,XINE_STREAM_INFO_VIDEO_HAS_STILL as InfoVideoHasStill\n ,XINE_STREAM_INFO_MAX_AUDIO_CHANNEL as InfoMaxAudioChannel\n ,XINE_STREAM_INFO_MAX_SPU_CHANNEL as InfoMaxSpuChannel\n ,XINE_STREAM_INFO_AUDIO_MODE as InfoAudioMode\n ,XINE_STREAM_INFO_SKIPPED_FRAMES as InfoSkippedFrames\n ,XINE_STREAM_INFO_DISCARDED_FRAMES as InfoDiscardedFrames\n ,XINE_STREAM_INFO_VIDEO_AFD as InfoVideoAFD\n ,XINE_STREAM_INFO_DVD_TITLE_NUMBER as InfoDvdTitleNumber\n ,XINE_STREAM_INFO_DVD_TITLE_COUNT as InfoDvdTitleCount\n ,XINE_STREAM_INFO_DVD_CHAPTER_NUMBER as InfoDvdChapterNumber\n ,XINE_STREAM_INFO_DVD_CHAPTER_COUNT as InfoDvdChapterCount\n ,XINE_STREAM_INFO_DVD_ANGLE_NUMBER as InfoDvdAngleNumber\n ,XINE_STREAM_INFO_DVD_ANGLE_COUNT as InfoDvdAngleCount}#}\n\n{#enum define MetaType\n {XINE_META_INFO_TITLE as MetaTitle\n ,XINE_META_INFO_COMMENT as MetaComment\n ,XINE_META_INFO_ARTIST as MetaArtist\n ,XINE_META_INFO_GENRE as MetaGenre\n ,XINE_META_INFO_ALBUM as MetaAlbum\n ,XINE_META_INFO_YEAR as MetaYear\n ,XINE_META_INFO_VIDEOCODEC as MetaVideoCodec\n ,XINE_META_INFO_AUDIOCODEC as MetaAudioCodec\n ,XINE_META_INFO_SYSTEMLAYER as MetaSystemLayer\n ,XINE_META_INFO_INPUT_PLUGIN as MetaInputPlugin\n ,XINE_META_INFO_CDINDEX_DISCID as MetaDiscId\n ,XINE_META_INFO_TRACK_NUMBER as MetaTrackNumber\n ,XINE_META_INFO_COMPOSER as MetaComposer\n ,XINE_META_INFO_PUBLISHER as MetaPublisher\n ,XINE_META_INFO_LICENSE as MetaLicense\n ,XINE_META_INFO_ARRANGER as MetaArranger\n ,XINE_META_INFO_LYRICIST as MetaLyricist\n ,XINE_META_INFO_CONDUCTOR as MetaConductor\n ,XINE_META_INFO_PERFORMER as MetaPerformer\n ,XINE_META_INFO_ENSEMBLE as MetaEnsemble\n ,XINE_META_INFO_OPUS as MetaOpus\n ,XINE_META_INFO_PART as MetaPart\n ,XINE_META_INFO_PARTNUMBER as MetaPartNumber\n ,XINE_META_INFO_LOCATION as MetaLocation}#}\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\n-- |\n-- Module : Xine.Foreign\n-- Copyright : (c) Joachim Fasting 2010\n-- License : LGPL (see COPYING)\n-- Maintainer : Joachim Fasting \n-- Stability : unstable\n-- Portability : not portable\n--\n-- A simple binding to xine-lib. Low-level bindings.\n-- Made for xine-lib version 1.1.18.1\n\nmodule Xine.Foreign (\n -- * Version information\n xine_get_version_string, xine_get_version, xine_check_version,\n -- * Global engine handling\n Engine, AudioPort, VideoPort, VisualType(..),\n xine_new, xine_init, xine_open_audio_driver, xine_open_video_driver,\n xine_close_audio_driver, xine_close_video_driver, xine_exit,\n -- * Stream handling\n Stream, StreamParam(..), Speed(..), NormalSpeed(..), Zoom(..),\n AspectRatio(..), MRL, EngineParam(..), Affection(..), TrickMode(..),\n xine_stream_new, xine_stream_master_slave, xine_open, xine_play,\n xine_dispose, xine_eject,\n xine_trick_mode, xine_stop, xine_close, xine_engine_set_param,\n xine_engine_get_param, xine_set_param, xine_get_param,\n -- * Information retrieval\n EngineStatus(..), XineError(..),\n xine_get_error, xine_get_status,\n xine_get_audio_lang, xine_get_spu_lang,\n xine_get_pos_length,\n InfoType(..), MetaType(..),\n xine_get_stream_info, xine_get_meta_info\n ) where\n\nimport Control.Monad (liftM)\nimport Data.Bits\nimport Foreign\nimport Foreign.C\n\n#include \n\n-- Define the name of the dynamic library that has to be loaded before any of\n-- the external C functions may be invoked.\n-- The prefix declaration allows us to refer to identifiers while omitting the\n-- prefix. Prefix matching is case insensitive and any underscore characters\n-- between the prefix and the stem of the identifiers are also removed.\n{#context lib=\"xine\" prefix=\"xine\"#}\n\n-- Opaque types used for structures that are never dereferenced on the\n-- Haskell side.\n{#pointer *xine_t as Engine foreign newtype#}\n{#pointer *xine_audio_port_t as AudioPort foreign newtype#}\n{#pointer *xine_video_port_t as VideoPort foreign newtype#}\n{#pointer *xine_stream_t as Stream foreign newtype#}\n\n-- XXX: just a hack. We really want to be able to pass\n-- custom structs to functions. See 'withData', 'xine_open_audio_driver'.\nnewtype Data = Data (Ptr Data)\n\n-- | Media Resource Locator.\n-- Describes the media to read from. Valid MRLs may be plain file names or\n-- one of the following:\n--\n-- * Filesystem:\n--\n-- file:\\\n--\n-- fifo:\\\n--\n-- stdin:\\\/\n--\n-- * CD and DVD:\n--\n-- dvd:\\\/[device_name][\\\/title[.part]]\n--\n-- dvd:\\\/DVD_image_file[\\\/title[.part]]\n--\n-- dvd:\\\/DVD_directory[\\\/title[.part]]\n--\n-- vcd:\\\/\\\/[CD_image_or_device_name][\\@[letter]number]\n--\n-- vcdo:\\\/\\\/track_number\n--\n-- cdda:\\\/[device][\\\/track_number]\n--\n-- * Video devices:\n--\n-- v4l:\\\/\\\/[tuner_device\\\/frequency\n--\n-- v4l2:\\\/\\\/tuner_device\n--\n-- dvb:\\\/\\\/channel_number\n--\n-- dvb:\\\/\\\/channel_name\n--\n-- dvbc:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvbs:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvbt:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvba:\\\/\\\/channel_name:tuning_parameters\n--\n-- pvr:\\\/tmp_files_path!saved_files_path!max_page_age\n--\n-- * Network:\n--\n-- http:\\\/\\\/host\n--\n-- tcp:\\\/\\\/host[:port]\n--\n-- udp:\\\/\\\/host[:port[?iface=interface]]\n--\n-- rtp:\\\/\\\/host[:port[?iface=interface]]\n--\n-- smb:\\\/\\\/\n--\n-- mms:\\\/\\\/host\n--\n-- pnm:\\\/\\\/host\n--\n-- rtsp:\\\/\\\/host\ntype MRL = String\n\n------------------------------------------------------------------------------\n-- Marshalling\n------------------------------------------------------------------------------\n\ncint2bool :: CInt -> Bool\ncint2bool = (\/= 0)\n{-# INLINE cint2bool #-}\n\nint2cint :: Int -> CInt\nint2cint = fromIntegral\n{-# INLINE int2cint #-}\n\ncint2int :: CInt -> Int\ncint2int = fromIntegral\n{-# INLINE cint2int #-}\n\ncuint2int :: CUInt -> Int\ncuint2int = fromIntegral\n{-# INLINE cuint2int #-}\n\ncint2enum :: Enum a => CInt -> a\ncint2enum = toEnum . cint2int\n{-# INLINE cint2enum #-}\n\nenum2cint :: Enum a => a -> CInt\nenum2cint = int2cint . fromEnum\n{-# INLINE enum2cint #-}\n\npeekInt :: Ptr CInt -> IO Int\npeekInt = liftM cint2int . peek\n{-# INLINE peekInt #-}\n\n-- For pointers which may be NULL.\nmaybeForeignPtr_ c x | x == nullPtr = return Nothing\n | otherwise = (Just . c) `liftM` newForeignPtr_ x\n\npeekEngine = liftM Engine . newForeignPtr_\n{-# INLINE peekEngine #-}\n\npeekAudioPort = maybeForeignPtr_ AudioPort\n{-# INLINE peekAudioPort #-}\n\npeekVideoPort = maybeForeignPtr_ VideoPort\n{-# INLINE peekVideoPort #-}\n\npeekStream = maybeForeignPtr_ Stream\n{-# INLINE peekStream #-}\n\n-- XXX: just a temporary hack until we can actually support\n-- passing a custom struct to functions which support it.\nwithData f = f nullPtr\n\n-- Handle strings which may be NULL.\nwithMaybeString :: Maybe String -> (CString -> IO a) -> IO a\nwithMaybeString Nothing f = f nullPtr\nwithMaybeString (Just s) f = withCString s f\n\n------------------------------------------------------------------------------\n-- Version information\n------------------------------------------------------------------------------\n\n-- | Get xine-lib version string.\n--\n-- Header declaration:\n--\n-- const char *xine_get_version_string (void)\n{#fun pure xine_get_version_string {} -> `String' peekCString*#}\n\n-- | Get version as a triple: major, minor, sub\n--\n-- Header declaration:\n--\n-- void xine_get_version (int *major, int *minor, int *sub)\n{#fun pure xine_get_version\n {alloca- `Int' peekInt*,\n alloca- `Int' peekInt*,\n alloca- `Int' peekInt*} -> `()'#}\n\n-- | Compare given version to xine-lib version (major, minor, sub).\n--\n-- Header declaration:\n--\n-- int xine_check_version (int major, int minor, int sub)\n--\n-- returns 1 if compatible, 0 otherwise.\n{#fun pure xine_check_version\n {int2cint `Int',\n int2cint `Int',\n int2cint `Int'} -> `Bool' cint2bool#}\n\n------------------------------------------------------------------------------\n-- Global engine handling\n------------------------------------------------------------------------------\n\n-- | Valid visual types\n{#enum define VisualType {XINE_VISUAL_TYPE_NONE as None\n ,XINE_VISUAL_TYPE_X11 as X11\n ,XINE_VISUAL_TYPE_X11_2 as X11_2\n ,XINE_VISUAL_TYPE_AA as AA\n ,XINE_VISUAL_TYPE_FB as FB\n ,XINE_VISUAL_TYPE_GTK as GTK\n ,XINE_VISUAL_TYPE_DFB as DFB\n ,XINE_VISUAL_TYPE_PM as PM\n ,XINE_VISUAL_TYPE_DIRECTX as DirectX\n ,XINE_VISUAL_TYPE_CACA as CACA\n ,XINE_VISUAL_TYPE_MACOSX as MacOSX\n ,XINE_VISUAL_TYPE_XCB as XCB\n ,XINE_VISUAL_TYPE_RAW as Raw\n }#}\n\n-- | Pre-init the Xine engine.\n--\n-- Header declaration:\n--\n-- xine_t *xine_new (void)\n{#fun unsafe xine_new {} -> `Engine' peekEngine*#}\n\n-- | Post-init the Xine engine.\n--\n-- Header declaration:\n--\n-- void xine_init (xine_t *self)\n{#fun unsafe xine_init {withEngine* `Engine'} -> `()'#}\n\n-- | Initialise audio driver.\n--\n-- Header declaration:\n--\n-- xine_audio_port_t *xine_open_audio_driver (xine_t *self, const char *id,\n-- void *data)\n--\n-- id: identifier of the driver, may be NULL for auto-detection\n--\n-- data: special data struct for ui\/driver communication\n--\n-- May return NULL if the driver failed to load.\n{#fun unsafe xine_open_audio_driver\n {withEngine* `Engine'\n ,withMaybeString* `(Maybe String)'\n ,withData- `Data'} -> `(Maybe AudioPort)' peekAudioPort*#}\n\n-- | Initialise video driver.\n--\n-- Header declaration:\n--\n-- xine_video_port_t *xine_open_video_driver (xine_t *self, const char *id,\n-- int visual, void *data)\n--\n-- id: identifier of the driver, may be NULL for auto-detection\n--\n-- data: special data struct for ui\/driver communication\n--\n-- visual : video driver flavor selector\n--\n-- May return NULL if the driver failed to load.\n{#fun unsafe xine_open_video_driver\n {withEngine* `Engine'\n ,withMaybeString* `(Maybe String)'\n ,enum2cint `VisualType'\n ,withData- `Data'} -> `(Maybe VideoPort)' peekVideoPort*#}\n\n-- | Close audio port.\n--\n-- Header declaration:\n--\n-- void xine_close_audio_driver (xine_t *self, xine_audio_port_t *driver)\n{#fun unsafe xine_close_audio_driver\n {withEngine* `Engine'\n ,withAudioPort* `AudioPort'} -> `()'#}\n\n-- | Close video port.\n--\n-- Header declaration:\n--\n-- void xine_close_video_driver (xine_t *self, xine_video_port_t *driver)\n{#fun unsafe xine_close_video_driver\n {withEngine* `Engine'\n ,withVideoPort* `VideoPort'} -> `()'#}\n\n-- | Free all resources, close all plugins, close engine.\n--\n-- Header declaration:\n--\n-- void xine_exit (xine_t *self)\n{#fun unsafe xine_exit {withEngine* `Engine'} -> `()'#}\n\n------------------------------------------------------------------------------\n-- Stream handling\n------------------------------------------------------------------------------\n\n-- | Engine parameter enumeration.\n{#enum define EngineParam\n {XINE_ENGINE_PARAM_VERBOSITY as EngineVerbosity}#}\n\n-- | Stream parameter enumeration.\n{#enum define StreamParam\n {XINE_PARAM_SPEED as Speed\n ,XINE_PARAM_AV_OFFSET as AvOffset\n ,XINE_PARAM_AUDIO_CHANNEL_LOGICAL as AudioChannelLogical\n ,XINE_PARAM_SPU_CHANNEL as SpuChannel\n ,XINE_PARAM_AUDIO_VOLUME as AudioVolume\n ,XINE_PARAM_AUDIO_MUTE as AudioMute\n ,XINE_PARAM_AUDIO_COMPR_LEVEL as AudioComprLevel\n ,XINE_PARAM_AUDIO_REPORT_LEVEL as AudioReportLevel\n ,XINE_PARAM_VERBOSITY as Verbosity\n ,XINE_PARAM_SPU_OFFSET as SpuOffset\n ,XINE_PARAM_IGNORE_VIDEO as IgnoreVideo\n ,XINE_PARAM_IGNORE_AUDIO as IgnoreAudio\n ,XINE_PARAM_BROADCASTER_PORT as BroadcasterPort\n ,XINE_PARAM_METRONOM_PREBUFFER as MetronomPrebuffer\n ,XINE_PARAM_EQ_30HZ as Eq30Hz\n ,XINE_PARAM_EQ_60HZ as Eq60Hz\n ,XINE_PARAM_EQ_125HZ as Eq125Hz\n ,XINE_PARAM_EQ_500HZ as Eq500Hz\n ,XINE_PARAM_EQ_1000HZ as Eq1000Hz\n ,XINE_PARAM_EQ_2000HZ as Eq2000Hz\n ,XINE_PARAM_EQ_4000HZ as Eq4000Hz\n ,XINE_PARAM_EQ_8000HZ as Eq8000Hz\n ,XINE_PARAM_EQ_16000HZ as Eq16000Hz\n ,XINE_PARAM_AUDIO_CLOSE_DEVICE as AudioCloseDevice\n ,XINE_PARAM_AUDIO_AMP_MUTE as AmpMute\n ,XINE_PARAM_FINE_SPEED as FineSpeed\n ,XINE_PARAM_EARLY_FINISHED_EVENT as EarlyFinishedEvent\n ,XINE_PARAM_GAPLESS_SWITCH as GaplessSwitch\n ,XINE_PARAM_DELAY_FINISHED_EVENT as DelayFinishedEvent\n ,XINE_PARAM_VO_DEINTERLACE as Deinterlace\n ,XINE_PARAM_VO_ASPECT_RATIO as AspectRatio\n ,XINE_PARAM_VO_HUE as Hue\n ,XINE_PARAM_VO_SATURATION as Saturation\n ,XINE_PARAM_VO_CONTRAST as Contrast\n ,XINE_PARAM_VO_BRIGHTNESS as Brightness\n ,XINE_PARAM_VO_ZOOM_X as ZoomX\n ,XINE_PARAM_VO_ZOOM_Y as ZoomY\n ,XINE_PARAM_VO_PAN_SCAN as PanScan\n ,XINE_PARAM_VO_TVMODE as TvMode\n ,XINE_PARAM_VO_WINDOW_WIDTH as WindowWidth\n ,XINE_PARAM_VO_WINDOW_HEIGHT as WindowHeight\n ,XINE_PARAM_VO_CROP_LEFT as CropLeft\n ,XINE_PARAM_VO_CROP_RIGHT as CropRight\n ,XINE_PARAM_VO_CROP_TOP as CropTop\n ,XINE_PARAM_VO_CROP_BOTTOM as CropBottom\n }#}\n\n-- | Values for XINE_PARAM_SPEED parameter.\n{#enum define Speed\n {XINE_SPEED_PAUSE as Pause\n ,XINE_SPEED_SLOW_4 as Slow4\n ,XINE_SPEED_SLOW_2 as Slow2\n ,XINE_SPEED_NORMAL as Normal\n ,XINE_SPEED_FAST_2 as Fast2\n ,XINE_SPEED_FAST_4 as Fast4\n }#}\n\nderiving instance Eq Speed\n\n-- | Value for XINE_PARAM_FINE_SPEED\n{#enum define NormalSpeed\n {XINE_FINE_SPEED_NORMAL as NormalSpeed}#}\n\n-- | Values for XINE_PARAM_VO_ZOOM_\n{#enum define Zoom\n {XINE_VO_ZOOM_STEP as ZoomStep\n ,XINE_VO_ZOOM_MAX as ZoomMax\n ,XINE_VO_ZOOM_MIN as ZoomMin}#}\n\n-- | Values for XINE_PARAM_VO_ASPECT_RATIO\n{#enum define AspectRatio\n {XINE_VO_ASPECT_AUTO as AspectAuto\n ,XINE_VO_ASPECT_SQUARE as AspectSquare\n ,XINE_VO_ASPECT_4_3 as Aspect43\n ,XINE_VO_ASPECT_ANAMORPHIC as AspectAnamorphic\n ,XINE_VO_ASPECT_DVB as AspectDvb\n ,XINE_VO_ASPECT_NUM_RATIOS as AspectNumRatios\n }#}\n\n-- | Create a new stream for media playback.\n--\n-- Header declaration:\n--\n-- xine_stream_t *xine_stream_new (xine_t *self,\n-- xine_audio_port *ao, xine_video_port_t *vo)\n--\n-- Returns xine_stream_t* if OK, NULL on error (use 'xine_get_error' for\n-- details).\n{#fun unsafe xine_stream_new\n {withEngine* `Engine'\n ,withAudioPort* `AudioPort'\n ,withVideoPort* `VideoPort'} -> `(Maybe Stream)' peekStream*#}\n\n-- | Make one stream the slave of another.\n-- Certain operations on the master stream are also applied to the slave\n-- stream.\n--\n-- Header declaration:\n--\n-- int xine_stream_master_slave (xine_stream_t *master, xine_stream_t *slave,\n-- int affection)\n--\n-- returns 1 on success, 0 on failure.\n{#fun unsafe xine_stream_master_slave\n {withStream* `Stream'\n ,withStream* `Stream'\n ,combineAffection `[Affection]'} -> `Int' cint2int#}\n\n-- | The affection determines which actions on the master stream\n-- are also to be applied to the slave stream. See 'xine_stream_master_slave'.\n{#enum define Affection\n {XINE_MASTER_SLAVE_PLAY as AffectionPlay\n ,XINE_MASTER_SLAVE_STOP as AffectionStop\n ,XINE_MASTER_SLAVE_SPEED as AffectionSpeed}#}\n\n-- | Affections can be ORed together.\ncombineAffection :: [Affection] -> CInt\ncombineAffection [] = enum2cint AffectionSpeed\ncombineAffection xs = foldr1 (.&.) (map enum2cint xs)\n\n-- | Open a stream.\n--\n-- Header declaration:\n--\n-- int xine_open (xine_stream_t *stream, const char *mrl)\n--\n-- Returns 1 if OK, 0 on error (use 'xine_get_error' for details).\n{#fun unsafe xine_open\n {withStream* `Stream'\n ,withCAString* `MRL'} -> `Int' cint2int#}\n\n-- | Play a stream from a given position.\n--\n-- Header declaration:\n--\n-- int xine_play (xine_stream_t *stream, int start_pos, int start_time)\n--\n-- Returns 1 if OK, 0 on error (use 'xine_get_error' for details).\n{#fun unsafe xine_play\n {withStream* `Stream'\n ,int2cint `Int'\n ,int2cint `Int'} -> `Int' cint2int#}\n\n-- | Set xine to a trick mode for fast forward, backwards playback,\n-- low latency seeking.\n--\n-- Header declaration:\n--\n-- int xine_trick_mode (xine_stream_t *stream, int mode, int value)\n--\n-- Returns 1 if OK, 0 on error (use 'xine_get_error' for details).\n{#fun unsafe xine_trick_mode\n {withStream* `Stream'\n ,enum2cint `TrickMode'\n ,int2cint `Int'} -> `Int' cint2int#}\n\n{#enum define TrickMode\n {XINE_TRICK_MODE_OFF as TrickOff\n ,XINE_TRICK_MODE_SEEK_TO_POSITION as TrickSeekToPosition\n ,XINE_TRICK_MODE_SEEK_TO_TIME as TrickSeekToTime\n ,XINE_TRICK_MODE_FAST_FORWARD as TrickFastForward\n ,XINE_TRICK_MODE_FAST_REWIND as TrickRewind}#}\n\n-- | Stop stream playback.\n-- The stream stays valid for new 'xine_open' or 'xine_play'.\n--\n-- Header declaration:\n--\n-- void xine_stop (xine_stream *stream)\n{#fun unsafe xine_stop {withStream* `Stream'} -> `()'#}\n\n-- | Free all stream-related resources.\n-- The stream stays valid for new 'xine_open'.\n--\n-- Header declaration:\n--\n-- void xine_close (xine_stream_t *stream)\n{#fun unsafe xine_close {withStream* `Stream'} -> `()'#}\n\n-- | Ask current input plugin to eject media.\n--\n-- Header declaration:\n--\n-- int xine_eject (xine_stream_t *stream)\n{#fun unsafe xine_eject {withStream* `Stream'} -> `Int' cint2int#}\n\n-- | Stop playback, dispose all stream-related resources.\n-- The stream is no longer valid after this.\n--\n-- Header declaration:\n--\n-- void xine_dispose (xine_stream_t *stream)\n{#fun unsafe xine_dispose {withStream* `Stream'} -> `()'#}\n\n-- | Set engine parameter.\n--\n-- Header declaration:\n--\n-- void xine_engine_set_param (xine_t *self, int param, int value)\n{#fun unsafe xine_engine_set_param\n {withEngine* `Engine'\n ,enum2cint `EngineParam'\n ,int2cint `Int'} -> `()'#}\n\n-- | Get engine parameter.\n--\n-- Header declaration:\n--\n-- int xine_engine_get_param(xine_t *self, int param)\n{#fun unsafe xine_engine_get_param\n {withEngine* `Engine'\n ,enum2cint `EngineParam'} -> `Int' cint2int#}\n\n-- | Set stream parameter.\n--\n-- Header declaration:\n--\n-- void xine_set_param (xine_stream_t *stream, int param, int value)\n{#fun unsafe xine_set_param\n `(Enum a)' =>\n {withStream* `Stream'\n ,enum2cint `StreamParam'\n ,enum2cint `a'} -> `()'#}\n\n-- | Get stream parameter.\n--\n-- Header declaration:\n--\n-- int xine_get_param (xine_stream_t *stream, int param)\n{#fun unsafe xine_get_param\n `(Enum a)' =>\n {withStream* `Stream'\n ,enum2cint `StreamParam'} -> `a' cint2enum#}\n\n------------------------------------------------------------------------------\n-- Information retrieval\n------------------------------------------------------------------------------\n\n-- | Engine status codes.\n{#enum define EngineStatus\n {XINE_STATUS_IDLE as Idle\n ,XINE_STATUS_STOP as Stopped\n ,XINE_STATUS_PLAY as Playing\n ,XINE_STATUS_QUIT as Quitting}#}\n\nderiving instance Eq EngineStatus\nderiving instance Show EngineStatus\n\n-- | Xine error codes.\n{#enum define XineError\n {XINE_ERROR_NONE as NoError\n ,XINE_ERROR_NO_INPUT_PLUGIN as NoInputPlugin\n ,XINE_ERROR_NO_DEMUX_PLUGIN as NoDemuxPlugin\n ,XINE_ERROR_MALFORMED_MRL as MalformedMrl\n ,XINE_ERROR_INPUT_FAILED as InputFailed}#}\n\nderiving instance Eq XineError\nderiving instance Show XineError\n\n-- | Return last error.\n--\n-- Header declaration:\n--\n-- int xine_get_error (xine_stream_t *stream)\n{#fun unsafe xine_get_error\n {withStream* `Stream'} -> `XineError' cint2enum#}\n\n-- | Get current xine engine status.\n--\n-- int xine_get_status (xine_stream_t *stream)\n{#fun unsafe xine_get_status\n {withStream* `Stream'} -> `EngineStatus' cint2enum#}\n\n-- | Find the audio language of the given channel (use -1 for\n-- current channel).\n--\n-- Header declaration:\n--\n-- int xine_get_audio_lang (xine_stream_t *stream, int channel,\n-- char *lang)\n--\n-- lang must point to a buffer of at least XINE_LANG_MAX bytes.\n--\n-- Returns 1 on success, 0 on failure.\n{#fun unsafe xine_get_audio_lang\n {withStream* `Stream'\n ,int2cint `Int'\n ,allocLangBuf- `String' peekCString*} -> `Int' cint2int#}\n\n-- XXX: read the constant XINE_LANG_MAX\nallocLangBuf = allocaArray0 32\n\n-- | Find the spu language of the given channel (use -1 for\n-- current channel).\n--\n-- Header declaration:\n--\n-- int xine_get_spu_lang (xine_stream_t *stream, int channel,\n-- char *lang)\n--\n-- lang must point to a buffer of at least XINE_LANG_MAX bytes.\n--\n-- Returns 1 on success, 0 on failure.\n{#fun unsafe xine_get_spu_lang\n {withStream* `Stream'\n ,int2cint `Int'\n ,allocLangBuf- `String' peekCString*} -> `Int' cint2int#}\n\n-- | Get position\\\/length information.\n--\n-- Header declaration:\n--\n-- int xine_get_pos_length (xine_stream_t *stream, int *pos_stream,\n-- int *pos_time, int *length_time)\n--\n-- Returns 1 on success, 0 on failure.\n{#fun unsafe xine_get_pos_length\n {withStream* `Stream'\n ,alloca- `Int' peekInt*\n ,alloca- `Int' peekInt*\n ,alloca- `Int' peekInt*} -> `Int' cint2int#}\n\n-- | Get information about the stream.\n--\n-- Header declaration:\n--\n-- int32_t xine_get_stream_info (xine_stream_t *stream, int info)\n{#fun unsafe xine_get_stream_info\n {withStream* `Stream'\n ,enum2cint `InfoType'} -> `Int' cuint2int#}\n\n-- | Get meta information about the stream.\n--\n-- Header declaration:\n--\n-- const char *xine_get_meta_info (xine_stream_t *stream, int info)\n{#fun unsafe xine_get_meta_info\n {withStream* `Stream'\n ,enum2cint `MetaType'} -> `String' peekCString*#}\n\n{#enum define InfoType\n {XINE_STREAM_INFO_BITRATE as InfoBitrate\n ,XINE_STREAM_INFO_SEEKABLE as InfoSeekable\n ,XINE_STREAM_INFO_VIDEO_WIDTH as InfoVideoWidth\n ,XINE_STREAM_INFO_VIDEO_HEIGHT as InfoVideoHeight\n ,XINE_STREAM_INFO_VIDEO_RATIO as InfoVideoRatio\n ,XINE_STREAM_INFO_VIDEO_CHANNELS as InfoVideoChannels\n ,XINE_STREAM_INFO_VIDEO_STREAMS as InfoVideoStreams\n ,XINE_STREAM_INFO_VIDEO_BITRATE as InfoVideoBitrate\n ,XINE_STREAM_INFO_VIDEO_FOURCC as InfoVideoFourCC\n ,XINE_STREAM_INFO_VIDEO_HANDLED as InfoVideoHandled\n ,XINE_STREAM_INFO_FRAME_DURATION as InfoFrameDuration\n ,XINE_STREAM_INFO_AUDIO_CHANNELS as InfoAudioChannels\n ,XINE_STREAM_INFO_AUDIO_BITS as InfoAudioBits\n ,XINE_STREAM_INFO_AUDIO_SAMPLERATE as InfoAudioSamplerate\n ,XINE_STREAM_INFO_AUDIO_BITRATE as InfoAudioBitrate\n ,XINE_STREAM_INFO_AUDIO_FOURCC as InfoAudioFourCC\n ,XINE_STREAM_INFO_AUDIO_HANDLED as InfoAudioHandled\n ,XINE_STREAM_INFO_HAS_CHAPTERS as InfoHasChapters\n ,XINE_STREAM_INFO_HAS_VIDEO as InfoHasVideo\n ,XINE_STREAM_INFO_HAS_AUDIO as InfoHasAudio\n ,XINE_STREAM_INFO_IGNORE_VIDEO as InfoIgnoreVideo\n ,XINE_STREAM_INFO_IGNORE_AUDIO as InfoIgnoreAudio\n ,XINE_STREAM_INFO_IGNORE_SPU as InfoIgnoreSpu\n ,XINE_STREAM_INFO_VIDEO_HAS_STILL as InfoVideoHasStill\n ,XINE_STREAM_INFO_MAX_AUDIO_CHANNEL as InfoMaxAudioChannel\n ,XINE_STREAM_INFO_MAX_SPU_CHANNEL as InfoMaxSpuChannel\n ,XINE_STREAM_INFO_AUDIO_MODE as InfoAudioMode\n ,XINE_STREAM_INFO_SKIPPED_FRAMES as InfoSkippedFrames\n ,XINE_STREAM_INFO_DISCARDED_FRAMES as InfoDiscardedFrames\n ,XINE_STREAM_INFO_VIDEO_AFD as InfoVideoAFD\n ,XINE_STREAM_INFO_DVD_TITLE_NUMBER as InfoDvdTitleNumber\n ,XINE_STREAM_INFO_DVD_TITLE_COUNT as InfoDvdTitleCount\n ,XINE_STREAM_INFO_DVD_CHAPTER_NUMBER as InfoDvdChapterNumber\n ,XINE_STREAM_INFO_DVD_CHAPTER_COUNT as InfoDvdChapterCount\n ,XINE_STREAM_INFO_DVD_ANGLE_NUMBER as InfoDvdAngleNumber\n ,XINE_STREAM_INFO_DVD_ANGLE_COUNT as InfoDvdAngleCount}#}\n\n{#enum define MetaType\n {XINE_META_INFO_TITLE as MetaTitle\n ,XINE_META_INFO_COMMENT as MetaComment\n ,XINE_META_INFO_ARTIST as MetaArtist\n ,XINE_META_INFO_GENRE as MetaGenre\n ,XINE_META_INFO_ALBUM as MetaAlbum\n ,XINE_META_INFO_YEAR as MetaYear\n ,XINE_META_INFO_VIDEOCODEC as MetaVideoCodec\n ,XINE_META_INFO_AUDIOCODEC as MetaAudioCodec\n ,XINE_META_INFO_SYSTEMLAYER as MetaSystemLayer\n ,XINE_META_INFO_INPUT_PLUGIN as MetaInputPlugin\n ,XINE_META_INFO_CDINDEX_DISCID as MetaDiscId\n ,XINE_META_INFO_TRACK_NUMBER as MetaTrackNumber\n ,XINE_META_INFO_COMPOSER as MetaComposer\n ,XINE_META_INFO_PUBLISHER as MetaPublisher\n ,XINE_META_INFO_LICENSE as MetaLicense\n ,XINE_META_INFO_ARRANGER as MetaArranger\n ,XINE_META_INFO_LYRICIST as MetaLyricist\n ,XINE_META_INFO_CONDUCTOR as MetaConductor\n ,XINE_META_INFO_PERFORMER as MetaPerformer\n ,XINE_META_INFO_ENSEMBLE as MetaEnsemble\n ,XINE_META_INFO_OPUS as MetaOpus\n ,XINE_META_INFO_PART as MetaPart\n ,XINE_META_INFO_PARTNUMBER as MetaPartNumber\n ,XINE_META_INFO_LOCATION as MetaLocation}#}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"401c702dc358a2dfd1949b902a0f0c5955ba6759","subject":"Improve documentation for Texture functions","message":"Improve documentation for Texture functions\n","repos":"mwu-tow\/cuda","old_file":"Foreign\/CUDA\/Driver\/Texture.chs","new_file":"Foreign\/CUDA\/Driver\/Texture.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# OPTIONS_HADDOCK prune #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Texture\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Texture management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Texture (\n\n -- * Texture Reference Management\n Texture(..), Format(..), AddressMode(..), FilterMode(..), ReadMode(..),\n bind, bind2D,\n getAddressMode, getFilterMode, getFormat,\n setAddressMode, setFilterMode, setFormat, setReadMode,\n\n -- Deprecated\n create, destroy,\n\n -- Internal\n peekTex\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Ptr\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Marshal\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n#if CUDA_VERSION >= 3020\n{-# DEPRECATED create, destroy \"as of CUDA version 3.2\" #-}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A texture reference\n--\nnewtype Texture = Texture { useTexture :: {# type CUtexref #}}\n deriving (Eq, Show)\n\ninstance Storable Texture where\n sizeOf _ = sizeOf (undefined :: {# type CUtexref #})\n alignment _ = alignment (undefined :: {# type CUtexref #})\n peek p = Texture `fmap` peek (castPtr p)\n poke p t = poke (castPtr p) (useTexture t)\n\n-- |\n-- Texture reference addressing modes\n--\n{# enum CUaddress_mode as AddressMode\n { underscoreToCase }\n with prefix=\"CU_TR_ADDRESS_MODE\" deriving (Eq, Show) #}\n\n-- |\n-- Texture reference filtering mode\n--\n{# enum CUfilter_mode as FilterMode\n { underscoreToCase }\n with prefix=\"CU_TR_FILTER_MODE\" deriving (Eq, Show) #}\n\n-- |\n-- Texture read mode options\n--\n#c\ntypedef enum CUtexture_flag_enum {\n CU_TEXTURE_FLAG_READ_AS_INTEGER = CU_TRSF_READ_AS_INTEGER,\n CU_TEXTURE_FLAG_NORMALIZED_COORDINATES = CU_TRSF_NORMALIZED_COORDINATES,\n CU_TEXTURE_FLAG_SRGB = CU_TRSF_SRGB\n} CUtexture_flag;\n#endc\n\n{# enum CUtexture_flag as ReadMode\n { underscoreToCase\n , CU_TEXTURE_FLAG_SRGB as SRGB }\n with prefix=\"CU_TEXTURE_FLAG\" deriving (Eq, Show) #}\n\n-- |\n-- Texture data formats\n--\n{# enum CUarray_format as Format\n { underscoreToCase\n , UNSIGNED_INT8 as Word8\n , UNSIGNED_INT16 as Word16\n , UNSIGNED_INT32 as Word32\n , SIGNED_INT8 as Int8\n , SIGNED_INT16 as Int16\n , SIGNED_INT32 as Int32 }\n with prefix=\"CU_AD_FORMAT\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Texture management\n--------------------------------------------------------------------------------\n\n-- |\n-- Create a new texture reference. Once created, the application must call\n-- 'setPtr' to associate the reference with allocated memory. Other texture\n-- reference functions are used to specify the format and interpretation to be\n-- used when the memory is read through this reference.\n--\n-- \n--\n{-# INLINEABLE create #-}\ncreate :: IO Texture\ncreate = resultIfOk =<< cuTexRefCreate\n\n{-# INLINE cuTexRefCreate #-}\n{# fun unsafe cuTexRefCreate\n { alloca- `Texture' peekTex* } -> `Status' cToEnum #}\n\n\n-- |\n-- Destroy a texture reference.\n--\n-- \n--\n{-# INLINEABLE destroy #-}\ndestroy :: Texture -> IO ()\ndestroy !tex = nothingIfOk =<< cuTexRefDestroy tex\n\n{-# INLINE cuTexRefDestroy #-}\n{# fun unsafe cuTexRefDestroy\n { useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |\n-- Bind a linear array address of the given size (bytes) as a texture\n-- reference. Any previously bound references are unbound.\n--\n-- \n--\n{-# INLINEABLE bind #-}\nbind :: Texture -> DevicePtr a -> Int64 -> IO ()\nbind !tex !dptr !bytes = nothingIfOk =<< cuTexRefSetAddress tex dptr bytes\n\n{-# INLINE cuTexRefSetAddress #-}\n{# fun unsafe cuTexRefSetAddress\n { alloca- `Int'\n , useTexture `Texture'\n , useDeviceHandle `DevicePtr a'\n , `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Bind a linear address range to the given texture reference as a\n-- two-dimensional arena. Any previously bound reference is unbound. Note that\n-- calls to 'setFormat' can not follow a call to 'bind2D' for the same texture\n-- reference.\n--\n-- \n--\n{-# INLINEABLE bind2D #-}\nbind2D :: Texture -> Format -> Int -> DevicePtr a -> (Int,Int) -> Int64 -> IO ()\nbind2D !tex !fmt !chn !dptr (!width,!height) !pitch =\n nothingIfOk =<< cuTexRefSetAddress2DSimple tex fmt chn dptr width height pitch\n\n{-# INLINE cuTexRefSetAddress2DSimple #-}\n{# fun unsafe cuTexRefSetAddress2DSimple\n { useTexture `Texture'\n , cFromEnum `Format'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Get the addressing mode used by a texture reference, corresponding to the\n-- given dimension (currently the only supported dimension values are 0 or 1).\n--\n-- \n--\n{-# INLINEABLE getAddressMode #-}\ngetAddressMode :: Texture -> Int -> IO AddressMode\ngetAddressMode !tex !dim = resultIfOk =<< cuTexRefGetAddressMode tex dim\n\n{-# INLINE cuTexRefGetAddressMode #-}\n{# fun unsafe cuTexRefGetAddressMode\n { alloca- `AddressMode' peekEnum*\n , useTexture `Texture'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Get the filtering mode used by a texture reference.\n--\n-- \n--\n{-# INLINEABLE getFilterMode #-}\ngetFilterMode :: Texture -> IO FilterMode\ngetFilterMode !tex = resultIfOk =<< cuTexRefGetFilterMode tex\n\n{-# INLINE cuTexRefGetFilterMode #-}\n{# fun unsafe cuTexRefGetFilterMode\n { alloca- `FilterMode' peekEnum*\n , useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |\n-- Get the data format and number of channel components of the bound texture.\n--\n-- \n--\n{-# INLINEABLE getFormat #-}\ngetFormat :: Texture -> IO (Format, Int)\ngetFormat !tex = do\n (!status,!fmt,!dim) <- cuTexRefGetFormat tex\n resultIfOk (status,(fmt,dim))\n\n{-# INLINE cuTexRefGetFormat #-}\n{# fun unsafe cuTexRefGetFormat\n { alloca- `Format' peekEnum*\n , alloca- `Int' peekIntConv*\n , useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the addressing mode for the given dimension of a texture reference.\n--\n-- \n--\n{-# INLINEABLE setAddressMode #-}\nsetAddressMode :: Texture -> Int -> AddressMode -> IO ()\nsetAddressMode !tex !dim !mode = nothingIfOk =<< cuTexRefSetAddressMode tex dim mode\n\n{-# INLINE cuTexRefSetAddressMode #-}\n{# fun unsafe cuTexRefSetAddressMode\n { useTexture `Texture'\n , `Int'\n , cFromEnum `AddressMode' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the filtering mode to be used when reading memory through a texture\n-- reference.\n--\n-- \n--\n{-# INLINEABLE setFilterMode #-}\nsetFilterMode :: Texture -> FilterMode -> IO ()\nsetFilterMode !tex !mode = nothingIfOk =<< cuTexRefSetFilterMode tex mode\n\n{-# INLINE cuTexRefSetFilterMode #-}\n{# fun unsafe cuTexRefSetFilterMode\n { useTexture `Texture'\n , cFromEnum `FilterMode' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify additional characteristics for reading and indexing the texture\n-- reference.\n--\n-- \n--\n{-# INLINEABLE setReadMode #-}\nsetReadMode :: Texture -> ReadMode -> IO ()\nsetReadMode !tex !mode = nothingIfOk =<< cuTexRefSetFlags tex mode\n\n{-# INLINE cuTexRefSetFlags #-}\n{# fun unsafe cuTexRefSetFlags\n { useTexture `Texture'\n , cFromEnum `ReadMode' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the format of the data and number of packed components per element to\n-- be read by the texture reference.\n--\n-- \n--\n{-# INLINEABLE setFormat #-}\nsetFormat :: Texture -> Format -> Int -> IO ()\nsetFormat !tex !fmt !chn = nothingIfOk =<< cuTexRefSetFormat tex fmt chn\n\n{-# INLINE cuTexRefSetFormat #-}\n{# fun unsafe cuTexRefSetFormat\n { useTexture `Texture'\n , cFromEnum `Format'\n , `Int' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE peekTex #-}\npeekTex :: Ptr {# type CUtexref #} -> IO Texture\npeekTex = liftM Texture . peek\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# OPTIONS_HADDOCK prune #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Texture\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Texture management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Texture (\n\n -- * Texture Reference Management\n Texture(..), Format(..), AddressMode(..), FilterMode(..), ReadMode(..),\n create, destroy,\n bind, bind2D,\n getAddressMode, getFilterMode, getFormat,\n setAddressMode, setFilterMode, setFormat, setReadMode,\n\n -- Internal\n peekTex\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Ptr\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Marshal\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad\n\n#if CUDA_VERSION >= 3020\n{-# DEPRECATED create, destroy \"as of CUDA version 3.2\" #-}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A texture reference\n--\nnewtype Texture = Texture { useTexture :: {# type CUtexref #}}\n deriving (Eq, Show)\n\ninstance Storable Texture where\n sizeOf _ = sizeOf (undefined :: {# type CUtexref #})\n alignment _ = alignment (undefined :: {# type CUtexref #})\n peek p = Texture `fmap` peek (castPtr p)\n poke p t = poke (castPtr p) (useTexture t)\n\n-- |\n-- Texture reference addressing modes\n--\n{# enum CUaddress_mode as AddressMode\n { underscoreToCase }\n with prefix=\"CU_TR_ADDRESS_MODE\" deriving (Eq, Show) #}\n\n-- |\n-- Texture reference filtering mode\n--\n{# enum CUfilter_mode as FilterMode\n { underscoreToCase }\n with prefix=\"CU_TR_FILTER_MODE\" deriving (Eq, Show) #}\n\n-- |\n-- Texture read mode options\n--\n#c\ntypedef enum CUtexture_flag_enum {\n CU_TEXTURE_FLAG_READ_AS_INTEGER = CU_TRSF_READ_AS_INTEGER,\n CU_TEXTURE_FLAG_NORMALIZED_COORDINATES = CU_TRSF_NORMALIZED_COORDINATES,\n CU_TEXTURE_FLAG_SRGB = CU_TRSF_SRGB\n} CUtexture_flag;\n#endc\n\n{# enum CUtexture_flag as ReadMode\n { underscoreToCase\n , CU_TEXTURE_FLAG_SRGB as SRGB }\n with prefix=\"CU_TEXTURE_FLAG\" deriving (Eq, Show) #}\n\n-- |\n-- Texture data formats\n--\n{# enum CUarray_format as Format\n { underscoreToCase\n , UNSIGNED_INT8 as Word8\n , UNSIGNED_INT16 as Word16\n , UNSIGNED_INT32 as Word32\n , SIGNED_INT8 as Int8\n , SIGNED_INT16 as Int16\n , SIGNED_INT32 as Int32 }\n with prefix=\"CU_AD_FORMAT\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Texture management\n--------------------------------------------------------------------------------\n\n-- |\n-- Create a new texture reference. Once created, the application must call\n-- 'setPtr' to associate the reference with allocated memory. Other texture\n-- reference functions are used to specify the format and interpretation to be\n-- used when the memory is read through this reference.\n--\n{-# INLINEABLE create #-}\ncreate :: IO Texture\ncreate = resultIfOk =<< cuTexRefCreate\n\n{-# INLINE cuTexRefCreate #-}\n{# fun unsafe cuTexRefCreate\n { alloca- `Texture' peekTex* } -> `Status' cToEnum #}\n\n\n-- |\n-- Destroy a texture reference\n--\n{-# INLINEABLE destroy #-}\ndestroy :: Texture -> IO ()\ndestroy !tex = nothingIfOk =<< cuTexRefDestroy tex\n\n{-# INLINE cuTexRefDestroy #-}\n{# fun unsafe cuTexRefDestroy\n { useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |\n-- Bind a linear array address of the given size (bytes) as a texture\n-- reference. Any previously bound references are unbound.\n--\n{-# INLINEABLE bind #-}\nbind :: Texture -> DevicePtr a -> Int64 -> IO ()\nbind !tex !dptr !bytes = nothingIfOk =<< cuTexRefSetAddress tex dptr bytes\n\n{-# INLINE cuTexRefSetAddress #-}\n{# fun unsafe cuTexRefSetAddress\n { alloca- `Int'\n , useTexture `Texture'\n , useDeviceHandle `DevicePtr a'\n , `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Bind a linear address range to the given texture reference as a\n-- two-dimensional arena. Any previously bound reference is unbound. Note that\n-- calls to 'setFormat' can not follow a call to 'bind2D' for the same texture\n-- reference.\n--\n{-# INLINEABLE bind2D #-}\nbind2D :: Texture -> Format -> Int -> DevicePtr a -> (Int,Int) -> Int64 -> IO ()\nbind2D !tex !fmt !chn !dptr (!width,!height) !pitch =\n nothingIfOk =<< cuTexRefSetAddress2DSimple tex fmt chn dptr width height pitch\n\n{-# INLINE cuTexRefSetAddress2DSimple #-}\n{# fun unsafe cuTexRefSetAddress2DSimple\n { useTexture `Texture'\n , cFromEnum `Format'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Get the addressing mode used by a texture reference, corresponding to the\n-- given dimension (currently the only supported dimension values are 0 or 1).\n--\n{-# INLINEABLE getAddressMode #-}\ngetAddressMode :: Texture -> Int -> IO AddressMode\ngetAddressMode !tex !dim = resultIfOk =<< cuTexRefGetAddressMode tex dim\n\n{-# INLINE cuTexRefGetAddressMode #-}\n{# fun unsafe cuTexRefGetAddressMode\n { alloca- `AddressMode' peekEnum*\n , useTexture `Texture'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Get the filtering mode used by a texture reference\n--\n{-# INLINEABLE getFilterMode #-}\ngetFilterMode :: Texture -> IO FilterMode\ngetFilterMode !tex = resultIfOk =<< cuTexRefGetFilterMode tex\n\n{-# INLINE cuTexRefGetFilterMode #-}\n{# fun unsafe cuTexRefGetFilterMode\n { alloca- `FilterMode' peekEnum*\n , useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |\n-- Get the data format and number of channel components of the bound texture\n--\n{-# INLINEABLE getFormat #-}\ngetFormat :: Texture -> IO (Format, Int)\ngetFormat !tex = do\n (!status,!fmt,!dim) <- cuTexRefGetFormat tex\n resultIfOk (status,(fmt,dim))\n\n{-# INLINE cuTexRefGetFormat #-}\n{# fun unsafe cuTexRefGetFormat\n { alloca- `Format' peekEnum*\n , alloca- `Int' peekIntConv*\n , useTexture `Texture' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the addressing mode for the given dimension of a texture reference\n--\n{-# INLINEABLE setAddressMode #-}\nsetAddressMode :: Texture -> Int -> AddressMode -> IO ()\nsetAddressMode !tex !dim !mode = nothingIfOk =<< cuTexRefSetAddressMode tex dim mode\n\n{-# INLINE cuTexRefSetAddressMode #-}\n{# fun unsafe cuTexRefSetAddressMode\n { useTexture `Texture'\n , `Int'\n , cFromEnum `AddressMode' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the filtering mode to be used when reading memory through a texture\n-- reference\n--\n{-# INLINEABLE setFilterMode #-}\nsetFilterMode :: Texture -> FilterMode -> IO ()\nsetFilterMode !tex !mode = nothingIfOk =<< cuTexRefSetFilterMode tex mode\n\n{-# INLINE cuTexRefSetFilterMode #-}\n{# fun unsafe cuTexRefSetFilterMode\n { useTexture `Texture'\n , cFromEnum `FilterMode' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify additional characteristics for reading and indexing the texture\n-- reference\n--\n{-# INLINEABLE setReadMode #-}\nsetReadMode :: Texture -> ReadMode -> IO ()\nsetReadMode !tex !mode = nothingIfOk =<< cuTexRefSetFlags tex mode\n\n{-# INLINE cuTexRefSetFlags #-}\n{# fun unsafe cuTexRefSetFlags\n { useTexture `Texture'\n , cFromEnum `ReadMode' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the format of the data and number of packed components per element to\n-- be read by the texture reference\n--\n{-# INLINEABLE setFormat #-}\nsetFormat :: Texture -> Format -> Int -> IO ()\nsetFormat !tex !fmt !chn = nothingIfOk =<< cuTexRefSetFormat tex fmt chn\n\n{-# INLINE cuTexRefSetFormat #-}\n{# fun unsafe cuTexRefSetFormat\n { useTexture `Texture'\n , cFromEnum `Format'\n , `Int' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\n{-# INLINE peekTex #-}\npeekTex :: Ptr {# type CUtexref #} -> IO Texture\npeekTex = liftM Texture . peek\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"845e1cbf92c91e67991b8ad33886c058229a0f8b","subject":"index.h","message":"index.h\n","repos":"norm2782\/hgit2","old_file":"Git2.chs","new_file":"Git2.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\n#include \"git2.h\"\n\nmodule Git2 where\n\nimport Data.Bits\nimport Data.Maybe\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO.Unsafe\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype CPtr = Ptr ()\ntype Ptr2Int = CPtr -> IO CInt\n\nnewtype ObjDB = ObjDB CPtr\nnewtype Repository = Repository CPtr\nnewtype Index = Index CPtr\nnewtype Blob = Blob CPtr\nnewtype ObjID = ObjID CPtr\nnewtype Commit = Commit CPtr\nnewtype Signature = Signature CPtr\nnewtype Tree = Tree CPtr\nnewtype Config = Config CPtr\nnewtype IndexEntry = IndexEntry CPtr\nnewtype IndexEntryUnMerged = IndexEntryUnMerged CPtr\n\ndefaultPort :: String\ndefaultPort = \"9418\" -- TODO: Import from net.h?\n\n{#enum define Direction { GIT_DIR_FETCH as Fetch\n , GIT_DIR_PUSH as Push}#}\n\n{-\n#define GIT_STATUS_CURRENT 0\n\/** Flags for index status *\/\n#define GIT_STATUS_INDEX_NEW (1 << 0)\n#define GIT_STATUS_INDEX_MODIFIED (1 << 1)\n#define GIT_STATUS_INDEX_DELETED (1 << 2)\n\n\/** Flags for worktree status *\/\n#define GIT_STATUS_WT_NEW (1 << 3)\n#define GIT_STATUS_WT_MODIFIED (1 << 4)\n#define GIT_STATUS_WT_DELETED (1 << 5)\n\n\/\/ TODO Ignored files not handled yet\n#define GIT_STATUS_IGNORED (1 << 6)\n-}\n\n{-\n{#enum define Status { GIT_STATUS_CURRENT as Current\n , GIT_STATUS_INDEX_NEW as NewIndex\n , GIT_STATUS_INDEX_MODIFIED as ModifiedIndex\n , GIT_STATUS_INDEX_DELETED as DeletedIndex\n , GIT_STATUS_WT_NEW as NewWorkTree\n , GIT_STATUS_WT_MODIFIED as ModifiedWorkTree\n , GIT_STATUS_WT_DELETED as DeletedWorkTree\n , GIT_STATUS_IGNORED as Ignored}#}\n-}\n\n{#enum git_otype as OType {underscoreToCase}#}\n{#enum git_rtype as RType {underscoreToCase}#}\n{#enum git_repository_pathid as RepositoryPathID {underscoreToCase}#}\n{#enum git_error as GitError {underscoreToCase}#}\n{#enum git_odb_streammode as ODBStreamMode {underscoreToCase}#}\n\nderiving instance Show GitError\n\n\n\nretEither :: CInt -> IO (Either GitError a) -> IO (Either GitError a)\nretEither res f | res == 0 = f\n | otherwise = return . Left . toEnum . fromIntegral $ res\n\n\nretMaybeRes :: CInt -> IO (Maybe GitError)\nretMaybeRes res | res == 0 = return Nothing\n | otherwise = return $ Just . toEnum . fromIntegral $ res\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: blob.h\n-------------------------------------------------------------------------------\n\n{-\n\/**\n * Get a read-only buffer with the raw content of a blob.\n *\n * A pointer to the raw content of a blob is returned;\n * this pointer is owned internally by the object and shall\n * not be free'd. The pointer may be invalidated at a later\n * time.\n *\n * @param blob pointer to the blob\n * @return the pointer; NULL if the blob has no contents\n *\/\nGIT_EXTERN(const void *) git_blob_rawcontent(git_blob *blob);\n-}\n-- TODO: Could the next two be made \"pure\"\n-- TODO: Figure out what this function should return...\nrawBlobContent :: Blob -> IO CPtr\nrawBlobContent (Blob b) = {#call git_blob_rawcontent#} b\n\nrawBlobSize :: Blob -> IO Int\nrawBlobSize (Blob b) = return . fromIntegral =<< {#call git_blob_rawsize#} b\n\nblobFromFile :: ObjID -> Repository -> String -> IO (Maybe GitError)\nblobFromFile (ObjID obj) (Repository repo) path = do\n pathStr <- newCString path\n res <- {#call git_blob_create_fromfile #} obj repo pathStr\n retMaybeRes res\n\n-- TODO: CPtr here?\nblobFromBuffer :: ObjID -> Repository -> CPtr -> IO (Maybe GitError)\nblobFromBuffer (ObjID objId) (Repository repo) buf = do\n res <- {#call git_blob_create_frombuffer#} objId repo buf\n (fromIntegral $ sizeOf buf)\n retMaybeRes res\n\n-------------------------------------------------------------------------------\n-- END: blob.h\n-------------------------------------------------------------------------------\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: commit.h\n-------------------------------------------------------------------------------\n\ncommitId :: Commit -> ObjID\ncommitId (Commit c) = unsafePerformIO $\n return . ObjID =<< {#call unsafe git_commit_id#} c\n\nshortCommitMsg :: Commit -> String\nshortCommitMsg (Commit c) = unsafePerformIO $\n peekCString =<< {#call unsafe git_commit_message_short#} c\n\ncommitMsg :: Commit -> String\ncommitMsg (Commit c) = unsafePerformIO $\n peekCString =<< {#call unsafe git_commit_message#} c\n\ncommitTime :: Commit -> TimeT\ncommitTime (Commit c) = unsafePerformIO $\n return =<< {#call unsafe git_commit_time#} c\n\ntimeOffset :: Commit -> Int\ntimeOffset (Commit c) = unsafePerformIO $\n return . fromIntegral =<< {#call unsafe git_commit_time_offset#} c\n\ncommitter :: Commit -> Signature\ncommitter (Commit c) = unsafePerformIO $\n return . Signature =<< {#call unsafe git_commit_committer#} c\n\nauthor :: Commit -> Signature\nauthor (Commit c) = unsafePerformIO $\n return . Signature =<< {#call unsafe git_commit_author#} c\n\ntree :: Commit -> IO (Either GitError Tree)\ntree (Commit c) = alloca $ \\tree -> do\n res <- {#call git_commit_tree#} tree c\n retEither res $ fmap (Right . Tree) $ peek tree\n\ntreeOid :: Commit -> ObjID\ntreeOid (Commit c) = unsafePerformIO $\n return . ObjID =<< {#call unsafe git_commit_tree_oid#} c\n\nparentCount :: Commit -> IO Int\nparentCount (Commit c) =\n return . fromIntegral =<< {#call unsafe git_commit_parentcount#} c\n\nparent :: Commit -> Int -> IO (Either GitError Commit)\nparent (Commit c) n = alloca $ \\parent -> do\n res <- {#call git_commit_parent#} parent c (fromIntegral n)\n retEither res $ fmap (Right . Commit) $ peek parent\n\nparentObjID :: Commit -> Int -> IO (Maybe ObjID)\nparentObjID (Commit c) n = do\n res <- {#call git_commit_parent_oid#} c (fromIntegral n)\n if res == nullPtr\n then return Nothing\n else return . Just . ObjID $ res\n\ncreateCommit :: ObjID -> Repository -> Maybe String -> Signature -> Signature\n -> String -> Tree -> [Commit] -> IO (Maybe GitError)\ncreateCommit (ObjID objId) (Repository r) mref (Signature ausig)\n (Signature comsig) msg (Tree t) ps = do\n updRef <- case mref of\n Nothing -> return nullPtr\n Just x -> newCString x\n msgStr <- newCString msg\n carr <- newArray [c | Commit c <- ps]\n res <- {#call git_commit_create#} objId r updRef ausig comsig msgStr t cnt carr\n retMaybeRes res\n where cnt = fromIntegral $ length ps\n\n-------------------------------------------------------------------------------\n-- END: commit.h\n-------------------------------------------------------------------------------\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: common.h\n-------------------------------------------------------------------------------\n\n-- TODO: Support?\n-- GIT_EXTERN(void) git_strarray_free(git_strarray *array);\n{-\n\/**\n * Return the version of the libgit2 library\n * being currently used.\n *\n * @param major Store the major version number\n * @param minor Store the minor version number\n * @param rev Store the revision (patch) number\n *\/\nGIT_EXTERN(void) git_libgit2_version(int *major, int *minor, int *rev);\n-}\n\n-------------------------------------------------------------------------------\n-- END: common.h\n-------------------------------------------------------------------------------\n\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: config.h\n-------------------------------------------------------------------------------\n\n{-\n\/**\n * Locate the path to the global configuration file\n *\n * The user or global configuration file is usually\n * located in `$HOME\/.gitconfig`.\n *\n * This method will try to guess the full path to that\n * file, if the file exists. The returned path\n * may be used on any `git_config` call to load the\n * global configuration file.\n *\n * @param global_config_path Buffer of GIT_PATH_MAX length to store the path\n * @return GIT_SUCCESS if a global configuration file has been\n *\tfound. Its path will be stored in `buffer`.\n *\/\nGIT_EXTERN(int) git_config_find_global(char *global_config_path);\n\n\/**\n * Open the global configuration file\n *\n * Utility wrapper that calls `git_config_find_global`\n * and opens the located file, if it exists.\n *\n * @param out Pointer to store the config instance\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_open_global(git_config **out);\n\n\/**\n * Create a configuration file backend for ondisk files\n *\n * These are the normal `.gitconfig` files that Core Git\n * processes. Note that you first have to add this file to a\n * configuration object before you can query it for configuration\n * variables.\n *\n * @param out the new backend\n * @param path where the config file is located\n *\/\nGIT_EXTERN(int) git_config_file__ondisk(struct git_config_file **out, const char *path);\n\n\/**\n * Allocate a new configuration object\n *\n * This object is empty, so you have to add a file to it before you\n * can do anything with it.\n *\n * @param out pointer to the new configuration\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_new(git_config **out);\n\n\/**\n * Add a generic config file instance to an existing config\n *\n * Note that the configuration object will free the file\n * automatically.\n *\n * Further queries on this config object will access each\n * of the config file instances in order (instances with\n * a higher priority will be accessed first).\n *\n * @param cfg the configuration to add the file to\n * @param file the configuration file (backend) to add\n * @param priority the priority the backend should have\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_add_file(git_config *cfg, git_config_file *file, int priority);\n\n\/**\n * Add an on-disk config file instance to an existing config\n *\n * The on-disk file pointed at by `path` will be opened and\n * parsed; it's expected to be a native Git config file following\n * the default Git config syntax (see man git-config).\n *\n * Note that the configuration object will free the file\n * automatically.\n *\n * Further queries on this config object will access each\n * of the config file instances in order (instances with\n * a higher priority will be accessed first).\n *\n * @param cfg the configuration to add the file to\n * @param path path to the configuration file (backend) to add\n * @param priority the priority the backend should have\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_add_file_ondisk(git_config *cfg, const char *path, int priority);\n\n\n\/**\n * Create a new config instance containing a single on-disk file\n *\n * This method is a simple utility wrapper for the following sequence\n * of calls:\n *\t- git_config_new\n *\t- git_config_add_file_ondisk\n *\n * @param cfg The configuration instance to create\n * @param path Path to the on-disk file to open\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_open_ondisk(git_config **cfg, const char *path);\n\n\/**\n * Free the configuration and its associated memory and files\n *\n * @param cfg the configuration to free\n *\/\nGIT_EXTERN(void) git_config_free(git_config *cfg);\n\n\/**\n * Get the value of an integer config variable.\n *\n * @param cfg where to look for the variable\n * @param name the variable's name\n * @param out pointer to the variable where the value should be stored\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_get_int(git_config *cfg, const char *name, int *out);\n\n\/**\n * Get the value of a long integer config variable.\n *\n * @param cfg where to look for the variable\n * @param name the variable's name\n * @param out pointer to the variable where the value should be stored\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_get_long(git_config *cfg, const char *name, long int *out);\n\n\/**\n * Get the value of a boolean config variable.\n *\n * This function uses the usual C convention of 0 being false and\n * anything else true.\n *\n * @param cfg where to look for the variable\n * @param name the variable's name\n * @param out pointer to the variable where the value should be stored\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_get_bool(git_config *cfg, const char *name, int *out);\n\n\/**\n * Get the value of a string config variable.\n *\n * The string is owned by the variable and should not be freed by the\n * user.\n *\n * @param cfg where to look for the variable\n * @param name the variable's name\n * @param out pointer to the variable's value\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_get_string(git_config *cfg, const char *name, const char **out);\n\n\/**\n * Set the value of an integer config variable.\n *\n * @param cfg where to look for the variable\n * @param name the variable's name\n * @param value Integer value for the variable\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_set_int(git_config *cfg, const char *name, int value);\n\n\/**\n * Set the value of a long integer config variable.\n *\n * @param cfg where to look for the variable\n * @param name the variable's name\n * @param value Long integer value for the variable\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_set_long(git_config *cfg, const char *name, long int value);\n\n\/**\n * Set the value of a boolean config variable.\n *\n * @param cfg where to look for the variable\n * @param name the variable's name\n * @param value the value to store\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_set_bool(git_config *cfg, const char *name, int value);\n\n\/**\n * Set the value of a string config variable.\n *\n * A copy of the string is made and the user is free to use it\n * afterwards.\n *\n * @param cfg where to look for the variable\n * @param name the variable's name\n * @param value the string to store.\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_set_string(git_config *cfg, const char *name, const char *value);\n\n\/**\n * Delete a config variable\n *\n * @param cfg the configuration\n * @param name the variable to delete\n *\/\nGIT_EXTERN(int) git_config_delete(git_config *cfg, const char *name);\n\n\/**\n * Perform an operation on each config variable.\n *\n * The callback receives the normalized name and value of each variable\n * in the config backend, and the data pointer passed to this function.\n * As soon as one of the callback functions returns something other than 0,\n * this function returns that value.\n *\n * @param cfg where to get the variables from\n * @param callback the function to call on each variable\n * @param payload the data to pass to the callback\n * @return GIT_SUCCESS or the return value of the callback which didn't return 0\n *\/\nGIT_EXTERN(int) git_config_foreach(\n\tgit_config *cfg,\n\tint (*callback)(const char *var_name, const char *value, void *payload),\n\tvoid *payload);\n-}\n\n-------------------------------------------------------------------------------\n-- END: config.h\n-------------------------------------------------------------------------------\n\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: errors.h\n-------------------------------------------------------------------------------\n\nlastError :: IO String\nlastError = peekCString =<< {#call git_lasterror#}\n\nclearError :: IO ()\nclearError = {#call git_clearerror#}\n\n-------------------------------------------------------------------------------\n-- END: errors.h\n-------------------------------------------------------------------------------\n\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: index.h\n-------------------------------------------------------------------------------\n{#enum define IdxEntry { GIT_IDXENTRY_NAMEMASK as NameMask\n , GIT_IDXENTRY_STAGEMASK as StageMask\n , GIT_IDXENTRY_EXTENDED as ExtendedOrSkipWorkTree\n , GIT_IDXENTRY_VALID as ValidOrExtended2\n , GIT_IDXENTRY_STAGESHIFT as StageShift\n , GIT_IDXENTRY_UPDATE as Update\n , GIT_IDXENTRY_REMOVE as Remove\n , GIT_IDXENTRY_UPTODATE as UpToDate\n , GIT_IDXENTRY_ADDED as Added\n , GIT_IDXENTRY_HASHED as Hashed\n , GIT_IDXENTRY_UNHASHED as UnHashed\n , GIT_IDXENTRY_WT_REMOVE as WTRemove\n , GIT_IDXENTRY_CONFLICTED as Conflicted\n , GIT_IDXENTRY_UNPACKED as Unpacked\n , GIT_IDXENTRY_NEW_SKIP_WORKTREE as NewSkipWorkTree\n , GIT_IDXENTRY_INTENT_TO_ADD as IntentToAdd\n , GIT_IDXENTRY_SKIP_WORKTREE as SkipWorkTree\n , GIT_IDXENTRY_EXTENDED2 as Extended2\n }#}\n\n-- TODO: Can we get this into IdxEntry somehow?\nidxExtFlags :: Int\nidxExtFlags = fromEnum IntentToAdd .|. fromEnum SkipWorkTree\n\n-- | Create a new bare Git index object as a memory representation of the Git\n-- index file in the provided path, without a repository to back it.\nopenIndex :: String -> IO (Either GitError Index)\nopenIndex path = alloca $ \\index -> do\n pth <- newCString path\n res <- {#call git_index_open#} index pth\n retEither res $ fmap (Right . Index) $ peek index\n\n-- | Clear the contents (all the entries) of an index object. This clears the\n-- index object in memory; changes must be manually written to disk for them to\n-- take effect.\nclearIndex :: Index -> IO ()\nclearIndex (Index idx) = {#call git_index_clear#} idx\n\n-- | Free an existing index object.\nfreeIndex :: Index -> IO ()\nfreeIndex (Index idx) = {#call git_index_free#} idx\n\n-- | Update the contents of an existing index object in memory by reading from\n-- the hard disk.\nreadIndex :: Index -> IO (Maybe GitError)\nreadIndex (Index idx) = do\n res <- {#call git_index_read#} idx\n retMaybeRes res\n\n-- | Write an existing index object from memory back to disk using an atomic\n-- file lock.\nwriteIndex :: Index -> IO (Maybe GitError)\nwriteIndex (Index idx) = do\n res <- {#call git_index_write#} idx\n retMaybeRes res\n\n-- | Find the first index of any entries which point to given path in the Git\n-- index.\nfindIndex :: Index -> String -> IO (Maybe Int)\nfindIndex (Index idx) path = do\n pth <- newCString path\n res <- {#call git_index_find#} idx pth\n if res >= 0\n then return . Just $ fromIntegral res\n else return Nothing\n\n-- | Remove all entries with equal path except last added\nuniqIndex :: Index -> IO ()\nuniqIndex (Index idx) = {#call git_index_uniq#} idx\n\n-- | Add or update an index entry from a file in disk\naddIndex :: Index -> String -> Int -> IO (Maybe GitError)\naddIndex (Index idx) path stage = do\n pth <- newCString path\n res <- {#call git_index_add#} idx pth (fromIntegral stage)\n retMaybeRes res\n\n-- | Add or update an index entry from an in-memory struct\naddIndex2 :: Index -> IndexEntry -> IO (Maybe GitError)\naddIndex2 (Index idx) (IndexEntry ie) = do\n res <- {#call git_index_add2#} idx ie\n retMaybeRes res\n\n-- | Add (append) an index entry from a file in disk\nappendIndex :: Index -> String -> Int -> IO (Maybe GitError)\nappendIndex (Index idx) path stage = do\n pth <- newCString path\n res <- {#call git_index_append#} idx pth (fromIntegral stage)\n retMaybeRes res\n\n-- | Add (append) an index entry from an in-memory struct\nappendIndex2 :: Index -> IndexEntry -> IO (Maybe GitError)\nappendIndex2 (Index idx) (IndexEntry ie) = do\n res <- {#call git_index_append2#} idx ie\n retMaybeRes res\n\n-- | Remove an entry from the index\nremove :: Index -> Int -> IO (Maybe GitError)\nremove (Index idx) n = do\n res <- {#call git_index_remove#} idx (fromIntegral n)\n retMaybeRes res\n\n-- | Get a pointer to one of the entries in the index\ngetIndex :: Index -> Int -> IO (Maybe IndexEntry)\ngetIndex (Index idx) n = do\n res <- {#call git_index_get#} idx (fromIntegral n)\n return $ if res == nullPtr\n then Nothing\n else Just $ IndexEntry res\n\n-- | Get the count of entries currently in the index\nentryCount :: Index -> IO Int\nentryCount (Index idx) =\n return . fromIntegral =<< {#call git_index_entrycount#} idx\n\n-- | Get the count of unmerged entries currently in the index\nentryCountUnMerged :: Index -> IO Int\nentryCountUnMerged (Index idx) =\n return . fromIntegral =<< {#call git_index_entrycount_unmerged#} idx\n\n-- | Get an unmerged entry from the index.\nunmergedByPath :: Index -> String -> IO (Maybe IndexEntryUnMerged)\nunmergedByPath (Index idx) path = do\n pth <- newCString path\n res <- {#call git_index_get_unmerged_bypath#} idx pth\n return $ if res == nullPtr\n then Nothing\n else Just $ IndexEntryUnMerged res\n\n-- | Get an unmerged entry from the index.\nunmergedByIndex :: Index -> Int -> IO (Maybe IndexEntryUnMerged)\nunmergedByIndex (Index idx) n = do\n res <- {#call git_index_get_unmerged_byindex#} idx (fromIntegral n)\n return $ if res == nullPtr\n then Nothing\n else Just $ IndexEntryUnMerged res\n\n-- | Return the stage number from a git index entry\nentryStage :: IndexEntry -> IO Int\nentryStage (IndexEntry ie) =\n return . fromIntegral =<< {#call git_index_entry_stage#} ie\n\n-------------------------------------------------------------------------------\n-- END: index.h\n-------------------------------------------------------------------------------\n\n\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: repositoy.h\n-------------------------------------------------------------------------------\n\nrepoIs :: Ptr2Int -> Repository -> IO Bool\nrepoIs ffi (Repository ptr) = return . toBool =<< ffi ptr\n\nopenRepo :: String -> IO (Either GitError Repository)\nopenRepo path = alloca $ \\pprepo -> do\n pstr <- newCString path\n res <- {#call git_repository_open#} pprepo pstr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nopenRepoObjDir :: String -> String -> String -> String\n -> IO (Either GitError Repository)\nopenRepoObjDir dir objDir idxFile workTree = alloca $ \\pprepo -> do\n dirStr <- newCString dir\n objDStr <- newCString objDir\n idxFStr <- newCString idxFile\n wtrStr <- newCString workTree\n res <- {#call git_repository_open2#} pprepo dirStr objDStr idxFStr wtrStr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nopenRepoObjDb :: String -> ObjDB -> String -> String\n -> IO (Either GitError Repository)\nopenRepoObjDb dir (ObjDB db) idxFile workTree = alloca $ \\pprepo -> do\n dirStr <- newCString dir\n idxFStr <- newCString idxFile\n wtrStr <- newCString workTree\n res <- {#call git_repository_open3#} pprepo dirStr db idxFStr wtrStr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\ndiscover :: String -> Bool -> String -> IO (Either GitError String)\ndiscover startPath acrossFs ceilingDirs = alloca $ \\path -> do\n spStr <- newCString startPath\n cdsStr <- newCString ceilingDirs\n res <- {#call git_repository_discover#} path (fromIntegral $ sizeOf path)\n spStr (fromBool acrossFs) cdsStr\n retEither res $ fmap Right $ peekCString path\n\ndatabase :: Repository -> IO ObjDB\ndatabase (Repository r) = return . ObjDB =<< {#call git_repository_database#} r\n\nindex :: Repository -> IO (Either GitError Index)\nindex (Repository r) = alloca $ \\idx -> do\n res <- {#call git_repository_index#} idx r\n retEither res $ fmap (Right . Index) $ peek idx\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\ninit :: String -> Bool -> IO (Either GitError Repository)\ninit path isBare = alloca $ \\pprepo -> do\n pstr <- newCString path\n res <- {#call git_repository_init#} pprepo pstr (fromBool isBare)\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nisHeadDetached :: Repository -> IO Bool\nisHeadDetached = repoIs {#call git_repository_head_detached#}\n\nisHeadOrphan :: Repository -> IO Bool\nisHeadOrphan = repoIs {#call git_repository_head_orphan#}\n\nisEmpty :: Repository -> IO Bool\nisEmpty = repoIs {#call git_repository_is_empty#}\n\npath :: Repository -> RepositoryPathID -> IO String\npath (Repository r) pathID = peekCString =<< {#call git_repository_path#} r p\n where p = fromIntegral $ fromEnum pathID\n\nisBare :: Repository -> IO Bool\nisBare = repoIs {#call git_repository_is_bare#}\n\n-------------------------------------------------------------------------------\n-- END: repository.h\n-------------------------------------------------------------------------------\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\n#include \"git2.h\"\n\nmodule Git2 where\n\nimport Data.Bits\nimport Data.Maybe\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO.Unsafe\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype CPtr = Ptr ()\ntype Ptr2Int = CPtr -> IO CInt\n\nnewtype ObjDB = ObjDB CPtr\nnewtype Repository = Repository CPtr\nnewtype Index = Index CPtr\nnewtype Blob = Blob CPtr\nnewtype ObjID = ObjID CPtr\nnewtype Commit = Commit CPtr\nnewtype Signature = Signature CPtr\nnewtype Tree = Tree CPtr\nnewtype Config = Config CPtr\n\ndefaultPort :: String\ndefaultPort = \"9418\" -- TODO: Import from net.h?\n\n{#enum define Direction { GIT_DIR_FETCH as Fetch\n , GIT_DIR_PUSH as Push}#}\n\n{-\n#define GIT_STATUS_CURRENT 0\n\/** Flags for index status *\/\n#define GIT_STATUS_INDEX_NEW (1 << 0)\n#define GIT_STATUS_INDEX_MODIFIED (1 << 1)\n#define GIT_STATUS_INDEX_DELETED (1 << 2)\n\n\/** Flags for worktree status *\/\n#define GIT_STATUS_WT_NEW (1 << 3)\n#define GIT_STATUS_WT_MODIFIED (1 << 4)\n#define GIT_STATUS_WT_DELETED (1 << 5)\n\n\/\/ TODO Ignored files not handled yet\n#define GIT_STATUS_IGNORED (1 << 6)\n-}\n\n{-\n{#enum define Status { GIT_STATUS_CURRENT as Current\n , GIT_STATUS_INDEX_NEW as NewIndex\n , GIT_STATUS_INDEX_MODIFIED as ModifiedIndex\n , GIT_STATUS_INDEX_DELETED as DeletedIndex\n , GIT_STATUS_WT_NEW as NewWorkTree\n , GIT_STATUS_WT_MODIFIED as ModifiedWorkTree\n , GIT_STATUS_WT_DELETED as DeletedWorkTree\n , GIT_STATUS_IGNORED as Ignored}#}\n-}\n\n{#enum git_otype as OType {underscoreToCase}#}\n{#enum git_rtype as RType {underscoreToCase}#}\n{#enum git_repository_pathid as RepositoryPathID {underscoreToCase}#}\n{#enum git_error as GitError {underscoreToCase}#}\n{#enum git_odb_streammode as ODBStreamMode {underscoreToCase}#}\n\nderiving instance Show GitError\n\n\n\nretEither :: CInt -> IO (Either GitError a) -> IO (Either GitError a)\nretEither res f | res == 0 = f\n | otherwise = return . Left . toEnum . fromIntegral $ res\n\n\nretMaybeRes :: CInt -> IO (Maybe GitError)\nretMaybeRes res | res == 0 = return Nothing\n | otherwise = return $ Just . toEnum . fromIntegral $ res\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: blob.h\n-------------------------------------------------------------------------------\n\n{-\n\/**\n * Get a read-only buffer with the raw content of a blob.\n *\n * A pointer to the raw content of a blob is returned;\n * this pointer is owned internally by the object and shall\n * not be free'd. The pointer may be invalidated at a later\n * time.\n *\n * @param blob pointer to the blob\n * @return the pointer; NULL if the blob has no contents\n *\/\nGIT_EXTERN(const void *) git_blob_rawcontent(git_blob *blob);\n-}\n-- TODO: Could the next two be made \"pure\"\n-- TODO: Figure out what this function should return...\nrawBlobContent :: Blob -> IO CPtr\nrawBlobContent (Blob b) = {#call git_blob_rawcontent#} b\n\nrawBlobSize :: Blob -> IO Int\nrawBlobSize (Blob b) = return . fromIntegral =<< {#call git_blob_rawsize#} b\n\nblobFromFile :: ObjID -> Repository -> String -> IO (Maybe GitError)\nblobFromFile (ObjID obj) (Repository repo) path = do\n pathStr <- newCString path\n res <- {#call git_blob_create_fromfile #} obj repo pathStr\n retMaybeRes res\n\n-- TODO: CPtr here?\nblobFromBuffer :: ObjID -> Repository -> CPtr -> IO (Maybe GitError)\nblobFromBuffer (ObjID objId) (Repository repo) buf = do\n res <- {#call git_blob_create_frombuffer#} objId repo buf\n (fromIntegral $ sizeOf buf)\n retMaybeRes res\n\n-------------------------------------------------------------------------------\n-- END: blob.h\n-------------------------------------------------------------------------------\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: commit.h\n-------------------------------------------------------------------------------\n\ncommitId :: Commit -> ObjID\ncommitId (Commit c) = unsafePerformIO $\n return . ObjID =<< {#call unsafe git_commit_id#} c\n\nshortCommitMsg :: Commit -> String\nshortCommitMsg (Commit c) = unsafePerformIO $\n peekCString =<< {#call unsafe git_commit_message_short#} c\n\ncommitMsg :: Commit -> String\ncommitMsg (Commit c) = unsafePerformIO $\n peekCString =<< {#call unsafe git_commit_message#} c\n\ncommitTime :: Commit -> TimeT\ncommitTime (Commit c) = unsafePerformIO $\n return =<< {#call unsafe git_commit_time#} c\n\ntimeOffset :: Commit -> Int\ntimeOffset (Commit c) = unsafePerformIO $\n return . fromIntegral =<< {#call unsafe git_commit_time_offset#} c\n\ncommitter :: Commit -> Signature\ncommitter (Commit c) = unsafePerformIO $\n return . Signature =<< {#call unsafe git_commit_committer#} c\n\nauthor :: Commit -> Signature\nauthor (Commit c) = unsafePerformIO $\n return . Signature =<< {#call unsafe git_commit_author#} c\n\ntree :: Commit -> IO (Either GitError Tree)\ntree (Commit c) = alloca $ \\tree -> do\n res <- {#call git_commit_tree#} tree c\n retEither res $ fmap (Right . Tree) $ peek tree\n\ntreeOid :: Commit -> ObjID\ntreeOid (Commit c) = unsafePerformIO $\n return . ObjID =<< {#call unsafe git_commit_tree_oid#} c\n\nparentCount :: Commit -> IO Int\nparentCount (Commit c) =\n return . fromIntegral =<< {#call unsafe git_commit_parentcount#} c\n\nparent :: Commit -> Int -> IO (Either GitError Commit)\nparent (Commit c) n = alloca $ \\parent -> do\n res <- {#call git_commit_parent#} parent c (fromIntegral n)\n retEither res $ fmap (Right . Commit) $ peek parent\n\nparentObjID :: Commit -> Int -> IO (Maybe ObjID)\nparentObjID (Commit c) n = do\n res <- {#call git_commit_parent_oid#} c (fromIntegral n)\n if res == nullPtr\n then return Nothing\n else return . Just . ObjID $ res\n\ncreateCommit :: ObjID -> Repository -> Maybe String -> Signature -> Signature\n -> String -> Tree -> [Commit] -> IO (Maybe GitError)\ncreateCommit (ObjID objId) (Repository r) mref (Signature ausig)\n (Signature comsig) msg (Tree t) ps = do\n updRef <- case mref of\n Nothing -> return nullPtr\n Just x -> newCString x\n msgStr <- newCString msg\n carr <- newArray [c | Commit c <- ps]\n res <- {#call git_commit_create#} objId r updRef ausig comsig msgStr t cnt carr\n retMaybeRes res\n where cnt = fromIntegral $ length ps\n\n-------------------------------------------------------------------------------\n-- END: commit.h\n-------------------------------------------------------------------------------\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: common.h\n-------------------------------------------------------------------------------\n\n-- TODO: Support?\n-- GIT_EXTERN(void) git_strarray_free(git_strarray *array);\n{-\n\/**\n * Return the version of the libgit2 library\n * being currently used.\n *\n * @param major Store the major version number\n * @param minor Store the minor version number\n * @param rev Store the revision (patch) number\n *\/\nGIT_EXTERN(void) git_libgit2_version(int *major, int *minor, int *rev);\n-}\n\n-------------------------------------------------------------------------------\n-- END: common.h\n-------------------------------------------------------------------------------\n\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: config.h\n-------------------------------------------------------------------------------\n\n{-\n\/**\n * Locate the path to the global configuration file\n *\n * The user or global configuration file is usually\n * located in `$HOME\/.gitconfig`.\n *\n * This method will try to guess the full path to that\n * file, if the file exists. The returned path\n * may be used on any `git_config` call to load the\n * global configuration file.\n *\n * @param global_config_path Buffer of GIT_PATH_MAX length to store the path\n * @return GIT_SUCCESS if a global configuration file has been\n *\tfound. Its path will be stored in `buffer`.\n *\/\nGIT_EXTERN(int) git_config_find_global(char *global_config_path);\n\n\/**\n * Open the global configuration file\n *\n * Utility wrapper that calls `git_config_find_global`\n * and opens the located file, if it exists.\n *\n * @param out Pointer to store the config instance\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_open_global(git_config **out);\n\n\/**\n * Create a configuration file backend for ondisk files\n *\n * These are the normal `.gitconfig` files that Core Git\n * processes. Note that you first have to add this file to a\n * configuration object before you can query it for configuration\n * variables.\n *\n * @param out the new backend\n * @param path where the config file is located\n *\/\nGIT_EXTERN(int) git_config_file__ondisk(struct git_config_file **out, const char *path);\n\n\/**\n * Allocate a new configuration object\n *\n * This object is empty, so you have to add a file to it before you\n * can do anything with it.\n *\n * @param out pointer to the new configuration\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_new(git_config **out);\n\n\/**\n * Add a generic config file instance to an existing config\n *\n * Note that the configuration object will free the file\n * automatically.\n *\n * Further queries on this config object will access each\n * of the config file instances in order (instances with\n * a higher priority will be accessed first).\n *\n * @param cfg the configuration to add the file to\n * @param file the configuration file (backend) to add\n * @param priority the priority the backend should have\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_add_file(git_config *cfg, git_config_file *file, int priority);\n\n\/**\n * Add an on-disk config file instance to an existing config\n *\n * The on-disk file pointed at by `path` will be opened and\n * parsed; it's expected to be a native Git config file following\n * the default Git config syntax (see man git-config).\n *\n * Note that the configuration object will free the file\n * automatically.\n *\n * Further queries on this config object will access each\n * of the config file instances in order (instances with\n * a higher priority will be accessed first).\n *\n * @param cfg the configuration to add the file to\n * @param path path to the configuration file (backend) to add\n * @param priority the priority the backend should have\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_add_file_ondisk(git_config *cfg, const char *path, int priority);\n\n\n\/**\n * Create a new config instance containing a single on-disk file\n *\n * This method is a simple utility wrapper for the following sequence\n * of calls:\n *\t- git_config_new\n *\t- git_config_add_file_ondisk\n *\n * @param cfg The configuration instance to create\n * @param path Path to the on-disk file to open\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_open_ondisk(git_config **cfg, const char *path);\n\n\/**\n * Free the configuration and its associated memory and files\n *\n * @param cfg the configuration to free\n *\/\nGIT_EXTERN(void) git_config_free(git_config *cfg);\n\n\/**\n * Get the value of an integer config variable.\n *\n * @param cfg where to look for the variable\n * @param name the variable's name\n * @param out pointer to the variable where the value should be stored\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_get_int(git_config *cfg, const char *name, int *out);\n\n\/**\n * Get the value of a long integer config variable.\n *\n * @param cfg where to look for the variable\n * @param name the variable's name\n * @param out pointer to the variable where the value should be stored\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_get_long(git_config *cfg, const char *name, long int *out);\n\n\/**\n * Get the value of a boolean config variable.\n *\n * This function uses the usual C convention of 0 being false and\n * anything else true.\n *\n * @param cfg where to look for the variable\n * @param name the variable's name\n * @param out pointer to the variable where the value should be stored\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_get_bool(git_config *cfg, const char *name, int *out);\n\n\/**\n * Get the value of a string config variable.\n *\n * The string is owned by the variable and should not be freed by the\n * user.\n *\n * @param cfg where to look for the variable\n * @param name the variable's name\n * @param out pointer to the variable's value\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_get_string(git_config *cfg, const char *name, const char **out);\n\n\/**\n * Set the value of an integer config variable.\n *\n * @param cfg where to look for the variable\n * @param name the variable's name\n * @param value Integer value for the variable\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_set_int(git_config *cfg, const char *name, int value);\n\n\/**\n * Set the value of a long integer config variable.\n *\n * @param cfg where to look for the variable\n * @param name the variable's name\n * @param value Long integer value for the variable\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_set_long(git_config *cfg, const char *name, long int value);\n\n\/**\n * Set the value of a boolean config variable.\n *\n * @param cfg where to look for the variable\n * @param name the variable's name\n * @param value the value to store\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_set_bool(git_config *cfg, const char *name, int value);\n\n\/**\n * Set the value of a string config variable.\n *\n * A copy of the string is made and the user is free to use it\n * afterwards.\n *\n * @param cfg where to look for the variable\n * @param name the variable's name\n * @param value the string to store.\n * @return GIT_SUCCESS on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_config_set_string(git_config *cfg, const char *name, const char *value);\n\n\/**\n * Delete a config variable\n *\n * @param cfg the configuration\n * @param name the variable to delete\n *\/\nGIT_EXTERN(int) git_config_delete(git_config *cfg, const char *name);\n\n\/**\n * Perform an operation on each config variable.\n *\n * The callback receives the normalized name and value of each variable\n * in the config backend, and the data pointer passed to this function.\n * As soon as one of the callback functions returns something other than 0,\n * this function returns that value.\n *\n * @param cfg where to get the variables from\n * @param callback the function to call on each variable\n * @param payload the data to pass to the callback\n * @return GIT_SUCCESS or the return value of the callback which didn't return 0\n *\/\nGIT_EXTERN(int) git_config_foreach(\n\tgit_config *cfg,\n\tint (*callback)(const char *var_name, const char *value, void *payload),\n\tvoid *payload);\n-}\n\n-------------------------------------------------------------------------------\n-- END: config.h\n-------------------------------------------------------------------------------\n\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: errors.h\n-------------------------------------------------------------------------------\n\nlastError :: IO String\nlastError = peekCString =<< {#call git_lasterror#}\n\nclearError :: IO ()\nclearError = {#call git_clearerror#}\n\n-------------------------------------------------------------------------------\n-- END: errors.h\n-------------------------------------------------------------------------------\n\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: index.h\n-------------------------------------------------------------------------------\n{#enum define IdxEntry { GIT_IDXENTRY_NAMEMASK as NameMask\n , GIT_IDXENTRY_STAGEMASK as StageMask\n , GIT_IDXENTRY_EXTENDED as ExtendedOrSkipWorkTree\n , GIT_IDXENTRY_VALID as ValidOrExtended2\n , GIT_IDXENTRY_STAGESHIFT as StageShift\n , GIT_IDXENTRY_UPDATE as Update\n , GIT_IDXENTRY_REMOVE as Remove\n , GIT_IDXENTRY_UPTODATE as UpToDate\n , GIT_IDXENTRY_ADDED as Added\n , GIT_IDXENTRY_HASHED as Hashed\n , GIT_IDXENTRY_UNHASHED as UnHashed\n , GIT_IDXENTRY_WT_REMOVE as WTRemove\n , GIT_IDXENTRY_CONFLICTED as Conflicted\n , GIT_IDXENTRY_UNPACKED as Unpacked\n , GIT_IDXENTRY_NEW_SKIP_WORKTREE as NewSkipWorkTree\n , GIT_IDXENTRY_INTENT_TO_ADD as IntentToAdd\n , GIT_IDXENTRY_SKIP_WORKTREE as SkipWorkTree\n , GIT_IDXENTRY_EXTENDED2 as Extended2\n }#}\n\n-- TODO: Can we get this into IdxEntry somehow?\nidxExtFlags :: Int\nidxExtFlags = fromEnum IntentToAdd .|. fromEnum SkipWorkTree\n\n-- | Create a new bare Git index object as a memory representation of the Git\n-- index file in the provided path, without a repository to back it.\nopenIndex :: String -> IO (Either GitError Index)\nopenIndex path = alloca $ \\index -> do\n pth <- newCString path\n res <- {#call git_index_open#} index pth\n retEither res $ fmap (Right . Index) $ peek index\n\n-- | Clear the contents (all the entries) of an index object. This clears the\n-- index object in memory; changes must be manually written to disk for them to\n-- take effect.\nclearIndex :: Index -> IO ()\nclearIndex (Index idx) = {#call git_index_clear#} idx\n\n-- | Free an existing index object.\nfreeIndex :: Index -> IO ()\nfreeIndex (Index idx) = {#call git_index_free#} idx\n\n-- | Update the contents of an existing index object in memory by reading from\n-- the hard disk.\nreadIndex :: Index -> IO (Maybe GitError)\nreadIndex (Index idx) = do\n res <- {#call git_index_read#} idx\n retMaybeRes res\n\n-- | Write an existing index object from memory back to disk using an atomic\n-- file lock.\nwriteIndex :: Index -> IO (Maybe GitError)\nwriteIndex (Index idx) = do\n res <- {#call git_index_write#} idx\n retMaybeRes res\n\n-- | Find the first index of any entries which point to given path in the Git\n-- index.\nfindIndex :: Index -> String -> IO (Maybe Int)\nfindIndex (Index idx) path = do\n pth <- newCString path\n res <- {#call git_index_find#} idx pth\n if res >= 0\n then return . Just $ fromIntegral res\n else return Nothing\n\n-- | Remove all entries with equal path except last added\nuniqIndex :: Index -> IO ()\nuniqIndex (Index idx) = {#call git_index_uniq#} idx\n\n-- | Add or update an index entry from a file in disk\naddIndex :: Index -> String -> Int -> IO (Maybe GitError)\naddIndex (Index idx) path stage = do\n pth <- newCString path\n res <- {#call git_index_add#} idx pth (fromIntegral stage)\n retMaybeRes res\n\n\n\n{-\n\/**\n * Add or update an index entry from an in-memory struct\n *\n * A full copy (including the 'path' string) of the given\n * 'source_entry' will be inserted on the index.\n *\n * @param index an existing index object\n * @param source_entry new entry object\n * @return 0 on success, otherwise an error code\n *\/\nGIT_EXTERN(int) git_index_add2(git_index *index, const git_index_entry *source_entry);\n\n\/**\n * Add (append) an index entry from a file in disk\n *\n * A new entry will always be inserted into the index;\n * if the index already contains an entry for such\n * path, the old entry will **not** be replaced.\n *\n * The file `path` must be relative to the repository's\n * working folder and must be readable.\n *\n * This method will fail in bare index instances.\n *\n * @param index an existing index object\n * @param path filename to add\n * @param stage stage for the entry\n * @return 0 on success, otherwise an error code\n *\/\nGIT_EXTERN(int) git_index_append(git_index *index, const char *path, int stage);\n\n\/**\n * Add (append) an index entry from an in-memory struct\n *\n * A new entry will always be inserted into the index;\n * if the index already contains an entry for the path\n * in the `entry` struct, the old entry will **not** be\n * replaced.\n *\n * A full copy (including the 'path' string) of the given\n * 'source_entry' will be inserted on the index.\n *\n * @param index an existing index object\n * @param source_entry new entry object\n * @return 0 on success, otherwise an error code\n *\/\nGIT_EXTERN(int) git_index_append2(git_index *index, const git_index_entry *source_entry);\n\n\/**\n * Remove an entry from the index\n *\n * @param index an existing index object\n * @param position position of the entry to remove\n * @return 0 on success, otherwise an error code\n *\/\nGIT_EXTERN(int) git_index_remove(git_index *index, int position);\n\n\n\/**\n * Get a pointer to one of the entries in the index\n *\n * This entry can be modified, and the changes will be written\n * back to disk on the next write() call.\n *\n * The entry should not be freed by the caller.\n *\n * @param index an existing index object\n * @param n the position of the entry\n * @return a pointer to the entry; NULL if out of bounds\n *\/\nGIT_EXTERN(git_index_entry *) git_index_get(git_index *index, unsigned int n);\n\n\/**\n * Get the count of entries currently in the index\n *\n * @param index an existing index object\n * @return integer of count of current entries\n *\/\nGIT_EXTERN(unsigned int) git_index_entrycount(git_index *index);\n\n\/**\n * Get the count of unmerged entries currently in the index\n *\n * @param index an existing index object\n * @return integer of count of current unmerged entries\n *\/\nGIT_EXTERN(unsigned int) git_index_entrycount_unmerged(git_index *index);\n\n\/**\n * Get an unmerged entry from the index.\n *\n * The returned entry is read-only and should not be modified\n * of freed by the caller.\n *\n * @param index an existing index object\n * @param path path to search\n * @return the unmerged entry; NULL if not found\n *\/\nGIT_EXTERN(const git_index_entry_unmerged *) git_index_get_unmerged_bypath(git_index *index, const char *path);\n\n\/**\n * Get an unmerged entry from the index.\n *\n * The returned entry is read-only and should not be modified\n * of freed by the caller.\n *\n * @param index an existing index object\n * @param n the position of the entry\n * @return a pointer to the unmerged entry; NULL if out of bounds\n *\/\nGIT_EXTERN(const git_index_entry_unmerged *) git_index_get_unmerged_byindex(git_index *index, unsigned int n);\n\n\/**\n * Return the stage number from a git index entry\n *\n * This entry is calculated from the entrie's flag\n * attribute like this:\n *\n *\t(entry->flags & GIT_IDXENTRY_STAGEMASK) >> GIT_IDXENTRY_STAGESHIFT\n *\n * @param entry The entry\n * @returns the stage number\n *\/\nGIT_EXTERN(int) git_index_entry_stage(const git_index_entry *entry);\n\n\n-}\n\n\n-------------------------------------------------------------------------------\n-- END: index.h\n-------------------------------------------------------------------------------\n\n\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: repositoy.h\n-------------------------------------------------------------------------------\n\nrepoIs :: Ptr2Int -> Repository -> IO Bool\nrepoIs ffi (Repository ptr) = return . toBool =<< ffi ptr\n\nopenRepo :: String -> IO (Either GitError Repository)\nopenRepo path = alloca $ \\pprepo -> do\n pstr <- newCString path\n res <- {#call git_repository_open#} pprepo pstr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nopenRepoObjDir :: String -> String -> String -> String\n -> IO (Either GitError Repository)\nopenRepoObjDir dir objDir idxFile workTree = alloca $ \\pprepo -> do\n dirStr <- newCString dir\n objDStr <- newCString objDir\n idxFStr <- newCString idxFile\n wtrStr <- newCString workTree\n res <- {#call git_repository_open2#} pprepo dirStr objDStr idxFStr wtrStr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nopenRepoObjDb :: String -> ObjDB -> String -> String\n -> IO (Either GitError Repository)\nopenRepoObjDb dir (ObjDB db) idxFile workTree = alloca $ \\pprepo -> do\n dirStr <- newCString dir\n idxFStr <- newCString idxFile\n wtrStr <- newCString workTree\n res <- {#call git_repository_open3#} pprepo dirStr db idxFStr wtrStr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\ndiscover :: String -> Bool -> String -> IO (Either GitError String)\ndiscover startPath acrossFs ceilingDirs = alloca $ \\path -> do\n spStr <- newCString startPath\n cdsStr <- newCString ceilingDirs\n res <- {#call git_repository_discover#} path (fromIntegral $ sizeOf path)\n spStr (fromBool acrossFs) cdsStr\n retEither res $ fmap Right $ peekCString path\n\ndatabase :: Repository -> IO ObjDB\ndatabase (Repository r) = return . ObjDB =<< {#call git_repository_database#} r\n\nindex :: Repository -> IO (Either GitError Index)\nindex (Repository r) = alloca $ \\idx -> do\n res <- {#call git_repository_index#} idx r\n retEither res $ fmap (Right . Index) $ peek idx\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\ninit :: String -> Bool -> IO (Either GitError Repository)\ninit path isBare = alloca $ \\pprepo -> do\n pstr <- newCString path\n res <- {#call git_repository_init#} pprepo pstr (fromBool isBare)\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nisHeadDetached :: Repository -> IO Bool\nisHeadDetached = repoIs {#call git_repository_head_detached#}\n\nisHeadOrphan :: Repository -> IO Bool\nisHeadOrphan = repoIs {#call git_repository_head_orphan#}\n\nisEmpty :: Repository -> IO Bool\nisEmpty = repoIs {#call git_repository_is_empty#}\n\npath :: Repository -> RepositoryPathID -> IO String\npath (Repository r) pathID = peekCString =<< {#call git_repository_path#} r p\n where p = fromIntegral $ fromEnum pathID\n\nisBare :: Repository -> IO Bool\nisBare = repoIs {#call git_repository_is_bare#}\n\n-------------------------------------------------------------------------------\n-- END: repository.h\n-------------------------------------------------------------------------------\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"4cb07926355557e1f8644798342eb23908f11ac4","subject":"Add ability to map BGRA D8 colour images.","message":"Add ability to map BGRA D8 colour images.\n","repos":"BeautifulDestinations\/CV","old_file":"CV\/Image.chs","new_file":"CV\/Image.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns,ParallelListComp, FlexibleInstances, FlexibleContexts, TypeFamilies, EmptyDataDecls, ScopedTypeVariables, StandaloneDeriving, DeriveDataTypeable, UndecidableInstances, MultiParamTypeClasses #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, MutableImage(..)\n, Mask\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\n, withMask\n, withMutableClone\n, withCloneValue\n, CreateImage\n, Save(..)\n\n-- * Colour spaces\n, ChannelOf\n, GrayScale\n, Complex\n, BGR\n, RGB\n, RGBA\n, BGRA\n, RGB_Channel(..)\n, LAB\n, LAB_Channel(..)\n, D32\n, D64\n, D8\n, Tag\n, lab\n, rgba\n, rgb\n, compose\n, composeMultichannelImage\n\n-- * IO operations\n, Loadable(..)\n, saveImage\n, loadColorImage\n, loadColorImage8\n, loadColorImage8'\n, loadColorAlphaImage\n, loadImage\n\n-- * Pixel level access\n, GetPixel(..)\n, SetPixel(..)\n, safeGetPixel\n, unsafeSetPixel\n, getAllPixels\n, getAllPixelsRowMajor\n, mapImageInplace\n, mapColourImageInplace\n-- * Image information\n, ImageDepth\n, Sized(..)\n, biggerThan\n, getArea\n, getChannel\n, getImageChannels\n, getImageDepth\n, getImageInfo\n\n-- * ROI's, COI's and subregions\n, setCOI\n, setROI\n, resetROI\n, getRegion\n, withIOROI\n--, withROI\n\n-- * Blitting\n, blendBlit\n, blendBlit2\n, blit\n, blitM\n, subPixelBlit\n, safeBlit\n, montage\n, tileImages\n\n-- * Conversions\n, convertTo\n, rgbToGray\n, rgbToGray8\n, grayToRGB\n, rgbToLab\n, bgrToRgb\n, rgbToBgr\n, bgrTobgra\n, cloneTo64F\n, unsafeImageTo32F\n, unsafeImageTo64F\n, unsafeImageTo8Bit\n\n-- * Low level access operations\n, BareImage(..)\n, creatingImage\n, unImage\n, unS\n, withGenBareImage\n, withBareImage\n, creatingBareImage\n, withGenImage\n, withImage\n, withMutableImage\n, withRawImageData\n, imageFPTR\n, ensure32F\n\n-- * Extended error handling\n, setCatch\n, CvException\n, CvSizeError(..)\n, CvIOError(..)\n) where\n\nimport System.Mem\nimport System.Directory\nimport System.FilePath\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Utils\nimport Foreign.ForeignPtr hiding (newForeignPtr,unsafeForeignPtrToPtr)\nimport Foreign.Concurrent\nimport Foreign.Ptr\nimport Control.Parallel.Strategies\nimport Control.DeepSeq\nimport Control.Lens\n\nimport CV.Bindings.Error\n\nimport Data.Maybe(catMaybes)\nimport Data.List(genericLength)\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)\nimport Foreign.Storable\nimport Foreign.Storable.Tuple\nimport System.IO.Unsafe\nimport Data.Word\nimport qualified Data.Complex as C\nimport Control.Monad\nimport Control.Exception\nimport Data.Data\nimport Data.Typeable\n\nimport Utils.GeometryClass\nimport Control.Applicative hiding (empty)\n\n\n\n\n-- Colorspaces\n\n-- | Single channel grayscale image\ndata GrayScale\ndata Complex\ndata RGB\ndata RGB_Channel = Red |\u00a0Green |\u00a0Blue deriving (Eq,Ord,Enum)\n\ndata BGR\n\ndata LAB\ndata YUV\ndata RGBA\ndata BGRA\ndata LAB_Channel = LAB_L |\u00a0LAB_A |\u00a0LAB_B deriving (Eq,Ord,Enum)\ndata YUV_Channel = YUV_Y |\u00a0YUV_U |\u00a0YUV_V deriving (Eq,Ord,Enum)\n\n-- | Type family for expressing which channels a colorspace contains. This needs to be fixed wrt. the BGR color space.\ntype family ChannelOf a :: *\ntype instance ChannelOf RGB_Channel = RGB\ntype instance ChannelOf LAB_Channel = LAB\ntype instance ChannelOf YUV_Channel = YUV\n\n-- Bit Depths\ntype D8 = Word8\ntype D32 = Float\ntype D64 = Double\n\n-- | The type for Images\nnewtype Image channels depth = S BareImage\nnewtype MutableImage channels depth = Mutable (Image channels depth)\n\n-- | Alias for images used as masks\ntype Mask = Maybe (Image GrayScale D8)\n\n-- |\u00a0Remove typing info from an image\nunS (S i) = i -- Unsafe and ugly\n\nimageFPTR :: Image c d -> ForeignPtr BareImage\nimageFPTR (S (BareImage fptr)) = fptr\n\nwithImage :: Image c d -> (Ptr BareImage ->IO a) -> IO a\nwithImage (S i) op = withBareImage i op\n--withGenNewImage (S i) op = withGenImage i op\n\nwithRawImageData :: Image c d -> (Int -> Ptr Word8 -> IO a) -> IO a\nwithRawImageData (S i) op = withBareImage i $ \\pp-> do\n d <- {#get IplImage->imageData#} pp\n wd <- {#get IplImage->widthStep#} pp\n op (fromIntegral wd) (castPtr d)\n\n-- Ok. this is just the example why I need image types\nwithUniPtr with x fun = with x $ \\y ->\n fun (castPtr y)\n\nwithGenImage :: Image c d -> (Ptr b -> IO a) -> IO a\nwithGenImage = withUniPtr withImage\n\n-- |\u00a0This function converts masks to pointers. Masks which are nothing are converted\n-- to null pointers.\nwithMask :: Mask -> (Ptr b -> IO a) -> IO a\nwithMask (Just i) op = withUniPtr withImage i op\nwithMask Nothing op = op nullPtr\n\nwithMutableImage :: MutableImage c d -> (Ptr b -> IO a) -> IO a\nwithMutableImage (Mutable i) o = withGenImage i o\n\nwithGenBareImage :: BareImage -> (Ptr b -> IO a) -> IO a\nwithGenBareImage = withUniPtr withBareImage\n\n{#pointer *IplImage as BareImage foreign newtype#}\n\nfreeBareImage ptr = with ptr {#call cvReleaseImage#}\n\n--foreign import ccall \"& wrapReleaseImage\" releaseImage :: FinalizerPtr BareImage\n\ninstance NFData (Image a b) where\n rnf a@(S (BareImage fptr)) = (unsafeForeignPtrToPtr) fptr `seq` a `seq` ()-- This might also need peek?\n\n\ncreatingImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . S . BareImage $ fptr\n\ncreatingBareImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . BareImage $ fptr\n\ncreatingMaybeBareImage fun = do\n iptr <- fun\n if iptr == nullPtr\n then return Nothing\n else do\n -- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . Just . BareImage $ fptr\n\nunImage (S (BareImage fptr)) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\nrgba = undefined :: Tag RGBA\nlab = undefined :: Tag LAB\n\n-- | Typeclass for elements that are build from component elements. For example,\n-- RGB images can be constructed from three grayscale images.\nclass Composes a where\n type Source a :: *\n compose :: Source a -> a\n\ninstance (CreateImage (Image RGBA a)) => Composes (Image RGBA a) where\n type Source (Image RGBA a) = (Image GrayScale a, Image GrayScale a\n ,Image GrayScale a, Image GrayScale a)\n compose (r,g,b,a) = composeMultichannelImage (Just b) (Just g) (Just r) (Just a) rgba\n\ninstance (CreateImage (Image RGB a)) => Composes (Image RGB a) where\n type Source (Image RGB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (r,g,b) = composeMultichannelImage (Just b) (Just g) (Just r) Nothing rgb\n\ninstance (CreateImage (Image LAB a)) => Composes (Image LAB a) where\n type Source (Image LAB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (l,a,b) = composeMultichannelImage (Just l) (Just a) (Just b) Nothing lab\n\n{-# DEPRECATED composeMultichannelImage \"This is unsafe. Use compose instead\" #-}\ncomposeMultichannelImage :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannelImage = composeMultichannel\n\ncomposeMultichannel :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannel (c2)\n (c1)\n (c3)\n (c4)\n totag\n = unsafePerformIO $\u00a0do\n res <- create (size) -- TODO: Check channel count -- This is NOT correct\n withMaybe c1 $ \\cc1 ->\n withMaybe c2 $ \\cc2 ->\n withMaybe c3 $ \\cc3 ->\n withMaybe c4 $ \\cc4 ->\n withGenImage res $ \\cres -> {#call cvMerge#} cc1 cc2 cc3 cc4 cres\n return res\n where\n withMaybe (Just i) op = withGenImage i op\n withMaybe (Nothing) op = op nullPtr\n size = getSize . head . catMaybes $ [c1,c2,c3,c4]\n\n\n-- | Typeclass for CV items that can be read from file. Mainly images at this point.\nclass Loadable a where\n readFromFile :: FilePath -> IO a\n\n\ninstance Loadable ((Image GrayScale D32)) where\n readFromFile fp = do\n e <- loadImage fp\n case e of\n Just i -> return i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D32)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ unsafeImageTo32F $ bgrToRgb i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D8)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ bgrToRgb i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image GrayScale D8)) where\n readFromFile fp = do\n e <- loadImage8 fp\n case e of\n Just i -> return i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\n\n-- | This function loads and converts image to an arbitrary format. Notice that it is\n-- polymorphic enough to cause run time errors if the declared and actual types of the\n-- images do not match. Use with care.\nunsafeloadUsing x p n = do\n exists <- doesFileExist n\n if not exists then return Nothing\n else do\n mi <- withCString n $ \\name ->\n creatingMaybeBareImage ({#call cvLoadImage #} name p)\n case mi of\n Nothing -> return Nothing\n Just i -> do\n bw <- x i\n return . Just .\u00a0S $ bw\n\nloadImage :: FilePath -> IO (Maybe (Image GrayScale D32))\nloadImage = unsafeloadUsing imageTo32F 0\nloadImage8 :: FilePath -> IO (Maybe (Image GrayScale D8))\nloadImage8 = unsafeloadUsing imageTo8Bit 0\nloadColorImage :: FilePath -> IO (Maybe (Image BGR D32))\nloadColorImage = unsafeloadUsing imageTo32F 1\nloadColorImage8 :: FilePath -> IO (Maybe (Image BGR D8))\nloadColorImage8 = unsafeloadUsing imageTo8Bit 1\nloadColorImage8' :: FilePath -> IO (Maybe (Image BGRA D8))\nloadColorImage8' fp = fmap bgrTobgra <$> unsafeloadUsing imageTo8Bit 1 fp\n\nforeign import ccall safe \"CV\/Image.chs.h cvLoadImage\"\n cvLoadImageWithOpts :: ((Ptr CChar) -> (CInt -> (CInt -> (IO (Ptr (BareImage))))))\n\nloadColorAlphaImage :: FilePath -> IO (Maybe (Image BGRA D8))\nloadColorAlphaImage = unsafeloadUsing imageTo8Bit (-1)\n\ninstance Sized (MutableImage a b) where\n type Size (MutableImage a b) = IO (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize (Mutable i) = evaluate (deep (getSize i))\n where\n deep a = a `deepseq` a\n\ninstance Sized BareImage where\n type Size BareImage = (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize image = unsafePerformIO $ withBareImage image $ \\i -> do\n w <- {#call getImageWidth#} i\n h <- {#call getImageHeight#} i\n return (fromIntegral w,fromIntegral h)\n\ninstance Sized (Image c d) where\n type Size (Image c d) = (Int,Int)\n getSize = getSize . unS\n\n\n#c\nenum CvtFlags {\n CvtFlip = CV_CVTIMG_FLIP,\n CvtSwapRB = CV_CVTIMG_SWAP_RB\n };\n#endc\n\n#c\nenum CvtCodes {\n BGR2BGRA =0,\n RGB2RGBA =BGR2BGRA,\n\n BGRA2BGR =1,\n RGBA2RGB =BGRA2BGR,\n\n BGR2RGBA =2,\n RGB2BGRA =BGR2RGBA,\n\n RGBA2BGR =3,\n BGRA2RGB =RGBA2BGR,\n\n BGR2RGB =4,\n RGB2BGR =BGR2RGB,\n\n BGRA2RGBA =5,\n RGBA2BGRA =BGRA2RGBA,\n\n BGR2GRAY =6,\n RGB2GRAY =7,\n GRAY2BGR =8,\n GRAY2RGB =GRAY2BGR,\n GRAY2BGRA =9,\n GRAY2RGBA =GRAY2BGRA,\n BGRA2GRAY =10,\n RGBA2GRAY =11,\n\n BGR2BGR565 =12,\n RGB2BGR565 =13,\n BGR5652BGR =14,\n BGR5652RGB =15,\n BGRA2BGR565 =16,\n RGBA2BGR565 =17,\n BGR5652BGRA =18,\n BGR5652RGBA =19,\n\n GRAY2BGR565 =20,\n BGR5652GRAY =21,\n\n BGR2BGR555 =22,\n RGB2BGR555 =23,\n BGR5552BGR =24,\n BGR5552RGB =25,\n BGRA2BGR555 =26,\n RGBA2BGR555 =27,\n BGR5552BGRA =28,\n BGR5552RGBA =29,\n\n GRAY2BGR555 =30,\n BGR5552GRAY =31,\n\n BGR2XYZ =32,\n RGB2XYZ =33,\n XYZ2BGR =34,\n XYZ2RGB =35,\n\n BGR2YCrCb =36,\n RGB2YCrCb =37,\n YCrCb2BGR =38,\n YCrCb2RGB =39,\n\n BGR2HSV =40,\n RGB2HSV =41,\n\n BGR2Lab =44,\n RGB2Lab =45,\n\n BayerBG2BGR =46,\n BayerGB2BGR =47,\n BayerRG2BGR =48,\n BayerGR2BGR =49,\n\n BayerBG2RGB =BayerRG2BGR,\n BayerGB2RGB =BayerGR2BGR,\n BayerRG2RGB =BayerBG2BGR,\n BayerGR2RGB =BayerGB2BGR,\n\n BGR2Luv =50,\n RGB2Luv =51,\n BGR2HLS =52,\n RGB2HLS =53,\n\n HSV2BGR =54,\n HSV2RGB =55,\n\n Lab2BGR =56,\n Lab2RGB =57,\n Luv2BGR =58,\n Luv2RGB =59,\n HLS2BGR =60,\n HLS2RGB =61,\n\n BayerBG2BGR_VNG =62,\n BayerGB2BGR_VNG =63,\n BayerRG2BGR_VNG =64,\n BayerGR2BGR_VNG =65,\n\n BayerBG2RGB_VNG =BayerRG2BGR_VNG,\n BayerGB2RGB_VNG =BayerGR2BGR_VNG,\n BayerRG2RGB_VNG =BayerBG2BGR_VNG,\n BayerGR2RGB_VNG =BayerGB2BGR_VNG,\n\n BGR2HSV_FULL = 66,\n RGB2HSV_FULL = 67,\n BGR2HLS_FULL = 68,\n RGB2HLS_FULL = 69,\n\n HSV2BGR_FULL = 70,\n HSV2RGB_FULL = 71,\n HLS2BGR_FULL = 72,\n HLS2RGB_FULL = 73,\n\n LBGR2Lab = 74,\n LRGB2Lab = 75,\n LBGR2Luv = 76,\n LRGB2Luv = 77,\n\n Lab2LBGR = 78,\n Lab2LRGB = 79,\n Luv2LBGR = 80,\n Luv2LRGB = 81,\n\n BGR2YUV = 82,\n RGB2YUV = 83,\n YUV2BGR = 84,\n YUV2RGB = 85,\n\n COLORCVT_MAX =100\n};\n#endc\n\n{#enum CvtCodes {}#}\n\n{#enum CvtFlags {}#}\n\nrgbToLab :: Image RGB D32 -> Image LAB D32\nrgbToLab = S . convertTo RGB2Lab 3 . unS\n\nrgbToYUV :: Image RGB D32 -> Image YUV D32\nrgbToYUV = S . convertTo RGB2YUV 3 . unS\n\nrgbToGray :: Image RGB D32 -> Image GrayScale D32\nrgbToGray = S . convertTo RGB2GRAY 1 . unS\n\nrgbToGray8 :: Image RGB D8 -> Image GrayScale D8\nrgbToGray8 = S . convert8UTo RGB2GRAY 1 . unS\n\ngrayToRGB :: Image GrayScale D32 -> Image RGB D32\ngrayToRGB = S . convertTo GRAY2BGR 3 . unS\n\nbgrTobgra = S . convert8UTo BGR2BGRA 4 . unS\n\nbgrToRgb :: Image BGR D8 -> Image RGB D8\nbgrToRgb = S . swapRB . unS\n\nrgbToBgr :: Image RGB D8 -> Image BGR D8\nrgbToBgr = S . swapRB . unS\n\nswapRB :: BareImage -> BareImage\nswapRB img = unsafePerformIO $ do\n res <- cloneBareImage img\n withBareImage img $ \\cimg ->\n withBareImage res $ \\cres ->\n {#call cvConvertImage#} (castPtr cimg) (castPtr cres) (fromIntegral . fromEnum $ CvtSwapRB)\n return res\n\n\nsafeGetPixel :: (Sized image, Size image ~ (Int,Int), GetPixel image) => (P image) -> (Int,Int) -> image -> P image\nsafeGetPixel def (x,y) i |\u00a0x<0 || x>= w || y<0 || y>=h = def\n | otherwise = getPixel (x,y) i\n where\n (w,h) = getSize i\n -- (x',y') = (clamp (0,w-1) x, clamp (0,h-1) y)\n\nclamp :: Ord a => (a, a) -> a -> a\nclamp (a,b) x = max a (min b x)\n\ninstance (NFData (P (Image a b)), GetPixel (Image a b)) => GetPixel (MutableImage a b) where\n type P (MutableImage a b) = IO (P (Image a b))\n getPixel xy (Mutable i) = let p = getPixel xy i\n in p `deepseq` return p\n\nclass GetPixel a where\n type P a :: *\n getPixel :: (Int,Int) -> a -> P a\n\n-- #define FGET(img,x,y) (((float *)((img)->imageData + (y)*(img)->widthStep))[(x)])\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Float))):: Ptr Float)\n\ninstance GetPixel (Image GrayScale D8) where\n type P (Image GrayScale D8) = D8\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Word8))):: Ptr Word8)\n\ninstance GetPixel (Image Complex D32) where\n type P (Image Complex D32) = C.Complex D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n re <- peek (castPtr (d`plusPtr` (y*cs + x*2*fs)))\n im <- peek (castPtr (d`plusPtr` (y*cs +(x*2+1)*fs)))\n return (re C.:+ im)\n\n-- #define UGETC(img,color,x,y) (((uint8_t *)((img)->imageData + (y)*(img)->widthStep))[(x)*3+(color)])\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\ninstance GetPixel (Image BGR D32) where\n type P (Image BGR D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\ninstance GetPixel (Image BGR D8) where\n type P (Image BGR D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image RGB D8) where\n type P (Image RGB D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image BGRA D8) where\n type P (Image BGRA D8) = (D8,D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*4*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*4+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*4+2)*fs)))\n a <- peek (castPtr (d`plusPtr` (y*cs +(x*4+3)*fs)))\n return (b,g,r,a)\n\ninstance GetPixel (Image LAB D32) where\n type P (Image LAB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n l <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n a <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n b <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (l,a,b)\n\n-- | Perform (a destructive) inplace map of the image. This should be wrapped inside\n-- withClone or an image operation\nmapImageInplace :: (P (Image GrayScale D32) -> P (Image GrayScale D32))\n -> MutableImage GrayScale D32\n -> IO ()\nmapImageInplace f image = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n (w,h) <- getSize image\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n forM_ [(x,y) | x<-[0..w-1], y <- [0..h-1]] $ \\(x,y) ->\u00a0do\n v <- peek (castPtr (d `plusPtr` (y*cs+x*fs)))\n poke (castPtr (d `plusPtr` (y*cs+x*fs))) (f v)\n\nmapColourImageInplace :: (P (Image BGRA D8) -> P (Image BGRA D8))\n -> MutableImage BGRA D8\n -> IO ()\nmapColourImageInplace f image = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n (w,h) <- getSize image\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n forM_ [(x,y) | x<-[0..w-1], y <- [0..h-1]] $ \\(x,y) ->\u00a0do\n v <- peek (castPtr (d `plusPtr` (y*cs+x*fs)))\n poke (castPtr (d `plusPtr` (y*cs+x*fs))) (f v)\n\n\nconvert8UTo :: CvtCodes -> CInt -> BareImage -> BareImage\nconvert8UTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage8U#} w h channels\n withBareImage img $ \\cimg ->\n {#call cvCvtColor#} (castPtr cimg) (castPtr res) (fromIntegral . fromEnum $ code)\n return res\n where\n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\nconvertTo :: CvtCodes -> CInt -> BareImage -> BareImage\nconvertTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage32F#} w h channels\n withBareImage img $ \\cimg ->\n {#call cvCvtColor#} (castPtr cimg) (castPtr res) (fromIntegral . fromEnum $ code)\n return res\n where\n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\n-- |\u00a0Class for images that exist.\nclass CreateImage a where\n -- | Create an image from size\n create :: (Int,Int) -> IO a\n\ncreateWith :: CreateImage (Image c d) => (Int,Int) -> (MutableImage c d -> IO (MutableImage c d)) -> IO (Image c d)\ncreateWith s f = do\n c <- create s\n Mutable r <- f (Mutable c)\n return r\n\n\n\n\ninstance CreateImage (Image GrayScale D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image Complex D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 2\ninstance CreateImage (Image LAB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image BGR D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 4\ninstance CreateImage (Image BGRA D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 4\ninstance CreateImage (Image BGRA D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image c d) => CreateImage (MutableImage c d) where\n create s = Mutable <$> create s\n\n\n-- | Allocate a new empty image\nempty :: (CreateImage (Image a b)) => (Int,Int) -> (Image a b)\nempty size = unsafePerformIO $ create size\n\n-- |\u00a0Allocate a new image that of the same size and type as the exemplar image given.\nemptyCopy :: (CreateImage (Image a b)) => Image a b -> (Image a b)\nemptyCopy img = unsafePerformIO $ create (getSize img)\n\nemptyCopy' :: (CreateImage (Image a b)) => Image a b -> IO (Image a b)\nemptyCopy' img = create (getSize img)\n\n-- | Save image. This will convert the image to 8 bit one before saving\nclass Save a where\n save :: FilePath -> a -> IO ()\n\ninstance Save (Image BGR D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image)\n\ninstance Save (Image RGB D32) where\n save filename image = primitiveSave filename (swapRB . unS . unsafeImageTo8Bit $ image)\n\ninstance Save (Image BGRA D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image)\n\ninstance Save (Image BGRA D8) where\n save filename image = primitiveSave filename (unS $ image)\n\ninstance Save (Image RGB D8) where\n save filename image = primitiveSave filename (swapRB . unS $ image)\n\ninstance Save (Image GrayScale D8) where\n save filename image = primitiveSave filename (unS $ image)\n\ninstance Save (Image GrayScale D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image)\n\nprimitiveSave :: FilePath -> BareImage -> IO ()\nprimitiveSave filename fpi = do\n exists <- doesDirectoryExist (takeDirectory filename)\n when (not exists) $\u00a0throw (CvIOError $ \"Directory does not exist: \" ++ (takeDirectory filename))\n withCString filename $ \\name ->\n withGenBareImage fpi $ \\cvArr ->\n alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\n-- |Save an image as 8 bit gray scale\nsaveImage :: (Save (Image c d)) => FilePath -> Image c d -> IO ()\nsaveImage = save\n\ngetArea :: (Sized a,Num b, Size a ~ (b,b)) => a -> b\ngetArea = uncurry (*).getSize\n\ngetRegion :: (Int,Int) -> (Int,Int) -> Image c d -> Image c d\ngetRegion (fromIntegral -> x,fromIntegral -> y) (fromIntegral -> w,fromIntegral -> h) image\n | x+w <= width && y+h <= height = S . getRegion' (x,y) (w,h) $ unS image\n | otherwise = error $ \"Region outside image:\"\n ++ show (getSize image) ++\n \"\/\"++show (x+w,y+h)\n where\n (fromIntegral -> width,fromIntegral -> height) = getSize image\n\ngetRegion' (x,y) (w,h) image = unsafePerformIO $\n withBareImage image $ \\i ->\n creatingBareImage ({#call getSubImage#}\n i x y w h)\n\n\n-- | Tile images by overlapping them on a black canvas.\ntileImages image1 image2 (x,y) = unsafePerformIO $\n withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n creatingImage ({#call simpleMergeImages#}\n i1 i2 x y)\n-- | Blit image2 onto image1.\nclass Blittable channels depth\ninstance Blittable GrayScale D32\ninstance Blittable RGB D32\n\nblit :: Blittable c d => MutableImage c d -> Image c d -> (Int,Int) -> IO ()\nblit image1 image2 (x,y) = do\n (w1,h1) <- getSize image1\n let ((w2,h2)) = getSize image2\n if x+w2>w1 || y+h2>h1 || x<0 || y<0\n then error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n else withMutableImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call plainBlit#} i1 i2 (fromIntegral y) (fromIntegral x))\n\n-- | Create an image by blitting multiple images onto an empty image.\nblitM :: (CreateImage (MutableImage GrayScale D32)) =>\n (Int,Int) -> [((Int,Int),Image GrayScale D32)] -> Image GrayScale D32\nblitM (rw,rh) imgs = unsafePerformIO $ resultPic >>= fromMutable\n where\n resultPic = do\n r <- create (fromIntegral rw,fromIntegral rh)\n sequence_ [blit r i (fromIntegral x, fromIntegral y)\n | ((x,y),i) <- imgs ]\n return r\n\n\nsubPixelBlit :: MutableImage c d -> Image c d -> (CDouble, CDouble) -> IO ()\nsubPixelBlit (image1) (image2) (x,y) = do\n (w1,h1) <- getSize image1\n let ((w2,h2)) = getSize image2\n if ceiling x+w2>w1 || ceiling y+h2>h1 ||\u00a0x<0 || y<0\n then error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n else withMutableImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call subpixel_blit#} i1 i2 y x)\n\nsafeBlit i1 i2 (x,y) = unsafePerformIO $ do\n res <- toMutable i1-- createImage32F (getSize i1) 1\n blit res i2 (x,y)\n return res\n\n-- | Blit image2 onto image1.\n-- This uses an alpha channel bitmap for determining the regions where the image should be \"blended\" with\n-- the base image.\nblendBlit :: MutableImage c d -> Image c1 d1 -> Image c3 d3 -> Image c2 d2\n -> (CInt, CInt) -> IO ()\nblendBlit image1 image1Alpha image2 image2Alpha (x,y) =\n withMutableImage image1 $ \\i1 ->\n withImage image1Alpha $ \\i1a ->\n withImage image2Alpha $ \\i2a ->\n withImage image2 $ \\i2 ->\n ({#call alphaBlit#} i1 i1a i2 i2a y x)\n\nblendBlit2Helper :: MutableImage c d -> Image c1 d1 -> (Int, Int) -> IO ()\nblendBlit2Helper image1 image2 (x,y) =\n withMutableImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call alphaBlit2#} i1 i2 (fromIntegral y) (fromIntegral x))\n\n-- Is probably safe as mutable state is encapsulated\nblendBlit2 img img2 pos = unsafePerformIO $ do\n result <- withMutableClone img $ \\mutImg -> do\n blendBlit2Helper mutImg img2 pos\n return mutImg\n fromMutable result\n\n\n-- | Create a copy of an image\ncloneImage :: Image a b -> IO (Image a b)\ncloneImage img = withGenImage img $ \\image ->\n creatingImage ({#call cvCloneImage #} image)\n\ntoMutable :: Image a b -> IO (MutableImage a b)\ntoMutable img = withGenImage img $ \\image ->\n Mutable <$>\u00a0creatingImage ({#call cvCloneImage #} image)\n\nfromMutable :: MutableImage a b -> IO (Image a b)\nfromMutable (Mutable img) = cloneImage img\n\n-- | Create a copy of a non-types image\ncloneBareImage :: BareImage -> IO BareImage\ncloneBareImage img = withGenBareImage img $ \\image ->\n creatingBareImage ({#call cvCloneImage #} image)\n\nwithMutableClone\n :: Image channels depth\n -> (MutableImage channels depth -> IO a)\n -> IO a\nwithMutableClone img fun = do\n result <- toMutable img\n fun result\n\nwithClone\n :: Image channels depth\n -> (Image channels depth -> IO ())\n -> IO (Image channels depth)\nwithClone img fun = do\n result <- cloneImage img\n fun result\n return result\n\nwithCloneValue\n :: Image channels depth\n -> (Image channels depth -> IO a)\n -> IO a\nwithCloneValue img fun = do\n result <- cloneImage img\n r <- fun result\n return r\n\ncloneTo64F :: Image c d -> IO (Image c D64)\ncloneTo64F img = withGenImage img $ \\image ->\n creatingImage\n ({#call ensure64F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 64 bit, floating point, image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image.\nunsafeImageTo64F :: Image c d -> Image c D64\nunsafeImageTo64F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure64F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 32 bit, floating point, image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image.\nunsafeImageTo32F :: Image c d -> Image c D32\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure32F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 8 bit image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image.\nunsafeImageTo8Bit :: Image cspace a -> Image cspace D8\nunsafeImageTo8Bit img =\n unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage ({#call ensure8U #} image)\n\n--toD32 :: Image c d -> Image c D32\n--toD32 i =\n-- unsafePerformIO $\n-- withImage i $ \\i_ptr ->\n-- creatingImage\n\n\nimageTo32F img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure32F #} image)\n\nimageTo8Bit img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure8U #} image)\n#c\nenum ImageDepth {\n Depth32F = IPL_DEPTH_32F,\n Depth64F = IPL_DEPTH_64F,\n Depth8U = IPL_DEPTH_8U,\n Depth8S = IPL_DEPTH_8S,\n Depth16U = IPL_DEPTH_16U,\n Depth16S = IPL_DEPTH_16S,\n Depth32S = IPL_DEPTH_32S\n };\n#endc\n\n{#enum ImageDepth {}#}\n\nderiving instance Show ImageDepth\n\ngetImageDepth :: Image c d -> IO ImageDepth\ngetImageDepth i = withImage i $ \\c_img -> {#get IplImage->depth #} c_img >>= return.toEnum.fromIntegral\ngetImageChannels i = withImage i $ \\c_img -> {#get IplImage->nChannels #} c_img\n\ngetImageInfo x = do\n let s = getSize x\n d <- getImageDepth x\n c <- getImageChannels x\n return (s,d,c)\n\n\n-- | Set the region of interest for a mutable image\nsetROI :: (Integral a) => (a,a) -> (a,a) -> MutableImage c d -> IO ()\nsetROI (fromIntegral -> x,fromIntegral -> y)\n (fromIntegral -> w,fromIntegral -> h)\n image = withMutableImage image $ \\i ->\n {#call wrapSetImageROI#} i x y w h\n\n-- | Set the region of interest to cover the entire image.\nresetROI :: MutableImage c d -> IO ()\nresetROI image = withMutableImage image $ \\i ->\n {#call cvResetImageROI#} i\n\nsetCOI :: (Enum a) => a -> MutableImage (ChannelOf a) d -> IO ()\nsetCOI chnl image = withMutableImage image $ \\i ->\n {#call cvSetImageCOI#} i (fromIntegral . (+1) . fromEnum $ chnl)\n -- CV numbers channels starting from 1. 0 means all channels\n\nresetCOI :: MutableImage a d -> IO ()\nresetCOI image = withMutableImage image $ \\i ->\n {#call cvSetImageCOI#} i 0\n\n\ngetChannel :: (Enum a) => a -> Image (ChannelOf a) d -> Image GrayScale d\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n mut <- toMutable image\n setCOI no mut\n cres <- {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\n withMutableImage mut $ \\cimage ->\n {#call cvCopy#} cimage (castPtr cres) (nullPtr)\n resetCOI mut\n return cres\n\nwithIOROI :: (Int,Int) -> (Int,Int) -> MutableImage c d -> IO a -> IO a\nwithIOROI pos size image op = do\n setROI pos size image\n x <- op\n resetROI image\n return x\n\n--withROI :: (Int, Int) -> (Int, Int) -> Image c d -> (MutableImage c d -> a) -> a\n--withROI pos size image op = unsafePerformIO $ do\n-- setROI pos size image\n-- let x = op image -- BUG\n-- resetROI image\n-- return x\n\nclass SetPixel a where\n type SP a :: *\n setPixel :: (Int,Int) -> SP a -> a -> IO ()\n\ninstance SetPixel (MutableImage GrayScale D32) where\n type SP (MutableImage GrayScale D32) = D32\n {-#INLINE setPixel#-}\n setPixel (x,y) v (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Float))):: Ptr Float)\n v\n\ninstance SetPixel (MutableImage GrayScale D8) where\n type SP (MutableImage GrayScale D8) = D8\n {-#INLINE setPixel#-}\n setPixel (x,y) v (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Word8))):: Ptr Word8)\n v\n\ninstance SetPixel (MutableImage RGB D8) where\n type SP (MutableImage RGB D8) = (D8,D8,D8)\n {-#INLINE setPixel#-}\n setPixel (x,y) (r,g,b) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n poke (castPtr (d`plusPtr` (y*cs +x*3*fs))) b\n poke (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs))) g\n poke (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs))) r\n\ninstance SetPixel (MutableImage RGB D32) where\n type SP (MutableImage RGB D32) = (D32,D32,D32)\n {-#INLINE setPixel#-}\n setPixel (x,y) (r,g,b) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs +x*3*fs))) b\n poke (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs))) g\n poke (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs))) r\n\ninstance SetPixel (MutableImage Complex D32) where\n type SP (MutableImage Complex D32) = C.Complex D32\n {-#INLINE setPixel#-}\n setPixel (x,y) (re C.:+ im) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs + x*2*fs))) re\n poke (castPtr (d`plusPtr` (y*cs + (x*2+1)*fs))) im\n\n\nunsafeSetPixel (x,y) (r,g,b, a) c_i = do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n poke (castPtr (d`plusPtr` (y*cs +x*4*fs))) b\n poke (castPtr (d`plusPtr` (y*cs +(x*4+1)*fs))) g\n poke (castPtr (d`plusPtr` (y*cs +(x*4+2)*fs))) r\n poke (castPtr (d`plusPtr` (y*cs +(x*4+3)*fs))) a\n\ngetAllPixels image = [getPixel (i,j) image\n | i <- [0..width-1 ]\n , j <- [0..height-1]]\n where\n (width,height) = getSize image\n\ngetAllPixelsRowMajor image = [getPixel (i,j) image\n | j <- [0..height-1]\n , i <- [0..width-1]\n ]\n where\n (width,height) = getSize image\n\n-- |Create a montage form given images (u,v) determines the layout and space the spacing\n-- between images. Images are assumed to be the same size (determined by the first image)\nmontage :: (Blittable c d) => (CreateImage (MutableImage c d)) => (Int,Int) -> Int -> [Image c d] -> Image c d\nmontage (u',v') space' imgs\n | u'*v' < (length imgs) = error (\"Montage mismatch: \"++show (u,v, length imgs))\n | otherwise = resultPic\n where\n space = fromIntegral space'\n (u,v) = (fromIntegral u', fromIntegral v')\n (rw,rh) = (u*xstep,v*ystep)\n (w,h) = foldl (\\(mx,my) (x,y) -> (max mx x, max my y)) (0,0) $ map getSize imgs\n (xstep,ystep) = (fromIntegral space + w,fromIntegral space + h)\n edge = space`div`2\n resultPic = unsafePerformIO $ do\n r <- create (rw,rh)\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep)\n | y <- [0..v-1] , x <- [0..u-1]\n | i <- imgs ]\n let (Mutable i) = r\n i `seq` return i\n\ndata CvException = CvException Int String String String Int\n deriving (Show, Typeable)\n\ndata CvIOError = CvIOError String deriving (Show,Typeable)\ndata CvSizeError = CvSizeError String deriving (Show,Typeable)\n\ninstance Exception CvException\ninstance Exception CvIOError\ninstance Exception CvSizeError\n\nsetCatch = do\n let catch i cstr1 cstr2 cstr3 j = do\n func <- peekCString cstr1\n msg <- peekCString cstr2\n file <- peekCString cstr3\n throw (CvException (fromIntegral i) func msg file (fromIntegral j))\n return 0\n cb <- mk'CvErrorCallback catch\n c'cvRedirectError cb nullPtr nullPtr\n c'cvSetErrMode c'CV_ErrModeSilent\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns,ParallelListComp, FlexibleInstances, FlexibleContexts, TypeFamilies, EmptyDataDecls, ScopedTypeVariables, StandaloneDeriving, DeriveDataTypeable, UndecidableInstances, MultiParamTypeClasses #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, MutableImage(..)\n, Mask\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\n, withMask\n, withMutableClone\n, withCloneValue\n, CreateImage\n, Save(..)\n\n-- * Colour spaces\n, ChannelOf\n, GrayScale\n, Complex\n, BGR\n, RGB\n, RGBA\n, BGRA\n, RGB_Channel(..)\n, LAB\n, LAB_Channel(..)\n, D32\n, D64\n, D8\n, Tag\n, lab\n, rgba\n, rgb\n, compose\n, composeMultichannelImage\n\n-- * IO operations\n, Loadable(..)\n, saveImage\n, loadColorImage\n, loadColorImage8\n, loadColorImage8'\n, loadColorAlphaImage\n, loadImage\n\n-- * Pixel level access\n, GetPixel(..)\n, SetPixel(..)\n, safeGetPixel\n, unsafeSetPixel\n, getAllPixels\n, getAllPixelsRowMajor\n, mapImageInplace\n-- * Image information\n, ImageDepth\n, Sized(..)\n, biggerThan\n, getArea\n, getChannel\n, getImageChannels\n, getImageDepth\n, getImageInfo\n\n-- * ROI's, COI's and subregions\n, setCOI\n, setROI\n, resetROI\n, getRegion\n, withIOROI\n--, withROI\n\n-- * Blitting\n, blendBlit\n, blendBlit2\n, blit\n, blitM\n, subPixelBlit\n, safeBlit\n, montage\n, tileImages\n\n-- * Conversions\n, convertTo\n, rgbToGray\n, rgbToGray8\n, grayToRGB\n, rgbToLab\n, bgrToRgb\n, rgbToBgr\n, bgrTobgra\n, cloneTo64F\n, unsafeImageTo32F\n, unsafeImageTo64F\n, unsafeImageTo8Bit\n\n-- * Low level access operations\n, BareImage(..)\n, creatingImage\n, unImage\n, unS\n, withGenBareImage\n, withBareImage\n, creatingBareImage\n, withGenImage\n, withImage\n, withMutableImage\n, withRawImageData\n, imageFPTR\n, ensure32F\n\n-- * Extended error handling\n, setCatch\n, CvException\n, CvSizeError(..)\n, CvIOError(..)\n) where\n\nimport System.Mem\nimport System.Directory\nimport System.FilePath\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Utils\nimport Foreign.ForeignPtr hiding (newForeignPtr,unsafeForeignPtrToPtr)\nimport Foreign.Concurrent\nimport Foreign.Ptr\nimport Control.Parallel.Strategies\nimport Control.DeepSeq\nimport Control.Lens\n\nimport CV.Bindings.Error\n\nimport Data.Maybe(catMaybes)\nimport Data.List(genericLength)\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)\nimport Foreign.Storable\nimport System.IO.Unsafe\nimport Data.Word\nimport qualified Data.Complex as C\nimport Control.Monad\nimport Control.Exception\nimport Data.Data\nimport Data.Typeable\n\nimport Utils.GeometryClass\nimport Control.Applicative hiding (empty)\n\n\n\n\n-- Colorspaces\n\n-- | Single channel grayscale image\ndata GrayScale\ndata Complex\ndata RGB\ndata RGB_Channel = Red |\u00a0Green |\u00a0Blue deriving (Eq,Ord,Enum)\n\ndata BGR\n\ndata LAB\ndata YUV\ndata RGBA\ndata BGRA\ndata LAB_Channel = LAB_L |\u00a0LAB_A |\u00a0LAB_B deriving (Eq,Ord,Enum)\ndata YUV_Channel = YUV_Y |\u00a0YUV_U |\u00a0YUV_V deriving (Eq,Ord,Enum)\n\n-- | Type family for expressing which channels a colorspace contains. This needs to be fixed wrt. the BGR color space.\ntype family ChannelOf a :: *\ntype instance ChannelOf RGB_Channel = RGB\ntype instance ChannelOf LAB_Channel = LAB\ntype instance ChannelOf YUV_Channel = YUV\n\n-- Bit Depths\ntype D8 = Word8\ntype D32 = Float\ntype D64 = Double\n\n-- | The type for Images\nnewtype Image channels depth = S BareImage\nnewtype MutableImage channels depth = Mutable (Image channels depth)\n\n-- | Alias for images used as masks\ntype Mask = Maybe (Image GrayScale D8)\n\n-- |\u00a0Remove typing info from an image\nunS (S i) = i -- Unsafe and ugly\n\nimageFPTR :: Image c d -> ForeignPtr BareImage\nimageFPTR (S (BareImage fptr)) = fptr\n\nwithImage :: Image c d -> (Ptr BareImage ->IO a) -> IO a\nwithImage (S i) op = withBareImage i op\n--withGenNewImage (S i) op = withGenImage i op\n\nwithRawImageData :: Image c d -> (Int -> Ptr Word8 -> IO a) -> IO a\nwithRawImageData (S i) op = withBareImage i $ \\pp-> do\n d <- {#get IplImage->imageData#} pp\n wd <- {#get IplImage->widthStep#} pp\n op (fromIntegral wd) (castPtr d)\n\n-- Ok. this is just the example why I need image types\nwithUniPtr with x fun = with x $ \\y ->\n fun (castPtr y)\n\nwithGenImage :: Image c d -> (Ptr b -> IO a) -> IO a\nwithGenImage = withUniPtr withImage\n\n-- |\u00a0This function converts masks to pointers. Masks which are nothing are converted\n-- to null pointers.\nwithMask :: Mask -> (Ptr b -> IO a) -> IO a\nwithMask (Just i) op = withUniPtr withImage i op\nwithMask Nothing op = op nullPtr\n\nwithMutableImage :: MutableImage c d -> (Ptr b -> IO a) -> IO a\nwithMutableImage (Mutable i) o = withGenImage i o\n\nwithGenBareImage :: BareImage -> (Ptr b -> IO a) -> IO a\nwithGenBareImage = withUniPtr withBareImage\n\n{#pointer *IplImage as BareImage foreign newtype#}\n\nfreeBareImage ptr = with ptr {#call cvReleaseImage#}\n\n--foreign import ccall \"& wrapReleaseImage\" releaseImage :: FinalizerPtr BareImage\n\ninstance NFData (Image a b) where\n rnf a@(S (BareImage fptr)) = (unsafeForeignPtrToPtr) fptr `seq` a `seq` ()-- This might also need peek?\n\n\ncreatingImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . S . BareImage $ fptr\n\ncreatingBareImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . BareImage $ fptr\n\ncreatingMaybeBareImage fun = do\n iptr <- fun\n if iptr == nullPtr\n then return Nothing\n else do\n -- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . Just . BareImage $ fptr\n\nunImage (S (BareImage fptr)) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\nrgba = undefined :: Tag RGBA\nlab = undefined :: Tag LAB\n\n-- | Typeclass for elements that are build from component elements. For example,\n-- RGB images can be constructed from three grayscale images.\nclass Composes a where\n type Source a :: *\n compose :: Source a -> a\n\ninstance (CreateImage (Image RGBA a)) => Composes (Image RGBA a) where\n type Source (Image RGBA a) = (Image GrayScale a, Image GrayScale a\n ,Image GrayScale a, Image GrayScale a)\n compose (r,g,b,a) = composeMultichannelImage (Just b) (Just g) (Just r) (Just a) rgba\n\ninstance (CreateImage (Image RGB a)) => Composes (Image RGB a) where\n type Source (Image RGB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (r,g,b) = composeMultichannelImage (Just b) (Just g) (Just r) Nothing rgb\n\ninstance (CreateImage (Image LAB a)) => Composes (Image LAB a) where\n type Source (Image LAB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (l,a,b) = composeMultichannelImage (Just l) (Just a) (Just b) Nothing lab\n\n{-# DEPRECATED composeMultichannelImage \"This is unsafe. Use compose instead\" #-}\ncomposeMultichannelImage :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannelImage = composeMultichannel\n\ncomposeMultichannel :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannel (c2)\n (c1)\n (c3)\n (c4)\n totag\n = unsafePerformIO $\u00a0do\n res <- create (size) -- TODO: Check channel count -- This is NOT correct\n withMaybe c1 $ \\cc1 ->\n withMaybe c2 $ \\cc2 ->\n withMaybe c3 $ \\cc3 ->\n withMaybe c4 $ \\cc4 ->\n withGenImage res $ \\cres -> {#call cvMerge#} cc1 cc2 cc3 cc4 cres\n return res\n where\n withMaybe (Just i) op = withGenImage i op\n withMaybe (Nothing) op = op nullPtr\n size = getSize . head . catMaybes $ [c1,c2,c3,c4]\n\n\n-- | Typeclass for CV items that can be read from file. Mainly images at this point.\nclass Loadable a where\n readFromFile :: FilePath -> IO a\n\n\ninstance Loadable ((Image GrayScale D32)) where\n readFromFile fp = do\n e <- loadImage fp\n case e of\n Just i -> return i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D32)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ unsafeImageTo32F $ bgrToRgb i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D8)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ bgrToRgb i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image GrayScale D8)) where\n readFromFile fp = do\n e <- loadImage8 fp\n case e of\n Just i -> return i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\n\n-- | This function loads and converts image to an arbitrary format. Notice that it is\n-- polymorphic enough to cause run time errors if the declared and actual types of the\n-- images do not match. Use with care.\nunsafeloadUsing x p n = do\n exists <- doesFileExist n\n if not exists then return Nothing\n else do\n mi <- withCString n $ \\name ->\n creatingMaybeBareImage ({#call cvLoadImage #} name p)\n case mi of\n Nothing -> return Nothing\n Just i -> do\n bw <- x i\n return . Just .\u00a0S $ bw\n\nloadImage :: FilePath -> IO (Maybe (Image GrayScale D32))\nloadImage = unsafeloadUsing imageTo32F 0\nloadImage8 :: FilePath -> IO (Maybe (Image GrayScale D8))\nloadImage8 = unsafeloadUsing imageTo8Bit 0\nloadColorImage :: FilePath -> IO (Maybe (Image BGR D32))\nloadColorImage = unsafeloadUsing imageTo32F 1\nloadColorImage8 :: FilePath -> IO (Maybe (Image BGR D8))\nloadColorImage8 = unsafeloadUsing imageTo8Bit 1\nloadColorImage8' :: FilePath -> IO (Maybe (Image BGRA D8))\nloadColorImage8' fp = fmap bgrTobgra <$> unsafeloadUsing imageTo8Bit 1 fp\n\nforeign import ccall safe \"CV\/Image.chs.h cvLoadImage\"\n cvLoadImageWithOpts :: ((Ptr CChar) -> (CInt -> (CInt -> (IO (Ptr (BareImage))))))\n\nloadColorAlphaImage :: FilePath -> IO (Maybe (Image BGRA D8))\nloadColorAlphaImage = unsafeloadUsing imageTo8Bit (-1)\n\ninstance Sized (MutableImage a b) where\n type Size (MutableImage a b) = IO (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize (Mutable i) = evaluate (deep (getSize i))\n where\n deep a = a `deepseq` a\n\ninstance Sized BareImage where\n type Size BareImage = (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize image = unsafePerformIO $ withBareImage image $ \\i -> do\n w <- {#call getImageWidth#} i\n h <- {#call getImageHeight#} i\n return (fromIntegral w,fromIntegral h)\n\ninstance Sized (Image c d) where\n type Size (Image c d) = (Int,Int)\n getSize = getSize . unS\n\n\n#c\nenum CvtFlags {\n CvtFlip = CV_CVTIMG_FLIP,\n CvtSwapRB = CV_CVTIMG_SWAP_RB\n };\n#endc\n\n#c\nenum CvtCodes {\n BGR2BGRA =0,\n RGB2RGBA =BGR2BGRA,\n\n BGRA2BGR =1,\n RGBA2RGB =BGRA2BGR,\n\n BGR2RGBA =2,\n RGB2BGRA =BGR2RGBA,\n\n RGBA2BGR =3,\n BGRA2RGB =RGBA2BGR,\n\n BGR2RGB =4,\n RGB2BGR =BGR2RGB,\n\n BGRA2RGBA =5,\n RGBA2BGRA =BGRA2RGBA,\n\n BGR2GRAY =6,\n RGB2GRAY =7,\n GRAY2BGR =8,\n GRAY2RGB =GRAY2BGR,\n GRAY2BGRA =9,\n GRAY2RGBA =GRAY2BGRA,\n BGRA2GRAY =10,\n RGBA2GRAY =11,\n\n BGR2BGR565 =12,\n RGB2BGR565 =13,\n BGR5652BGR =14,\n BGR5652RGB =15,\n BGRA2BGR565 =16,\n RGBA2BGR565 =17,\n BGR5652BGRA =18,\n BGR5652RGBA =19,\n\n GRAY2BGR565 =20,\n BGR5652GRAY =21,\n\n BGR2BGR555 =22,\n RGB2BGR555 =23,\n BGR5552BGR =24,\n BGR5552RGB =25,\n BGRA2BGR555 =26,\n RGBA2BGR555 =27,\n BGR5552BGRA =28,\n BGR5552RGBA =29,\n\n GRAY2BGR555 =30,\n BGR5552GRAY =31,\n\n BGR2XYZ =32,\n RGB2XYZ =33,\n XYZ2BGR =34,\n XYZ2RGB =35,\n\n BGR2YCrCb =36,\n RGB2YCrCb =37,\n YCrCb2BGR =38,\n YCrCb2RGB =39,\n\n BGR2HSV =40,\n RGB2HSV =41,\n\n BGR2Lab =44,\n RGB2Lab =45,\n\n BayerBG2BGR =46,\n BayerGB2BGR =47,\n BayerRG2BGR =48,\n BayerGR2BGR =49,\n\n BayerBG2RGB =BayerRG2BGR,\n BayerGB2RGB =BayerGR2BGR,\n BayerRG2RGB =BayerBG2BGR,\n BayerGR2RGB =BayerGB2BGR,\n\n BGR2Luv =50,\n RGB2Luv =51,\n BGR2HLS =52,\n RGB2HLS =53,\n\n HSV2BGR =54,\n HSV2RGB =55,\n\n Lab2BGR =56,\n Lab2RGB =57,\n Luv2BGR =58,\n Luv2RGB =59,\n HLS2BGR =60,\n HLS2RGB =61,\n\n BayerBG2BGR_VNG =62,\n BayerGB2BGR_VNG =63,\n BayerRG2BGR_VNG =64,\n BayerGR2BGR_VNG =65,\n\n BayerBG2RGB_VNG =BayerRG2BGR_VNG,\n BayerGB2RGB_VNG =BayerGR2BGR_VNG,\n BayerRG2RGB_VNG =BayerBG2BGR_VNG,\n BayerGR2RGB_VNG =BayerGB2BGR_VNG,\n\n BGR2HSV_FULL = 66,\n RGB2HSV_FULL = 67,\n BGR2HLS_FULL = 68,\n RGB2HLS_FULL = 69,\n\n HSV2BGR_FULL = 70,\n HSV2RGB_FULL = 71,\n HLS2BGR_FULL = 72,\n HLS2RGB_FULL = 73,\n\n LBGR2Lab = 74,\n LRGB2Lab = 75,\n LBGR2Luv = 76,\n LRGB2Luv = 77,\n\n Lab2LBGR = 78,\n Lab2LRGB = 79,\n Luv2LBGR = 80,\n Luv2LRGB = 81,\n\n BGR2YUV = 82,\n RGB2YUV = 83,\n YUV2BGR = 84,\n YUV2RGB = 85,\n\n COLORCVT_MAX =100\n};\n#endc\n\n{#enum CvtCodes {}#}\n\n{#enum CvtFlags {}#}\n\nrgbToLab :: Image RGB D32 -> Image LAB D32\nrgbToLab = S . convertTo RGB2Lab 3 . unS\n\nrgbToYUV :: Image RGB D32 -> Image YUV D32\nrgbToYUV = S . convertTo RGB2YUV 3 . unS\n\nrgbToGray :: Image RGB D32 -> Image GrayScale D32\nrgbToGray = S . convertTo RGB2GRAY 1 . unS\n\nrgbToGray8 :: Image RGB D8 -> Image GrayScale D8\nrgbToGray8 = S . convert8UTo RGB2GRAY 1 . unS\n\ngrayToRGB :: Image GrayScale D32 -> Image RGB D32\ngrayToRGB = S . convertTo GRAY2BGR 3 . unS\n\nbgrTobgra = S . convert8UTo BGR2BGRA 4 . unS\n\nbgrToRgb :: Image BGR D8 -> Image RGB D8\nbgrToRgb = S . swapRB . unS\n\nrgbToBgr :: Image RGB D8 -> Image BGR D8\nrgbToBgr = S . swapRB . unS\n\nswapRB :: BareImage -> BareImage\nswapRB img = unsafePerformIO $ do\n res <- cloneBareImage img\n withBareImage img $ \\cimg ->\n withBareImage res $ \\cres ->\n {#call cvConvertImage#} (castPtr cimg) (castPtr cres) (fromIntegral . fromEnum $ CvtSwapRB)\n return res\n\n\nsafeGetPixel :: (Sized image, Size image ~ (Int,Int), GetPixel image) => (P image) -> (Int,Int) -> image -> P image\nsafeGetPixel def (x,y) i |\u00a0x<0 || x>= w || y<0 || y>=h = def\n | otherwise = getPixel (x,y) i\n where\n (w,h) = getSize i\n -- (x',y') = (clamp (0,w-1) x, clamp (0,h-1) y)\n\nclamp :: Ord a => (a, a) -> a -> a\nclamp (a,b) x = max a (min b x)\n\ninstance (NFData (P (Image a b)), GetPixel (Image a b)) => GetPixel (MutableImage a b) where\n type P (MutableImage a b) = IO (P (Image a b))\n getPixel xy (Mutable i) = let p = getPixel xy i\n in p `deepseq` return p\n\nclass GetPixel a where\n type P a :: *\n getPixel :: (Int,Int) -> a -> P a\n\n-- #define FGET(img,x,y) (((float *)((img)->imageData + (y)*(img)->widthStep))[(x)])\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Float))):: Ptr Float)\n\ninstance GetPixel (Image GrayScale D8) where\n type P (Image GrayScale D8) = D8\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Word8))):: Ptr Word8)\n\ninstance GetPixel (Image Complex D32) where\n type P (Image Complex D32) = C.Complex D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n re <- peek (castPtr (d`plusPtr` (y*cs + x*2*fs)))\n im <- peek (castPtr (d`plusPtr` (y*cs +(x*2+1)*fs)))\n return (re C.:+ im)\n\n-- #define UGETC(img,color,x,y) (((uint8_t *)((img)->imageData + (y)*(img)->widthStep))[(x)*3+(color)])\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\ninstance GetPixel (Image BGR D32) where\n type P (Image BGR D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\ninstance GetPixel (Image BGR D8) where\n type P (Image BGR D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image RGB D8) where\n type P (Image RGB D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image LAB D32) where\n type P (Image LAB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n l <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n a <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n b <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (l,a,b)\n\n-- | Perform (a destructive) inplace map of the image. This should be wrapped inside\n-- withClone or an image operation\nmapImageInplace :: (P (Image GrayScale D32) -> P (Image GrayScale D32))\n -> MutableImage GrayScale D32\n -> IO ()\nmapImageInplace f image = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n (w,h) <- getSize image\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n forM_ [(x,y) | x<-[0..w-1], y <- [0..h-1]] $ \\(x,y) ->\u00a0do\n v <- peek (castPtr (d `plusPtr` (y*cs+x*fs)))\n poke (castPtr (d `plusPtr` (y*cs+x*fs))) (f v)\n\n\n\nconvert8UTo :: CvtCodes -> CInt -> BareImage -> BareImage\nconvert8UTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage8U#} w h channels\n withBareImage img $ \\cimg ->\n {#call cvCvtColor#} (castPtr cimg) (castPtr res) (fromIntegral . fromEnum $ code)\n return res\n where\n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\nconvertTo :: CvtCodes -> CInt -> BareImage -> BareImage\nconvertTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage32F#} w h channels\n withBareImage img $ \\cimg ->\n {#call cvCvtColor#} (castPtr cimg) (castPtr res) (fromIntegral . fromEnum $ code)\n return res\n where\n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\n-- |\u00a0Class for images that exist.\nclass CreateImage a where\n -- | Create an image from size\n create :: (Int,Int) -> IO a\n\ncreateWith :: CreateImage (Image c d) => (Int,Int) -> (MutableImage c d -> IO (MutableImage c d)) -> IO (Image c d)\ncreateWith s f = do\n c <- create s\n Mutable r <- f (Mutable c)\n return r\n\n\n\n\ninstance CreateImage (Image GrayScale D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image Complex D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 2\ninstance CreateImage (Image LAB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image BGR D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 4\ninstance CreateImage (Image BGRA D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 4\ninstance CreateImage (Image BGRA D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image c d) => CreateImage (MutableImage c d) where\n create s = Mutable <$> create s\n\n\n-- | Allocate a new empty image\nempty :: (CreateImage (Image a b)) => (Int,Int) -> (Image a b)\nempty size = unsafePerformIO $ create size\n\n-- |\u00a0Allocate a new image that of the same size and type as the exemplar image given.\nemptyCopy :: (CreateImage (Image a b)) => Image a b -> (Image a b)\nemptyCopy img = unsafePerformIO $ create (getSize img)\n\nemptyCopy' :: (CreateImage (Image a b)) => Image a b -> IO (Image a b)\nemptyCopy' img = create (getSize img)\n\n-- | Save image. This will convert the image to 8 bit one before saving\nclass Save a where\n save :: FilePath -> a -> IO ()\n\ninstance Save (Image BGR D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image)\n\ninstance Save (Image RGB D32) where\n save filename image = primitiveSave filename (swapRB . unS . unsafeImageTo8Bit $ image)\n\ninstance Save (Image BGRA D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image)\n\ninstance Save (Image BGRA D8) where\n save filename image = primitiveSave filename (unS $ image)\n\ninstance Save (Image RGB D8) where\n save filename image = primitiveSave filename (swapRB . unS $ image)\n\ninstance Save (Image GrayScale D8) where\n save filename image = primitiveSave filename (unS $ image)\n\ninstance Save (Image GrayScale D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image)\n\nprimitiveSave :: FilePath -> BareImage -> IO ()\nprimitiveSave filename fpi = do\n exists <- doesDirectoryExist (takeDirectory filename)\n when (not exists) $\u00a0throw (CvIOError $ \"Directory does not exist: \" ++ (takeDirectory filename))\n withCString filename $ \\name ->\n withGenBareImage fpi $ \\cvArr ->\n alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\n-- |Save an image as 8 bit gray scale\nsaveImage :: (Save (Image c d)) => FilePath -> Image c d -> IO ()\nsaveImage = save\n\ngetArea :: (Sized a,Num b, Size a ~ (b,b)) => a -> b\ngetArea = uncurry (*).getSize\n\ngetRegion :: (Int,Int) -> (Int,Int) -> Image c d -> Image c d\ngetRegion (fromIntegral -> x,fromIntegral -> y) (fromIntegral -> w,fromIntegral -> h) image\n | x+w <= width && y+h <= height = S . getRegion' (x,y) (w,h) $ unS image\n | otherwise = error $ \"Region outside image:\"\n ++ show (getSize image) ++\n \"\/\"++show (x+w,y+h)\n where\n (fromIntegral -> width,fromIntegral -> height) = getSize image\n\ngetRegion' (x,y) (w,h) image = unsafePerformIO $\n withBareImage image $ \\i ->\n creatingBareImage ({#call getSubImage#}\n i x y w h)\n\n\n-- | Tile images by overlapping them on a black canvas.\ntileImages image1 image2 (x,y) = unsafePerformIO $\n withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n creatingImage ({#call simpleMergeImages#}\n i1 i2 x y)\n-- | Blit image2 onto image1.\nclass Blittable channels depth\ninstance Blittable GrayScale D32\ninstance Blittable RGB D32\n\nblit :: Blittable c d => MutableImage c d -> Image c d -> (Int,Int) -> IO ()\nblit image1 image2 (x,y) = do\n (w1,h1) <- getSize image1\n let ((w2,h2)) = getSize image2\n if x+w2>w1 || y+h2>h1 || x<0 || y<0\n then error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n else withMutableImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call plainBlit#} i1 i2 (fromIntegral y) (fromIntegral x))\n\n-- | Create an image by blitting multiple images onto an empty image.\nblitM :: (CreateImage (MutableImage GrayScale D32)) =>\n (Int,Int) -> [((Int,Int),Image GrayScale D32)] -> Image GrayScale D32\nblitM (rw,rh) imgs = unsafePerformIO $ resultPic >>= fromMutable\n where\n resultPic = do\n r <- create (fromIntegral rw,fromIntegral rh)\n sequence_ [blit r i (fromIntegral x, fromIntegral y)\n | ((x,y),i) <- imgs ]\n return r\n\n\nsubPixelBlit :: MutableImage c d -> Image c d -> (CDouble, CDouble) -> IO ()\nsubPixelBlit (image1) (image2) (x,y) = do\n (w1,h1) <- getSize image1\n let ((w2,h2)) = getSize image2\n if ceiling x+w2>w1 || ceiling y+h2>h1 ||\u00a0x<0 || y<0\n then error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n else withMutableImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call subpixel_blit#} i1 i2 y x)\n\nsafeBlit i1 i2 (x,y) = unsafePerformIO $ do\n res <- toMutable i1-- createImage32F (getSize i1) 1\n blit res i2 (x,y)\n return res\n\n-- | Blit image2 onto image1.\n-- This uses an alpha channel bitmap for determining the regions where the image should be \"blended\" with\n-- the base image.\nblendBlit :: MutableImage c d -> Image c1 d1 -> Image c3 d3 -> Image c2 d2\n -> (CInt, CInt) -> IO ()\nblendBlit image1 image1Alpha image2 image2Alpha (x,y) =\n withMutableImage image1 $ \\i1 ->\n withImage image1Alpha $ \\i1a ->\n withImage image2Alpha $ \\i2a ->\n withImage image2 $ \\i2 ->\n ({#call alphaBlit#} i1 i1a i2 i2a y x)\n\nblendBlit2Helper :: MutableImage c d -> Image c1 d1 -> (Int, Int) -> IO ()\nblendBlit2Helper image1 image2 (x,y) =\n withMutableImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call alphaBlit2#} i1 i2 (fromIntegral y) (fromIntegral x))\n\n-- Is probably safe as mutable state is encapsulated\nblendBlit2 img img2 pos = unsafePerformIO $ do\n result <- withMutableClone img $ \\mutImg -> do\n blendBlit2Helper mutImg img2 pos\n return mutImg\n fromMutable result\n\n\n-- | Create a copy of an image\ncloneImage :: Image a b -> IO (Image a b)\ncloneImage img = withGenImage img $ \\image ->\n creatingImage ({#call cvCloneImage #} image)\n\ntoMutable :: Image a b -> IO (MutableImage a b)\ntoMutable img = withGenImage img $ \\image ->\n Mutable <$>\u00a0creatingImage ({#call cvCloneImage #} image)\n\nfromMutable :: MutableImage a b -> IO (Image a b)\nfromMutable (Mutable img) = cloneImage img\n\n-- | Create a copy of a non-types image\ncloneBareImage :: BareImage -> IO BareImage\ncloneBareImage img = withGenBareImage img $ \\image ->\n creatingBareImage ({#call cvCloneImage #} image)\n\nwithMutableClone\n :: Image channels depth\n -> (MutableImage channels depth -> IO a)\n -> IO a\nwithMutableClone img fun = do\n result <- toMutable img\n fun result\n\nwithClone\n :: Image channels depth\n -> (Image channels depth -> IO ())\n -> IO (Image channels depth)\nwithClone img fun = do\n result <- cloneImage img\n fun result\n return result\n\nwithCloneValue\n :: Image channels depth\n -> (Image channels depth -> IO a)\n -> IO a\nwithCloneValue img fun = do\n result <- cloneImage img\n r <- fun result\n return r\n\ncloneTo64F :: Image c d -> IO (Image c D64)\ncloneTo64F img = withGenImage img $ \\image ->\n creatingImage\n ({#call ensure64F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 64 bit, floating point, image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image.\nunsafeImageTo64F :: Image c d -> Image c D64\nunsafeImageTo64F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure64F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 32 bit, floating point, image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image.\nunsafeImageTo32F :: Image c d -> Image c D32\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure32F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 8 bit image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image.\nunsafeImageTo8Bit :: Image cspace a -> Image cspace D8\nunsafeImageTo8Bit img =\n unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage ({#call ensure8U #} image)\n\n--toD32 :: Image c d -> Image c D32\n--toD32 i =\n-- unsafePerformIO $\n-- withImage i $ \\i_ptr ->\n-- creatingImage\n\n\nimageTo32F img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure32F #} image)\n\nimageTo8Bit img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure8U #} image)\n#c\nenum ImageDepth {\n Depth32F = IPL_DEPTH_32F,\n Depth64F = IPL_DEPTH_64F,\n Depth8U = IPL_DEPTH_8U,\n Depth8S = IPL_DEPTH_8S,\n Depth16U = IPL_DEPTH_16U,\n Depth16S = IPL_DEPTH_16S,\n Depth32S = IPL_DEPTH_32S\n };\n#endc\n\n{#enum ImageDepth {}#}\n\nderiving instance Show ImageDepth\n\ngetImageDepth :: Image c d -> IO ImageDepth\ngetImageDepth i = withImage i $ \\c_img -> {#get IplImage->depth #} c_img >>= return.toEnum.fromIntegral\ngetImageChannels i = withImage i $ \\c_img -> {#get IplImage->nChannels #} c_img\n\ngetImageInfo x = do\n let s = getSize x\n d <- getImageDepth x\n c <- getImageChannels x\n return (s,d,c)\n\n\n-- | Set the region of interest for a mutable image\nsetROI :: (Integral a) => (a,a) -> (a,a) -> MutableImage c d -> IO ()\nsetROI (fromIntegral -> x,fromIntegral -> y)\n (fromIntegral -> w,fromIntegral -> h)\n image = withMutableImage image $ \\i ->\n {#call wrapSetImageROI#} i x y w h\n\n-- | Set the region of interest to cover the entire image.\nresetROI :: MutableImage c d -> IO ()\nresetROI image = withMutableImage image $ \\i ->\n {#call cvResetImageROI#} i\n\nsetCOI :: (Enum a) => a -> MutableImage (ChannelOf a) d -> IO ()\nsetCOI chnl image = withMutableImage image $ \\i ->\n {#call cvSetImageCOI#} i (fromIntegral . (+1) . fromEnum $ chnl)\n -- CV numbers channels starting from 1. 0 means all channels\n\nresetCOI :: MutableImage a d -> IO ()\nresetCOI image = withMutableImage image $ \\i ->\n {#call cvSetImageCOI#} i 0\n\n\ngetChannel :: (Enum a) => a -> Image (ChannelOf a) d -> Image GrayScale d\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n mut <- toMutable image\n setCOI no mut\n cres <- {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\n withMutableImage mut $ \\cimage ->\n {#call cvCopy#} cimage (castPtr cres) (nullPtr)\n resetCOI mut\n return cres\n\nwithIOROI :: (Int,Int) -> (Int,Int) -> MutableImage c d -> IO a -> IO a\nwithIOROI pos size image op = do\n setROI pos size image\n x <- op\n resetROI image\n return x\n\n--withROI :: (Int, Int) -> (Int, Int) -> Image c d -> (MutableImage c d -> a) -> a\n--withROI pos size image op = unsafePerformIO $ do\n-- setROI pos size image\n-- let x = op image -- BUG\n-- resetROI image\n-- return x\n\nclass SetPixel a where\n type SP a :: *\n setPixel :: (Int,Int) -> SP a -> a -> IO ()\n\ninstance SetPixel (MutableImage GrayScale D32) where\n type SP (MutableImage GrayScale D32) = D32\n {-#INLINE setPixel#-}\n setPixel (x,y) v (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Float))):: Ptr Float)\n v\n\ninstance SetPixel (MutableImage GrayScale D8) where\n type SP (MutableImage GrayScale D8) = D8\n {-#INLINE setPixel#-}\n setPixel (x,y) v (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Word8))):: Ptr Word8)\n v\n\ninstance SetPixel (MutableImage RGB D8) where\n type SP (MutableImage RGB D8) = (D8,D8,D8)\n {-#INLINE setPixel#-}\n setPixel (x,y) (r,g,b) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n poke (castPtr (d`plusPtr` (y*cs +x*3*fs))) b\n poke (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs))) g\n poke (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs))) r\n\ninstance SetPixel (MutableImage RGB D32) where\n type SP (MutableImage RGB D32) = (D32,D32,D32)\n {-#INLINE setPixel#-}\n setPixel (x,y) (r,g,b) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs +x*3*fs))) b\n poke (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs))) g\n poke (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs))) r\n\ninstance SetPixel (MutableImage Complex D32) where\n type SP (MutableImage Complex D32) = C.Complex D32\n {-#INLINE setPixel#-}\n setPixel (x,y) (re C.:+ im) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs + x*2*fs))) re\n poke (castPtr (d`plusPtr` (y*cs + (x*2+1)*fs))) im\n\n\nunsafeSetPixel (x,y) (r,g,b, a) c_i = do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n poke (castPtr (d`plusPtr` (y*cs +x*4*fs))) b\n poke (castPtr (d`plusPtr` (y*cs +(x*4+1)*fs))) g\n poke (castPtr (d`plusPtr` (y*cs +(x*4+2)*fs))) r\n poke (castPtr (d`plusPtr` (y*cs +(x*4+3)*fs))) a\n\ngetAllPixels image = [getPixel (i,j) image\n | i <- [0..width-1 ]\n , j <- [0..height-1]]\n where\n (width,height) = getSize image\n\ngetAllPixelsRowMajor image = [getPixel (i,j) image\n | j <- [0..height-1]\n , i <- [0..width-1]\n ]\n where\n (width,height) = getSize image\n\n-- |Create a montage form given images (u,v) determines the layout and space the spacing\n-- between images. Images are assumed to be the same size (determined by the first image)\nmontage :: (Blittable c d) => (CreateImage (MutableImage c d)) => (Int,Int) -> Int -> [Image c d] -> Image c d\nmontage (u',v') space' imgs\n | u'*v' < (length imgs) = error (\"Montage mismatch: \"++show (u,v, length imgs))\n | otherwise = resultPic\n where\n space = fromIntegral space'\n (u,v) = (fromIntegral u', fromIntegral v')\n (rw,rh) = (u*xstep,v*ystep)\n (w,h) = foldl (\\(mx,my) (x,y) -> (max mx x, max my y)) (0,0) $ map getSize imgs\n (xstep,ystep) = (fromIntegral space + w,fromIntegral space + h)\n edge = space`div`2\n resultPic = unsafePerformIO $ do\n r <- create (rw,rh)\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep)\n | y <- [0..v-1] , x <- [0..u-1]\n | i <- imgs ]\n let (Mutable i) = r\n i `seq` return i\n\ndata CvException = CvException Int String String String Int\n deriving (Show, Typeable)\n\ndata CvIOError = CvIOError String deriving (Show,Typeable)\ndata CvSizeError = CvSizeError String deriving (Show,Typeable)\n\ninstance Exception CvException\ninstance Exception CvIOError\ninstance Exception CvSizeError\n\nsetCatch = do\n let catch i cstr1 cstr2 cstr3 j = do\n func <- peekCString cstr1\n msg <- peekCString cstr2\n file <- peekCString cstr3\n throw (CvException (fromIntegral i) func msg file (fromIntegral j))\n return 0\n cb <- mk'CvErrorCallback catch\n c'cvRedirectError cb nullPtr nullPtr\n c'cvSetErrMode c'CV_ErrModeSilent\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"2272b8e6fecd1731abec40afeecc88e73b1149e9","subject":"part 4: utilities","message":"part 4: utilities\n\nIgnore-this: fe0fc906d902b784739bf00f86f2c93a\n\ndarcs-hash:20091219115308-dcabc-d9a3a353a0b86a16205b9ea3c24809a1cc590cfb.gz\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Runtime\/Utils.chs","new_file":"Foreign\/CUDA\/Runtime\/Utils.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Utils\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Utility functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Utils\n (\n runtimeVersion, driverVersion\n )\n where\n\n#include \n{# context lib=\"cudart\" #}\n\n-- Friends\nimport Foreign.CUDA.Runtime.Error\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\n\n\n-- |\n-- Return the version number of the installed CUDA driver\n--\nruntimeVersion :: IO Int\nruntimeVersion = resultIfOk =<< cudaRuntimeGetVersion\n\n{# fun unsafe cudaRuntimeGetVersion\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the version number of the installed CUDA runtime\n--\ndriverVersion :: IO Int\ndriverVersion = resultIfOk =<< cudaDriverGetVersion\n\n{# fun unsafe cudaDriverGetVersion\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Utils\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Utility functions\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Utils\n (\n forceEither,\n runtimeVersion,\n driverVersion\n )\n where\n\nimport Foreign\nimport Foreign.C\n\nimport Foreign.CUDA.Runtime.Error\nimport Foreign.CUDA.Internal.C2HS\n\n#include \n{# context lib=\"cudart\" #}\n\n\n-- |\n-- Unwrap an Either construct, throwing an error for non-right values\n--\nforceEither :: Either String a -> a\nforceEither (Left s) = error s\nforceEither (Right r) = r\n\n\n-- |\n-- Return the version number of the installed CUDA driver\n--\nruntimeVersion :: IO (Either String Int)\nruntimeVersion = resultIfOk `fmap` cudaRuntimeGetVersion\n\n{# fun unsafe cudaRuntimeGetVersion\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n\n-- |\n-- Return the version number of the installed CUDA runtime\n--\ndriverVersion :: IO (Either String Int)\ndriverVersion = resultIfOk `fmap` cudaDriverGetVersion\n\n{# fun unsafe cudaDriverGetVersion\n { alloca- `Int' peekIntConv* } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"e86f2a4ffef5caf3387a49e291041ac0d6495428","subject":"gstreamer: M.S.G.Core.Bus documentation cleanup","message":"gstreamer: M.S.G.Core.Bus documentation cleanup\n","repos":"gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/vte","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Bus.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Bus.chs","new_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gstreamer -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GStreamer, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GStreamer documentation.\n-- \n-- |\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\n-- \n-- An asynchronous message bus subsystem.\nmodule Media.Streaming.GStreamer.Core.Bus (\n-- * Detail\n -- | The 'Bus' is resposible for delivering 'Message's in a\n -- first-in, first-out order, from the streaming threads to the\n -- application.\n -- \n -- Since the application typically only wants to deal with\n -- delivery of these messages from one thread, the 'Bus' will\n -- marshal the messages between different threads. This is\n -- important since the actual streaming of media is done in\n -- a thread separate from the application.\n --\n -- The 'Bus' provides support for 'System.Glib.MainLoop.Source'\n -- based notifications. This makes it possible to handle the\n -- delivery in the GLib 'System.Glib.MainLoop.Source'.\n --\n -- A message is posted on the bus with the 'busPost' method. With\n -- the 'busPeek' and 'busPop' methods one can look at or retrieve\n -- a previously posted message.\n --\n -- The bus can be polled with the 'busPoll' method. This methods\n -- blocks up to the specified timeout value until one of the\n -- specified messages types is posted on the bus. The application\n -- can then pop the messages from the bus to handle\n -- them. Alternatively the application can register an\n -- asynchronous bus function using 'busAddWatch'. This function\n -- will install a 'System.Glib.MainLoop.Source' in the default\n -- GLib main loop and will deliver messages a short while after\n -- they have been posted. Note that the main loop should be\n -- running for the asynchronous callbacks.\n --\n -- It is also possible to get messages from the bus without any\n -- thread marshalling with the 'busSetSyncHandler' method. This\n -- makes it possible to react to a message in the same thread that\n -- posted the message on the bus. This should only be used if the\n -- application is able to deal with messages from different\n -- threads.\n -- \n -- Every 'Pipeline' has one bus.\n --\n -- Note that a 'Pipeline' will set its bus into flushing state\n -- when changing from 'StateReady' to 'StateNull'.\n\n-- * Types\n Bus,\n -- | The result of a 'BusSyncHandler'.\n BusSyncReply,\n -- | A handler that will be invoked synchronously when a new message\n -- is injected into the bus. This function is mostly used internally.\n -- Only one sync handler may be attached to a given bus.\n BusSyncHandler,\n BusClass,\n castToBus,\n toBus,\n-- * Bus Operations\n busGetFlags,\n busSetFlags,\n busUnsetFlags,\n busNew,\n busPost,\n busHavePending,\n busPeek,\n busPop,\n busTimedPop,\n busSetFlushing,\n busSetSyncHandler,\n busUseSyncSignalHandler,\n busCreateWatch,\n busAddWatch,\n busDisableSyncMessageEmission,\n busEnableSyncMessageEmission,\n busAddSignalWatch,\n busRemoveSignalWatch,\n busPoll,\n \n-- * Bus Signals\n onBusMessage,\n afterBusMessage,\n onBusSyncMessage,\n afterBusSyncMessage\n \n ) where\n\nimport Control.Monad ( liftM\n , when )\n{#import Media.Streaming.GStreamer.Core.Object#}\n{#import Media.Streaming.GStreamer.Core.Types#}\n{#import Media.Streaming.GStreamer.Core.Signals#}\n{#import System.Glib.MainLoop#}\nimport System.Glib.Flags\nimport System.Glib.FFI\n{#import System.Glib.GObject#}\n{#import System.Glib.MainLoop#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\n-- | Get the flags set on this bus.\nbusGetFlags :: BusClass busT\n => busT\n -> IO [BusFlags]\nbusGetFlags = mkObjectGetFlags\n\n-- | Set flags on this bus.\nbusSetFlags :: BusClass busT\n => busT\n -> [BusFlags]\n -> IO ()\nbusSetFlags = mkObjectSetFlags\n\n-- | Unset flags on this bus.\nbusUnsetFlags :: BusClass busT\n => busT\n -> [BusFlags]\n -> IO ()\nbusUnsetFlags = mkObjectUnsetFlags\n\n-- | Create a new bus.\nbusNew :: IO Bus\nbusNew =\n {# call bus_new #} >>= takeObject\n\n-- | Post a message to the bus.\nbusPost :: BusClass busT\n => busT\n -> Message\n -> IO Bool\nbusPost bus message =\n do {# call gst_mini_object_ref #} (toMiniObject message)\n liftM toBool $ {# call bus_post #} (toBus bus) message\n\n-- | Check if there are pending messages on the bus.\nbusHavePending :: BusClass busT\n => busT\n -> IO Bool\nbusHavePending bus =\n liftM toBool $ {# call bus_have_pending #} $ toBus bus\n\n-- | Get the message at the front of the queue. It will remain on the\n-- queue.\nbusPeek :: BusClass busT\n => busT\n -> IO (Maybe Message)\nbusPeek bus =\n {# call bus_peek #} (toBus bus) >>= maybePeek takeMiniObject\n\n-- | Get the message at the front of the queue. It will be removed\n-- from the queue.\nbusPop :: BusClass busT\n => busT\n -> IO (Maybe Message)\nbusPop bus =\n {# call bus_pop #} (toBus bus) >>= maybePeek takeMiniObject\n\n-- | Get a message from the bus, waiting up to the specified timeout.\n-- If the time given is 'Nothing', the function will wait forever.\n-- If the time given is @0@, the function will behave like 'busPop'.\nbusTimedPop :: BusClass busT\n => busT\n -> Maybe ClockTime\n -> IO (Maybe Message)\nbusTimedPop bus timeoutM =\n let timeout = case timeoutM of\n Just timeout' -> timeout'\n Nothing -> clockTimeNone\n in {# call bus_timed_pop #} (toBus bus) (fromIntegral timeout) >>=\n maybePeek takeMiniObject\n\n-- | If @flushing@ is 'True', the bus will flush out any queued\n-- messages, as well as any future messages, until the function is\n-- called with @flushing@ set to 'False'.\nbusSetFlushing :: BusClass busT\n => busT\n -> Bool\n -> IO ()\nbusSetFlushing bus flushing =\n {# call bus_set_flushing #} (toBus bus) $ fromBool flushing\n\n-- these will leak memory, maybe one day we can set a destroy notifier...\n\ntype CBusSyncHandler = Ptr Bus\n -> Ptr Message\n -> {# type gpointer #}\n -> IO {# type GstBusSyncReply #}\nmarshalBusSyncHandler :: BusSyncHandler\n -> IO {# type GstBusSyncHandler #}\nmarshalBusSyncHandler busSyncHandler =\n makeBusSyncHandler cBusSyncHandler\n where cBusSyncHandler :: CBusSyncHandler\n cBusSyncHandler busPtr messagePtr _ =\n do bus <- peekObject busPtr\n message <- peekMiniObject messagePtr\n reply <- busSyncHandler bus message\n when (reply == BusDrop) $\n {# call gst_mini_object_unref #} (toMiniObject message)\n return $ fromIntegral $ fromEnum reply\nforeign import ccall \"wrapper\"\n makeBusSyncHandler :: CBusSyncHandler\n -> IO {# type GstBusSyncHandler #}\n\n-- the following mess is necessary to clean up safely after busSetSyncHandler.\n-- gstreamer doesn't give us a nice way to do this (such as a DestroyNotify)\nweakNotifyQuark, funPtrQuark :: Quark\nweakNotifyQuark = unsafePerformIO $ quarkFromString \"Gtk2HS::SyncHandlerWeakNotify\"\nfunPtrQuark = unsafePerformIO $ quarkFromString \"Gtk2HS::SyncHandlerFunPtr\"\n\ngetWeakNotify :: BusClass busT\n => busT\n -> IO (Maybe GWeakNotify)\ngetWeakNotify = objectGetAttributeUnsafe weakNotifyQuark\n\nsetWeakNotify :: BusClass busT\n => busT\n -> Maybe GWeakNotify\n -> IO ()\nsetWeakNotify = objectSetAttribute weakNotifyQuark\n\ngetFunPtr :: BusClass busT\n => busT\n -> IO (Maybe {# type GstBusSyncHandler #})\ngetFunPtr = objectGetAttributeUnsafe funPtrQuark\n\nsetFunPtr :: BusClass busT\n => busT\n -> Maybe {# type GstBusSyncHandler #}\n -> IO ()\nsetFunPtr = objectSetAttribute funPtrQuark\n\nunsetSyncHandler :: BusClass busT\n => busT\n -> IO ()\nunsetSyncHandler bus = do\n {# call bus_set_sync_handler #} (toBus bus) nullFunPtr nullPtr\n oldWeakNotifyM <- getWeakNotify bus\n case oldWeakNotifyM of\n Just oldWeakNotify -> objectWeakunref bus oldWeakNotify\n Nothing -> return ()\n setWeakNotify bus Nothing\n oldFunPtrM <- getFunPtr bus\n case oldFunPtrM of\n Just oldFunPtr -> freeHaskellFunPtr oldFunPtr\n Nothing -> return ()\n setFunPtr bus Nothing\n\n-- | Set the synchronous message handler on the bus. The function will\n-- be called every time a new message is posted to the bus. Note\n-- that the function will be called from the thread context of the\n-- poster.\n-- \n-- Calling this function will replace any previously set sync\n-- handler. If 'Nothing' is passed to this function, it will unset\n-- the handler.\nbusSetSyncHandler :: BusClass busT\n => busT\n -> Maybe BusSyncHandler\n -> IO ()\nbusSetSyncHandler bus busSyncHandlerM = do\n objectWithLock bus $ do\n unsetSyncHandler bus\n case busSyncHandlerM of\n Just busSyncHandler ->\n do funPtr <- marshalBusSyncHandler busSyncHandler\n setFunPtr bus $ Just funPtr\n weakNotify <- objectWeakref bus $ freeHaskellFunPtr funPtr\n setWeakNotify bus $ Just weakNotify\n {# call bus_set_sync_handler #} (toBus bus) funPtr nullPtr\n Nothing ->\n return ()\n\n-- | Use a synchronous message handler that converts all messages to signals.\nbusUseSyncSignalHandler :: BusClass busT\n => busT\n -> IO ()\nbusUseSyncSignalHandler bus = do\n objectWithLock bus $ do\n unsetSyncHandler bus\n {# call bus_set_sync_handler #} (toBus bus) cBusSyncSignalHandlerPtr nullPtr\nforeign import ccall unsafe \"&gst_bus_sync_signal_handler\"\n cBusSyncSignalHandlerPtr :: {# type GstBusSyncHandler #}\n\n-- | Create a watch for the bus. The 'Source' will dispatch a signal\n-- whenever a message is on the bus. After the signal is dispatched,\n-- the message is popped off the bus.\nbusCreateWatch :: BusClass busT\n => busT\n -> IO Source\nbusCreateWatch bus =\n liftM Source $ {# call bus_create_watch #} (toBus bus) >>=\n flip newForeignPtr sourceFinalizer\nforeign import ccall unsafe \"&g_source_unref\"\n sourceFinalizer :: FunPtr (Ptr Source -> IO ())\n\ntype CBusFunc = Ptr Bus\n -> Ptr Message\n -> {# type gpointer #}\n -> IO {# type gboolean #}\nmarshalBusFunc :: BusFunc\n -> IO {# type GstBusFunc #}\nmarshalBusFunc busFunc =\n makeBusFunc cBusFunc\n where cBusFunc :: CBusFunc\n cBusFunc busPtr messagePtr userData =\n do bus <- peekObject busPtr\n message <- peekMiniObject messagePtr\n liftM fromBool $ busFunc bus message\nforeign import ccall \"wrapper\"\n makeBusFunc :: CBusFunc\n -> IO {# type GstBusFunc #}\n\n-- | Adds a bus watch to the default main context with the given\n-- priority. This function is used to receive asynchronous messages\n-- in the main loop.\n-- \n-- The watch can be removed by calling 'System.Glib.MainLoop.sourceRemove'.\nbusAddWatch :: BusClass busT\n => busT\n -> Priority\n -> BusFunc\n -> IO HandlerId\nbusAddWatch bus priority func =\n do busFuncPtr <- marshalBusFunc func\n destroyNotify <- mkFunPtrDestroyNotify busFuncPtr\n liftM fromIntegral $\n {# call bus_add_watch_full #}\n (toBus bus)\n (fromIntegral priority)\n busFuncPtr\n nullPtr\n destroyNotify\n\n-- | Instructs GStreamer to stop emitting the @\"sync-message\"@ signal\n-- for this bus. See 'busEnableSyncMessageEmission' for more\n-- information.\n-- \n-- In the event that multiple pieces of code have called\n-- 'busEnableSyncMessageEmission', the sync-message\n-- emissions will only be stopped after all calls to\n-- 'busEnableSyncMessageEmission' were \"cancelled\" by\n-- calling this function.\nbusDisableSyncMessageEmission :: BusClass busT\n => busT\n -> IO ()\nbusDisableSyncMessageEmission =\n {# call bus_disable_sync_message_emission #} . toBus\n\n-- | Instructs GStreamer to emit the @\"sync-message\"@ signal after\n-- running the bus's sync handler. This function is here so that\n-- programmers can ensure that they can synchronously receive\n-- messages without having to affect what the bin's sync handler is.\n-- \n-- This function may be called multiple times. To clean up, the\n-- caller is responsible for calling 'busDisableSyncMessageEmission'\n-- as many times as this function is called.\n-- \n-- While this function looks similar to 'busAddSignalWatch', it is\n-- not exactly the same -- this function enables synchronous\n-- emission of signals when messages arrive; 'busAddSignalWatch'\n-- adds an idle callback to pop messages off the bus\n-- asynchronously. The @\"sync-message\"@ signal comes from the thread\n-- of whatever object posted the message; the @\"message\"@ signal is\n-- marshalled to the main thread via the main loop.\nbusEnableSyncMessageEmission :: BusClass busT\n => busT\n -> IO ()\nbusEnableSyncMessageEmission =\n {# call bus_enable_sync_message_emission #} . toBus\n\n-- | Adds a bus signal watch to the default main context with the\n-- given priority. After calling this method, the bus will emit the\n-- @\"message\"@ signal for each message posted on the bus.\n-- \n-- This function may be called multiple times. To clean up, the\n-- caller is responsible for calling 'busRemoveSignalWatch' as many\n-- times.\nbusAddSignalWatch :: BusClass busT\n => busT\n -> Priority\n -> IO ()\nbusAddSignalWatch bus priority =\n {# call bus_add_signal_watch_full #} (toBus bus) $ fromIntegral priority\n\n-- | Remove the signal watch that was added with 'busAddSignalWatch'.\nbusRemoveSignalWatch :: BusClass busT\n => busT\n -> IO ()\nbusRemoveSignalWatch =\n {# call bus_remove_signal_watch #} . toBus\n\n-- | Poll the bus for a message. Will block while waiting for messages\n-- to come. You can specify the maximum amount of time to wait with\n-- the @timeout@ parameter. If @timeout@ is negative, the function\n-- will wait indefinitely.\n-- \n-- Messages not in @events@ will be popped off the bus and ignored.\n-- \n-- Because 'busPoll' is implemented using the @\"message\"@ signal\n-- enabled by 'busAddSignalWatch', calling 'busPoll' will cause the\n-- @\"message\"@ signal to be emitted for every message that the\n-- function sees. Thus, a @\"message\"@ signal handler will see every\n-- message that 'busPoll' sees -- neither will steal messages from\n-- the other.\n-- \n-- This function will run a main loop in the default main context\n-- while polling.\nbusPoll :: Bus\n -> [MessageType]\n -> ClockTimeDiff\n -> IO Message\nbusPoll bus events timeout =\n {# call bus_poll #} bus\n (fromIntegral $ fromFlags events)\n (fromIntegral timeout) >>=\n takeMiniObject\n\n-- | Connect to the @\"message\"@ signal. Emitted from a 'Source' added\n-- to the mainloop. This signal will only be emitted when there is a\n-- 'MainLoop' running.\nonBusMessage, afterBusMessage :: BusClass bus\n => bus\n -> (Message -> IO ())\n -> IO (ConnectId bus)\nonBusMessage =\n connect_BOXED__NONE \"message\" peekMiniObject False\nafterBusMessage =\n connect_BOXED__NONE \"message\" peekMiniObject True\n\n-- | A message has been posted on the bus. This signal is emitted from\n-- the thread that posted the message so one has to be careful with\n-- locking.\n-- \n-- This signal will not be emitted by default, you must first call\n-- 'busUseSyncSignalHandler' if you want this signal to be emitted\n-- when a message is posted on the bus.\nonBusSyncMessage, afterBusSyncMessage :: BusClass bus\n => bus\n -> (Message -> IO ())\n -> IO (ConnectId bus)\nonBusSyncMessage =\n connect_BOXED__NONE \"sync-message\" peekMiniObject False\nafterBusSyncMessage =\n connect_BOXED__NONE \"sync-message\" peekMiniObject True\n","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gstreamer -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GStreamer, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GStreamer documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\n-- \n-- An asynchronous message bus subsystem.\n-- \nmodule Media.Streaming.GStreamer.Core.Bus (\n-- * Types \n -- | The 'Bus' is resposible for delivering 'Message's in a\n -- first-in, first-out order, from the streaming threads to the\n -- application.\n -- \n -- Since the application typically only wants to deal with\n -- delivery of these messages from one thread, the 'Bus' will\n -- marshal the messages between different threads. This is\n -- important since the actual streaming of media is done in\n -- a thread separate from the application.\n --\n -- The 'Bus' provides support for 'System.Glib.MainLoop.Source'\n -- based notifications. This makes it possible to handle the\n -- delivery in the GLib 'System.Glib.MainLoop.Source'.\n --\n -- A message is posted on the bus with the 'busPost' method. With\n -- the 'busPeek' and 'busPop' methods one can look at or retrieve\n -- a previously posted message.\n --\n -- The bus can be polled with the 'busPoll' method. This methods\n -- blocks up to the specified timeout value until one of the\n -- specified messages types is posted on the bus. The application\n -- can then pop the messages from the bus to handle\n -- them. Alternatively the application can register an\n -- asynchronous bus function using 'busAddWatch'. This function\n -- will install a 'System.Glib.MainLoop.Source' in the default\n -- GLib main loop and will deliver messages a short while after\n -- they have been posted. Note that the main loop should be\n -- running for the asynchronous callbacks.\n --\n -- It is also possible to get messages from the bus without any\n -- thread marshalling with the 'busSetSyncHandler' method. This\n -- makes it possible to react to a message in the same thread that\n -- posted the message on the bus. This should only be used if the\n -- application is able to deal with messages from different\n -- threads.\n -- \n -- Every 'Pipeline' has one bus.\n --\n -- Note that a 'Pipeline' will set its bus into flushing state\n -- when changing from 'StateReady' to 'StateNull'.\n Bus,\n -- | The result of a 'BusSyncHandler'.\n BusSyncReply,\n -- | A handler that will be invoked synchronously when a new message\n -- is injected into the bus. This function is mostly used internally.\n -- Only one sync handler may be attached to a given bus.\n BusSyncHandler,\n BusClass,\n castToBus,\n toBus,\n-- * Bus Operations\n busGetFlags,\n busSetFlags,\n busUnsetFlags,\n busNew,\n busPost,\n busHavePending,\n busPeek,\n busPop,\n busTimedPop,\n busSetFlushing,\n busSetSyncHandler,\n busUseSyncSignalHandler,\n busCreateWatch,\n busAddWatch,\n busDisableSyncMessageEmission,\n busEnableSyncMessageEmission,\n busAddSignalWatch,\n busRemoveSignalWatch,\n busPoll,\n \n-- * Bus Signals\n onBusMessage,\n afterBusMessage,\n onBusSyncMessage,\n afterBusSyncMessage\n \n ) where\n\nimport Control.Monad ( liftM\n , when )\n{#import Media.Streaming.GStreamer.Core.Object#}\n{#import Media.Streaming.GStreamer.Core.Types#}\n{#import Media.Streaming.GStreamer.Core.Signals#}\n{#import System.Glib.MainLoop#}\nimport System.Glib.Flags\nimport System.Glib.FFI\n{#import System.Glib.GObject#}\n{#import System.Glib.MainLoop#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\n-- | Get the flags set on this bus.\nbusGetFlags :: BusClass busT\n => busT\n -> IO [BusFlags]\nbusGetFlags = mkObjectGetFlags\n\n-- | Set flags on this bus.\nbusSetFlags :: BusClass busT\n => busT\n -> [BusFlags]\n -> IO ()\nbusSetFlags = mkObjectSetFlags\n\n-- | Unset flags on this bus.\nbusUnsetFlags :: BusClass busT\n => busT\n -> [BusFlags]\n -> IO ()\nbusUnsetFlags = mkObjectUnsetFlags\n\n-- | Create a new bus.\nbusNew :: IO Bus\nbusNew =\n {# call bus_new #} >>= takeObject\n\n-- | Post a message to the bus.\nbusPost :: BusClass busT\n => busT\n -> Message\n -> IO Bool\nbusPost bus message =\n do {# call gst_mini_object_ref #} (toMiniObject message)\n liftM toBool $ {# call bus_post #} (toBus bus) message\n\n-- | Check if there are pending messages on the bus.\nbusHavePending :: BusClass busT\n => busT\n -> IO Bool\nbusHavePending bus =\n liftM toBool $ {# call bus_have_pending #} $ toBus bus\n\n-- | Get the message at the front of the queue. It will remain on the\n-- queue.\nbusPeek :: BusClass busT\n => busT\n -> IO (Maybe Message)\nbusPeek bus =\n {# call bus_peek #} (toBus bus) >>= maybePeek takeMiniObject\n\n-- | Get the message at the front of the queue. It will be removed\n-- from the queue.\nbusPop :: BusClass busT\n => busT\n -> IO (Maybe Message)\nbusPop bus =\n {# call bus_pop #} (toBus bus) >>= maybePeek takeMiniObject\n\n-- | Get a message from the bus, waiting up to the specified timeout.\n-- If the time given is 'Nothing', the function will wait forever.\n-- If the time given is @0@, the function will behave like 'busPop'.\nbusTimedPop :: BusClass busT\n => busT\n -> Maybe ClockTime\n -> IO (Maybe Message)\nbusTimedPop bus timeoutM =\n let timeout = case timeoutM of\n Just timeout' -> timeout'\n Nothing -> clockTimeNone\n in {# call bus_timed_pop #} (toBus bus) (fromIntegral timeout) >>=\n maybePeek takeMiniObject\n\n-- | If @flushing@ is 'True', the bus will flush out any queued\n-- messages, as well as any future messages, until the function is\n-- called with @flushing@ set to 'False'.\nbusSetFlushing :: BusClass busT\n => busT\n -> Bool\n -> IO ()\nbusSetFlushing bus flushing =\n {# call bus_set_flushing #} (toBus bus) $ fromBool flushing\n\n-- these will leak memory, maybe one day we can set a destroy notifier...\n\ntype CBusSyncHandler = Ptr Bus\n -> Ptr Message\n -> {# type gpointer #}\n -> IO {# type GstBusSyncReply #}\nmarshalBusSyncHandler :: BusSyncHandler\n -> IO {# type GstBusSyncHandler #}\nmarshalBusSyncHandler busSyncHandler =\n makeBusSyncHandler cBusSyncHandler\n where cBusSyncHandler :: CBusSyncHandler\n cBusSyncHandler busPtr messagePtr _ =\n do bus <- peekObject busPtr\n message <- peekMiniObject messagePtr\n reply <- busSyncHandler bus message\n when (reply == BusDrop) $\n {# call gst_mini_object_unref #} (toMiniObject message)\n return $ fromIntegral $ fromEnum reply\nforeign import ccall \"wrapper\"\n makeBusSyncHandler :: CBusSyncHandler\n -> IO {# type GstBusSyncHandler #}\n\n-- the following mess is necessary to clean up safely after busSetSyncHandler.\n-- gstreamer doesn't give us a nice way to do this (such as a DestroyNotify)\nweakNotifyQuark, funPtrQuark :: Quark\nweakNotifyQuark = unsafePerformIO $ quarkFromString \"Gtk2HS::SyncHandlerWeakNotify\"\nfunPtrQuark = unsafePerformIO $ quarkFromString \"Gtk2HS::SyncHandlerFunPtr\"\n\ngetWeakNotify :: BusClass busT\n => busT\n -> IO (Maybe GWeakNotify)\ngetWeakNotify = objectGetAttributeUnsafe weakNotifyQuark\n\nsetWeakNotify :: BusClass busT\n => busT\n -> Maybe GWeakNotify\n -> IO ()\nsetWeakNotify = objectSetAttribute weakNotifyQuark\n\ngetFunPtr :: BusClass busT\n => busT\n -> IO (Maybe {# type GstBusSyncHandler #})\ngetFunPtr = objectGetAttributeUnsafe funPtrQuark\n\nsetFunPtr :: BusClass busT\n => busT\n -> Maybe {# type GstBusSyncHandler #}\n -> IO ()\nsetFunPtr = objectSetAttribute funPtrQuark\n\nunsetSyncHandler :: BusClass busT\n => busT\n -> IO ()\nunsetSyncHandler bus = do\n {# call bus_set_sync_handler #} (toBus bus) nullFunPtr nullPtr\n oldWeakNotifyM <- getWeakNotify bus\n case oldWeakNotifyM of\n Just oldWeakNotify -> objectWeakunref bus oldWeakNotify\n Nothing -> return ()\n setWeakNotify bus Nothing\n oldFunPtrM <- getFunPtr bus\n case oldFunPtrM of\n Just oldFunPtr -> freeHaskellFunPtr oldFunPtr\n Nothing -> return ()\n setFunPtr bus Nothing\n\n-- | Set the synchronous message handler on the bus. The function will\n-- be called every time a new message is posted to the bus. Note\n-- that the function will be called from the thread context of the\n-- poster.\n-- \n-- Calling this function will replace any previously set sync\n-- handler. If 'Nothing' is passed to this function, it will unset\n-- the handler.\nbusSetSyncHandler :: BusClass busT\n => busT\n -> Maybe BusSyncHandler\n -> IO ()\nbusSetSyncHandler bus busSyncHandlerM = do\n objectWithLock bus $ do\n unsetSyncHandler bus\n case busSyncHandlerM of\n Just busSyncHandler ->\n do funPtr <- marshalBusSyncHandler busSyncHandler\n setFunPtr bus $ Just funPtr\n weakNotify <- objectWeakref bus $ freeHaskellFunPtr funPtr\n setWeakNotify bus $ Just weakNotify\n {# call bus_set_sync_handler #} (toBus bus) funPtr nullPtr\n Nothing ->\n return ()\n\n-- | Use a synchronous message handler that converts all messages to signals.\nbusUseSyncSignalHandler :: BusClass busT\n => busT\n -> IO ()\nbusUseSyncSignalHandler bus = do\n objectWithLock bus $ do\n unsetSyncHandler bus\n {# call bus_set_sync_handler #} (toBus bus) cBusSyncSignalHandlerPtr nullPtr\nforeign import ccall unsafe \"&gst_bus_sync_signal_handler\"\n cBusSyncSignalHandlerPtr :: {# type GstBusSyncHandler #}\n\n-- | Create a watch for the bus. The 'Source' will dispatch a signal\n-- whenever a message is on the bus. After the signal is dispatched,\n-- the message is popped off the bus.\nbusCreateWatch :: BusClass busT\n => busT\n -> IO Source\nbusCreateWatch bus =\n liftM Source $ {# call bus_create_watch #} (toBus bus) >>=\n flip newForeignPtr sourceFinalizer\nforeign import ccall unsafe \"&g_source_unref\"\n sourceFinalizer :: FunPtr (Ptr Source -> IO ())\n\ntype CBusFunc = Ptr Bus\n -> Ptr Message\n -> {# type gpointer #}\n -> IO {# type gboolean #}\nmarshalBusFunc :: BusFunc\n -> IO {# type GstBusFunc #}\nmarshalBusFunc busFunc =\n makeBusFunc cBusFunc\n where cBusFunc :: CBusFunc\n cBusFunc busPtr messagePtr userData =\n do bus <- peekObject busPtr\n message <- peekMiniObject messagePtr\n liftM fromBool $ busFunc bus message\nforeign import ccall \"wrapper\"\n makeBusFunc :: CBusFunc\n -> IO {# type GstBusFunc #}\n\n-- | Adds a bus watch to the default main context with the given\n-- priority. This function is used to receive asynchronous messages\n-- in the main loop.\n-- \n-- The watch can be removed by calling 'System.Glib.MainLoop.sourceRemove'.\nbusAddWatch :: BusClass busT\n => busT\n -> Priority\n -> BusFunc\n -> IO HandlerId\nbusAddWatch bus priority func =\n do busFuncPtr <- marshalBusFunc func\n destroyNotify <- mkFunPtrDestroyNotify busFuncPtr\n liftM fromIntegral $\n {# call bus_add_watch_full #}\n (toBus bus)\n (fromIntegral priority)\n busFuncPtr\n nullPtr\n destroyNotify\n\n-- | Instructs GStreamer to stop emitting the @\"sync-message\"@ signal\n-- for this bus. See 'busEnableSyncMessageEmission' for more\n-- information.\n-- \n-- In the event that multiple pieces of code have called\n-- 'busEnableSyncMessageEmission', the sync-message\n-- emissions will only be stopped after all calls to\n-- 'busEnableSyncMessageEmission' were \"cancelled\" by\n-- calling this function.\nbusDisableSyncMessageEmission :: BusClass busT\n => busT\n -> IO ()\nbusDisableSyncMessageEmission =\n {# call bus_disable_sync_message_emission #} . toBus\n\n-- | Instructs GStreamer to emit the @\"sync-message\"@ signal after\n-- running the bus's sync handler. This function is here so that\n-- programmers can ensure that they can synchronously receive\n-- messages without having to affect what the bin's sync handler is.\n-- \n-- This function may be called multiple times. To clean up, the\n-- caller is responsible for calling 'busDisableSyncMessageEmission'\n-- as many times as this function is called.\n-- \n-- While this function looks similar to 'busAddSignalWatch', it is\n-- not exactly the same -- this function enables synchronous\n-- emission of signals when messages arrive; 'busAddSignalWatch'\n-- adds an idle callback to pop messages off the bus\n-- asynchronously. The @\"sync-message\"@ signal comes from the thread\n-- of whatever object posted the message; the @\"message\"@ signal is\n-- marshalled to the main thread via the main loop.\nbusEnableSyncMessageEmission :: BusClass busT\n => busT\n -> IO ()\nbusEnableSyncMessageEmission =\n {# call bus_enable_sync_message_emission #} . toBus\n\n-- | Adds a bus signal watch to the default main context with the\n-- given priority. After calling this method, the bus will emit the\n-- @\"message\"@ signal for each message posted on the bus.\n-- \n-- This function may be called multiple times. To clean up, the\n-- caller is responsible for calling 'busRemoveSignalWatch' as many\n-- times.\nbusAddSignalWatch :: BusClass busT\n => busT\n -> Priority\n -> IO ()\nbusAddSignalWatch bus priority =\n {# call bus_add_signal_watch_full #} (toBus bus) $ fromIntegral priority\n\n-- | Remove the signal watch that was added with 'busAddSignalWatch'.\nbusRemoveSignalWatch :: BusClass busT\n => busT\n -> IO ()\nbusRemoveSignalWatch =\n {# call bus_remove_signal_watch #} . toBus\n\n-- | Poll the bus for a message. Will block while waiting for messages\n-- to come. You can specify the maximum amount of time to wait with\n-- the @timeout@ parameter. If @timeout@ is negative, the function\n-- will wait indefinitely.\n-- \n-- Messages not in @events@ will be popped off the bus and ignored.\n-- \n-- Because 'busPoll' is implemented using the @\"message\"@ signal\n-- enabled by 'busAddSignalWatch', calling 'busPoll' will cause the\n-- @\"message\"@ signal to be emitted for every message that the\n-- function sees. Thus, a @\"message\"@ signal handler will see every\n-- message that 'busPoll' sees -- neither will steal messages from\n-- the other.\n-- \n-- This function will run a main loop in the default main context\n-- while polling.\nbusPoll :: Bus\n -> [MessageType]\n -> ClockTimeDiff\n -> IO Message\nbusPoll bus events timeout =\n {# call bus_poll #} bus\n (fromIntegral $ fromFlags events)\n (fromIntegral timeout) >>=\n takeMiniObject\n\n-- | Connect to the @\"message\"@ signal. Emitted from a 'Source' added\n-- to the mainloop. This signal will only be emitted when there is a\n-- 'MainLoop' running.\nonBusMessage, afterBusMessage :: BusClass bus\n => bus\n -> (Message -> IO ())\n -> IO (ConnectId bus)\nonBusMessage =\n connect_BOXED__NONE \"message\" peekMiniObject False\nafterBusMessage =\n connect_BOXED__NONE \"message\" peekMiniObject True\n\n-- | A message has been posted on the bus. This signal is emitted from\n-- the thread that posted the message so one has to be careful with\n-- locking.\n-- \n-- This signal will not be emitted by default, you must first call\n-- 'busUseSyncSignalHandler' if you want this signal to be emitted\n-- when a message is posted on the bus.\nonBusSyncMessage, afterBusSyncMessage :: BusClass bus\n => bus\n -> (Message -> IO ())\n -> IO (ConnectId bus)\nonBusSyncMessage =\n connect_BOXED__NONE \"sync-message\" peekMiniObject False\nafterBusSyncMessage =\n connect_BOXED__NONE \"sync-message\" peekMiniObject True\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"317b67a21677763b1ab6dd4aa99e2829e7669b1a","subject":"Remove an unnecessary import","message":"Remove an unnecessary import\n","repos":"travitch\/llvm-data-interop,travitch\/llvm-data-interop","old_file":"src\/LLVM\/Internal\/Interop.chs","new_file":"src\/LLVM\/Internal\/Interop.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, RankNTypes, OverloadedStrings, CPP #-}\nmodule LLVM.Internal.Interop where\n\nimport Control.Applicative\nimport Control.Monad.Trans ( MonadIO, liftIO )\nimport Data.Array.Storable ( getElems )\n#if __GLASGOW_HASKELL__ >= 704\nimport Data.Array.Unsafe ( unsafeForeignPtrToStorableArray )\n#else\nimport Data.Array.Storable ( unsafeForeignPtrToStorableArray )\n#endif\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport Data.Text ( Text )\nimport Data.Text.Encoding ( decodeUtf8 )\nimport Foreign.C\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Data.LLVM.Types\n\n#include \"c++\/marshal.h\"\n\n{#enum TypeTag {} deriving (Show, Eq) #}\n{#enum ValueTag {underscoreToCase} deriving (Show, Eq) #}\n{#enum MetaTag {underscoreToCase} deriving (Show, Eq) #}\n\ndata CModule\n{#pointer *CModule as ModulePtr -> CModule #}\n\nmakeText :: CString -> IO Text\nmakeText p = do\n s <- BS.packCString p\n return (decodeUtf8 s)\n\ncModuleIdentifier :: ModulePtr -> IO Text\ncModuleIdentifier m = ({#get CModule->moduleIdentifier#} m) >>= makeText\n\ncModuleDataLayout :: ModulePtr -> IO Text\ncModuleDataLayout m = ({#get CModule->moduleDataLayout#} m) >>= makeText\n\ncModuleTargetTriple :: ModulePtr -> IO Text\ncModuleTargetTriple m = ({#get CModule->targetTriple#} m) >>= makeText\n\ncModuleInlineAsm :: ModulePtr -> IO Text\ncModuleInlineAsm m = ({#get CModule->moduleInlineAsm#} m) >>= makeText\n\ncModuleHasError :: ModulePtr -> IO Bool\ncModuleHasError m = toBool <$> ({#get CModule->hasError#} m)\n\ncModuleErrorMessage :: ModulePtr -> IO (Maybe String)\ncModuleErrorMessage m = do\n hasError <- cModuleHasError m\n case hasError of\n True -> do\n msgPtr <- ({#get CModule->errMsg#} m)\n s <- peekCString msgPtr\n return (Just s)\n False -> return Nothing\n\ncModuleLittleEndian :: ModulePtr -> IO Bool\ncModuleLittleEndian m = toBool <$> ({#get CModule->littleEndian#} m)\n\ncModulePointerSize :: ModulePtr -> IO Int\ncModulePointerSize m = fromIntegral <$> ({#get CModule->pointerSize#} m)\n\ncModuleGlobalVariables :: ModulePtr -> IO [ValuePtr]\ncModuleGlobalVariables m =\n peekArray m {#get CModule->globalVariables#} {#get CModule->numGlobalVariables#}\n\ncModuleGlobalAliases :: ModulePtr -> IO [ValuePtr]\ncModuleGlobalAliases m =\n peekArray m ({#get CModule->globalAliases#}) ({#get CModule->numGlobalAliases#})\n\ncModuleFunctions :: ModulePtr -> IO [ValuePtr]\ncModuleFunctions m =\n peekArray m ({#get CModule->functions#}) ({#get CModule->numFunctions#})\n\ncModuleEnumMetadata :: ModulePtr -> IO [MetaPtr]\ncModuleEnumMetadata m =\n peekArray m {#get CModule->enumMetadata#} {#get CModule->numEnumMetadata#}\n\ncModuleRetainedTypeMetadata :: ModulePtr -> IO [MetaPtr]\ncModuleRetainedTypeMetadata m =\n peekArray m {#get CModule->retainedTypeMetadata#} {#get CModule->numRetainedTypes#}\n\ncModuleTypes :: ModulePtr -> IO [TypePtr]\ncModuleTypes m =\n peekArray m {#get CModule->types#} {#get CModule->numTypes#}\n\npeekArray :: forall a b c e . (Integral c, Storable e) =>\n a -> (a -> IO (Ptr b)) -> (a -> IO c) -> IO [e]\npeekArray obj arrAccessor sizeAccessor = do\n nElts <- sizeAccessor obj\n arrPtr <- arrAccessor obj\n case nElts == 0 || arrPtr == nullPtr of\n True -> return []\n False -> do\n fArrPtr <- newForeignPtr_ (castPtr arrPtr)\n let elementCount :: Int\n elementCount = fromIntegral nElts\n arr <- unsafeForeignPtrToStorableArray fArrPtr (1, elementCount)\n getElems arr\n\ndata CType\n{#pointer *CType as TypePtr -> CType #}\ncTypeTag :: TypePtr -> IO TypeTag\ncTypeTag t = toEnum . fromIntegral <$> {#get CType->typeTag#} t\ncTypeSize :: TypePtr -> IO Int\ncTypeSize t = fromIntegral <$> {#get CType->size#} t\ncTypeIsVarArg :: TypePtr -> IO Bool\ncTypeIsVarArg t = toBool <$> {#get CType->isVarArg#} t\ncTypeIsPacked :: TypePtr -> IO Bool\ncTypeIsPacked t = toBool <$> {#get CType->isPacked#} t\ncTypeList :: TypePtr -> IO [TypePtr]\ncTypeList t =\n peekArray t {#get CType->typeList#} {#get CType->typeListLen#}\ncTypeInner :: TypePtr -> IO TypePtr\ncTypeInner = {#get CType->innerType#}\ncTypeName :: TypePtr -> IO (Maybe String)\ncTypeName t = do\n n <- optionalField {#get CType->name#} t\n case n of\n Nothing -> return Nothing\n Just n' -> do\n s <- peekCString n'\n return (Just s)\ncTypeAddrSpace :: TypePtr -> IO Int\ncTypeAddrSpace t = fromIntegral <$> {#get CType->addrSpace#} t\n\ncTypeSizeInBytes :: TypePtr -> IO Int\ncTypeSizeInBytes t = fromIntegral <$> {#get CType->sizeInBytes#} t\n\ndata CValue\n{#pointer *CValue as ValuePtr -> CValue #}\ndata CMeta\n{#pointer *CMeta as MetaPtr -> CMeta #}\n\ncValueTag :: ValuePtr -> IO ValueTag\ncValueTag v = toEnum . fromIntegral <$> ({#get CValue->valueTag#} v)\ncValueType :: ValuePtr -> IO TypePtr\ncValueType = {#get CValue->valueType#}\ncValueName :: (InternString m) => ValuePtr -> m (Maybe Identifier)\ncValueName v = do\n tag <- liftIO $ cValueTag v\n namePtr <- liftIO $ ({#get CValue->name#}) v\n case namePtr == nullPtr of\n True -> return Nothing\n False -> do\n rawName <- liftIO $ makeText namePtr\n name <- internString rawName\n rawIdent <- case tag of\n ValFunction -> return $! makeGlobalIdentifier name\n ValGlobalvariable -> return $! makeGlobalIdentifier name\n ValAlias -> return $! makeGlobalIdentifier name\n _ -> return $! makeLocalIdentifier name\n ident <- internIdentifier rawIdent\n return $! (Just ident)\ncValueMetadata :: ValuePtr -> IO [MetaPtr]\ncValueMetadata v = peekArray v {#get CValue->md#} {#get CValue->numMetadata#}\ncValueSrcLoc :: ValuePtr -> IO MetaPtr\ncValueSrcLoc = {#get CValue->srcLoc#}\ncValueData :: ValuePtr -> IO (Ptr ())\ncValueData = {#get CValue->data#}\n\n\ncMetaTypeTag :: MetaPtr -> IO MetaTag\ncMetaTypeTag v = toEnum . fromIntegral <$> {#get CMeta->metaTag #} v\n\ncMetaTag :: MetaPtr -> IO DW_TAG\ncMetaTag p = do\n t <- {#get CMeta->tag#} p\n case dw_tag t of\n Nothing -> return DW_TAG_unspecified_type\n Just t' -> return t'\n\ncMetaArrayElts :: MetaPtr -> IO [Maybe MetaPtr]\ncMetaArrayElts p = map convertNull <$>\n peekArray p {#get CMeta->u.metaArrayInfo.arrayElts#} {#get CMeta->u.metaArrayInfo.arrayLen#}\n where\n convertNull ptr =\n case ptr == nullPtr of\n True -> Nothing\n False -> Just ptr\n\ncMetaEnumeratorName :: InternString m => MetaPtr -> m Text\ncMetaEnumeratorName = shareString {#get CMeta->u.metaEnumeratorInfo.enumName#}\ncMetaEnumeratorValue :: MetaPtr -> IO Int64\ncMetaEnumeratorValue p = fromIntegral <$> {#get CMeta->u.metaEnumeratorInfo.enumValue#} p\ncMetaGlobalContext :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaGlobalContext = optionalField {#get CMeta->u.metaGlobalInfo.context #}\ncMetaGlobalName :: InternString m => MetaPtr -> m Text\ncMetaGlobalName = shareString {#get CMeta->u.metaGlobalInfo.name#}\ncMetaGlobalDisplayName :: InternString m => MetaPtr -> m Text\ncMetaGlobalDisplayName = shareString {#get CMeta->u.metaGlobalInfo.displayName#}\ncMetaGlobalLinkageName :: InternString m => MetaPtr -> m Text\ncMetaGlobalLinkageName = shareString {#get CMeta->u.metaGlobalInfo.linkageName#}\n-- cMetaGlobalCompileUnit :: MetaPtr -> IO MetaPtr\n-- cMetaGlobalCompileUnit = {#get CMeta->u.metaGlobalInfo.compileUnit#}\ncMetaGlobalLine :: MetaPtr -> IO Int32\ncMetaGlobalLine p = fromIntegral <$> {#get CMeta->u.metaGlobalInfo.lineNumber#} p\ncMetaGlobalType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaGlobalType = optionalField {#get CMeta->u.metaGlobalInfo.globalType#}\ncMetaGlobalIsLocal :: MetaPtr -> IO Bool\ncMetaGlobalIsLocal p = toBool <$> {#get CMeta->u.metaGlobalInfo.isLocalToUnit#} p\ncMetaGlobalIsDefinition :: MetaPtr -> IO Bool\ncMetaGlobalIsDefinition p = toBool <$> {#get CMeta->u.metaGlobalInfo.isDefinition#} p\ncMetaLocationLine :: MetaPtr -> IO Int32\ncMetaLocationLine p = fromIntegral <$> {#get CMeta->u.metaLocationInfo.lineNumber#} p\ncMetaLocationColumn :: MetaPtr -> IO Int32\ncMetaLocationColumn p = fromIntegral <$> {#get CMeta->u.metaLocationInfo.columnNumber#} p\ncMetaLocationScope :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaLocationScope = optionalField {#get CMeta->u.metaLocationInfo.scope#}\ncMetaSubrangeLo :: MetaPtr -> IO Int64\ncMetaSubrangeLo p = fromIntegral <$> {#get CMeta->u.metaSubrangeInfo.lo#} p\ncMetaSubrangeHi :: MetaPtr -> IO Int64\ncMetaSubrangeHi p = fromIntegral <$> {#get CMeta->u.metaSubrangeInfo.hi#} p\ncMetaTemplateTypeContext :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTemplateTypeContext = optionalField {#get CMeta->u.metaTemplateTypeInfo.context#}\ncMetaTemplateTypeName :: InternString m => MetaPtr -> m Text\ncMetaTemplateTypeName = shareString {#get CMeta->u.metaTemplateTypeInfo.name#}\ncMetaTemplateTypeType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTemplateTypeType = optionalField {#get CMeta->u.metaTemplateTypeInfo.type#}\ncMetaTemplateTypeLine :: MetaPtr -> IO Int32\ncMetaTemplateTypeLine p = fromIntegral <$> {#get CMeta->u.metaTemplateTypeInfo.lineNumber#} p\ncMetaTemplateTypeColumn :: MetaPtr -> IO Int32\ncMetaTemplateTypeColumn p = fromIntegral <$> {#get CMeta->u.metaTemplateTypeInfo.columnNumber#} p\ncMetaTemplateValueContext :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTemplateValueContext = optionalField {#get CMeta->u.metaTemplateValueInfo.context#}\ncMetaTemplateValueName :: InternString m => MetaPtr -> m Text\ncMetaTemplateValueName = shareString {#get CMeta->u.metaTemplateValueInfo.name#}\ncMetaTemplateValueType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTemplateValueType = optionalField {#get CMeta->u.metaTemplateValueInfo.type#}\ncMetaTemplateValueValue :: MetaPtr -> IO Int64\ncMetaTemplateValueValue p = fromIntegral <$> {#get CMeta->u.metaTemplateValueInfo.value#} p\ncMetaTemplateValueLine :: MetaPtr -> IO Int32\ncMetaTemplateValueLine p = fromIntegral <$> {#get CMeta->u.metaTemplateValueInfo.lineNumber#} p\ncMetaTemplateValueColumn :: MetaPtr -> IO Int32\ncMetaTemplateValueColumn p = fromIntegral <$> {#get CMeta->u.metaTemplateValueInfo.columnNumber#} p\ncMetaVariableContext :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaVariableContext = optionalField {#get CMeta->u.metaVariableInfo.context#}\ncMetaVariableName :: InternString m => MetaPtr -> m Text\ncMetaVariableName = shareString {#get CMeta->u.metaVariableInfo.name#}\n-- cMetaVariableCompileUnit :: MetaPtr -> IO MetaPtr\n-- cMetaVariableCompileUnit = {#get CMeta->u.metaVariableInfo.compileUnit#}\ncMetaVariableLine :: MetaPtr -> IO Int32\ncMetaVariableLine p = fromIntegral <$> {#get CMeta->u.metaVariableInfo.lineNumber#} p\ncMetaVariableArgNumber :: MetaPtr -> IO Int32\ncMetaVariableArgNumber p = fromIntegral <$> {#get CMeta->u.metaVariableInfo.argNumber#} p\ncMetaVariableType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaVariableType = optionalField {#get CMeta->u.metaVariableInfo.type#}\ncMetaVariableIsArtificial :: MetaPtr -> IO Bool\ncMetaVariableIsArtificial p = toBool <$> {#get CMeta->u.metaVariableInfo.isArtificial#} p\ncMetaVariableHasComplexAddress :: MetaPtr -> IO Bool\ncMetaVariableHasComplexAddress p = toBool <$> {#get CMeta->u.metaVariableInfo.hasComplexAddress #} p\ncMetaVariableAddrElements :: MetaPtr -> IO [Int64]\ncMetaVariableAddrElements p = do\n ca <- cMetaVariableHasComplexAddress p\n case ca of\n True -> peekArray p {#get CMeta->u.metaVariableInfo.addrElements#} {#get CMeta->u.metaVariableInfo.numAddrElements#}\n False -> return []\ncMetaVariableIsBlockByRefVar :: MetaPtr -> IO Bool\ncMetaVariableIsBlockByRefVar p = toBool <$> {#get CMeta->u.metaVariableInfo.isBlockByRefVar#} p\ncMetaCompileUnitLanguage :: MetaPtr -> IO DW_LANG\ncMetaCompileUnitLanguage p = dw_lang <$> {#get CMeta->u.metaCompileUnitInfo.language#} p\ncMetaCompileUnitFilename :: InternString m => MetaPtr -> m Text\ncMetaCompileUnitFilename = shareString {#get CMeta->u.metaCompileUnitInfo.filename#}\ncMetaCompileUnitDirectory :: InternString m => MetaPtr -> m Text\ncMetaCompileUnitDirectory = shareString {#get CMeta->u.metaCompileUnitInfo.directory#}\ncMetaCompileUnitProducer :: InternString m => MetaPtr -> m Text\ncMetaCompileUnitProducer = shareString {#get CMeta->u.metaCompileUnitInfo.producer#}\ncMetaCompileUnitIsMain :: MetaPtr -> IO Bool\ncMetaCompileUnitIsMain p = toBool <$> {#get CMeta->u.metaCompileUnitInfo.isMain#} p\ncMetaCompileUnitIsOptimized :: MetaPtr -> IO Bool\ncMetaCompileUnitIsOptimized p = toBool <$> {#get CMeta->u.metaCompileUnitInfo.isOptimized#} p\ncMetaCompileUnitFlags :: InternString m => MetaPtr -> m Text\ncMetaCompileUnitFlags = shareString {#get CMeta->u.metaCompileUnitInfo.flags#}\ncMetaCompileUnitRuntimeVersion :: MetaPtr -> IO Int32\ncMetaCompileUnitRuntimeVersion p = fromIntegral <$> {#get CMeta->u.metaCompileUnitInfo.runtimeVersion#} p\ncMetaCompileUnitEnumTypes :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaCompileUnitEnumTypes = optionalField {#get CMeta->u.metaCompileUnitInfo.enumTypes#}\ncMetaCompileUnitRetainedTypes :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaCompileUnitRetainedTypes = optionalField {#get CMeta->u.metaCompileUnitInfo.retainedTypes#}\ncMetaCompileUnitSubprograms :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaCompileUnitSubprograms = optionalField {#get CMeta->u.metaCompileUnitInfo.subprograms#}\ncMetaCompileUnitGlobalVariables :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaCompileUnitGlobalVariables = optionalField {#get CMeta->u.metaCompileUnitInfo.globalVariables#}\ncMetaFileFilename :: InternString m => MetaPtr -> m Text\ncMetaFileFilename = shareString {#get CMeta->u.metaFileInfo.filename#}\ncMetaFileDirectory :: InternString m => MetaPtr -> m Text\ncMetaFileDirectory = shareString {#get CMeta->u.metaFileInfo.directory#}\n-- cMetaFileCompileUnit :: MetaPtr -> IO MetaPtr\n-- cMetaFileCompileUnit = {#get CMeta->u.metaFileInfo.compileUnit#}\ncMetaLexicalBlockContext :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaLexicalBlockContext = optionalField {#get CMeta->u.metaLexicalBlockInfo.context#}\ncMetaLexicalBlockLine :: MetaPtr -> IO Int32\ncMetaLexicalBlockLine p = fromIntegral <$> {#get CMeta->u.metaLexicalBlockInfo.lineNumber#} p\ncMetaLexicalBlockColumn :: MetaPtr -> IO Int32\ncMetaLexicalBlockColumn p = fromIntegral <$> {#get CMeta->u.metaLexicalBlockInfo.columnNumber#} p\ncMetaNamespaceContext :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaNamespaceContext = optionalField {#get CMeta->u.metaNamespaceInfo.context#}\ncMetaNamespaceName :: InternString m => MetaPtr -> m Text\ncMetaNamespaceName = shareString {#get CMeta->u.metaNamespaceInfo.name#}\n-- cMetaNamespaceCompileUnit :: MetaPtr -> IO MetaPtr\n-- cMetaNamespaceCompileUnit = {#get CMeta->u.metaNamespaceInfo.compileUnit#}\ncMetaNamespaceLine :: MetaPtr -> IO Int32\ncMetaNamespaceLine p = fromIntegral <$> {#get CMeta->u.metaNamespaceInfo.lineNumber#} p\ncMetaSubprogramContext :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaSubprogramContext = optionalField {#get CMeta->u.metaSubprogramInfo.context#}\ncMetaSubprogramName :: InternString m => MetaPtr -> m Text\ncMetaSubprogramName = shareString {#get CMeta->u.metaSubprogramInfo.name#}\ncMetaSubprogramDisplayName :: InternString m => MetaPtr -> m Text\ncMetaSubprogramDisplayName = shareString {#get CMeta->u.metaSubprogramInfo.displayName#}\ncMetaSubprogramLinkageName :: InternString m => MetaPtr -> m Text\ncMetaSubprogramLinkageName = shareString {#get CMeta->u.metaSubprogramInfo.linkageName#}\n-- cMetaSubprogramCompileUnit :: MetaPtr -> IO MetaPtr\n-- cMetaSubprogramCompileUnit = {#get CMeta->u.metaSubprogramInfo.compileUnit#}\ncMetaSubprogramLine :: MetaPtr -> IO Int32\ncMetaSubprogramLine p = fromIntegral <$> {#get CMeta->u.metaSubprogramInfo.lineNumber#} p\ncMetaSubprogramType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaSubprogramType = optionalField {#get CMeta->u.metaSubprogramInfo.type#}\ncMetaSubprogramIsLocal :: MetaPtr -> IO Bool\ncMetaSubprogramIsLocal p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isLocalToUnit#} p\ncMetaSubprogramIsDefinition :: MetaPtr -> IO Bool\ncMetaSubprogramIsDefinition p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isDefinition#} p\ncMetaSubprogramVirtuality :: MetaPtr -> IO DW_VIRTUALITY\ncMetaSubprogramVirtuality p = dw_virtuality <$> {#get CMeta->u.metaSubprogramInfo.virtuality#} p\ncMetaSubprogramVirtualIndex :: MetaPtr -> IO Int32\ncMetaSubprogramVirtualIndex p = fromIntegral <$> {#get CMeta->u.metaSubprogramInfo.virtualIndex#} p\ncMetaSubprogramContainingType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaSubprogramContainingType = optionalField {#get CMeta->u.metaSubprogramInfo.containingType#}\ncMetaSubprogramIsArtificial :: MetaPtr -> IO Bool\ncMetaSubprogramIsArtificial p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isArtificial#} p\ncMetaSubprogramIsPrivate :: MetaPtr -> IO Bool\ncMetaSubprogramIsPrivate p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isPrivate#} p\ncMetaSubprogramIsProtected :: MetaPtr -> IO Bool\ncMetaSubprogramIsProtected p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isProtected#} p\ncMetaSubprogramIsExplicit :: MetaPtr -> IO Bool\ncMetaSubprogramIsExplicit p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isExplicit#} p\ncMetaSubprogramIsPrototyped :: MetaPtr -> IO Bool\ncMetaSubprogramIsPrototyped p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isPrototyped#} p\ncMetaSubprogramIsOptimized :: MetaPtr -> IO Bool\ncMetaSubprogramIsOptimized p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isOptimized#} p\ncMetaTypeContext :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeContext = optionalField {#get CMeta->u.metaTypeInfo.context#}\ncMetaTypeName :: InternString m => MetaPtr -> m Text\ncMetaTypeName = shareString {#get CMeta->u.metaTypeInfo.name#}\n-- cMetaTypeCompileUnit :: MetaPtr -> IO (Maybe MetaPtr)\n-- cMetaTypeCompileUnit = optionalField {#get CMeta->u.metaTypeInfo.compileUnit#}\n-- cMetaTypeFile :: MetaPtr -> IO (Maybe MetaPtr)\n-- cMetaTypeFile = optionalField {#get CMeta->u.metaTypeInfo.file#}\ncMetaTypeLine :: MetaPtr -> IO Int32\ncMetaTypeLine p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.lineNumber#} p\ncMetaTypeSize :: MetaPtr -> IO Int64\ncMetaTypeSize p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.sizeInBits#} p\ncMetaTypeAlign :: MetaPtr -> IO Int64\ncMetaTypeAlign p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.alignInBits#} p\ncMetaTypeOffset :: MetaPtr -> IO Int64\ncMetaTypeOffset p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.offsetInBits#} p\ncMetaTypeFlags :: MetaPtr -> IO Int32\ncMetaTypeFlags p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.flags#} p\ncMetaTypeIsPrivate :: MetaPtr -> IO Bool\ncMetaTypeIsPrivate p = toBool <$> {#get CMeta->u.metaTypeInfo.isPrivate#} p\ncMetaTypeIsProtected :: MetaPtr -> IO Bool\ncMetaTypeIsProtected p = toBool <$> {#get CMeta->u.metaTypeInfo.isProtected#} p\ncMetaTypeIsForward :: MetaPtr -> IO Bool\ncMetaTypeIsForward p = toBool <$> {#get CMeta->u.metaTypeInfo.isForward#} p\ncMetaTypeIsByRefStruct :: MetaPtr -> IO Bool\ncMetaTypeIsByRefStruct p = toBool <$> {#get CMeta->u.metaTypeInfo.isByRefStruct#} p\ncMetaTypeIsVirtual :: MetaPtr -> IO Bool\ncMetaTypeIsVirtual p = toBool <$> {#get CMeta->u.metaTypeInfo.isVirtual#} p\ncMetaTypeIsArtificial :: MetaPtr -> IO Bool\ncMetaTypeIsArtificial p = toBool <$> {#get CMeta->u.metaTypeInfo.isArtificial#} p\ncMetaTypeDirectory :: InternString m => MetaPtr -> m Text\ncMetaTypeDirectory = shareString {#get CMeta->u.metaTypeInfo.directory#}\ncMetaTypeFilename :: InternString m => MetaPtr -> m Text\ncMetaTypeFilename = shareString {#get CMeta->u.metaTypeInfo.filename#}\ncMetaTypeEncoding :: MetaPtr -> IO DW_ATE\ncMetaTypeEncoding p = dw_ate <$> {#get CMeta->u.metaTypeInfo.encoding#} p\ncMetaTypeDerivedFrom :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeDerivedFrom = optionalField {#get CMeta->u.metaTypeInfo.typeDerivedFrom#}\ncMetaTypeCompositeComponents :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeCompositeComponents = optionalField {#get CMeta->u.metaTypeInfo.typeArray#}\ncMetaTypeRuntimeLanguage :: MetaPtr -> IO Int32\ncMetaTypeRuntimeLanguage p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.runTimeLang#} p\ncMetaTypeContainingType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeContainingType = optionalField {#get CMeta->u.metaTypeInfo.containingType#}\ncMetaTypeTemplateParams :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeTemplateParams = optionalField {#get CMeta->u.metaTypeInfo.templateParams#}\ncMetaUnknownRepr :: InternString m => MetaPtr -> m Text\ncMetaUnknownRepr = shareString {#get CMeta->u.metaUnknownInfo.repr#}\n\noptionalField :: (a -> IO (Ptr b)) -> a -> IO (Maybe (Ptr b))\noptionalField accessor p = do\n v <- accessor p\n case v == nullPtr of\n True -> return Nothing\n False -> return (Just v)\n\nclass MonadIO m => InternString m where\n internString :: Text -> m Text\n internIdentifier :: Identifier -> m Identifier\n\n-- | This helper converts C char* strings into Texts, sharing\n-- identical bytestrings on the Haskell side. This is a simple\n-- space-saving optimization (assuming the entire cache is garbage\n-- collected)\nshareString :: InternString m => (a -> IO CString) -> a -> m Text\nshareString accessor ptr = do\n sp <- liftIO $ accessor ptr\n str <- case sp == nullPtr of\n False -> liftIO $ BS.packCString sp\n True -> return $ BS.pack \"\"\n internString (decodeUtf8 str)\n\ndata CGlobalInfo\n{#pointer *CGlobalInfo as GlobalInfoPtr -> CGlobalInfo #}\ncGlobalIsExternal :: GlobalInfoPtr -> IO Bool\ncGlobalIsExternal g = toBool <$> ({#get CGlobalInfo->isExternal#} g)\ncGlobalAlignment :: GlobalInfoPtr -> IO Int64\ncGlobalAlignment g = fromIntegral <$> ({#get CGlobalInfo->alignment#} g)\ncGlobalVisibility :: GlobalInfoPtr -> IO VisibilityStyle\ncGlobalVisibility g = toEnum . fromIntegral <$> ({#get CGlobalInfo->visibility#} g)\ncGlobalLinkage :: GlobalInfoPtr -> IO LinkageType\ncGlobalLinkage g = toEnum . fromIntegral <$> ({#get CGlobalInfo->linkage#} g)\ncGlobalSection :: GlobalInfoPtr -> IO (Maybe Text)\ncGlobalSection g = do\n s <- {#get CGlobalInfo->section#} g\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just (decodeUtf8 bs)\ncGlobalInitializer :: GlobalInfoPtr -> IO ValuePtr\ncGlobalInitializer = {#get CGlobalInfo->initializer#}\ncGlobalIsThreadLocal :: GlobalInfoPtr -> IO Bool\ncGlobalIsThreadLocal g = toBool <$> ({#get CGlobalInfo->isThreadLocal#} g)\ncGlobalAliasee :: GlobalInfoPtr -> IO ValuePtr\ncGlobalAliasee = {#get CGlobalInfo->aliasee#}\ncGlobalIsConstant :: GlobalInfoPtr -> IO Bool\ncGlobalIsConstant g = toBool <$> {#get CGlobalInfo->isConstant#} g\n\ndata CFunctionInfo\n{#pointer *CFunctionInfo as FunctionInfoPtr -> CFunctionInfo #}\ncFunctionIsExternal :: FunctionInfoPtr -> IO Bool\ncFunctionIsExternal f = toBool <$> {#get CFunctionInfo->isExternal#} f\ncFunctionAlignment :: FunctionInfoPtr -> IO Int64\ncFunctionAlignment f = fromIntegral <$> {#get CFunctionInfo->alignment#} f\ncFunctionVisibility :: FunctionInfoPtr -> IO VisibilityStyle\ncFunctionVisibility f = toEnum . fromIntegral <$> {#get CFunctionInfo->visibility#} f\ncFunctionLinkage :: FunctionInfoPtr -> IO LinkageType\ncFunctionLinkage f = toEnum . fromIntegral <$> {#get CFunctionInfo->linkage#} f\ncFunctionSection :: FunctionInfoPtr -> IO (Maybe Text)\ncFunctionSection f = do\n s <- {#get CFunctionInfo->section#} f\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just (decodeUtf8 bs)\ncFunctionIsVarArg :: FunctionInfoPtr -> IO Bool\ncFunctionIsVarArg f = toBool <$> {#get CFunctionInfo->isVarArg#} f\ncFunctionCallingConvention :: FunctionInfoPtr -> IO CallingConvention\ncFunctionCallingConvention f = toEnum . fromIntegral <$> {#get CFunctionInfo->callingConvention#} f\ncFunctionGCName :: FunctionInfoPtr -> IO (Maybe Text)\ncFunctionGCName f = do\n s <- {#get CFunctionInfo->gcName#} f\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just (decodeUtf8 bs)\ncFunctionArguments :: FunctionInfoPtr -> IO [ValuePtr]\ncFunctionArguments f =\n peekArray f {#get CFunctionInfo->arguments#} {#get CFunctionInfo->argListLen#}\ncFunctionBlocks :: FunctionInfoPtr -> IO [ValuePtr]\ncFunctionBlocks f =\n peekArray f {#get CFunctionInfo->body#} {#get CFunctionInfo->blockListLen#}\n\ndata CArgInfo\n{#pointer *CArgumentInfo as ArgInfoPtr -> CArgInfo #}\ncArgInfoHasSRet :: ArgInfoPtr -> IO Bool\ncArgInfoHasSRet a = toBool <$> ({#get CArgumentInfo->hasSRet#} a)\ncArgInfoHasByVal :: ArgInfoPtr -> IO Bool\ncArgInfoHasByVal a = toBool <$> ({#get CArgumentInfo->hasByVal#} a)\ncArgInfoHasNest :: ArgInfoPtr -> IO Bool\ncArgInfoHasNest a = toBool <$> ({#get CArgumentInfo->hasNest#} a)\ncArgInfoHasNoAlias :: ArgInfoPtr -> IO Bool\ncArgInfoHasNoAlias a = toBool <$> ({#get CArgumentInfo->hasNoAlias#} a)\ncArgInfoHasNoCapture :: ArgInfoPtr -> IO Bool\ncArgInfoHasNoCapture a = toBool <$> ({#get CArgumentInfo->hasNoCapture#} a)\n\ndata CBasicBlockInfo\n{#pointer *CBasicBlockInfo as BasicBlockPtr -> CBasicBlockInfo #}\n\ncBasicBlockInstructions :: BasicBlockPtr -> IO [ValuePtr]\ncBasicBlockInstructions b =\n peekArray b {#get CBasicBlockInfo->instructions#} {#get CBasicBlockInfo->blockLen#}\n\ndata CInlineAsmInfo\n{#pointer *CInlineAsmInfo as InlineAsmInfoPtr -> CInlineAsmInfo #}\n\ncInlineAsmString :: InlineAsmInfoPtr -> IO Text\ncInlineAsmString a =\n ({#get CInlineAsmInfo->asmString#} a) >>= makeText\ncInlineAsmConstraints :: InlineAsmInfoPtr -> IO Text\ncInlineAsmConstraints a =\n ({#get CInlineAsmInfo->constraintString#} a) >>= makeText\n\ndata CBlockAddrInfo\n{#pointer *CBlockAddrInfo as BlockAddrInfoPtr -> CBlockAddrInfo #}\n\ncBlockAddrFunc :: BlockAddrInfoPtr -> IO ValuePtr\ncBlockAddrFunc = {#get CBlockAddrInfo->func #}\ncBlockAddrBlock :: BlockAddrInfoPtr -> IO ValuePtr\ncBlockAddrBlock = {#get CBlockAddrInfo->block #}\n\ndata CAggregateInfo\n{#pointer *CConstAggregate as AggregateInfoPtr -> CAggregateInfo #}\n\ncAggregateValues :: AggregateInfoPtr -> IO [ValuePtr]\ncAggregateValues a =\n peekArray a {#get CConstAggregate->constants#} {#get CConstAggregate->numElements#}\n\ndata CConstFP\n{#pointer *CConstFP as FPInfoPtr -> CConstFP #}\ncFPVal :: FPInfoPtr -> IO Double\ncFPVal f = realToFrac <$> ({#get CConstFP->val#} f)\n\ndata CConstInt\n{#pointer *CConstInt as IntInfoPtr -> CConstInt #}\ncIntVal :: IntInfoPtr -> IO Integer\ncIntVal i = fromIntegral <$> ({#get CConstInt->val#} i)\ncIntHugeVal :: IntInfoPtr -> IO (Maybe Integer)\ncIntHugeVal i = do\n s <- {#get CConstInt->hugeVal#} i\n case s == nullPtr of\n True -> return Nothing\n False -> (Just . read) <$> peekCString s\n\ndata CInstructionInfo\n{#pointer *CInstructionInfo as InstInfoPtr -> CInstructionInfo #}\ncInstructionOperands :: InstInfoPtr -> IO [ValuePtr]\ncInstructionOperands i =\n peekArray i {#get CInstructionInfo->operands#} {#get CInstructionInfo->numOperands#}\ncInstructionArithFlags :: InstInfoPtr -> IO ArithFlags\ncInstructionArithFlags o = toEnum . fromIntegral <$> {#get CInstructionInfo->flags#} o\ncInstructionAlign :: InstInfoPtr -> IO Int64\ncInstructionAlign u = fromIntegral <$> {#get CInstructionInfo->align#} u\ncInstructionIsVolatile :: InstInfoPtr -> IO Bool\ncInstructionIsVolatile u = toBool <$> {#get CInstructionInfo->isVolatile#} u\ncInstructionAddrSpace :: InstInfoPtr -> IO Int\ncInstructionAddrSpace u = fromIntegral <$> {#get CInstructionInfo->addrSpace#} u\ncInstructionCmpPred :: InstInfoPtr -> IO CmpPredicate\ncInstructionCmpPred c = toEnum . fromIntegral <$> {#get CInstructionInfo->cmpPred#} c\ncInstructionInBounds :: InstInfoPtr -> IO Bool\ncInstructionInBounds g = toBool <$> {#get CInstructionInfo->inBounds#} g\ncInstructionIndices :: InstInfoPtr -> IO [Int]\ncInstructionIndices i =\n peekArray i {#get CInstructionInfo->indices#} {#get CInstructionInfo->numIndices#}\n\ndata CConstExprInfo\n{#pointer *CConstExprInfo as ConstExprPtr -> CConstExprInfo #}\ncConstExprTag :: ConstExprPtr -> IO ValueTag\ncConstExprTag e = toEnum . fromIntegral <$> {#get CConstExprInfo->instrType#} e\ncConstExprInstInfo :: ConstExprPtr -> IO InstInfoPtr\ncConstExprInstInfo = {#get CConstExprInfo->ii#}\n\ndata CPHIInfo\n{#pointer *CPHIInfo as PHIInfoPtr -> CPHIInfo #}\ncPHIValues :: PHIInfoPtr -> IO [ValuePtr]\ncPHIValues p =\n peekArray p {#get CPHIInfo->incomingValues#} {#get CPHIInfo->numIncomingValues#}\ncPHIBlocks :: PHIInfoPtr -> IO [ValuePtr]\ncPHIBlocks p =\n peekArray p {#get CPHIInfo->valueBlocks#} {#get CPHIInfo->numIncomingValues#}\n\ndata CCallInfo\n{#pointer *CCallInfo as CallInfoPtr -> CCallInfo #}\ncCallValue :: CallInfoPtr -> IO ValuePtr\ncCallValue = {#get CCallInfo->calledValue #}\ncCallArguments :: CallInfoPtr -> IO [ValuePtr]\ncCallArguments c =\n peekArray c {#get CCallInfo->arguments#} {#get CCallInfo->argListLen#}\ncCallConvention :: CallInfoPtr -> IO CallingConvention\ncCallConvention c = toEnum . fromIntegral <$> {#get CCallInfo->callingConvention#} c\ncCallHasSRet :: CallInfoPtr -> IO Bool\ncCallHasSRet c = toBool <$> {#get CCallInfo->hasSRet#} c\ncCallIsTail :: CallInfoPtr -> IO Bool\ncCallIsTail c = toBool <$> {#get CCallInfo->isTail#} c\ncCallUnwindDest :: CallInfoPtr -> IO ValuePtr\ncCallUnwindDest = {#get CCallInfo->unwindDest#}\ncCallNormalDest :: CallInfoPtr -> IO ValuePtr\ncCallNormalDest = {#get CCallInfo->normalDest#}\n\ndata CAtomicInfo\n{#pointer *CAtomicInfo as AtomicInfoPtr -> CAtomicInfo #}\ncAtomicOrdering :: AtomicInfoPtr -> IO AtomicOrdering\ncAtomicOrdering ai = toEnum . fromIntegral <$> {#get CAtomicInfo->ordering#} ai\ncAtomicScope :: AtomicInfoPtr -> IO SynchronizationScope\ncAtomicScope ai = toEnum . fromIntegral <$> {#get CAtomicInfo->scope#} ai\ncAtomicOperation :: AtomicInfoPtr -> IO AtomicOperation\ncAtomicOperation ai = toEnum . fromIntegral <$> {#get CAtomicInfo->operation#} ai\ncAtomicIsVolatile :: AtomicInfoPtr -> IO Bool\ncAtomicIsVolatile ai = toBool <$> {#get CAtomicInfo->isVolatile#} ai\ncAtomicAddressSpace :: AtomicInfoPtr -> IO Int\ncAtomicAddressSpace ai = fromIntegral <$> {#get CAtomicInfo->addrSpace#} ai\ncAtomicPointerOperand :: AtomicInfoPtr -> IO ValuePtr\ncAtomicPointerOperand = {#get CAtomicInfo->pointerOperand#}\ncAtomicValueOperand :: AtomicInfoPtr -> IO ValuePtr\ncAtomicValueOperand = {#get CAtomicInfo->valueOperand#}\ncAtomicCompareOperand :: AtomicInfoPtr -> IO ValuePtr\ncAtomicCompareOperand = {#get CAtomicInfo->compareOperand#}\n\ndata CLandingPadInfo\n{#pointer *CLandingPadInfo as LandingPadInfoPtr -> CLandingPadInfo#}\ncLandingPadPersonality :: LandingPadInfoPtr -> IO ValuePtr\ncLandingPadPersonality = {#get CLandingPadInfo->personality#}\ncLandingPadIsCleanup :: LandingPadInfoPtr -> IO Bool\ncLandingPadIsCleanup li = toBool <$> {#get CLandingPadInfo->isCleanup#} li\ncLandingPadClauses :: LandingPadInfoPtr -> IO [ValuePtr]\ncLandingPadClauses li =\n peekArray li {#get CLandingPadInfo->clauses #} {#get CLandingPadInfo->numClauses#}\ncLandingPadClauseTypes :: LandingPadInfoPtr -> IO [LandingPadClause]\ncLandingPadClauseTypes li = do\n arr <- peekArray li {#get CLandingPadInfo->clauseTypes #} {#get CLandingPadInfo->numClauses#}\n return $ map toEnum arr\n\n-- | Parse the named file into an FFI-friendly representation of an\n-- LLVM module.\n{#fun marshalLLVM { id `Ptr CChar', `Int', fromBool `Bool' } -> `ModulePtr' id #}\n{#fun marshalLLVMFile { `String', fromBool `Bool' } -> `ModulePtr' id #}\n\n-- | Free all of the resources allocated by 'marshalLLVM'\n{#fun disposeCModule { id `ModulePtr' } -> `()' #}\n\n-- Helpers\n\n-- This only seems to be necessary on i386 for some reason.\ncIntConv :: (Integral a, Num b) => a -> b\ncIntConv = fromIntegral\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, RankNTypes, OverloadedStrings, CPP #-}\nmodule LLVM.Internal.Interop where\n\nimport Control.Applicative\nimport Control.Monad ( when )\nimport Control.Monad.Trans ( MonadIO, liftIO )\nimport Data.Array.Storable ( getElems )\n#if __GLASGOW_HASKELL__ >= 704\nimport Data.Array.Unsafe ( unsafeForeignPtrToStorableArray )\n#else\nimport Data.Array.Storable ( unsafeForeignPtrToStorableArray )\n#endif\nimport qualified Data.ByteString.Char8 as BS\nimport Data.Int\nimport Data.Text ( Text )\nimport Data.Text.Encoding ( decodeUtf8 )\nimport Foreign.C\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\n\nimport Data.LLVM.Types\n\n#include \"c++\/marshal.h\"\n\n{#enum TypeTag {} deriving (Show, Eq) #}\n{#enum ValueTag {underscoreToCase} deriving (Show, Eq) #}\n{#enum MetaTag {underscoreToCase} deriving (Show, Eq) #}\n\ndata CModule\n{#pointer *CModule as ModulePtr -> CModule #}\n\nmakeText :: CString -> IO Text\nmakeText p = do\n s <- BS.packCString p\n return (decodeUtf8 s)\n\ncModuleIdentifier :: ModulePtr -> IO Text\ncModuleIdentifier m = ({#get CModule->moduleIdentifier#} m) >>= makeText\n\ncModuleDataLayout :: ModulePtr -> IO Text\ncModuleDataLayout m = ({#get CModule->moduleDataLayout#} m) >>= makeText\n\ncModuleTargetTriple :: ModulePtr -> IO Text\ncModuleTargetTriple m = ({#get CModule->targetTriple#} m) >>= makeText\n\ncModuleInlineAsm :: ModulePtr -> IO Text\ncModuleInlineAsm m = ({#get CModule->moduleInlineAsm#} m) >>= makeText\n\ncModuleHasError :: ModulePtr -> IO Bool\ncModuleHasError m = toBool <$> ({#get CModule->hasError#} m)\n\ncModuleErrorMessage :: ModulePtr -> IO (Maybe String)\ncModuleErrorMessage m = do\n hasError <- cModuleHasError m\n case hasError of\n True -> do\n msgPtr <- ({#get CModule->errMsg#} m)\n s <- peekCString msgPtr\n return (Just s)\n False -> return Nothing\n\ncModuleLittleEndian :: ModulePtr -> IO Bool\ncModuleLittleEndian m = toBool <$> ({#get CModule->littleEndian#} m)\n\ncModulePointerSize :: ModulePtr -> IO Int\ncModulePointerSize m = fromIntegral <$> ({#get CModule->pointerSize#} m)\n\ncModuleGlobalVariables :: ModulePtr -> IO [ValuePtr]\ncModuleGlobalVariables m =\n peekArray m {#get CModule->globalVariables#} {#get CModule->numGlobalVariables#}\n\ncModuleGlobalAliases :: ModulePtr -> IO [ValuePtr]\ncModuleGlobalAliases m =\n peekArray m ({#get CModule->globalAliases#}) ({#get CModule->numGlobalAliases#})\n\ncModuleFunctions :: ModulePtr -> IO [ValuePtr]\ncModuleFunctions m =\n peekArray m ({#get CModule->functions#}) ({#get CModule->numFunctions#})\n\ncModuleEnumMetadata :: ModulePtr -> IO [MetaPtr]\ncModuleEnumMetadata m =\n peekArray m {#get CModule->enumMetadata#} {#get CModule->numEnumMetadata#}\n\ncModuleRetainedTypeMetadata :: ModulePtr -> IO [MetaPtr]\ncModuleRetainedTypeMetadata m =\n peekArray m {#get CModule->retainedTypeMetadata#} {#get CModule->numRetainedTypes#}\n\ncModuleTypes :: ModulePtr -> IO [TypePtr]\ncModuleTypes m =\n peekArray m {#get CModule->types#} {#get CModule->numTypes#}\n\npeekArray :: forall a b c e . (Integral c, Storable e) =>\n a -> (a -> IO (Ptr b)) -> (a -> IO c) -> IO [e]\npeekArray obj arrAccessor sizeAccessor = do\n nElts <- sizeAccessor obj\n arrPtr <- arrAccessor obj\n case nElts == 0 || arrPtr == nullPtr of\n True -> return []\n False -> do\n fArrPtr <- newForeignPtr_ (castPtr arrPtr)\n let elementCount :: Int\n elementCount = fromIntegral nElts\n arr <- unsafeForeignPtrToStorableArray fArrPtr (1, elementCount)\n getElems arr\n\ndata CType\n{#pointer *CType as TypePtr -> CType #}\ncTypeTag :: TypePtr -> IO TypeTag\ncTypeTag t = toEnum . fromIntegral <$> {#get CType->typeTag#} t\ncTypeSize :: TypePtr -> IO Int\ncTypeSize t = fromIntegral <$> {#get CType->size#} t\ncTypeIsVarArg :: TypePtr -> IO Bool\ncTypeIsVarArg t = toBool <$> {#get CType->isVarArg#} t\ncTypeIsPacked :: TypePtr -> IO Bool\ncTypeIsPacked t = toBool <$> {#get CType->isPacked#} t\ncTypeList :: TypePtr -> IO [TypePtr]\ncTypeList t =\n peekArray t {#get CType->typeList#} {#get CType->typeListLen#}\ncTypeInner :: TypePtr -> IO TypePtr\ncTypeInner = {#get CType->innerType#}\ncTypeName :: TypePtr -> IO (Maybe String)\ncTypeName t = do\n n <- optionalField {#get CType->name#} t\n case n of\n Nothing -> return Nothing\n Just n' -> do\n s <- peekCString n'\n return (Just s)\ncTypeAddrSpace :: TypePtr -> IO Int\ncTypeAddrSpace t = fromIntegral <$> {#get CType->addrSpace#} t\n\ncTypeSizeInBytes :: TypePtr -> IO Int\ncTypeSizeInBytes t = fromIntegral <$> {#get CType->sizeInBytes#} t\n\ndata CValue\n{#pointer *CValue as ValuePtr -> CValue #}\ndata CMeta\n{#pointer *CMeta as MetaPtr -> CMeta #}\n\ncValueTag :: ValuePtr -> IO ValueTag\ncValueTag v = toEnum . fromIntegral <$> ({#get CValue->valueTag#} v)\ncValueType :: ValuePtr -> IO TypePtr\ncValueType = {#get CValue->valueType#}\ncValueName :: (InternString m) => ValuePtr -> m (Maybe Identifier)\ncValueName v = do\n tag <- liftIO $ cValueTag v\n namePtr <- liftIO $ ({#get CValue->name#}) v\n case namePtr == nullPtr of\n True -> return Nothing\n False -> do\n rawName <- liftIO $ makeText namePtr\n name <- internString rawName\n rawIdent <- case tag of\n ValFunction -> return $! makeGlobalIdentifier name\n ValGlobalvariable -> return $! makeGlobalIdentifier name\n ValAlias -> return $! makeGlobalIdentifier name\n _ -> return $! makeLocalIdentifier name\n ident <- internIdentifier rawIdent\n return $! (Just ident)\ncValueMetadata :: ValuePtr -> IO [MetaPtr]\ncValueMetadata v = peekArray v {#get CValue->md#} {#get CValue->numMetadata#}\ncValueSrcLoc :: ValuePtr -> IO MetaPtr\ncValueSrcLoc = {#get CValue->srcLoc#}\ncValueData :: ValuePtr -> IO (Ptr ())\ncValueData = {#get CValue->data#}\n\n\ncMetaTypeTag :: MetaPtr -> IO MetaTag\ncMetaTypeTag v = toEnum . fromIntegral <$> {#get CMeta->metaTag #} v\n\ncMetaTag :: MetaPtr -> IO DW_TAG\ncMetaTag p = do\n t <- {#get CMeta->tag#} p\n case dw_tag t of\n Nothing -> return DW_TAG_unspecified_type\n Just t' -> return t'\n\ncMetaArrayElts :: MetaPtr -> IO [Maybe MetaPtr]\ncMetaArrayElts p = map convertNull <$>\n peekArray p {#get CMeta->u.metaArrayInfo.arrayElts#} {#get CMeta->u.metaArrayInfo.arrayLen#}\n where\n convertNull ptr =\n case ptr == nullPtr of\n True -> Nothing\n False -> Just ptr\n\ncMetaEnumeratorName :: InternString m => MetaPtr -> m Text\ncMetaEnumeratorName = shareString {#get CMeta->u.metaEnumeratorInfo.enumName#}\ncMetaEnumeratorValue :: MetaPtr -> IO Int64\ncMetaEnumeratorValue p = fromIntegral <$> {#get CMeta->u.metaEnumeratorInfo.enumValue#} p\ncMetaGlobalContext :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaGlobalContext = optionalField {#get CMeta->u.metaGlobalInfo.context #}\ncMetaGlobalName :: InternString m => MetaPtr -> m Text\ncMetaGlobalName = shareString {#get CMeta->u.metaGlobalInfo.name#}\ncMetaGlobalDisplayName :: InternString m => MetaPtr -> m Text\ncMetaGlobalDisplayName = shareString {#get CMeta->u.metaGlobalInfo.displayName#}\ncMetaGlobalLinkageName :: InternString m => MetaPtr -> m Text\ncMetaGlobalLinkageName = shareString {#get CMeta->u.metaGlobalInfo.linkageName#}\n-- cMetaGlobalCompileUnit :: MetaPtr -> IO MetaPtr\n-- cMetaGlobalCompileUnit = {#get CMeta->u.metaGlobalInfo.compileUnit#}\ncMetaGlobalLine :: MetaPtr -> IO Int32\ncMetaGlobalLine p = fromIntegral <$> {#get CMeta->u.metaGlobalInfo.lineNumber#} p\ncMetaGlobalType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaGlobalType = optionalField {#get CMeta->u.metaGlobalInfo.globalType#}\ncMetaGlobalIsLocal :: MetaPtr -> IO Bool\ncMetaGlobalIsLocal p = toBool <$> {#get CMeta->u.metaGlobalInfo.isLocalToUnit#} p\ncMetaGlobalIsDefinition :: MetaPtr -> IO Bool\ncMetaGlobalIsDefinition p = toBool <$> {#get CMeta->u.metaGlobalInfo.isDefinition#} p\ncMetaLocationLine :: MetaPtr -> IO Int32\ncMetaLocationLine p = fromIntegral <$> {#get CMeta->u.metaLocationInfo.lineNumber#} p\ncMetaLocationColumn :: MetaPtr -> IO Int32\ncMetaLocationColumn p = fromIntegral <$> {#get CMeta->u.metaLocationInfo.columnNumber#} p\ncMetaLocationScope :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaLocationScope = optionalField {#get CMeta->u.metaLocationInfo.scope#}\ncMetaSubrangeLo :: MetaPtr -> IO Int64\ncMetaSubrangeLo p = fromIntegral <$> {#get CMeta->u.metaSubrangeInfo.lo#} p\ncMetaSubrangeHi :: MetaPtr -> IO Int64\ncMetaSubrangeHi p = fromIntegral <$> {#get CMeta->u.metaSubrangeInfo.hi#} p\ncMetaTemplateTypeContext :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTemplateTypeContext = optionalField {#get CMeta->u.metaTemplateTypeInfo.context#}\ncMetaTemplateTypeName :: InternString m => MetaPtr -> m Text\ncMetaTemplateTypeName = shareString {#get CMeta->u.metaTemplateTypeInfo.name#}\ncMetaTemplateTypeType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTemplateTypeType = optionalField {#get CMeta->u.metaTemplateTypeInfo.type#}\ncMetaTemplateTypeLine :: MetaPtr -> IO Int32\ncMetaTemplateTypeLine p = fromIntegral <$> {#get CMeta->u.metaTemplateTypeInfo.lineNumber#} p\ncMetaTemplateTypeColumn :: MetaPtr -> IO Int32\ncMetaTemplateTypeColumn p = fromIntegral <$> {#get CMeta->u.metaTemplateTypeInfo.columnNumber#} p\ncMetaTemplateValueContext :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTemplateValueContext = optionalField {#get CMeta->u.metaTemplateValueInfo.context#}\ncMetaTemplateValueName :: InternString m => MetaPtr -> m Text\ncMetaTemplateValueName = shareString {#get CMeta->u.metaTemplateValueInfo.name#}\ncMetaTemplateValueType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTemplateValueType = optionalField {#get CMeta->u.metaTemplateValueInfo.type#}\ncMetaTemplateValueValue :: MetaPtr -> IO Int64\ncMetaTemplateValueValue p = fromIntegral <$> {#get CMeta->u.metaTemplateValueInfo.value#} p\ncMetaTemplateValueLine :: MetaPtr -> IO Int32\ncMetaTemplateValueLine p = fromIntegral <$> {#get CMeta->u.metaTemplateValueInfo.lineNumber#} p\ncMetaTemplateValueColumn :: MetaPtr -> IO Int32\ncMetaTemplateValueColumn p = fromIntegral <$> {#get CMeta->u.metaTemplateValueInfo.columnNumber#} p\ncMetaVariableContext :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaVariableContext = optionalField {#get CMeta->u.metaVariableInfo.context#}\ncMetaVariableName :: InternString m => MetaPtr -> m Text\ncMetaVariableName = shareString {#get CMeta->u.metaVariableInfo.name#}\n-- cMetaVariableCompileUnit :: MetaPtr -> IO MetaPtr\n-- cMetaVariableCompileUnit = {#get CMeta->u.metaVariableInfo.compileUnit#}\ncMetaVariableLine :: MetaPtr -> IO Int32\ncMetaVariableLine p = fromIntegral <$> {#get CMeta->u.metaVariableInfo.lineNumber#} p\ncMetaVariableArgNumber :: MetaPtr -> IO Int32\ncMetaVariableArgNumber p = fromIntegral <$> {#get CMeta->u.metaVariableInfo.argNumber#} p\ncMetaVariableType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaVariableType = optionalField {#get CMeta->u.metaVariableInfo.type#}\ncMetaVariableIsArtificial :: MetaPtr -> IO Bool\ncMetaVariableIsArtificial p = toBool <$> {#get CMeta->u.metaVariableInfo.isArtificial#} p\ncMetaVariableHasComplexAddress :: MetaPtr -> IO Bool\ncMetaVariableHasComplexAddress p = toBool <$> {#get CMeta->u.metaVariableInfo.hasComplexAddress #} p\ncMetaVariableAddrElements :: MetaPtr -> IO [Int64]\ncMetaVariableAddrElements p = do\n ca <- cMetaVariableHasComplexAddress p\n case ca of\n True -> peekArray p {#get CMeta->u.metaVariableInfo.addrElements#} {#get CMeta->u.metaVariableInfo.numAddrElements#}\n False -> return []\ncMetaVariableIsBlockByRefVar :: MetaPtr -> IO Bool\ncMetaVariableIsBlockByRefVar p = toBool <$> {#get CMeta->u.metaVariableInfo.isBlockByRefVar#} p\ncMetaCompileUnitLanguage :: MetaPtr -> IO DW_LANG\ncMetaCompileUnitLanguage p = dw_lang <$> {#get CMeta->u.metaCompileUnitInfo.language#} p\ncMetaCompileUnitFilename :: InternString m => MetaPtr -> m Text\ncMetaCompileUnitFilename = shareString {#get CMeta->u.metaCompileUnitInfo.filename#}\ncMetaCompileUnitDirectory :: InternString m => MetaPtr -> m Text\ncMetaCompileUnitDirectory = shareString {#get CMeta->u.metaCompileUnitInfo.directory#}\ncMetaCompileUnitProducer :: InternString m => MetaPtr -> m Text\ncMetaCompileUnitProducer = shareString {#get CMeta->u.metaCompileUnitInfo.producer#}\ncMetaCompileUnitIsMain :: MetaPtr -> IO Bool\ncMetaCompileUnitIsMain p = toBool <$> {#get CMeta->u.metaCompileUnitInfo.isMain#} p\ncMetaCompileUnitIsOptimized :: MetaPtr -> IO Bool\ncMetaCompileUnitIsOptimized p = toBool <$> {#get CMeta->u.metaCompileUnitInfo.isOptimized#} p\ncMetaCompileUnitFlags :: InternString m => MetaPtr -> m Text\ncMetaCompileUnitFlags = shareString {#get CMeta->u.metaCompileUnitInfo.flags#}\ncMetaCompileUnitRuntimeVersion :: MetaPtr -> IO Int32\ncMetaCompileUnitRuntimeVersion p = fromIntegral <$> {#get CMeta->u.metaCompileUnitInfo.runtimeVersion#} p\ncMetaCompileUnitEnumTypes :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaCompileUnitEnumTypes = optionalField {#get CMeta->u.metaCompileUnitInfo.enumTypes#}\ncMetaCompileUnitRetainedTypes :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaCompileUnitRetainedTypes = optionalField {#get CMeta->u.metaCompileUnitInfo.retainedTypes#}\ncMetaCompileUnitSubprograms :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaCompileUnitSubprograms = optionalField {#get CMeta->u.metaCompileUnitInfo.subprograms#}\ncMetaCompileUnitGlobalVariables :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaCompileUnitGlobalVariables = optionalField {#get CMeta->u.metaCompileUnitInfo.globalVariables#}\ncMetaFileFilename :: InternString m => MetaPtr -> m Text\ncMetaFileFilename = shareString {#get CMeta->u.metaFileInfo.filename#}\ncMetaFileDirectory :: InternString m => MetaPtr -> m Text\ncMetaFileDirectory = shareString {#get CMeta->u.metaFileInfo.directory#}\n-- cMetaFileCompileUnit :: MetaPtr -> IO MetaPtr\n-- cMetaFileCompileUnit = {#get CMeta->u.metaFileInfo.compileUnit#}\ncMetaLexicalBlockContext :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaLexicalBlockContext = optionalField {#get CMeta->u.metaLexicalBlockInfo.context#}\ncMetaLexicalBlockLine :: MetaPtr -> IO Int32\ncMetaLexicalBlockLine p = fromIntegral <$> {#get CMeta->u.metaLexicalBlockInfo.lineNumber#} p\ncMetaLexicalBlockColumn :: MetaPtr -> IO Int32\ncMetaLexicalBlockColumn p = fromIntegral <$> {#get CMeta->u.metaLexicalBlockInfo.columnNumber#} p\ncMetaNamespaceContext :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaNamespaceContext = optionalField {#get CMeta->u.metaNamespaceInfo.context#}\ncMetaNamespaceName :: InternString m => MetaPtr -> m Text\ncMetaNamespaceName = shareString {#get CMeta->u.metaNamespaceInfo.name#}\n-- cMetaNamespaceCompileUnit :: MetaPtr -> IO MetaPtr\n-- cMetaNamespaceCompileUnit = {#get CMeta->u.metaNamespaceInfo.compileUnit#}\ncMetaNamespaceLine :: MetaPtr -> IO Int32\ncMetaNamespaceLine p = fromIntegral <$> {#get CMeta->u.metaNamespaceInfo.lineNumber#} p\ncMetaSubprogramContext :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaSubprogramContext = optionalField {#get CMeta->u.metaSubprogramInfo.context#}\ncMetaSubprogramName :: InternString m => MetaPtr -> m Text\ncMetaSubprogramName = shareString {#get CMeta->u.metaSubprogramInfo.name#}\ncMetaSubprogramDisplayName :: InternString m => MetaPtr -> m Text\ncMetaSubprogramDisplayName = shareString {#get CMeta->u.metaSubprogramInfo.displayName#}\ncMetaSubprogramLinkageName :: InternString m => MetaPtr -> m Text\ncMetaSubprogramLinkageName = shareString {#get CMeta->u.metaSubprogramInfo.linkageName#}\n-- cMetaSubprogramCompileUnit :: MetaPtr -> IO MetaPtr\n-- cMetaSubprogramCompileUnit = {#get CMeta->u.metaSubprogramInfo.compileUnit#}\ncMetaSubprogramLine :: MetaPtr -> IO Int32\ncMetaSubprogramLine p = fromIntegral <$> {#get CMeta->u.metaSubprogramInfo.lineNumber#} p\ncMetaSubprogramType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaSubprogramType = optionalField {#get CMeta->u.metaSubprogramInfo.type#}\ncMetaSubprogramIsLocal :: MetaPtr -> IO Bool\ncMetaSubprogramIsLocal p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isLocalToUnit#} p\ncMetaSubprogramIsDefinition :: MetaPtr -> IO Bool\ncMetaSubprogramIsDefinition p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isDefinition#} p\ncMetaSubprogramVirtuality :: MetaPtr -> IO DW_VIRTUALITY\ncMetaSubprogramVirtuality p = dw_virtuality <$> {#get CMeta->u.metaSubprogramInfo.virtuality#} p\ncMetaSubprogramVirtualIndex :: MetaPtr -> IO Int32\ncMetaSubprogramVirtualIndex p = fromIntegral <$> {#get CMeta->u.metaSubprogramInfo.virtualIndex#} p\ncMetaSubprogramContainingType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaSubprogramContainingType = optionalField {#get CMeta->u.metaSubprogramInfo.containingType#}\ncMetaSubprogramIsArtificial :: MetaPtr -> IO Bool\ncMetaSubprogramIsArtificial p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isArtificial#} p\ncMetaSubprogramIsPrivate :: MetaPtr -> IO Bool\ncMetaSubprogramIsPrivate p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isPrivate#} p\ncMetaSubprogramIsProtected :: MetaPtr -> IO Bool\ncMetaSubprogramIsProtected p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isProtected#} p\ncMetaSubprogramIsExplicit :: MetaPtr -> IO Bool\ncMetaSubprogramIsExplicit p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isExplicit#} p\ncMetaSubprogramIsPrototyped :: MetaPtr -> IO Bool\ncMetaSubprogramIsPrototyped p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isPrototyped#} p\ncMetaSubprogramIsOptimized :: MetaPtr -> IO Bool\ncMetaSubprogramIsOptimized p = toBool <$> {#get CMeta->u.metaSubprogramInfo.isOptimized#} p\ncMetaTypeContext :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeContext = optionalField {#get CMeta->u.metaTypeInfo.context#}\ncMetaTypeName :: InternString m => MetaPtr -> m Text\ncMetaTypeName = shareString {#get CMeta->u.metaTypeInfo.name#}\n-- cMetaTypeCompileUnit :: MetaPtr -> IO (Maybe MetaPtr)\n-- cMetaTypeCompileUnit = optionalField {#get CMeta->u.metaTypeInfo.compileUnit#}\n-- cMetaTypeFile :: MetaPtr -> IO (Maybe MetaPtr)\n-- cMetaTypeFile = optionalField {#get CMeta->u.metaTypeInfo.file#}\ncMetaTypeLine :: MetaPtr -> IO Int32\ncMetaTypeLine p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.lineNumber#} p\ncMetaTypeSize :: MetaPtr -> IO Int64\ncMetaTypeSize p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.sizeInBits#} p\ncMetaTypeAlign :: MetaPtr -> IO Int64\ncMetaTypeAlign p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.alignInBits#} p\ncMetaTypeOffset :: MetaPtr -> IO Int64\ncMetaTypeOffset p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.offsetInBits#} p\ncMetaTypeFlags :: MetaPtr -> IO Int32\ncMetaTypeFlags p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.flags#} p\ncMetaTypeIsPrivate :: MetaPtr -> IO Bool\ncMetaTypeIsPrivate p = toBool <$> {#get CMeta->u.metaTypeInfo.isPrivate#} p\ncMetaTypeIsProtected :: MetaPtr -> IO Bool\ncMetaTypeIsProtected p = toBool <$> {#get CMeta->u.metaTypeInfo.isProtected#} p\ncMetaTypeIsForward :: MetaPtr -> IO Bool\ncMetaTypeIsForward p = toBool <$> {#get CMeta->u.metaTypeInfo.isForward#} p\ncMetaTypeIsByRefStruct :: MetaPtr -> IO Bool\ncMetaTypeIsByRefStruct p = toBool <$> {#get CMeta->u.metaTypeInfo.isByRefStruct#} p\ncMetaTypeIsVirtual :: MetaPtr -> IO Bool\ncMetaTypeIsVirtual p = toBool <$> {#get CMeta->u.metaTypeInfo.isVirtual#} p\ncMetaTypeIsArtificial :: MetaPtr -> IO Bool\ncMetaTypeIsArtificial p = toBool <$> {#get CMeta->u.metaTypeInfo.isArtificial#} p\ncMetaTypeDirectory :: InternString m => MetaPtr -> m Text\ncMetaTypeDirectory = shareString {#get CMeta->u.metaTypeInfo.directory#}\ncMetaTypeFilename :: InternString m => MetaPtr -> m Text\ncMetaTypeFilename = shareString {#get CMeta->u.metaTypeInfo.filename#}\ncMetaTypeEncoding :: MetaPtr -> IO DW_ATE\ncMetaTypeEncoding p = dw_ate <$> {#get CMeta->u.metaTypeInfo.encoding#} p\ncMetaTypeDerivedFrom :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeDerivedFrom = optionalField {#get CMeta->u.metaTypeInfo.typeDerivedFrom#}\ncMetaTypeCompositeComponents :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeCompositeComponents = optionalField {#get CMeta->u.metaTypeInfo.typeArray#}\ncMetaTypeRuntimeLanguage :: MetaPtr -> IO Int32\ncMetaTypeRuntimeLanguage p = fromIntegral <$> {#get CMeta->u.metaTypeInfo.runTimeLang#} p\ncMetaTypeContainingType :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeContainingType = optionalField {#get CMeta->u.metaTypeInfo.containingType#}\ncMetaTypeTemplateParams :: MetaPtr -> IO (Maybe MetaPtr)\ncMetaTypeTemplateParams = optionalField {#get CMeta->u.metaTypeInfo.templateParams#}\ncMetaUnknownRepr :: InternString m => MetaPtr -> m Text\ncMetaUnknownRepr = shareString {#get CMeta->u.metaUnknownInfo.repr#}\n\noptionalField :: (a -> IO (Ptr b)) -> a -> IO (Maybe (Ptr b))\noptionalField accessor p = do\n v <- accessor p\n case v == nullPtr of\n True -> return Nothing\n False -> return (Just v)\n\nclass MonadIO m => InternString m where\n internString :: Text -> m Text\n internIdentifier :: Identifier -> m Identifier\n\n-- | This helper converts C char* strings into Texts, sharing\n-- identical bytestrings on the Haskell side. This is a simple\n-- space-saving optimization (assuming the entire cache is garbage\n-- collected)\nshareString :: InternString m => (a -> IO CString) -> a -> m Text\nshareString accessor ptr = do\n sp <- liftIO $ accessor ptr\n str <- case sp == nullPtr of\n False -> liftIO $ BS.packCString sp\n True -> return $ BS.pack \"\"\n internString (decodeUtf8 str)\n\ndata CGlobalInfo\n{#pointer *CGlobalInfo as GlobalInfoPtr -> CGlobalInfo #}\ncGlobalIsExternal :: GlobalInfoPtr -> IO Bool\ncGlobalIsExternal g = toBool <$> ({#get CGlobalInfo->isExternal#} g)\ncGlobalAlignment :: GlobalInfoPtr -> IO Int64\ncGlobalAlignment g = fromIntegral <$> ({#get CGlobalInfo->alignment#} g)\ncGlobalVisibility :: GlobalInfoPtr -> IO VisibilityStyle\ncGlobalVisibility g = toEnum . fromIntegral <$> ({#get CGlobalInfo->visibility#} g)\ncGlobalLinkage :: GlobalInfoPtr -> IO LinkageType\ncGlobalLinkage g = toEnum . fromIntegral <$> ({#get CGlobalInfo->linkage#} g)\ncGlobalSection :: GlobalInfoPtr -> IO (Maybe Text)\ncGlobalSection g = do\n s <- {#get CGlobalInfo->section#} g\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just (decodeUtf8 bs)\ncGlobalInitializer :: GlobalInfoPtr -> IO ValuePtr\ncGlobalInitializer = {#get CGlobalInfo->initializer#}\ncGlobalIsThreadLocal :: GlobalInfoPtr -> IO Bool\ncGlobalIsThreadLocal g = toBool <$> ({#get CGlobalInfo->isThreadLocal#} g)\ncGlobalAliasee :: GlobalInfoPtr -> IO ValuePtr\ncGlobalAliasee = {#get CGlobalInfo->aliasee#}\ncGlobalIsConstant :: GlobalInfoPtr -> IO Bool\ncGlobalIsConstant g = toBool <$> {#get CGlobalInfo->isConstant#} g\n\ndata CFunctionInfo\n{#pointer *CFunctionInfo as FunctionInfoPtr -> CFunctionInfo #}\ncFunctionIsExternal :: FunctionInfoPtr -> IO Bool\ncFunctionIsExternal f = toBool <$> {#get CFunctionInfo->isExternal#} f\ncFunctionAlignment :: FunctionInfoPtr -> IO Int64\ncFunctionAlignment f = fromIntegral <$> {#get CFunctionInfo->alignment#} f\ncFunctionVisibility :: FunctionInfoPtr -> IO VisibilityStyle\ncFunctionVisibility f = toEnum . fromIntegral <$> {#get CFunctionInfo->visibility#} f\ncFunctionLinkage :: FunctionInfoPtr -> IO LinkageType\ncFunctionLinkage f = toEnum . fromIntegral <$> {#get CFunctionInfo->linkage#} f\ncFunctionSection :: FunctionInfoPtr -> IO (Maybe Text)\ncFunctionSection f = do\n s <- {#get CFunctionInfo->section#} f\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just (decodeUtf8 bs)\ncFunctionIsVarArg :: FunctionInfoPtr -> IO Bool\ncFunctionIsVarArg f = toBool <$> {#get CFunctionInfo->isVarArg#} f\ncFunctionCallingConvention :: FunctionInfoPtr -> IO CallingConvention\ncFunctionCallingConvention f = toEnum . fromIntegral <$> {#get CFunctionInfo->callingConvention#} f\ncFunctionGCName :: FunctionInfoPtr -> IO (Maybe Text)\ncFunctionGCName f = do\n s <- {#get CFunctionInfo->gcName#} f\n case s == nullPtr of\n True -> return Nothing\n False -> do\n bs <- BS.packCString s\n return $! Just (decodeUtf8 bs)\ncFunctionArguments :: FunctionInfoPtr -> IO [ValuePtr]\ncFunctionArguments f =\n peekArray f {#get CFunctionInfo->arguments#} {#get CFunctionInfo->argListLen#}\ncFunctionBlocks :: FunctionInfoPtr -> IO [ValuePtr]\ncFunctionBlocks f =\n peekArray f {#get CFunctionInfo->body#} {#get CFunctionInfo->blockListLen#}\n\ndata CArgInfo\n{#pointer *CArgumentInfo as ArgInfoPtr -> CArgInfo #}\ncArgInfoHasSRet :: ArgInfoPtr -> IO Bool\ncArgInfoHasSRet a = toBool <$> ({#get CArgumentInfo->hasSRet#} a)\ncArgInfoHasByVal :: ArgInfoPtr -> IO Bool\ncArgInfoHasByVal a = toBool <$> ({#get CArgumentInfo->hasByVal#} a)\ncArgInfoHasNest :: ArgInfoPtr -> IO Bool\ncArgInfoHasNest a = toBool <$> ({#get CArgumentInfo->hasNest#} a)\ncArgInfoHasNoAlias :: ArgInfoPtr -> IO Bool\ncArgInfoHasNoAlias a = toBool <$> ({#get CArgumentInfo->hasNoAlias#} a)\ncArgInfoHasNoCapture :: ArgInfoPtr -> IO Bool\ncArgInfoHasNoCapture a = toBool <$> ({#get CArgumentInfo->hasNoCapture#} a)\n\ndata CBasicBlockInfo\n{#pointer *CBasicBlockInfo as BasicBlockPtr -> CBasicBlockInfo #}\n\ncBasicBlockInstructions :: BasicBlockPtr -> IO [ValuePtr]\ncBasicBlockInstructions b =\n peekArray b {#get CBasicBlockInfo->instructions#} {#get CBasicBlockInfo->blockLen#}\n\ndata CInlineAsmInfo\n{#pointer *CInlineAsmInfo as InlineAsmInfoPtr -> CInlineAsmInfo #}\n\ncInlineAsmString :: InlineAsmInfoPtr -> IO Text\ncInlineAsmString a =\n ({#get CInlineAsmInfo->asmString#} a) >>= makeText\ncInlineAsmConstraints :: InlineAsmInfoPtr -> IO Text\ncInlineAsmConstraints a =\n ({#get CInlineAsmInfo->constraintString#} a) >>= makeText\n\ndata CBlockAddrInfo\n{#pointer *CBlockAddrInfo as BlockAddrInfoPtr -> CBlockAddrInfo #}\n\ncBlockAddrFunc :: BlockAddrInfoPtr -> IO ValuePtr\ncBlockAddrFunc = {#get CBlockAddrInfo->func #}\ncBlockAddrBlock :: BlockAddrInfoPtr -> IO ValuePtr\ncBlockAddrBlock = {#get CBlockAddrInfo->block #}\n\ndata CAggregateInfo\n{#pointer *CConstAggregate as AggregateInfoPtr -> CAggregateInfo #}\n\ncAggregateValues :: AggregateInfoPtr -> IO [ValuePtr]\ncAggregateValues a =\n peekArray a {#get CConstAggregate->constants#} {#get CConstAggregate->numElements#}\n\ndata CConstFP\n{#pointer *CConstFP as FPInfoPtr -> CConstFP #}\ncFPVal :: FPInfoPtr -> IO Double\ncFPVal f = realToFrac <$> ({#get CConstFP->val#} f)\n\ndata CConstInt\n{#pointer *CConstInt as IntInfoPtr -> CConstInt #}\ncIntVal :: IntInfoPtr -> IO Integer\ncIntVal i = fromIntegral <$> ({#get CConstInt->val#} i)\ncIntHugeVal :: IntInfoPtr -> IO (Maybe Integer)\ncIntHugeVal i = do\n s <- {#get CConstInt->hugeVal#} i\n case s == nullPtr of\n True -> return Nothing\n False -> (Just . read) <$> peekCString s\n\ndata CInstructionInfo\n{#pointer *CInstructionInfo as InstInfoPtr -> CInstructionInfo #}\ncInstructionOperands :: InstInfoPtr -> IO [ValuePtr]\ncInstructionOperands i =\n peekArray i {#get CInstructionInfo->operands#} {#get CInstructionInfo->numOperands#}\ncInstructionArithFlags :: InstInfoPtr -> IO ArithFlags\ncInstructionArithFlags o = toEnum . fromIntegral <$> {#get CInstructionInfo->flags#} o\ncInstructionAlign :: InstInfoPtr -> IO Int64\ncInstructionAlign u = fromIntegral <$> {#get CInstructionInfo->align#} u\ncInstructionIsVolatile :: InstInfoPtr -> IO Bool\ncInstructionIsVolatile u = toBool <$> {#get CInstructionInfo->isVolatile#} u\ncInstructionAddrSpace :: InstInfoPtr -> IO Int\ncInstructionAddrSpace u = fromIntegral <$> {#get CInstructionInfo->addrSpace#} u\ncInstructionCmpPred :: InstInfoPtr -> IO CmpPredicate\ncInstructionCmpPred c = toEnum . fromIntegral <$> {#get CInstructionInfo->cmpPred#} c\ncInstructionInBounds :: InstInfoPtr -> IO Bool\ncInstructionInBounds g = toBool <$> {#get CInstructionInfo->inBounds#} g\ncInstructionIndices :: InstInfoPtr -> IO [Int]\ncInstructionIndices i =\n peekArray i {#get CInstructionInfo->indices#} {#get CInstructionInfo->numIndices#}\n\ndata CConstExprInfo\n{#pointer *CConstExprInfo as ConstExprPtr -> CConstExprInfo #}\ncConstExprTag :: ConstExprPtr -> IO ValueTag\ncConstExprTag e = toEnum . fromIntegral <$> {#get CConstExprInfo->instrType#} e\ncConstExprInstInfo :: ConstExprPtr -> IO InstInfoPtr\ncConstExprInstInfo = {#get CConstExprInfo->ii#}\n\ndata CPHIInfo\n{#pointer *CPHIInfo as PHIInfoPtr -> CPHIInfo #}\ncPHIValues :: PHIInfoPtr -> IO [ValuePtr]\ncPHIValues p =\n peekArray p {#get CPHIInfo->incomingValues#} {#get CPHIInfo->numIncomingValues#}\ncPHIBlocks :: PHIInfoPtr -> IO [ValuePtr]\ncPHIBlocks p =\n peekArray p {#get CPHIInfo->valueBlocks#} {#get CPHIInfo->numIncomingValues#}\n\ndata CCallInfo\n{#pointer *CCallInfo as CallInfoPtr -> CCallInfo #}\ncCallValue :: CallInfoPtr -> IO ValuePtr\ncCallValue = {#get CCallInfo->calledValue #}\ncCallArguments :: CallInfoPtr -> IO [ValuePtr]\ncCallArguments c =\n peekArray c {#get CCallInfo->arguments#} {#get CCallInfo->argListLen#}\ncCallConvention :: CallInfoPtr -> IO CallingConvention\ncCallConvention c = toEnum . fromIntegral <$> {#get CCallInfo->callingConvention#} c\ncCallHasSRet :: CallInfoPtr -> IO Bool\ncCallHasSRet c = toBool <$> {#get CCallInfo->hasSRet#} c\ncCallIsTail :: CallInfoPtr -> IO Bool\ncCallIsTail c = toBool <$> {#get CCallInfo->isTail#} c\ncCallUnwindDest :: CallInfoPtr -> IO ValuePtr\ncCallUnwindDest = {#get CCallInfo->unwindDest#}\ncCallNormalDest :: CallInfoPtr -> IO ValuePtr\ncCallNormalDest = {#get CCallInfo->normalDest#}\n\ndata CAtomicInfo\n{#pointer *CAtomicInfo as AtomicInfoPtr -> CAtomicInfo #}\ncAtomicOrdering :: AtomicInfoPtr -> IO AtomicOrdering\ncAtomicOrdering ai = toEnum . fromIntegral <$> {#get CAtomicInfo->ordering#} ai\ncAtomicScope :: AtomicInfoPtr -> IO SynchronizationScope\ncAtomicScope ai = toEnum . fromIntegral <$> {#get CAtomicInfo->scope#} ai\ncAtomicOperation :: AtomicInfoPtr -> IO AtomicOperation\ncAtomicOperation ai = toEnum . fromIntegral <$> {#get CAtomicInfo->operation#} ai\ncAtomicIsVolatile :: AtomicInfoPtr -> IO Bool\ncAtomicIsVolatile ai = toBool <$> {#get CAtomicInfo->isVolatile#} ai\ncAtomicAddressSpace :: AtomicInfoPtr -> IO Int\ncAtomicAddressSpace ai = fromIntegral <$> {#get CAtomicInfo->addrSpace#} ai\ncAtomicPointerOperand :: AtomicInfoPtr -> IO ValuePtr\ncAtomicPointerOperand = {#get CAtomicInfo->pointerOperand#}\ncAtomicValueOperand :: AtomicInfoPtr -> IO ValuePtr\ncAtomicValueOperand = {#get CAtomicInfo->valueOperand#}\ncAtomicCompareOperand :: AtomicInfoPtr -> IO ValuePtr\ncAtomicCompareOperand = {#get CAtomicInfo->compareOperand#}\n\ndata CLandingPadInfo\n{#pointer *CLandingPadInfo as LandingPadInfoPtr -> CLandingPadInfo#}\ncLandingPadPersonality :: LandingPadInfoPtr -> IO ValuePtr\ncLandingPadPersonality = {#get CLandingPadInfo->personality#}\ncLandingPadIsCleanup :: LandingPadInfoPtr -> IO Bool\ncLandingPadIsCleanup li = toBool <$> {#get CLandingPadInfo->isCleanup#} li\ncLandingPadClauses :: LandingPadInfoPtr -> IO [ValuePtr]\ncLandingPadClauses li =\n peekArray li {#get CLandingPadInfo->clauses #} {#get CLandingPadInfo->numClauses#}\ncLandingPadClauseTypes :: LandingPadInfoPtr -> IO [LandingPadClause]\ncLandingPadClauseTypes li = do\n arr <- peekArray li {#get CLandingPadInfo->clauseTypes #} {#get CLandingPadInfo->numClauses#}\n return $ map toEnum arr\n\n-- | Parse the named file into an FFI-friendly representation of an\n-- LLVM module.\n{#fun marshalLLVM { id `Ptr CChar', `Int', fromBool `Bool' } -> `ModulePtr' id #}\n{#fun marshalLLVMFile { `String', fromBool `Bool' } -> `ModulePtr' id #}\n\n-- | Free all of the resources allocated by 'marshalLLVM'\n{#fun disposeCModule { id `ModulePtr' } -> `()' #}\n\n-- Helpers\n\n-- This only seems to be necessary on i386 for some reason.\ncIntConv :: (Integral a, Num b) => a -> b\ncIntConv = fromIntegral\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"a234fc2291ca2f8048a1a4ad3410c55e1d5af658","subject":"SCardStatus can be shown, no need to export statusToString","message":"SCardStatus can be shown, no need to export statusToString\n","repos":"mfischer\/haskell-smartcard","old_file":"Lowlevel\/PCSCLite.chs","new_file":"Lowlevel\/PCSCLite.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Lowlevel.PCSCLite ( SCardStatus (..)\n , SCardShare (..)\n , SCardProtocol (..)\n , SCardScope (..)\n , SCardContext\n , SCardAction (..)\n , SCardCardState (..)\n , fromCLong\n , SCardIORequest\n , toSCardProtocol\n , mkSCardIORequestT0\n , mkSCardIORequestT1\n , mkSCardIORequestRaw)\nwhere\n\n\nimport Data.Int\nimport Foreign\nimport Foreign.C\nimport Foreign.Storable\nimport Control.Monad\nimport Control.Applicative\n\n#include \n\n-- | Converts a 'SCardStatus' to the error message.\nstatusToString :: SCardStatus -> String\nstatusToString s = unsafePerformIO $\n {#call pcsc_stringify_error as ^#} (fromIntegral $ fromEnum s) >>= peekCString\n\n-- | Returncodes given by the PC\\\/SC daemon.\n{#enum define SCardStatus { SCARD_S_SUCCESS as Ok\n , SCARD_F_INTERNAL_ERROR as InternalError\n , SCARD_E_CANCELLED as Cancelled\n , SCARD_E_INVALID_HANDLE as InvalidHandle\n , SCARD_E_INVALID_PARAMETER as InvalidParameter\n , SCARD_E_INVALID_TARGET as InvalidTarget\n , SCARD_E_NO_MEMORY as NoMemory\n , SCARD_F_WAITED_TOO_LONG as WaitTooLong\n , SCARD_E_INSUFFICIENT_BUFFER as InsufficientBuffer\n , SCARD_E_UNKNOWN_READER as ReaderUnknown\n , SCARD_E_TIMEOUT as Timeout\n , SCARD_E_SHARING_VIOLATION as SharingViolation\n , SCARD_E_NO_SMARTCARD as NoSmartCard\n , SCARD_E_UNKNOWN_CARD as UnknownCard\n , SCARD_E_CANT_DISPOSE as CannotDispose\n , SCARD_E_PROTO_MISMATCH as ProtocolMismatch\n , SCARD_E_NOT_READY as NotReady\n , SCARD_E_INVALID_VALUE as InvalidValue\n , SCARD_E_SYSTEM_CANCELLED as SystemCancelled\n , SCARD_F_COMM_ERROR as CommunicationError\n , SCARD_F_UNKNOWN_ERROR as UnknownError\n , SCARD_E_INVALID_ATR as InvalidATR\n , SCARD_E_NOT_TRANSACTED as NotTransacted\n , SCARD_E_READER_UNAVAILABLE as ReaderUnavailable\n , SCARD_P_SHUTDOWN as Shutdown\n , SCARD_E_PCI_TOO_SMALL as PciToSmall\n , SCARD_E_READER_UNSUPPORTED as ReaderUnsupported\n , SCARD_E_DUPLICATE_READER as DuplicateReader\n , SCARD_E_CARD_UNSUPPORTED as CardUnsupportedError\n , SCARD_E_NO_SERVICE as NoService\n , SCARD_E_SERVICE_STOPPED as ServiceStopped\n , SCARD_E_UNSUPPORTED_FEATURE as UnsupportedFeatureOrUnexpected\n , SCARD_E_ICC_INSTALLATION as IccInstallation\n , SCARD_E_ICC_CREATEORDER as IccCreateOrder\n , SCARD_E_DIR_NOT_FOUND as DirectoryNotFound\n , SCARD_E_FILE_NOT_FOUND as FileNotFound\n , SCARD_E_NO_DIR as NoDirectory\n , SCARD_E_NO_FILE as NoFile\n , SCARD_E_NO_ACCESS as NoAccess\n , SCARD_E_WRITE_TOO_MANY as TooManyWrites\n , SCARD_E_BAD_SEEK as BadSeek\n , SCARD_E_INVALID_CHV as InvalidCHV\n , SCARD_E_UNKNOWN_RES_MNG as UnknownResMNG\n , SCARD_E_NO_SUCH_CERTIFICATE as NoSuchCertificate\n , SCARD_E_CERTIFICATE_UNAVAILABLE as CertificateUnavailable\n , SCARD_E_NO_READERS_AVAILABLE as NoReaderAvailable\n , SCARD_E_COMM_DATA_LOST as CommunicationDataLost\n , SCARD_E_NO_KEY_CONTAINER as NoKeyContainer\n , SCARD_E_SERVER_TOO_BUSY as ServerToBusy\n , SCARD_W_UNSUPPORTED_CARD as CardUnsupportedWarning\n , SCARD_W_UNRESPONSIVE_CARD as UnresponsiveCard\n , SCARD_W_UNPOWERED_CARD as CardUnpowered\n , SCARD_W_RESET_CARD as CardReset\n , SCARD_W_REMOVED_CARD as CardRemoved\n , SCARD_W_SECURITY_VIOLATION as SecurityViolation\n , SCARD_W_WRONG_CHV as WrongCHV\n , SCARD_W_CHV_BLOCKED as CHVBlocked\n , SCARD_W_EOF as EOF\n , SCARD_W_CANCELLED_BY_USER as CancelledByUser\n , SCARD_W_CARD_NOT_AUTHENTICATED as CardNotAuthenticated}\n deriving (Eq)\n#}\n\ninstance Show SCardStatus where\n show = statusToString\n\nfromCLong :: (Integral a, Enum c) => a -> c\nfromCLong = toEnum . fromIntegral\n\n\n\n{#\nenum define SCardScope { SCARD_SCOPE_USER as UserScope\n , SCARD_SCOPE_TERMINAL as TerminalScope\n , SCARD_SCOPE_SYSTEM as SystemScope}\n#}\n\n\ntype SCardContext = {#type SCARDCONTEXT#}\n\n\n-- | These are the possible sharing modes for 'establishContext'\n{#\nenum define SCardShare { SCARD_SHARE_EXCLUSIVE as Exclusive\n , SCARD_SHARE_SHARED as Shared\n , SCARD_SHARE_DIRECT as Direct}\n#}\n\n{#\nenum define SCardProtocol { SCARD_PROTOCOL_T1 as T1\n , SCARD_PROTOCOL_T0 as T0\n , SCARD_PROTOCOL_T15 as T15\n , SCARD_PROTOCOL_UNDEFINED as Undefined\n , SCARD_PROTOCOL_RAW as Raw}\n#}\n\n-- | Converts a 'CULong' to the 'SCardProtocol'.\ntoSCardProtocol :: CULong -> SCardProtocol\ntoSCardProtocol = toEnum . fromIntegral\n\ninstance Show SCardProtocol where\n show T0 = \"T0\"\n show T1 = \"T1\"\n show T15 = \"T15\"\n show Raw = \"Raw\"\n show Undefined = \"Undefined\"\n\n{#\nenum define SCardAction { SCARD_LEAVE_CARD as LeaveCard\n , SCARD_RESET_CARD as ResetCard\n , SCARD_UNPOWER_CARD as UnpowerCard\n , SCARD_EJECT_CARD as EjectCard}\n#}\n\n-- | Creates a 'SCardIORequest' setup for the 'T0' protocol.\nmkSCardIORequestT0 :: SCardIORequest\nmkSCardIORequestT0 = SCardIORequest { getProtocol = T0\n , getSize = {#sizeof SCARD_IO_REQUEST#}}\n\n-- | Creates a 'SCardIORequest' setup for the 'T1' protocol.\nmkSCardIORequestT1 :: SCardIORequest\nmkSCardIORequestT1 = SCardIORequest { getProtocol = T1\n , getSize = {#sizeof SCARD_IO_REQUEST#}}\n\n-- | Creates a 'SCardIORequest' setup for the 'Raw' protocol.\nmkSCardIORequestRaw :: SCardIORequest\nmkSCardIORequestRaw = SCardIORequest { getProtocol = Raw\n , getSize = {#sizeof SCARD_IO_REQUEST#}}\n\ndata SCardIORequest = SCardIORequest { getProtocol :: SCardProtocol\n , getSize :: Int}\n\ninstance Storable SCardIORequest where\n sizeOf _ = {#sizeof SCARD_IO_REQUEST #}\n alignment _ = {#alignof SCARD_IO_REQUEST#}\n peek p = SCardIORequest\n <$> liftM toSCardProtocol ({#get SCARD_IO_REQUEST->dwProtocol #} p)\n <*> liftM fromIntegral ({#get SCARD_IO_REQUEST->cbPciLength #} p)\n poke p x = do\n {#set SCARD_IO_REQUEST.dwProtocol #} p $ fromIntegral . fromEnum $ getProtocol x\n {#set SCARD_IO_REQUEST.cbPciLength #} p $ fromIntegral $ getSize x\n\n\n{#\nenum define SCardCardState { SCARD_UNKNOWN as Unknown\n , SCARD_ABSENT as Absent\n , SCARD_PRESENT as Present\n , SCARD_POWERED as Powered\n , SCARD_NEGOTIABLE as Negotiable\n , SCARD_SPECIFIC as Specific}\n#}\n\ninstance Show SCardCardState where\n show Unknown = \"Unknown\"\n show Absent = \"Absent\"\n show Present = \"Present\"\n show Powered = \"Powered\"\n show Negotiable = \"Negotiable\"\n show Specific = \"Specific\"\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\nmodule Lowlevel.PCSCLite ( statusToString\n , SCardStatus (..)\n , SCardShare (..)\n , SCardProtocol (..)\n , SCardScope (..)\n , SCardContext\n , SCardAction (..)\n , SCardCardState (..)\n , fromCLong\n , SCardIORequest\n , toSCardProtocol\n , mkSCardIORequestT0\n , mkSCardIORequestT1\n , mkSCardIORequestRaw)\nwhere\n\n\nimport Data.Int\nimport Foreign\nimport Foreign.C\nimport Foreign.Storable\nimport Control.Monad\nimport Control.Applicative\n\n#include \n\n-- | Converts a 'SCardStatus' to the error message.\nstatusToString :: SCardStatus -> String\nstatusToString s = unsafePerformIO $\n {#call pcsc_stringify_error as ^#} (fromIntegral $ fromEnum s) >>= peekCString\n\n-- | Returncodes given by the PC\\\/SC daemon.\n{#enum define SCardStatus { SCARD_S_SUCCESS as Ok\n , SCARD_F_INTERNAL_ERROR as InternalError\n , SCARD_E_CANCELLED as Cancelled\n , SCARD_E_INVALID_HANDLE as InvalidHandle\n , SCARD_E_INVALID_PARAMETER as InvalidParameter\n , SCARD_E_INVALID_TARGET as InvalidTarget\n , SCARD_E_NO_MEMORY as NoMemory\n , SCARD_F_WAITED_TOO_LONG as WaitTooLong\n , SCARD_E_INSUFFICIENT_BUFFER as InsufficientBuffer\n , SCARD_E_UNKNOWN_READER as ReaderUnknown\n , SCARD_E_TIMEOUT as Timeout\n , SCARD_E_SHARING_VIOLATION as SharingViolation\n , SCARD_E_NO_SMARTCARD as NoSmartCard\n , SCARD_E_UNKNOWN_CARD as UnknownCard\n , SCARD_E_CANT_DISPOSE as CannotDispose\n , SCARD_E_PROTO_MISMATCH as ProtocolMismatch\n , SCARD_E_NOT_READY as NotReady\n , SCARD_E_INVALID_VALUE as InvalidValue\n , SCARD_E_SYSTEM_CANCELLED as SystemCancelled\n , SCARD_F_COMM_ERROR as CommunicationError\n , SCARD_F_UNKNOWN_ERROR as UnknownError\n , SCARD_E_INVALID_ATR as InvalidATR\n , SCARD_E_NOT_TRANSACTED as NotTransacted\n , SCARD_E_READER_UNAVAILABLE as ReaderUnavailable\n , SCARD_P_SHUTDOWN as Shutdown\n , SCARD_E_PCI_TOO_SMALL as PciToSmall\n , SCARD_E_READER_UNSUPPORTED as ReaderUnsupported\n , SCARD_E_DUPLICATE_READER as DuplicateReader\n , SCARD_E_CARD_UNSUPPORTED as CardUnsupportedError\n , SCARD_E_NO_SERVICE as NoService\n , SCARD_E_SERVICE_STOPPED as ServiceStopped\n , SCARD_E_UNSUPPORTED_FEATURE as UnsupportedFeatureOrUnexpected\n , SCARD_E_ICC_INSTALLATION as IccInstallation\n , SCARD_E_ICC_CREATEORDER as IccCreateOrder\n , SCARD_E_DIR_NOT_FOUND as DirectoryNotFound\n , SCARD_E_FILE_NOT_FOUND as FileNotFound\n , SCARD_E_NO_DIR as NoDirectory\n , SCARD_E_NO_FILE as NoFile\n , SCARD_E_NO_ACCESS as NoAccess\n , SCARD_E_WRITE_TOO_MANY as TooManyWrites\n , SCARD_E_BAD_SEEK as BadSeek\n , SCARD_E_INVALID_CHV as InvalidCHV\n , SCARD_E_UNKNOWN_RES_MNG as UnknownResMNG\n , SCARD_E_NO_SUCH_CERTIFICATE as NoSuchCertificate\n , SCARD_E_CERTIFICATE_UNAVAILABLE as CertificateUnavailable\n , SCARD_E_NO_READERS_AVAILABLE as NoReaderAvailable\n , SCARD_E_COMM_DATA_LOST as CommunicationDataLost\n , SCARD_E_NO_KEY_CONTAINER as NoKeyContainer\n , SCARD_E_SERVER_TOO_BUSY as ServerToBusy\n , SCARD_W_UNSUPPORTED_CARD as CardUnsupportedWarning\n , SCARD_W_UNRESPONSIVE_CARD as UnresponsiveCard\n , SCARD_W_UNPOWERED_CARD as CardUnpowered\n , SCARD_W_RESET_CARD as CardReset\n , SCARD_W_REMOVED_CARD as CardRemoved\n , SCARD_W_SECURITY_VIOLATION as SecurityViolation\n , SCARD_W_WRONG_CHV as WrongCHV\n , SCARD_W_CHV_BLOCKED as CHVBlocked\n , SCARD_W_EOF as EOF\n , SCARD_W_CANCELLED_BY_USER as CancelledByUser\n , SCARD_W_CARD_NOT_AUTHENTICATED as CardNotAuthenticated}\n deriving (Eq)\n#}\n\ninstance Show SCardStatus where\n show = statusToString\n\nfromCLong :: (Integral a, Enum c) => a -> c\nfromCLong = toEnum . fromIntegral\n\n\n\n{#\nenum define SCardScope { SCARD_SCOPE_USER as UserScope\n , SCARD_SCOPE_TERMINAL as TerminalScope\n , SCARD_SCOPE_SYSTEM as SystemScope}\n#}\n\n\ntype SCardContext = {#type SCARDCONTEXT#}\n\n\n-- | These are the possible sharing modes for 'establishContext'\n{#\nenum define SCardShare { SCARD_SHARE_EXCLUSIVE as Exclusive\n , SCARD_SHARE_SHARED as Shared\n , SCARD_SHARE_DIRECT as Direct}\n#}\n\n{#\nenum define SCardProtocol { SCARD_PROTOCOL_T1 as T1\n , SCARD_PROTOCOL_T0 as T0\n , SCARD_PROTOCOL_T15 as T15\n , SCARD_PROTOCOL_UNDEFINED as Undefined\n , SCARD_PROTOCOL_RAW as Raw}\n#}\n\n-- | Converts a 'CULong' to the 'SCardProtocol'.\ntoSCardProtocol :: CULong -> SCardProtocol\ntoSCardProtocol = toEnum . fromIntegral\n\ninstance Show SCardProtocol where\n show T0 = \"T0\"\n show T1 = \"T1\"\n show T15 = \"T15\"\n show Raw = \"Raw\"\n show Undefined = \"Undefined\"\n\n{#\nenum define SCardAction { SCARD_LEAVE_CARD as LeaveCard\n , SCARD_RESET_CARD as ResetCard\n , SCARD_UNPOWER_CARD as UnpowerCard\n , SCARD_EJECT_CARD as EjectCard}\n#}\n\n-- | Creates a 'SCardIORequest' setup for the 'T0' protocol.\nmkSCardIORequestT0 :: SCardIORequest\nmkSCardIORequestT0 = SCardIORequest { getProtocol = T0\n , getSize = {#sizeof SCARD_IO_REQUEST#}}\n\n-- | Creates a 'SCardIORequest' setup for the 'T1' protocol.\nmkSCardIORequestT1 :: SCardIORequest\nmkSCardIORequestT1 = SCardIORequest { getProtocol = T1\n , getSize = {#sizeof SCARD_IO_REQUEST#}}\n\n-- | Creates a 'SCardIORequest' setup for the 'Raw' protocol.\nmkSCardIORequestRaw :: SCardIORequest\nmkSCardIORequestRaw = SCardIORequest { getProtocol = Raw\n , getSize = {#sizeof SCARD_IO_REQUEST#}}\n\ndata SCardIORequest = SCardIORequest { getProtocol :: SCardProtocol\n , getSize :: Int}\n\ninstance Storable SCardIORequest where\n sizeOf _ = {#sizeof SCARD_IO_REQUEST #}\n alignment _ = {#alignof SCARD_IO_REQUEST#}\n peek p = SCardIORequest\n <$> liftM toSCardProtocol ({#get SCARD_IO_REQUEST->dwProtocol #} p)\n <*> liftM fromIntegral ({#get SCARD_IO_REQUEST->cbPciLength #} p)\n poke p x = do\n {#set SCARD_IO_REQUEST.dwProtocol #} p $ fromIntegral . fromEnum $ getProtocol x\n {#set SCARD_IO_REQUEST.cbPciLength #} p $ fromIntegral $ getSize x\n\n\n{#\nenum define SCardCardState { SCARD_UNKNOWN as Unknown\n , SCARD_ABSENT as Absent\n , SCARD_PRESENT as Present\n , SCARD_POWERED as Powered\n , SCARD_NEGOTIABLE as Negotiable\n , SCARD_SPECIFIC as Specific}\n#}\n\ninstance Show SCardCardState where\n show Unknown = \"Unknown\"\n show Absent = \"Absent\"\n show Present = \"Present\"\n show Powered = \"Powered\"\n show Negotiable = \"Negotiable\"\n show Specific = \"Specific\"\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"71ac592c1bd05cfe5dc0e868bda5705a68562423","subject":"Commit","message":"Commit\n","repos":"norm2782\/hgit2","old_file":"src\/haskell\/Data\/HGit2\/Commit.chs","new_file":"src\/haskell\/Data\/HGit2\/Commit.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE Rank2Types #-}\n\n#include \n\nmodule Data.HGit2.Commit where\n\nimport Data.HGit2.Git2\nimport Data.HGit2.Errors\nimport Data.HGit2.Repository\nimport Data.HGit2.Types\nimport Data.HGit2.Signature\nimport Data.HGit2.OID\nimport Data.HGit2.Tree\nimport Data.Maybe ()\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\nnewtype Commit = Commit CPtr\n\ninstance CWrapper Commit where\n unwrap (Commit c) = c\n\n-- | Get the id of a commit.\ncommitId :: Commit -> OID\ncommitId (Commit cfp) = unsafePerformIO $\n withForeignPtr cfp $ \\p -> do\n o <- mkFPtr =<< {#call unsafe git_commit_id#} p\n return $ OID o\n\n-- | Get the id of the tree pointed to by a commit. This differs from `tree` in\n-- that no attempts are made to fetch an object from the ODB.\ntreeOID :: Commit -> OID\ntreeOID (Commit cfp) = unsafePerformIO $\n withForeignPtr cfp $ \\p -> do\n o <- mkFPtr =<< {#call unsafe git_commit_tree_oid#} p\n return $ OID o\n\n-- | Get the short (one line) message of a commit.\nshortCommitMsg :: Commit -> String\nshortCommitMsg (Commit cfp) = unsafePerformIO $\n withForeignPtr cfp $ \\p ->\n peekCString =<< {#call unsafe git_commit_message_short#} p\n\n-- | Get the full message of a commit.\ncommitMsg :: Commit -> String\ncommitMsg (Commit cfp) = unsafePerformIO $\n withForeignPtr cfp $ \\p ->\n peekCString =<< {#call unsafe git_commit_message#} p\n\n-- | Get the commit time (i.e. committer time) of a commit.\ncommitTime :: Commit -> TimeT\ncommitTime (Commit cfp) = unsafePerformIO $\n withForeignPtr cfp $ \\p ->\n {#call unsafe git_commit_time#} p\n\n-- | Get the commit timezone offset (i.e. committer's preferred timezone) of a\n-- commit.\ntimeOffset :: Commit -> Int\ntimeOffset (Commit cfp) = unsafePerformIO $\n withForeignPtr cfp $ \\p ->\n retNum $ {#call unsafe git_commit_time_offset#} p\n\n-- | Get the committer of a commit.\ncommitter :: Commit -> Signature\ncommitter (Commit cfp) = unsafePerformIO $\n withForeignPtr cfp $ \\p -> do\n o <- mkFPtr =<< {#call unsafe git_commit_committer#} p\n return $ Signature o\n\n-- | Get the author of a commit.\nauthor :: Commit -> Signature\nauthor (Commit cfp) = unsafePerformIO $\n withForeignPtr cfp $ \\p -> do\n o <- mkFPtr =<< {#call unsafe git_commit_author#} p\n return $ Signature o\n\n-- | Get the tree pointed to by a commit.\ntree :: Commit -> IOEitherErr Tree\ntree (Commit cfp) =\n withForeignPtr cfp $ \\c ->\n callPeek Tree (\\out -> {#call git_commit_tree#} out c)\n\n-- | Get the number of parents of this commit\nparentCount :: Commit -> IO Int\nparentCount (Commit cfp) =\n withForeignPtr cfp $ \\p ->\n retNum $ {#call git_commit_parentcount#} p\n\n-- | Get the specified parent of the commit.\nparent :: Commit -> Int -> IOEitherErr Commit\nparent (Commit cfp) n =\n withForeignPtr cfp $ \\c ->\n callPeek Commit (\\out -> {#call git_commit_parent#} out c (fromIntegral n))\n\n-- | Get the oid of a specified parent for a commit. This is different from\n-- `parent`, which will attempt to load the parent commit from the ODB.\nparentOID :: Commit -> Int -> IO (Maybe OID)\nparentOID (Commit cfp) n =\n withForeignPtr cfp $ \\c -> do\n r <- mkFPtr =<< {#call git_commit_parent_oid#} c (fromIntegral n)\n retRes OID r\n\n-- | Create a new commit in the repository\n-- TODO: Support list of commits here\ncreateCommit :: OID -> Repository -> Maybe String -> Signature -> Signature\n -> String -> Tree -> Commit -> IO (Maybe GitError)\ncreateCommit (OID ofp) (Repository rfp) mref (Signature afp) (Signature cfp)\n msg (Tree tfp) (Commit mfp) =\n withForeignPtr ofp $ \\o ->\n withForeignPtr rfp $ \\r ->\n withForeignPtr afp $ \\ausig ->\n withForeignPtr cfp $ \\comsig ->\n withForeignPtr tfp $ \\t ->\n withForeignPtr mfp $ \\m ->\n withCString msg $ \\msgStr -> do\n carr <- newArray [m]\n let cc' = cc carr o r ausig comsig t msgStr\n let ret = case mref of\n Nothing -> cc' nullPtr\n Just x -> withCString x $ \\str -> cc' str\n free carr\n ret\n where cc carr o r as cs t ms ref = retMaybe =<< {#call git_commit_create#} o\n r ref as cs ms t (fromIntegral (1 :: Int)) carr\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE Rank2Types #-}\n\n#include \n\nmodule Data.HGit2.Commit where\n\nimport Data.HGit2.Git2\nimport Data.HGit2.Errors\nimport Data.HGit2.Repository\nimport Data.HGit2.Types\nimport Data.HGit2.Signature\nimport Data.HGit2.OID\nimport Data.HGit2.Tree\nimport Data.Maybe ()\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\nnewtype Commit = Commit CPtr\n\ninstance CWrapper Commit where\n unwrap (Commit c) = c\n\noidCall :: (Ptr () -> IO (Ptr ())) -> Commit -> OID\noidCall = undefined -- flipUSCall (return . OID)\n\nstrCall :: (Ptr () -> IO CString) -> Commit -> String\nstrCall = undefined -- flipUSCall peekCString\n\nsigCall :: (Ptr () -> IO (Ptr ())) -> Commit -> Signature\nsigCall = undefined -- flipUSCall (return . Signature)\n\ncommitId :: Commit -> OID\ncommitId = oidCall {#call unsafe git_commit_id#}\n\ntreeOID :: Commit -> OID\ntreeOID = oidCall {#call unsafe git_commit_tree_oid#}\n\nshortCommitMsg :: Commit -> String\nshortCommitMsg = strCall {#call unsafe git_commit_message_short#}\n\ncommitMsg :: Commit -> String\ncommitMsg = strCall {#call unsafe git_commit_message#}\n\ncommitTime :: Commit -> TimeT\ncommitTime = undefined -- usCall {#call unsafe git_commit_time#} (return =<<)\n\ntimeOffset :: Commit -> Int\ntimeOffset = undefined -- usCall {#call unsafe git_commit_time_offset#} retNum\n\ncommitter :: Commit -> Signature\ncommitter = sigCall {#call unsafe git_commit_committer#}\n\nauthor :: Commit -> Signature\nauthor = sigCall {#call unsafe git_commit_author#}\n\ntree :: Commit -> IOEitherErr Tree\ntree (Commit cfp) =\n withForeignPtr cfp $ \\c ->\n callPeek Tree (\\out -> {#call git_commit_tree#} out c)\n\nparentCount :: Commit -> IO Int\nparentCount = undefined -- wrapToMNum {#call git_commit_parentcount#}\n\nparent :: Commit -> Int -> IOEitherErr Commit\nparent (Commit cfp) n =\n withForeignPtr cfp $ \\c ->\n callPeek Commit (\\out -> {#call git_commit_parent#} out c (fromIntegral n))\n\nparentOID :: Commit -> Int -> IO (Maybe OID)\nparentOID (Commit cfp) n =\n withForeignPtr cfp $ \\c -> do\n r <- mkFPtr =<< {#call git_commit_parent_oid#} c (fromIntegral n)\n retRes OID r\n\n\n-- TODO: split up into two functions, so free doesn't need to be manual. use\n-- automated machanisms instead\ncreateCommit :: OID -> Repository -> Maybe String -> Signature -> Signature\n -> String -> Tree -> [Commit] -> IO (Maybe GitError)\ncreateCommit (OID ofp) (Repository rfp) mref (Signature afp) (Signature cfp)\n msg (Tree tfp) ps =\n withForeignPtr ofp $ \\o ->\n withForeignPtr rfp $ \\r ->\n withForeignPtr afp $ \\ausig ->\n withForeignPtr cfp $ \\comsig ->\n withForeignPtr tfp $ \\t ->\n withCString msg $ \\msgStr -> do\n updRef <- case mref of\n Nothing -> return nullPtr\n Just x -> newCString x\n {- carr <- newArray [c | Commit c <- ps]-}\n {- let ret = retMaybe =<< {#call git_commit_create#} o r updRef ausig comsig-}\n {- msgStr t (fromIntegral $ length ps) carr-}\n free updRef\n {- ret-}\n undefined\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"af8f36abcd382b6501217e025e402e30da02cbf5","subject":"When streaming, do RECV_STATUS_ON_CLIENT in the background.","message":"When streaming, do RECV_STATUS_ON_CLIENT in the background.\n\nThe end of a streaming RPC is defined by the RECV_STATUS_ON_CLIENT\nevent. \"Subscribe\" to the event by doing a callBatch without blocking\nfor the reply. Once the event is fired, update the statusEventFromServer\nMVar in ClientReaderWriter.\n","repos":"grpc\/grpc-haskell","old_file":"src\/Network\/Grpc\/Core\/Call.chs","new_file":"src\/Network\/Grpc\/Core\/Call.chs","new_contents":"-- Copyright (c) 2016, Google Inc.\n-- All rights reserved.\n--\n-- Redistribution and use in source and binary forms, with or without\n-- modification, are permitted provided that the following conditions are met:\n-- * Redistributions of source code must retain the above copyright\n-- notice, this list of conditions and the following disclaimer.\n-- * Redistributions in binary form must reproduce the above copyright\n-- notice, this list of conditions and the following disclaimer in the\n-- documentation and\/or other materials provided with the distribution.\n-- * Neither the name of Google Inc. nor the\n-- names of its contributors may be used to endorse or promote products\n-- derived from this software without specific prior written permission.\n--\n-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n-- DISCLAIMED. IN NO EVENT SHALL Google Inc. BE LIABLE FOR ANY\n-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n--\n--------------------------------------------------------------------------------\n{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, ExistentialQuantification, RecordWildCards #-}\nmodule Network.Grpc.Core.Call where\n\n\nimport Control.Concurrent\nimport Control.Exception\nimport Control.Monad\n\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Lazy as L\nimport Data.Monoid ((<>), Last(..))\nimport Data.IORef\n\nimport Foreign.C.Types as C\nimport qualified Foreign.Marshal.Alloc as C\nimport qualified Foreign.Marshal.Utils as C\nimport qualified Foreign.Ptr as C\nimport Foreign.Ptr (Ptr)\nimport qualified Foreign.Storable as C\n\n-- transformers\nimport Control.Monad.IO.Class\nimport Control.Monad.Trans.Class\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Reader\n\nimport qualified Network.Grpc.CompletionQueue as CQ\nimport Network.Grpc.Lib.PropagationBits\n{#import Network.Grpc.Lib.ByteBuffer#}\n{#import Network.Grpc.Lib.Metadata#}\n{#import Network.Grpc.Lib.TimeSpec#}\n{#import Network.Grpc.Lib.Core#}\n\n\n#include \n#include \"hs_grpc.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\ndata Deadline\n = AbsoluteDeadline TimeSpec\n | RelativeDeadline Int --seconds\n\ndata ClientContext = ClientContext\n { ccChannel :: Channel\n , ccCQ :: CompletionQueue\n , ccWorker :: CQ.Worker\n }\n\ndata CallOptions = CallOptions\n { coDeadline :: Maybe Deadline\n , coParentContext :: Maybe () -- todo\n , coPropagationMask :: Maybe PropagationMask\n , coMetadata :: [Metadata]\n }\n\ninstance Monoid CallOptions where\n mempty = CallOptions Nothing Nothing Nothing []\n mappend (CallOptions a b c d) (CallOptions a' b' c' d') =\n CallOptions\n (getLast (Last a <> Last a'))\n (getLast (Last b <> Last b'))\n (getLast (Last c <> Last c'))\n (d <> d')\n\nwithAbsoluteDeadline :: TimeSpec -> CallOptions\nwithAbsoluteDeadline deadline =\n mempty { coDeadline = Just (AbsoluteDeadline deadline) }\n\nwithRelativeDeadlineSeconds :: Int -> CallOptions\nwithRelativeDeadlineSeconds seconds =\n mempty { coDeadline = Just (RelativeDeadline seconds) }\n\nwithParentContext :: () -> CallOptions\nwithParentContext ctx =\n mempty { coParentContext = Just ctx }\n\nwithParentContextPropagating :: () -> PropagationMask -> CallOptions\nwithParentContextPropagating ctx prop =\n mempty { coParentContext = Just ctx\n , coPropagationMask = Just prop }\n\nwithMetadata :: [Metadata] -> CallOptions\nwithMetadata md =\n mempty { coMetadata = md }\n\nresolveDeadline :: CallOptions -> IO TimeSpec\nresolveDeadline co =\n case coDeadline co of\n Nothing -> return gprInfFuture\n Just (AbsoluteDeadline deadline) -> return deadline\n Just (RelativeDeadline seconds) ->\n secondsFromNow (fromIntegral seconds)\n\nnewClientContext :: Channel -> IO ClientContext\nnewClientContext chan = do\n cq <- completionQueueCreate reservedPtr\n cqt <- CQ.startCompletionQueueThread cq\n return (ClientContext chan cq cqt)\n\ndestroyClientContext :: ClientContext -> IO ()\ndestroyClientContext (ClientContext _ cq w) = do\n completionQueueShutdown cq\n CQ.waitWorkerTermination w\n\ntype MethodName = B.ByteString\ntype Arg = B.ByteString\n\n-- | Run the IO function once, cache it in the MVar.\nonceMVar :: MVar (Maybe a) -> IO a -> IO a\nonceMVar mvar io = modifyMVar mvar $ \\x ->\n case x of\n Just x' -> return (x, x')\n Nothing -> do\n x' <- io\n return (Just x', x')\n\nreservedPtr :: Ptr ()\nreservedPtr = C.nullPtr\n\ndata UnaryResult a = UnaryResult [Metadata] [Metadata] a deriving Show\n\ncallUnary :: ClientContext -> CallOptions -> MethodName -> Arg -> IO (RpcReply (UnaryResult L.ByteString))\ncallUnary ctx@(ClientContext chan cq _) co method arg = do\n deadline <- resolveDeadline co\n bracket (grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline) grpcCallDestroy $ \\call0 -> newMVar call0 >>= \\mcall -> do\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n recvStatusOp <- opRecvStatusOnClient crw\n recvMessageOp <- opRecvMessage\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX recvInitialMetadataOp\n , OpX recvMessageOp\n , OpX sendMessageOp\n , OpX recvStatusOp\n ]\n case res of\n RpcOk _ -> do\n (RpcStatus trailMD status statusDetails) <- opRead recvStatusOp\n case status of\n StatusOk -> do\n initMD <- opRead recvInitialMetadataOp\n answ <- opRead recvMessageOp\n let answ' = maybe L.empty id answ\n return (RpcOk (UnaryResult initMD trailMD answ'))\n _ -> return (RpcError (StatusError status statusDetails))\n RpcError err -> return (RpcError err)\n\ncallDownstream :: ClientContext -> CallOptions -> MethodName -> Arg -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallDownstream ctx@(ClientContext chan cq _) co method arg = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX sendMessageOp\n ]\n case res of\n RpcOk _ -> do\n res' <- callBatchStatusOnClient crw\n case res' of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n RpcError err -> return (RpcError err)\n\ncallUpstream :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallUpstream ctx@(ClientContext chan cq _) co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> do\n res' <- callBatchStatusOnClient crw\n case res' of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n RpcError err -> return (RpcError err)\n\ncallBidi :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallBidi ctx@(ClientContext chan cq _) co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n\n crw <- newClientReaderWriter ctx mcall\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> do\n res' <- callBatchStatusOnClient crw\n case res' of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n RpcError err -> return (RpcError err)\n\ndata Client req resp = Client\n { clientCrw :: ClientReaderWriter\n , clientEncoder :: Encoder req\n , clientDecoder :: Decoder resp\n }\n\ntype Decoder a = L.ByteString -> IO (RpcReply a)\ntype Encoder a = a -> IO (RpcReply B.ByteString)\n\ndefaultDecoder :: L.ByteString -> IO (RpcReply L.ByteString)\ndefaultDecoder bs = return (RpcOk bs)\n\ndefaultEncoder :: B.ByteString -> IO (RpcReply B.ByteString)\ndefaultEncoder bs = return (RpcOk bs)\n\ndata ClientReaderWriter = ClientReaderWriter {\n context :: ClientContext,\n callMVar_ :: MVar Call,\n initialMDRef :: !(IORef (Maybe [Metadata])),\n trailingMDRef :: !(IORef (Maybe [Metadata])),\n statusFromServer :: !(MVar RpcStatus),\n statusFromServerTag :: !(MVar CQ.EventDesc)\n}\n\nnewClientReaderWriter :: ClientContext -> MVar Call -> IO ClientReaderWriter\nnewClientReaderWriter ctx mcall = do\n initMD <- newIORef Nothing\n trailMD <- newIORef Nothing\n status <- newEmptyMVar\n statusEvent <- newEmptyMVar\n return (ClientReaderWriter ctx mcall initMD trailMD status statusEvent)\n\ndata OpX = forall t. OpX (OpT t)\n\ndata OpArray = OpArray { opArrPtr :: !GrpcOpPtr\n , opArrLen :: !CULong\n , opArrFinishAndFree :: !(IO ())\n }\n\ntoArray :: [OpX] -> IO OpArray\ntoArray ops = do\n aptr <- C.mallocBytes (length ops * {#sizeof grpc_op#})\n let ptrs = iterate (`C.plusPtr` {#sizeof grpc_op#}) aptr\n ops' = concatMap (\\(OpX op) -> opAdd op) ops\n free = C.free aptr >> sequence_ (map (\\(OpX op) -> opFinish op) ops)\n write op p = do\n {#set grpc_op->flags#} p 0\n {#set grpc_op->reserved#} p C.nullPtr\n op p\n zipWithM_ write ops' ptrs\n return $! OpArray aptr (fromIntegral $ length ops) free\n\ncallBatch :: ClientReaderWriter -> [OpX] -> IO (RpcReply ())\ncallBatch crw ops = do\n let ctx = context crw\n arr <- toArray ops\n let onBatchComplete = opArrFinishAndFree arr\n CQ.withEvent (ccWorker ctx) onBatchComplete $ \\eDesc -> do\n callStatus <- withMVar (callMVar_ crw) $ \\call ->\n grpcCallStartBatch call (opArrPtr arr) (opArrLen arr) (CQ.eventTag eDesc) reservedPtr\n case callStatus of\n CallOk -> do\n e <- CQ.interruptibleWaitEvent eDesc\n case e of\n QueueOpComplete OpSuccess _ -> return (RpcOk ())\n QueueOpComplete OpError _ -> return (RpcError (Error \"callBatch: op error\"))\n QueueTimeOut -> return (RpcError DeadlineExceeded)\n QueueShutdown -> return (RpcError (Error \"queue shutdown\"))\n _ -> do\n return (RpcError (CallErrorStatus callStatus))\n\ncallBatchStatusOnClient :: ClientReaderWriter -> IO (RpcReply ())\ncallBatchStatusOnClient crw@ClientReaderWriter{..} = do\n tag <- tryReadMVar statusFromServerTag\n case tag of\n Just _ -> return (RpcOk ()) -- already did this before\n Nothing -> do\n statusOp <- opRecvStatusOnClient crw\n arr <- toArray [ OpX statusOp ]\n let onBatchComplete = opArrFinishAndFree arr\n eDesc <- CQ.allocateEvent (ccWorker context) onBatchComplete\n putMVar statusFromServerTag eDesc\n callStatus <- withMVar callMVar_ $ \\call ->\n grpcCallStartBatch call (opArrPtr arr) (opArrLen arr) (CQ.eventTag eDesc) reservedPtr\n case callStatus of\n CallOk -> return (RpcOk ())\n _ -> return (RpcError (CallErrorStatus callStatus))\n\ndata OpT out = Op\n { opAdd :: [Ptr GrpcOp -> IO ()]\n , opValue :: IORef out\n , opFinish :: IO ()\n }\n\nopRead :: OpT a -> IO a\nopRead op = readIORef (opValue op)\n\nopRecvInitialMetadata :: ClientReaderWriter -> IO (OpT [Metadata])\nopRecvInitialMetadata crw = do\n arr <- mallocMetadataArray\n value <- newIORef (error \"opRecvInitialMetadata never finished\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvInitialMetadata))\n {#set grpc_op->data.recv_initial_metadata#} p arr\n ]\n finish = do\n mds <- readMetadataArray arr\n writeIORef (initialMDRef crw) (Just mds)\n writeIORef value mds\n freeMetadataArray arr\n return (Op add value finish)\n\nopSendMessage :: B.ByteString -> IO (OpT ())\nopSendMessage bs = do\n bb <- fromByteString bs\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendMessage))\n {#set grpc_op->data.send_message#} p bb\n ]\n finish =\n byteBufferDestroy bb\n return (Op add value finish)\n\nopRecvMessage :: IO (OpT (Maybe L.ByteString))\nopRecvMessage = do\n bbptr <- C.malloc :: IO (Ptr (Ptr CByteBuffer))\n value <- newIORef Nothing\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvMessage))\n {#set grpc_op->data.recv_message#} p bbptr\n ]\n finish = do\n bb <- C.peek bbptr\n C.free bbptr\n writeIORef value =<< if bb \/= C.nullPtr\n then do\n lbs <- toLazyByteString bb\n byteBufferDestroy bb\n return (Just lbs)\n else return Nothing\n return (Op add value finish)\n\nopSendInitialMetadata :: [Metadata] -> IO (OpT ())\nopSendInitialMetadata elems = do\n (mdArrPtr, free) <- mallocMetadata elems\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendInitialMetadata))\n {#set grpc_op->data.send_initial_metadata.count#} p (fromIntegral (length elems))\n {#set grpc_op->data.send_initial_metadata.metadata#} p (C.castPtr mdArrPtr)\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.is_set#} p 0\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.level#} p 0\n ]\n finish = do\n free\n return (Op add value finish)\n\ndata RpcStatus = RpcStatus [Metadata] StatusCode B.ByteString\n deriving Show\n\nopRecvStatusOnClient :: ClientReaderWriter -> IO (OpT RpcStatus)\nopRecvStatusOnClient (ClientReaderWriter{..}) = do\n trailingMetadataArrPtr <- mallocMetadataArray\n statusCodePtr <- C.malloc :: IO (Ptr StatusCodeT)\n ptrPtrStatusStr <- C.new C.nullPtr :: IO (Ptr (Ptr CChar))\n capacityPtr <- C.new 0 :: IO (Ptr SizeT)\n value <- newIORef (error \"opRecvStatusOnClient never ran\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvStatusOnClient))\n {#set grpc_op->data.recv_status_on_client.trailing_metadata#} p trailingMetadataArrPtr\n {#set grpc_op->data.recv_status_on_client.status#} p statusCodePtr\n {#set grpc_op->data.recv_status_on_client.status_details#} p ptrPtrStatusStr\n {#set grpc_op->data.recv_status_on_client.status_details_capacity#} p capacityPtr\n ]\n finish = do\n trailingMd <- readMetadataArray trailingMetadataArrPtr\n statusCode <- fmap toStatusCode (C.peek statusCodePtr)\n statusDetails <- B.packCString =<< C.peek ptrPtrStatusStr\n let status = RpcStatus trailingMd statusCode statusDetails\n writeIORef value status\n putMVar statusFromServer status\n free\n free = do\n freeMetadataArray trailingMetadataArrPtr\n C.free statusCodePtr\n C.free ptrPtrStatusStr\n C.free capacityPtr\n return (Op add value finish)\n\nopSendCloseFromClient :: IO (OpT ())\nopSendCloseFromClient = do\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendCloseFromClient))\n ]\n finish =\n return ()\n return (Op add value finish)\n\nclientWaitForInitialMetadata :: ClientReaderWriter -> IO (RpcReply [Metadata])\nclientWaitForInitialMetadata crw@(ClientReaderWriter { .. }) = do\n initMD <- readIORef initialMDRef\n case initMD of\n Just md -> return (RpcOk md)\n Nothing -> do\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n res <- callBatch crw [ OpX recvInitialMetadataOp ]\n case res of\n RpcOk _ -> do\n md <- opRead recvInitialMetadataOp\n writeIORef initialMDRef (Just md)\n return (RpcOk md)\n RpcError err ->\n return (RpcError err)\n\nclientReadInitialMetadata :: ClientReaderWriter -> IO (RpcReply (Maybe [Metadata]))\nclientReadInitialMetadata (ClientReaderWriter {..}) = do\n md <- readIORef initialMDRef\n return (RpcOk md)\n\nclientRead :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nclientRead crw = do\n _ <- clientWaitForInitialMetadata crw\n recvMessage crw\n\nrecvMessage :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nrecvMessage crw = do\n recvMessageOp <- opRecvMessage\n res <- callBatch crw [ OpX recvMessageOp ]\n case res of\n RpcOk _ -> do\n bs <- opRead recvMessageOp\n return (RpcOk bs)\n RpcError err -> do\n putStrLn \"recvMessage: callBatch failed\"\n return (RpcError err)\n\nclientWaitForStatus :: ClientReaderWriter -> IO (RpcReply RpcStatus)\nclientWaitForStatus ClientReaderWriter{..} = do\n status <- readMVar statusFromServer\n return (RpcOk status)\n\nclientClose :: ClientReaderWriter -> IO ()\nclientClose (ClientReaderWriter{..}) = do\n withMVar callMVar_ $ \\call ->\n grpcCallDestroy call\n\nclientWrite :: ClientReaderWriter -> B.ByteString -> IO (RpcReply ())\nclientWrite crw@(ClientReaderWriter{..}) arg = do\n sendMessageOp <- opSendMessage arg\n callBatch crw [ OpX sendMessageOp ]\n\nclientSendHalfClose :: ClientReaderWriter -> IO (RpcReply ())\nclientSendHalfClose crw@(ClientReaderWriter{..}) = do\n sendCloseOp <- opSendCloseFromClient\n callBatch crw [ OpX sendCloseOp ]\n\nclientCloseCall :: ClientReaderWriter -> IO ()\nclientCloseCall ClientReaderWriter{..} = do\n tag <- tryTakeMVar statusFromServerTag\n case tag of\n Nothing -> return ()\n Just eDesc ->\n CQ.releaseEvent (ccWorker context) eDesc\n withMVar callMVar_ $ \\call ->\n grpcCallDestroy call\n\ntype Rpc req resp a = ReaderT (Client req resp) (ExceptT RpcError IO) a\n\naskCrw :: Rpc req resp ClientReaderWriter\naskCrw = asks clientCrw\n\naskDecoder :: Rpc req resp (Decoder resp)\naskDecoder = asks clientDecoder\n\naskEncoder :: Rpc req resp (Encoder req)\naskEncoder = asks clientEncoder\n\njoinReply :: RpcReply a -> Rpc req resp a\njoinReply (RpcOk a) = return a\njoinReply (RpcError err) = lift (throwE err)\n\nwithNewClient :: RpcReply (Client req resp) -> Rpc req resp a -> IO (RpcReply a)\nwithNewClient r_client m = do\n case r_client of\n RpcOk client -> withClient client m\n RpcError err -> return (RpcError err)\n\nwithClient :: Client req resp -> Rpc req resp a -> IO (RpcReply a)\nwithClient client m = do\n e <- runExceptT (runReaderT m client)\n case e of\n Left err -> return (RpcError err)\n Right a -> return (RpcOk a)\n\nclientRWOp :: (ClientReaderWriter -> IO a) -> Rpc req resp a\nclientRWOp act = do\n crw <- askCrw\n liftIO (act crw)\n\njoinClientRWOp :: (ClientReaderWriter -> IO (RpcReply a)) -> Rpc req resp a\njoinClientRWOp act = do\n x <- clientRWOp act\n joinReply x\n\nabortIfStatus :: Rpc req resp ()\nabortIfStatus = do\n status <- clientRWOp (tryReadMVar . statusFromServer)\n case status of\n Nothing -> return ()\n Just (RpcStatus _ code msg) ->\n -- call has ended. no further batch ops can be executed.\n -- doesn't have to be an error, could be 200!\n lift (throwE (StatusError code msg))\n\ninitialMetadata :: Rpc req resp [Metadata]\ninitialMetadata = do\n status <- clientRWOp (tryReadMVar . statusFromServer)\n case status of\n Nothing -> joinClientRWOp clientWaitForInitialMetadata\n Just (RpcStatus md _ _) -> do\n return md\n\nwaitForStatus :: Rpc req resp RpcStatus\nwaitForStatus = do\n status <- clientRWOp (tryReadMVar . statusFromServer)\n case status of\n Nothing -> joinClientRWOp clientWaitForStatus\n Just status' -> return status'\n\nreceiveMessage :: Rpc req resp (Maybe resp)\nreceiveMessage = do\n abortIfStatus\n msg <- joinClientRWOp clientRead\n case msg of\n Nothing -> return Nothing\n Just x -> do\n decoder <- askDecoder\n liftM Just (joinReply =<< liftIO (decoder x))\n\nreceiveAllMessages :: Rpc req resp [resp]\nreceiveAllMessages = do\n decoder <- askDecoder\n let go acc = do\n value <- joinClientRWOp clientRead\n case value of\n Just x -> do\n y <- joinReply =<< (liftIO (decoder x))\n go (y:acc)\n Nothing -> return (reverse acc)\n go []\n\nsendMessage :: req -> Rpc req resp ()\nsendMessage req = do\n abortIfStatus\n encoder <- askEncoder\n bs <- joinReply =<< liftIO (encoder req)\n joinClientRWOp (\\crw -> clientWrite crw bs)\n\nsendHalfClose :: Rpc req resp ()\nsendHalfClose = do\n abortIfStatus\n joinClientRWOp clientSendHalfClose\n\ncloseCall :: Rpc req resp ()\ncloseCall =\n clientRWOp clientClose\n\ndata RpcReply a\n = RpcOk a\n | RpcError RpcError\n deriving Show\n\ndata RpcError\n = DeadlineExceeded\n | Cancelled\n | Error String\n | CallErrorStatus CallError\n | StatusError StatusCode B.ByteString\n deriving Show\n","old_contents":"-- Copyright (c) 2016, Google Inc.\n-- All rights reserved.\n--\n-- Redistribution and use in source and binary forms, with or without\n-- modification, are permitted provided that the following conditions are met:\n-- * Redistributions of source code must retain the above copyright\n-- notice, this list of conditions and the following disclaimer.\n-- * Redistributions in binary form must reproduce the above copyright\n-- notice, this list of conditions and the following disclaimer in the\n-- documentation and\/or other materials provided with the distribution.\n-- * Neither the name of Google Inc. nor the\n-- names of its contributors may be used to endorse or promote products\n-- derived from this software without specific prior written permission.\n--\n-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n-- DISCLAIMED. IN NO EVENT SHALL Google Inc. BE LIABLE FOR ANY\n-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n--\n--------------------------------------------------------------------------------\n{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, ExistentialQuantification, RecordWildCards #-}\nmodule Network.Grpc.Core.Call where\n\n\nimport Control.Concurrent\nimport Control.Exception\nimport Control.Monad\n\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Lazy as L\nimport Data.Monoid ((<>), Last(..))\nimport Data.IORef\n\nimport Foreign.C.Types as C\nimport qualified Foreign.Marshal.Alloc as C\nimport qualified Foreign.Marshal.Utils as C\nimport qualified Foreign.Ptr as C\nimport Foreign.Ptr (Ptr)\nimport qualified Foreign.Storable as C\n\n-- transformers\nimport Control.Monad.IO.Class\nimport Control.Monad.Trans.Class\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Reader\n\nimport qualified Network.Grpc.CompletionQueue as CQ\nimport Network.Grpc.Lib.PropagationBits\n{#import Network.Grpc.Lib.ByteBuffer#}\n{#import Network.Grpc.Lib.Metadata#}\n{#import Network.Grpc.Lib.TimeSpec#}\n{#import Network.Grpc.Lib.Core#}\n\n\n#include \n#include \"hs_grpc.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\ndata Deadline\n = AbsoluteDeadline TimeSpec\n | RelativeDeadline Int --seconds\n\ndata ClientContext = ClientContext\n { ccChannel :: Channel\n , ccCQ :: CompletionQueue\n , ccWorker :: CQ.Worker\n }\n\ndata CallOptions = CallOptions\n { coDeadline :: Maybe Deadline\n , coParentContext :: Maybe () -- todo\n , coPropagationMask :: Maybe PropagationMask\n , coMetadata :: [Metadata]\n }\n\ninstance Monoid CallOptions where\n mempty = CallOptions Nothing Nothing Nothing []\n mappend (CallOptions a b c d) (CallOptions a' b' c' d') =\n CallOptions\n (getLast (Last a <> Last a'))\n (getLast (Last b <> Last b'))\n (getLast (Last c <> Last c'))\n (d <> d')\n\nwithAbsoluteDeadline :: TimeSpec -> CallOptions\nwithAbsoluteDeadline deadline =\n mempty { coDeadline = Just (AbsoluteDeadline deadline) }\n\nwithRelativeDeadlineSeconds :: Int -> CallOptions\nwithRelativeDeadlineSeconds seconds =\n mempty { coDeadline = Just (RelativeDeadline seconds) }\n\nwithParentContext :: () -> CallOptions\nwithParentContext ctx =\n mempty { coParentContext = Just ctx }\n\nwithParentContextPropagating :: () -> PropagationMask -> CallOptions\nwithParentContextPropagating ctx prop =\n mempty { coParentContext = Just ctx\n , coPropagationMask = Just prop }\n\nwithMetadata :: [Metadata] -> CallOptions\nwithMetadata md =\n mempty { coMetadata = md }\n\nresolveDeadline :: CallOptions -> IO TimeSpec\nresolveDeadline co =\n case coDeadline co of\n Nothing -> return gprInfFuture\n Just (AbsoluteDeadline deadline) -> return deadline\n Just (RelativeDeadline seconds) ->\n secondsFromNow (fromIntegral seconds)\n\nnewClientContext :: Channel -> IO ClientContext\nnewClientContext chan = do\n cq <- completionQueueCreate reservedPtr\n cqt <- CQ.startCompletionQueueThread cq\n return (ClientContext chan cq cqt)\n\ndestroyClientContext :: ClientContext -> IO ()\ndestroyClientContext (ClientContext _ cq w) = do\n completionQueueShutdown cq\n CQ.waitWorkerTermination w\n\ntype MethodName = B.ByteString\ntype Arg = B.ByteString\n\n-- | Run the IO function once, cache it in the MVar.\nonceMVar :: MVar (Maybe a) -> IO a -> IO a\nonceMVar mvar io = modifyMVar mvar $ \\x ->\n case x of\n Just x' -> return (x, x')\n Nothing -> do\n x' <- io\n return (Just x', x')\n\nreservedPtr :: Ptr ()\nreservedPtr = C.nullPtr\n\ndata UnaryResult a = UnaryResult [Metadata] [Metadata] a deriving Show\n\ncallUnary :: ClientContext -> CallOptions -> MethodName -> Arg -> IO (RpcReply (UnaryResult L.ByteString))\ncallUnary ctx@(ClientContext chan cq _) co method arg = do\n deadline <- resolveDeadline co\n bracket (grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline) grpcCallDestroy $ \\call0 -> newMVar call0 >>= \\mcall -> do\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n recvStatusOp <- opRecvStatusOnClient crw\n recvMessageOp <- opRecvMessage\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX recvInitialMetadataOp\n , OpX recvMessageOp\n , OpX sendMessageOp\n , OpX recvStatusOp\n ]\n case res of\n RpcOk _ -> do\n (RpcStatus trailMD status statusDetails) <- opRead recvStatusOp\n case status of\n StatusOk -> do\n initMD <- opRead recvInitialMetadataOp\n answ <- opRead recvMessageOp\n let answ' = maybe L.empty id answ\n return (RpcOk (UnaryResult initMD trailMD answ'))\n _ -> return (RpcError (StatusError status statusDetails))\n RpcError err -> return (RpcError err)\n\ncallDownstream :: ClientContext -> CallOptions -> MethodName -> Arg -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallDownstream ctx@(ClientContext chan cq _) co method arg = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX sendMessageOp\n ]\n case res of\n RpcOk _ -> do\n return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n\ncallUpstream :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallUpstream ctx@(ClientContext chan cq _) co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> do\n return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n\ncallBidi :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallBidi ctx@(ClientContext chan cq _) co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n\n crw <- newClientReaderWriter ctx mcall\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n\ndata Client req resp = Client\n { clientCrw :: ClientReaderWriter\n , clientEncoder :: Encoder req\n , clientDecoder :: Decoder resp\n }\n\ntype Decoder a = L.ByteString -> IO (RpcReply a)\ntype Encoder a = a -> IO (RpcReply B.ByteString)\n\ndefaultDecoder :: L.ByteString -> IO (RpcReply L.ByteString)\ndefaultDecoder bs = return (RpcOk bs)\n\ndefaultEncoder :: B.ByteString -> IO (RpcReply B.ByteString)\ndefaultEncoder bs = return (RpcOk bs)\n\ndata ClientReaderWriter = ClientReaderWriter {\n context :: ClientContext,\n callMVar_ :: MVar Call,\n initialMDRef :: !(IORef (Maybe [Metadata])),\n trailingMDRef :: !(IORef (Maybe [Metadata])),\n statusFromServer :: !(MVar RpcStatus)\n}\n\nnewClientReaderWriter :: ClientContext -> MVar Call -> IO ClientReaderWriter\nnewClientReaderWriter ctx mcall = do\n initMD <- newIORef Nothing\n trailMD <- newIORef Nothing\n status <- newEmptyMVar\n return (ClientReaderWriter ctx mcall initMD trailMD status)\n\ndata OpX = forall t. OpX (OpT t)\n\ndata OpArray = OpArray { opArrPtr :: !GrpcOpPtr\n , opArrLen :: !CULong\n , opArrFinishAndFree :: !(IO ())\n }\n\ntoArray :: [OpX] -> IO OpArray\ntoArray ops = do\n aptr <- C.mallocBytes (length ops * {#sizeof grpc_op#})\n let ptrs = iterate (`C.plusPtr` {#sizeof grpc_op#}) aptr\n ops' = concatMap (\\(OpX op) -> opAdd op) ops\n free = C.free aptr >> sequence_ (map (\\(OpX op) -> opFinish op) ops)\n write op p = do\n {#set grpc_op->flags#} p 0\n {#set grpc_op->reserved#} p C.nullPtr\n op p\n zipWithM_ write ops' ptrs\n return $! OpArray aptr (fromIntegral $ length ops) free\n\ncallBatch :: ClientReaderWriter -> [OpX] -> IO (RpcReply ())\ncallBatch crw ops = do\n let ctx = context crw\n arr <- toArray ops\n let onBatchComplete = opArrFinishAndFree arr\n CQ.withEvent (ccWorker ctx) onBatchComplete $ \\eDesc -> do\n callStatus <- withMVar (callMVar_ crw) $ \\call ->\n grpcCallStartBatch call (opArrPtr arr) (opArrLen arr) (CQ.eventTag eDesc) reservedPtr\n case callStatus of\n CallOk -> do\n e <- CQ.interruptibleWaitEvent eDesc\n case e of\n QueueOpComplete OpSuccess _ -> return (RpcOk ())\n QueueOpComplete OpError _ -> return (RpcError (Error \"callBatch: op error\"))\n QueueTimeOut -> return (RpcError DeadlineExceeded)\n QueueShutdown -> return (RpcError (Error \"queue shutdown\"))\n _ -> do\n return (RpcError (CallErrorStatus callStatus))\n\ndata OpT out = Op\n { opAdd :: [Ptr GrpcOp -> IO ()]\n , opValue :: IORef out\n , opFinish :: IO ()\n }\n\nopRead :: OpT a -> IO a\nopRead op = readIORef (opValue op)\n\nopRecvInitialMetadata :: ClientReaderWriter -> IO (OpT [Metadata])\nopRecvInitialMetadata crw = do\n arr <- mallocMetadataArray\n value <- newIORef (error \"opRecvInitialMetadata never finished\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvInitialMetadata))\n {#set grpc_op->data.recv_initial_metadata#} p arr\n ]\n finish = do\n mds <- readMetadataArray arr\n writeIORef (initialMDRef crw) (Just mds)\n writeIORef value mds\n freeMetadataArray arr\n return (Op add value finish)\n\nopSendMessage :: B.ByteString -> IO (OpT ())\nopSendMessage bs = do\n bb <- fromByteString bs\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendMessage))\n {#set grpc_op->data.send_message#} p bb\n ]\n finish =\n byteBufferDestroy bb\n return (Op add value finish)\n\nopRecvMessage :: IO (OpT (Maybe L.ByteString))\nopRecvMessage = do\n bbptr <- C.malloc :: IO (Ptr (Ptr CByteBuffer))\n value <- newIORef Nothing\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvMessage))\n {#set grpc_op->data.recv_message#} p bbptr\n ]\n finish = do\n bb <- C.peek bbptr\n C.free bbptr\n writeIORef value =<< if bb \/= C.nullPtr\n then do\n lbs <- toLazyByteString bb\n byteBufferDestroy bb\n return (Just lbs)\n else return Nothing\n return (Op add value finish)\n\nopSendInitialMetadata :: [Metadata] -> IO (OpT ())\nopSendInitialMetadata elems = do\n (mdArrPtr, free) <- mallocMetadata elems\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendInitialMetadata))\n {#set grpc_op->data.send_initial_metadata.count#} p (fromIntegral (length elems))\n {#set grpc_op->data.send_initial_metadata.metadata#} p (C.castPtr mdArrPtr)\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.is_set#} p 0\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.level#} p 0\n ]\n finish = do\n free\n return (Op add value finish)\n\ndata RpcStatus = RpcStatus [Metadata] StatusCode B.ByteString\n deriving Show\n\nopRecvStatusOnClient :: ClientReaderWriter -> IO (OpT RpcStatus)\nopRecvStatusOnClient (ClientReaderWriter{..}) = do\n trailingMetadataArrPtr <- mallocMetadataArray\n statusCodePtr <- C.malloc :: IO (Ptr StatusCodeT)\n ptrPtrStatusStr <- C.new C.nullPtr :: IO (Ptr (Ptr CChar))\n capacityPtr <- C.new 0 :: IO (Ptr SizeT)\n value <- newIORef (error \"opRecvStatusOnClient never ran\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvStatusOnClient))\n {#set grpc_op->data.recv_status_on_client.trailing_metadata#} p trailingMetadataArrPtr\n {#set grpc_op->data.recv_status_on_client.status#} p statusCodePtr\n {#set grpc_op->data.recv_status_on_client.status_details#} p ptrPtrStatusStr\n {#set grpc_op->data.recv_status_on_client.status_details_capacity#} p capacityPtr\n ]\n finish = do\n trailingMd <- readMetadataArray trailingMetadataArrPtr\n statusCode <- fmap toStatusCode (C.peek statusCodePtr)\n statusDetails <- B.packCString =<< C.peek ptrPtrStatusStr\n let status = RpcStatus trailingMd statusCode statusDetails\n writeIORef value status\n putMVar statusFromServer status\n free\n free = do\n freeMetadataArray trailingMetadataArrPtr\n C.free statusCodePtr\n C.free ptrPtrStatusStr\n C.free capacityPtr\n return (Op add value finish)\n\nopSendCloseFromClient :: IO (OpT ())\nopSendCloseFromClient = do\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendCloseFromClient))\n ]\n finish =\n return ()\n return (Op add value finish)\n\nclientWaitForInitialMetadata :: ClientReaderWriter -> IO (RpcReply [Metadata])\nclientWaitForInitialMetadata crw@(ClientReaderWriter { .. }) = do\n initMD <- readIORef initialMDRef\n case initMD of\n Just md -> return (RpcOk md)\n Nothing -> do\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n res <- callBatch crw [ OpX recvInitialMetadataOp ]\n case res of\n RpcOk _ -> do\n md <- opRead recvInitialMetadataOp\n writeIORef initialMDRef (Just md)\n return (RpcOk md)\n RpcError err ->\n return (RpcError err)\n\nclientReadInitialMetadata :: ClientReaderWriter -> IO (RpcReply (Maybe [Metadata]))\nclientReadInitialMetadata (ClientReaderWriter {..}) = do\n md <- readIORef initialMDRef\n return (RpcOk md)\n\nclientRead :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nclientRead crw = do\n _ <- clientWaitForInitialMetadata crw\n recvMessage crw\n\nrecvMessage :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nrecvMessage crw = do\n recvMessageOp <- opRecvMessage\n res <- callBatch crw [ OpX recvMessageOp ]\n case res of\n RpcOk _ -> do\n bs <- opRead recvMessageOp\n return (RpcOk bs)\n RpcError err -> do\n putStrLn \"recvMessage: callBatch failed\"\n return (RpcError err)\n\nclientWaitForStatus :: ClientReaderWriter -> IO (RpcReply RpcStatus)\nclientWaitForStatus crw@(ClientReaderWriter{..}) = do\n status <- tryReadMVar statusFromServer\n case status of\n Nothing -> do\n recvStatusOp <- opRecvStatusOnClient crw\n res <- callBatch crw [ OpX recvStatusOp ]\n case res of\n RpcOk _ -> do\n st <- opRead recvStatusOp\n return (RpcOk st)\n RpcError err -> do\n return (RpcError err)\n Just st -> return (RpcOk st)\n\nclientClose :: ClientReaderWriter -> IO ()\nclientClose (ClientReaderWriter{..}) = do\n withMVar callMVar_ $ \\call ->\n grpcCallDestroy call\n\nclientWrite :: ClientReaderWriter -> B.ByteString -> IO (RpcReply ())\nclientWrite crw@(ClientReaderWriter{..}) arg = do\n sendMessageOp <- opSendMessage arg\n callBatch crw [ OpX sendMessageOp ]\n\nclientSendHalfClose :: ClientReaderWriter -> IO (RpcReply ())\nclientSendHalfClose crw@(ClientReaderWriter{..}) = do\n sendCloseOp <- opSendCloseFromClient\n callBatch crw [ OpX sendCloseOp ]\n\nclientCloseCall :: ClientReaderWriter -> IO ()\nclientCloseCall ClientReaderWriter { callMVar_ = callMVar } =\n withMVar callMVar $ \\call ->\n grpcCallDestroy call\n\ntype Rpc req resp a = ReaderT (Client req resp) (ExceptT RpcError IO) a\n\naskCrw :: Rpc req resp ClientReaderWriter\naskCrw = asks clientCrw\n\naskDecoder :: Rpc req resp (Decoder resp)\naskDecoder = asks clientDecoder\n\naskEncoder :: Rpc req resp (Encoder req)\naskEncoder = asks clientEncoder\n\njoinReply :: RpcReply a -> Rpc req resp a\njoinReply (RpcOk a) = return a\njoinReply (RpcError err) = lift (throwE err)\n\nwithNewClient :: RpcReply (Client req resp) -> Rpc req resp a -> IO (RpcReply a)\nwithNewClient r_client m = do\n case r_client of\n RpcOk client -> withClient client m\n RpcError err -> return (RpcError err)\n\nwithClient :: Client req resp -> Rpc req resp a -> IO (RpcReply a)\nwithClient client m = do\n e <- runExceptT (runReaderT m client)\n case e of\n Left err -> return (RpcError err)\n Right a -> return (RpcOk a)\n\nclientRWOp :: (ClientReaderWriter -> IO a) -> Rpc req resp a\nclientRWOp act = do\n crw <- askCrw\n liftIO (act crw)\n\njoinClientRWOp :: (ClientReaderWriter -> IO (RpcReply a)) -> Rpc req resp a\njoinClientRWOp act = do\n x <- clientRWOp act\n joinReply x\n\nabortIfStatus :: Rpc req resp ()\nabortIfStatus = do\n status <- clientRWOp (tryReadMVar . statusFromServer)\n case status of\n Nothing -> return ()\n Just (RpcStatus _ code msg) ->\n -- call has ended. no further batch ops can be executed.\n -- doesn't have to be an error, could be 200!\n lift (throwE (StatusError code msg))\n\ninitialMetadata :: Rpc req resp [Metadata]\ninitialMetadata = do\n status <- clientRWOp (tryReadMVar . statusFromServer)\n case status of\n Nothing -> joinClientRWOp clientWaitForInitialMetadata\n Just (RpcStatus md _ _) -> do\n return md\n\nwaitForStatus :: Rpc req resp RpcStatus\nwaitForStatus = do\n status <- clientRWOp (tryReadMVar . statusFromServer)\n case status of\n Nothing -> joinClientRWOp clientWaitForStatus\n Just status' -> return status'\n\nreceiveMessage :: Rpc req resp (Maybe resp)\nreceiveMessage = do\n abortIfStatus\n msg <- joinClientRWOp clientRead\n case msg of\n Nothing -> return Nothing\n Just x -> do\n decoder <- askDecoder\n liftM Just (joinReply =<< liftIO (decoder x))\n\nreceiveAllMessages :: Rpc req resp [resp]\nreceiveAllMessages = do\n decoder <- askDecoder\n let go acc = do\n value <- joinClientRWOp clientRead\n case value of\n Just x -> do\n y <- joinReply =<< (liftIO (decoder x))\n go (y:acc)\n Nothing -> return (reverse acc)\n go []\n\nsendMessage :: req -> Rpc req resp ()\nsendMessage req = do\n abortIfStatus\n encoder <- askEncoder\n bs <- joinReply =<< liftIO (encoder req)\n joinClientRWOp (\\crw -> clientWrite crw bs)\n\nsendHalfClose :: Rpc req resp ()\nsendHalfClose = do\n abortIfStatus\n joinClientRWOp clientSendHalfClose\n\ncloseCall :: Rpc req resp ()\ncloseCall =\n clientRWOp clientClose\n\ndata RpcReply a\n = RpcOk a\n | RpcError RpcError\n deriving Show\n\ndata RpcError\n = DeadlineExceeded\n | Cancelled\n | Error String\n | CallErrorStatus CallError\n | StatusError StatusCode B.ByteString\n deriving Show\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"C2hs Haskell"}
{"commit":"2ed52472192eb46eff349380e6aa80487b96dd7e","subject":"More newtypes","message":"More newtypes\n","repos":"norm2782\/hgit2","old_file":"Git2.chs","new_file":"Git2.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\n#include \"git2.h\"\n\nmodule Git2 where\n\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype CPtr = Ptr ()\ntype Ptr2Int = CPtr -> IO CInt\n\nnewtype ObjDB = ObjDB CPtr\nnewtype Repository = Repository CPtr\nnewtype Index = Index CPtr\nnewtype Blob = Blob CPtr\nnewtype ObjID = ObjID CPtr\n\ndefaultPort :: String\ndefaultPort = \"9418\" -- TODO: Import from net.h?\n\n{#enum define Direction { GIT_DIR_FETCH as Fetch\n , GIT_DIR_PUSH as Push}#}\n\n{-\n#define GIT_STATUS_CURRENT 0\n\/** Flags for index status *\/\n#define GIT_STATUS_INDEX_NEW (1 << 0)\n#define GIT_STATUS_INDEX_MODIFIED (1 << 1)\n#define GIT_STATUS_INDEX_DELETED (1 << 2)\n\n\/** Flags for worktree status *\/\n#define GIT_STATUS_WT_NEW (1 << 3)\n#define GIT_STATUS_WT_MODIFIED (1 << 4)\n#define GIT_STATUS_WT_DELETED (1 << 5)\n\n\/\/ TODO Ignored files not handled yet\n#define GIT_STATUS_IGNORED (1 << 6)\n-}\n\n{-\n{#enum define Status { GIT_STATUS_CURRENT as Current\n , GIT_STATUS_INDEX_NEW as NewIndex\n , GIT_STATUS_INDEX_MODIFIED as ModifiedIndex\n , GIT_STATUS_INDEX_DELETED as DeletedIndex\n , GIT_STATUS_WT_NEW as NewWorkTree\n , GIT_STATUS_WT_MODIFIED as ModifiedWorkTree\n , GIT_STATUS_WT_DELETED as DeletedWorkTree\n , GIT_STATUS_IGNORED as Ignored}#}\n-}\n\n{#enum git_otype as OType {underscoreToCase}#}\n{#enum git_rtype as RType {underscoreToCase}#}\n{#enum git_repository_pathid as RepositoryPathID {underscoreToCase}#}\n{#enum git_error as GitError {underscoreToCase}#}\n{#enum git_odb_streammode as ODBStreamMode {underscoreToCase}#}\n\nderiving instance Show GitError\n\n-------------------------------------------------------------------------------\n-- BEGIN: blob.h\n-------------------------------------------------------------------------------\n\n\n{-\n\/**\n * Lookup a blob object from a repository.\n *\n * @param blob pointer to the looked up blob\n * @param repo the repo to use when locating the blob.\n * @param id identity of the blob to locate.\n * @return 0 on success; error code otherwise\n *\/\nGIT_INLINE(int) git_blob_lookup(git_blob **blob, git_repository *repo, const git_oid *id)\n-}\nblobLookup :: Repository -> ObjID -> IO (Either GitError Blob)\nblobLookup = undefined\n\n\n{-\n\n\/**\n * Lookup a blob object from a repository,\n * given a prefix of its identifier (short id).\n *\n * @see git_object_lookup_prefix\n *\n * @param blob pointer to the looked up blob\n * @param repo the repo to use when locating the blob.\n * @param id identity of the blob to locate.\n * @param len the length of the short identifier\n * @return 0 on success; error code otherwise\n *\/\nGIT_INLINE(int) git_blob_lookup_prefix(git_blob **blob, git_repository *repo, const git_oid *id, unsigned int len)\n{\n\treturn git_object_lookup_prefix((git_object **)blob, repo, id, len, GIT_OBJ_BLOB);\n}\n-}\nblobLookupPrefix :: Repository -> ObjID -> Int -> IO (Either GitError Blob)\nblobLookupPrefix = undefined\n\n\n{-\n\/**\n * Close an open blob\n *\n * This is a wrapper around git_object_close()\n *\n * IMPORTANT:\n * It *is* necessary to call this method when you stop\n * using a blob. Failure to do so will cause a memory leak.\n *\n * @param blob the blob to close\n *\/\n\nGIT_INLINE(void) git_blob_close(git_blob *blob)\n{\n\tgit_object_close((git_object *) blob);\n}\n-}\ncloseBlob :: Blob -> IO ()\ncloseBlob = undefined\n\n\n{-\n\/**\n * Get a read-only buffer with the raw content of a blob.\n *\n * A pointer to the raw content of a blob is returned;\n * this pointer is owned internally by the object and shall\n * not be free'd. The pointer may be invalidated at a later\n * time.\n *\n * @param blob pointer to the blob\n * @return the pointer; NULL if the blob has no contents\n *\/\nGIT_EXTERN(const void *) git_blob_rawcontent(git_blob *blob);\n-}\n-- Return raw bytestring ? :x\nrawBlobContent = undefined\n\n\n{-\n\/**\n * Get the size in bytes of the contents of a blob\n *\n * @param blob pointer to the blob\n * @return size on bytes\n *\/\nGIT_EXTERN(int) git_blob_rawsize(git_blob *blob);\n-}\nrawBlobSize :: Blob -> Int\nrawBlobSize = undefined\n\n{-\n\/**\n * Read a file from the working folder of a repository\n * and write it to the Object Database as a loose blob\n *\n * @param oid return the id of the written blob\n * @param repo repository where the blob will be written.\n *\tthis repository cannot be bare\n * @param path file from which the blob will be created,\n *\trelative to the repository's working dir\n * @return 0 on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_blob_create_fromfile(git_oid *oid, git_repository *repo, const char *path);\n-}\ncreateBlobFromFile :: ObjID -> Repository -> String -> IO (Maybe GitError)\ncreateBlobFromFile (ObjID o) (Repository r) path = do\n pathStr <- newCString path\n res <- {#call git_blob_create_fromfile #} o r pathStr\n if res == 0\n then return Nothing\n else return $ Just . toEnum . fromIntegral $ res\n\n{-\n\/**\n * Write an in-memory buffer to the ODB as a blob\n *\n * @param oid return the oid of the written blob\n * @param repo repository where to blob will be written\n * @param buffer data to be written into the blob\n * @param len length of the data\n * @return 0 on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_blob_create_frombuffer(git_oid *oid, git_repository *repo, const void *buffer, size_t len);\n-}\n-- createBlobFromBuffer :: ObjID -> Repository -> ... -> Int -> IO (Maybe GitError)\ncreateBlobFromBuffer = undefined\n\n\n-------------------------------------------------------------------------------\n-- END: blob.h\n-------------------------------------------------------------------------------\n\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: repositoy.h\n-------------------------------------------------------------------------------\n\nrepoIs :: Ptr2Int -> Repository -> IO Bool\nrepoIs ffi (Repository ptr) = return . toBool =<< ffi ptr\n\nopenRepo :: String -> IO (Either GitError Repository)\nopenRepo path = alloca $ \\pprepo -> do\n pstr <- newCString path\n res <- {#call git_repository_open#} pprepo pstr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nopenRepoObjDir :: String -> String -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDir dir objDir idxFile workTree = alloca $ \\pprepo -> do\n dirStr <- newCString dir\n objDirStr <- newCString objDir\n idxFileStr <- newCString idxFile\n wtreeStr <- newCString workTree\n res <- {#call git_repository_open2#} pprepo dirStr objDirStr idxFileStr wtreeStr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nopenRepoObjDb :: String -> ObjDB -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDb dir (ObjDB db) idxFile workTree = alloca $ \\pprepo -> do\n dirStr <- newCString dir\n idxFileStr <- newCString idxFile\n wtreeStr <- newCString workTree\n res <- {#call git_repository_open3#} pprepo dirStr db idxFileStr wtreeStr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\ndiscover :: String -> Bool -> String -> IO (Either GitError String)\ndiscover startPath acrossFs ceilingDirs = alloca $ \\path -> do\n spStr <- newCString startPath\n cdsStr <- newCString ceilingDirs\n res <- {#call git_repository_discover#} path (fromIntegral $ sizeOf path) spStr (fromBool acrossFs) cdsStr\n retEither res $ fmap Right $ peekCString path\n\ndatabase :: Repository -> IO ObjDB\ndatabase (Repository r) = return . ObjDB =<< {#call git_repository_database#} r\n\nindex :: Repository -> IO (Either GitError Index)\nindex (Repository r) = alloca $ \\idx -> do\n res <- {#call git_repository_index#} idx r\n retEither res $ fmap (Right . Index) $ peek idx\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\ninit :: String -> Bool -> IO (Either GitError Repository)\ninit path isBare = alloca $ \\pprepo -> do\n pstr <- newCString path\n res <- {#call git_repository_init#} pprepo pstr (fromBool isBare)\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nretEither :: CInt -> IO (Either GitError a) -> IO (Either GitError a)\nretEither res f | res == 0 = f\n | otherwise = return . Left . toEnum . fromIntegral $ res\n\nisHeadDetached :: Repository -> IO Bool\nisHeadDetached = repoIs {#call git_repository_head_detached#}\n\nisHeadOrphan :: Repository -> IO Bool\nisHeadOrphan = repoIs {#call git_repository_head_orphan#}\n\nisEmpty :: Repository -> IO Bool\nisEmpty = repoIs {#call git_repository_is_empty#}\n\npath :: Repository -> RepositoryPathID -> IO String\npath (Repository r) pathID = peekCString =<< {#call git_repository_path#} r p\n where p = fromIntegral $ fromEnum pathID\n\nisBare :: Repository -> IO Bool\nisBare = repoIs {#call git_repository_is_bare#}\n\n-------------------------------------------------------------------------------\n-- END: repository.h\n-------------------------------------------------------------------------------\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\n#include \"git2.h\"\n\nmodule Git2 where\n\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype CPtr = Ptr ()\ntype Ptr2Int = CPtr -> IO CInt\n\nnewtype ObjDB = ObjDB CPtr\nnewtype Repository = Repository CPtr\nnewtype Index = Index CPtr\n\ndefaultPort :: String\ndefaultPort = \"9418\" -- TODO: Import from net.h?\n\n{#enum define Direction { GIT_DIR_FETCH as Fetch\n , GIT_DIR_PUSH as Push}#}\n\n{-\n#define GIT_STATUS_CURRENT 0\n\/** Flags for index status *\/\n#define GIT_STATUS_INDEX_NEW (1 << 0)\n#define GIT_STATUS_INDEX_MODIFIED (1 << 1)\n#define GIT_STATUS_INDEX_DELETED (1 << 2)\n\n\/** Flags for worktree status *\/\n#define GIT_STATUS_WT_NEW (1 << 3)\n#define GIT_STATUS_WT_MODIFIED (1 << 4)\n#define GIT_STATUS_WT_DELETED (1 << 5)\n\n\/\/ TODO Ignored files not handled yet\n#define GIT_STATUS_IGNORED (1 << 6)\n-}\n\n{-\n{#enum define Status { GIT_STATUS_CURRENT as Current\n , GIT_STATUS_INDEX_NEW as NewIndex\n , GIT_STATUS_INDEX_MODIFIED as ModifiedIndex\n , GIT_STATUS_INDEX_DELETED as DeletedIndex\n , GIT_STATUS_WT_NEW as NewWorkTree\n , GIT_STATUS_WT_MODIFIED as ModifiedWorkTree\n , GIT_STATUS_WT_DELETED as DeletedWorkTree\n , GIT_STATUS_IGNORED as Ignored}#}\n-}\n\n{#enum git_otype as OType {underscoreToCase}#}\n{#enum git_rtype as RType {underscoreToCase}#}\n{#enum git_oid as OID {underscoreToCase}#}\n{#enum git_blob as Blob {underscoreToCase}#}\n{#enum git_repository_pathid as RepositoryPathID {underscoreToCase}#}\n{#enum git_error as GitError {underscoreToCase}#}\n{#enum git_odb_streammode as ODBStreamMode {underscoreToCase}#}\n\nderiving instance Show GitError\n\n-------------------------------------------------------------------------------\n-- BEGIN: blob.h\n-------------------------------------------------------------------------------\n\n\n{-\n\/**\n * Lookup a blob object from a repository.\n *\n * @param blob pointer to the looked up blob\n * @param repo the repo to use when locating the blob.\n * @param id identity of the blob to locate.\n * @return 0 on success; error code otherwise\n *\/\nGIT_INLINE(int) git_blob_lookup(git_blob **blob, git_repository *repo, const git_oid *id)\n-}\nblobLookup :: Repository -> OID -> IO (Either GitError Blob)\nblobLookup = undefined\n\n\n{-\n\n\/**\n * Lookup a blob object from a repository,\n * given a prefix of its identifier (short id).\n *\n * @see git_object_lookup_prefix\n *\n * @param blob pointer to the looked up blob\n * @param repo the repo to use when locating the blob.\n * @param id identity of the blob to locate.\n * @param len the length of the short identifier\n * @return 0 on success; error code otherwise\n *\/\nGIT_INLINE(int) git_blob_lookup_prefix(git_blob **blob, git_repository *repo, const git_oid *id, unsigned int len)\n{\n\treturn git_object_lookup_prefix((git_object **)blob, repo, id, len, GIT_OBJ_BLOB);\n}\n-}\nblobLookupPrefix :: Repository -> OID -> Int -> IO (Either GitError Blob)\nblobLookupPrefix = undefined\n\n\n{-\n\/**\n * Close an open blob\n *\n * This is a wrapper around git_object_close()\n *\n * IMPORTANT:\n * It *is* necessary to call this method when you stop\n * using a blob. Failure to do so will cause a memory leak.\n *\n * @param blob the blob to close\n *\/\n\nGIT_INLINE(void) git_blob_close(git_blob *blob)\n{\n\tgit_object_close((git_object *) blob);\n}\n-}\ncloseBlob :: Blob -> IO ()\ncloseBlob = undefined\n\n\n{-\n\/**\n * Get a read-only buffer with the raw content of a blob.\n *\n * A pointer to the raw content of a blob is returned;\n * this pointer is owned internally by the object and shall\n * not be free'd. The pointer may be invalidated at a later\n * time.\n *\n * @param blob pointer to the blob\n * @return the pointer; NULL if the blob has no contents\n *\/\nGIT_EXTERN(const void *) git_blob_rawcontent(git_blob *blob);\n-}\n-- Return raw bytestring ? :x\nrawBlobContent = undefined\n\n\n{-\n\/**\n * Get the size in bytes of the contents of a blob\n *\n * @param blob pointer to the blob\n * @return size on bytes\n *\/\nGIT_EXTERN(int) git_blob_rawsize(git_blob *blob);\n-}\nrawBlobSize :: Blob -> Int\nrawBlobSize = undefined\n\n{-\n\/**\n * Read a file from the working folder of a repository\n * and write it to the Object Database as a loose blob\n *\n * @param oid return the id of the written blob\n * @param repo repository where the blob will be written.\n *\tthis repository cannot be bare\n * @param path file from which the blob will be created,\n *\trelative to the repository's working dir\n * @return 0 on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_blob_create_fromfile(git_oid *oid, git_repository *repo, const char *path);\n-}\ncreateBlobFromFile :: OID -> Repository -> String -> IO (Maybe GitError)\ncreateBlobFromFile (OID o) (Repository r) path = do\n pathStr <- newCString path\n res <- {#call git_blob_create_fromfile #} o r pathStr\n if res == 0\n then return Nothing\n else return $ Just . toEnum . fromIntegral $ res\n\n{-\n\/**\n * Write an in-memory buffer to the ODB as a blob\n *\n * @param oid return the oid of the written blob\n * @param repo repository where to blob will be written\n * @param buffer data to be written into the blob\n * @param len length of the data\n * @return 0 on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_blob_create_frombuffer(git_oid *oid, git_repository *repo, const void *buffer, size_t len);\n-}\n-- createBlobFromBuffer :: OID -> Repository -> ... -> Int -> IO (Maybe GitError)\ncreateBlobFromBuffer = undefined\n\n\n-------------------------------------------------------------------------------\n-- END: blob.h\n-------------------------------------------------------------------------------\n\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: repositoy.h\n-------------------------------------------------------------------------------\n\nrepoIs :: Ptr2Int -> Repository -> IO Bool\nrepoIs ffi (Repository ptr) = return . toBool =<< ffi ptr\n\nopenRepo :: String -> IO (Either GitError Repository)\nopenRepo path = alloca $ \\pprepo -> do\n pstr <- newCString path\n res <- {#call git_repository_open#} pprepo pstr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nopenRepoObjDir :: String -> String -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDir dir objDir idxFile workTree = alloca $ \\pprepo -> do\n dirStr <- newCString dir\n objDirStr <- newCString objDir\n idxFileStr <- newCString idxFile\n wtreeStr <- newCString workTree\n res <- {#call git_repository_open2#} pprepo dirStr objDirStr idxFileStr wtreeStr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nopenRepoObjDb :: String -> ObjDB -> String -> String -> IO (Either GitError Repository)\nopenRepoObjDb dir (ObjDB db) idxFile workTree = alloca $ \\pprepo -> do\n dirStr <- newCString dir\n idxFileStr <- newCString idxFile\n wtreeStr <- newCString workTree\n res <- {#call git_repository_open3#} pprepo dirStr db idxFileStr wtreeStr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\ndiscover :: String -> Bool -> String -> IO (Either GitError String)\ndiscover startPath acrossFs ceilingDirs = alloca $ \\path -> do\n spStr <- newCString startPath\n cdsStr <- newCString ceilingDirs\n res <- {#call git_repository_discover#} path (fromIntegral $ sizeOf path) spStr (fromBool acrossFs) cdsStr\n retEither res $ fmap Right $ peekCString path\n\ndatabase :: Repository -> IO ObjDB\ndatabase (Repository r) = return . ObjDB =<< {#call git_repository_database#} r\n\nindex :: Repository -> IO (Either GitError Index)\nindex (Repository r) = alloca $ \\idx -> do\n res <- {#call git_repository_index#} idx r\n retEither res $ fmap (Right . Index) $ peek idx\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\ninit :: String -> Bool -> IO (Either GitError Repository)\ninit path isBare = alloca $ \\pprepo -> do\n pstr <- newCString path\n res <- {#call git_repository_init#} pprepo pstr (fromBool isBare)\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nretEither :: CInt -> IO (Either GitError a) -> IO (Either GitError a)\nretEither res f | res == 0 = f\n | otherwise = return . Left . toEnum . fromIntegral $ res\n\nisHeadDetached :: Repository -> IO Bool\nisHeadDetached = repoIs {#call git_repository_head_detached#}\n\nisHeadOrphan :: Repository -> IO Bool\nisHeadOrphan = repoIs {#call git_repository_head_orphan#}\n\nisEmpty :: Repository -> IO Bool\nisEmpty = repoIs {#call git_repository_is_empty#}\n\npath :: Repository -> RepositoryPathID -> IO String\npath (Repository r) pathID = peekCString =<< {#call git_repository_path#} r p\n where p = fromIntegral $ fromEnum pathID\n\nisBare :: Repository -> IO Bool\nisBare = repoIs {#call git_repository_is_bare#}\n\n-------------------------------------------------------------------------------\n-- END: repository.h\n-------------------------------------------------------------------------------\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"c756afc75842fc6d600dc48cd766dd982f909212","subject":"haddock wibbles","message":"haddock wibbles\n","repos":"phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Runtime\/Marshal.chs","new_file":"Foreign\/CUDA\/Runtime\/Marshal.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Marshal\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Memory management for CUDA devices\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Marshal (\n\n -- * Host Allocation\n AllocFlag(..),\n mallocHostArray, freeHost,\n\n -- * Device Allocation\n mallocArray, allocaArray, free,\n\n -- * Unified Memory Allocation\n AttachFlag(..),\n mallocManagedArray,\n\n -- * Marshalling\n peekArray, peekArrayAsync, peekArray2D, peekArray2DAsync, peekListArray,\n pokeArray, pokeArrayAsync, pokeArray2D, pokeArray2DAsync, pokeListArray,\n copyArray, copyArrayAsync, copyArray2D, copyArray2DAsync,\n\n -- * Combined Allocation and Marshalling\n newListArray, newListArrayLen,\n withListArray, withListArrayLen,\n\n -- * Utility\n memset\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cudart\" #}\n\n-- Friends\nimport Foreign.CUDA.Ptr\nimport Foreign.CUDA.Runtime.Error\nimport Foreign.CUDA.Runtime.Stream\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Data.Int\nimport Data.Maybe\nimport Control.Exception\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.Storable\nimport qualified Foreign.Marshal as F\n\n#c\ntypedef enum cudaMemHostAlloc_option_enum {\n\/\/ CUDA_MEMHOSTALLOC_OPTION_DEFAULT = cudaHostAllocDefault,\n CUDA_MEMHOSTALLOC_OPTION_DEVICE_MAPPED = cudaHostAllocMapped,\n CUDA_MEMHOSTALLOC_OPTION_PORTABLE = cudaHostAllocPortable,\n CUDA_MEMHOSTALLOC_OPTION_WRITE_COMBINED = cudaHostAllocWriteCombined\n} cudaMemHostAlloc_option;\n#endc\n\n#if CUDART_VERSION >= 6000\n#c\ntypedef enum cudaMemAttachFlags_option_enum {\n CUDA_MEM_ATTACH_OPTION_GLOBAL = cudaMemAttachGlobal,\n CUDA_MEM_ATTACH_OPTION_HOST = cudaMemAttachHost,\n CUDA_MEM_ATTACH_OPTION_SINGLE = cudaMemAttachSingle\n} cudaMemAttachFlags_option;\n#endc\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Host Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Options for host allocation\n--\n{# enum cudaMemHostAlloc_option as AllocFlag\n { underscoreToCase }\n with prefix=\"CUDA_MEMHOSTALLOC_OPTION\" deriving (Eq, Show) #}\n\n\n-- |\n-- Allocate a section of linear memory on the host which is page-locked and\n-- directly accessible from the device. The storage is sufficient to hold the\n-- given number of elements of a storable type. The runtime system automatically\n-- accelerates calls to functions such as 'peekArrayAsync' and 'pokeArrayAsync'\n-- that refer to page-locked memory.\n--\n-- Note that since the amount of pageable memory is thusly reduced, overall\n-- system performance may suffer. This is best used sparingly to allocate\n-- staging areas for data exchange\n--\n{-# INLINEABLE mallocHostArray #-}\nmallocHostArray :: Storable a => [AllocFlag] -> Int -> IO (HostPtr a)\nmallocHostArray !flags = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (HostPtr a')\n doMalloc x !n = resultIfOk =<< cudaHostAlloc (fromIntegral n * fromIntegral (sizeOf x)) flags\n\n{-# INLINE cudaHostAlloc #-}\n{# fun unsafe cudaHostAlloc\n { alloca'- `HostPtr a' hptr*\n , cIntConv `Int64'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n hptr !p = (HostPtr . castPtr) `fmap` peek p\n\n\n-- |\n-- Free page-locked host memory previously allocated with 'mallecHost'\n--\n{-# INLINEABLE freeHost #-}\nfreeHost :: HostPtr a -> IO ()\nfreeHost !p = nothingIfOk =<< cudaFreeHost p\n\n{-# INLINE cudaFreeHost #-}\n{# fun unsafe cudaFreeHost\n { hptr `HostPtr a' } -> `Status' cToEnum #}\n where hptr = castPtr . useHostPtr\n\n\n--------------------------------------------------------------------------------\n-- Device Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a section of linear memory on the device, and return a reference to\n-- it. The memory is sufficient to hold the given number of elements of storable\n-- type. It is suitable aligned, and not cleared.\n--\n{-# INLINEABLE mallocArray #-}\nmallocArray :: Storable a => Int -> IO (DevicePtr a)\nmallocArray = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')\n doMalloc x !n = resultIfOk =<< cudaMalloc (fromIntegral n * fromIntegral (sizeOf x))\n\n{-# INLINE cudaMalloc #-}\n{# fun unsafe cudaMalloc\n { alloca'- `DevicePtr a' dptr*\n , cIntConv `Int64' } -> `Status' cToEnum #}\n where\n -- C-> Haskell doesn't like qualified imports in marshaller specifications\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n dptr !p = (castDevPtr . DevicePtr) `fmap` peek p\n\n\n-- |\n-- Execute a computation, passing a pointer to a temporarily allocated block of\n-- memory sufficient to hold the given number of elements of storable type. The\n-- memory is freed when the computation terminates (normally or via an\n-- exception), so the pointer must not be used after this.\n--\n-- Note that kernel launches can be asynchronous, so you may need to add a\n-- synchronisation point at the end of the computation.\n--\n{-# INLINEABLE allocaArray #-}\nallocaArray :: Storable a => Int -> (DevicePtr a -> IO b) -> IO b\nallocaArray n = bracket (mallocArray n) free\n\n\n-- |\n-- Free previously allocated memory on the device\n--\n{-# INLINEABLE free #-}\nfree :: DevicePtr a -> IO ()\nfree !p = nothingIfOk =<< cudaFree p\n\n{-# INLINE cudaFree #-}\n{# fun unsafe cudaFree\n { dptr `DevicePtr a' } -> `Status' cToEnum #}\n where\n dptr = useDevicePtr . castDevPtr\n\n\n--------------------------------------------------------------------------------\n-- Unified memory allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Options for unified memory allocations\n--\n#if CUDART_VERSION >= 6000\n{# enum cudaMemAttachFlags_option as AttachFlag\n { underscoreToCase }\n with prefix=\"CUDA_MEM_ATTACH_OPTION\" deriving (Eq, Show) #}\n#else\ndata AttachFlag\n#endif\n\n-- |\n-- Allocates memory that will be automatically managed by the Unified Memory\n-- system\n--\n{-# INLINEABLE mallocManagedArray #-}\nmallocManagedArray :: Storable a => [AttachFlag] -> Int -> IO (DevicePtr a)\n#if CUDART_VERSION < 6000\nmallocManagedArray _ _ = requireSDK 6.0 \"mallocManagedArray\"\n#else\nmallocManagedArray !flags = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')\n doMalloc x !n = resultIfOk =<< cudaMallocManaged (fromIntegral n * fromIntegral (sizeOf x)) flags\n\n{-# INLINE cudaMallocManaged #-}\n{# fun unsafe cudaMallocManaged\n { alloca'- `DevicePtr a' dptr*\n , cIntConv `Int64'\n , combineBitMasks `[AttachFlag]' } -> `Status' cToEnum #}\n where\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n dptr !p = (castDevPtr . DevicePtr) `fmap` peek p\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Copy a number of elements from the device to host memory. This is a\n-- synchronous operation.\n--\n{-# INLINEABLE peekArray #-}\npeekArray :: Storable a => Int -> DevicePtr a -> Ptr a -> IO ()\npeekArray !n !dptr !hptr = memcpy hptr (useDevicePtr dptr) n DeviceToHost\n\n\n-- |\n-- Copy memory from the device asynchronously, possibly associated with a\n-- particular stream. The destination memory must be page locked.\n--\n{-# INLINEABLE peekArrayAsync #-}\npeekArrayAsync :: Storable a => Int -> DevicePtr a -> HostPtr a -> Maybe Stream -> IO ()\npeekArrayAsync !n !dptr !hptr !mst =\n memcpyAsync (useHostPtr hptr) (useDevicePtr dptr) n DeviceToHost mst\n\n\n-- |\n-- Copy a 2D memory area from the device to the host. This is a synchronous\n-- operation.\n--\n{-# INLINEABLE peekArray2D #-}\npeekArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Ptr a -- ^ destination array\n -> Int -- ^ destination array width\n -> IO ()\npeekArray2D !w !h !dptr !dw !hptr !hw =\n memcpy2D hptr hw (useDevicePtr dptr) dw w h DeviceToHost\n\n\n-- |\n-- Copy a 2D memory area from the device to the host asynchronously, possibly\n-- associated with a particular stream. The destination array must be page\n-- locked.\n--\n{-# INLINEABLE peekArray2DAsync #-}\npeekArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> HostPtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Maybe Stream\n -> IO ()\npeekArray2DAsync !w !h !dptr !dw !hptr !hw !mst =\n memcpy2DAsync (useHostPtr hptr) hw (useDevicePtr dptr) dw w h DeviceToHost mst\n\n\n-- |\n-- Copy a number of elements from the device into a new Haskell list. Note that\n-- this requires two memory copies: firstly from the device into a heap\n-- allocated array, and from there marshalled into a list\n--\n{-# INLINEABLE peekListArray #-}\npeekListArray :: Storable a => Int -> DevicePtr a -> IO [a]\npeekListArray !n !dptr =\n F.allocaArray n $ \\p -> do\n peekArray n dptr p\n F.peekArray n p\n\n\n-- |\n-- Copy a number of elements onto the device. This is a synchronous operation.\n--\n{-# INLINEABLE pokeArray #-}\npokeArray :: Storable a => Int -> Ptr a -> DevicePtr a -> IO ()\npokeArray !n !hptr !dptr = memcpy (useDevicePtr dptr) hptr n HostToDevice\n\n\n-- |\n-- Copy memory onto the device asynchronously, possibly associated with a\n-- particular stream. The source memory must be page-locked.\n--\n{-# INLINEABLE pokeArrayAsync #-}\npokeArrayAsync :: Storable a => Int -> HostPtr a -> DevicePtr a -> Maybe Stream -> IO ()\npokeArrayAsync !n !hptr !dptr !mst =\n memcpyAsync (useDevicePtr dptr) (useHostPtr hptr) n HostToDevice mst\n\n\n-- |\n-- Copy a 2D memory area onto the device. This is a synchronous operation.\n--\n{-# INLINEABLE pokeArray2D #-}\npokeArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> Ptr a -- ^ source array\n -> Int -- ^ source array width\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> IO ()\npokeArray2D !w !h !hptr !dw !dptr !hw =\n memcpy2D (useDevicePtr dptr) dw hptr hw w h HostToDevice\n\n\n-- |\n-- Copy a 2D memory area onto the device asynchronously, possibly associated\n-- with a particular stream. The source array must be page locked.\n--\n{-# INLINEABLE pokeArray2DAsync #-}\npokeArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> HostPtr a -- ^ source array\n -> Int -- ^ source array width\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Maybe Stream\n -> IO ()\npokeArray2DAsync !w !h !hptr !hw !dptr !dw !mst =\n memcpy2DAsync (useDevicePtr dptr) dw (useHostPtr hptr) hw w h HostToDevice mst\n\n-- |\n-- Write a list of storable elements into a device array. The array must be\n-- sufficiently large to hold the entire list. This requires two marshalling\n-- operations\n--\n{-# INLINEABLE pokeListArray #-}\npokeListArray :: Storable a => [a] -> DevicePtr a -> IO ()\npokeListArray !xs !dptr = F.withArrayLen xs $ \\len p -> pokeArray len p dptr\n\n\n-- |\n-- Copy the given number of elements from the first device array (source) to the\n-- second (destination). The copied areas may not overlap. This operation is\n-- asynchronous with respect to host, but will not overlap other device\n-- operations.\n--\n{-# INLINEABLE copyArray #-}\ncopyArray :: Storable a => Int -> DevicePtr a -> DevicePtr a -> IO ()\ncopyArray !n !src !dst = memcpy (useDevicePtr dst) (useDevicePtr src) n DeviceToDevice\n\n\n-- |\n-- Copy the given number of elements from the first device array (source) to the\n-- second (destination). The copied areas may not overlap. This operation is\n-- asynchronous with respect to the host, and may be associated with a\n-- particular stream.\n--\n{-# INLINEABLE copyArrayAsync #-}\ncopyArrayAsync :: Storable a => Int -> DevicePtr a -> DevicePtr a -> Maybe Stream -> IO ()\ncopyArrayAsync !n !src !dst !mst =\n memcpyAsync (useDevicePtr dst) (useDevicePtr src) n DeviceToDevice mst\n\n\n-- |\n-- Copy a 2D memory area from the first device array (source) to the second\n-- (destination). The copied areas may not overlap. This operation is\n-- asynchronous with respect to the host, but will not overlap other device\n-- operations.\n--\n{-# INLINEABLE copyArray2D #-}\ncopyArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> IO ()\ncopyArray2D !w !h !src !sw !dst !dw =\n memcpy2D (useDevicePtr dst) dw (useDevicePtr src) sw w h DeviceToDevice\n\n\n-- |\n-- Copy a 2D memory area from the first device array (source) to the second\n-- device array (destination). The copied areas may not overlay. This operation\n-- is asynchronous with respect to the host, and may be associated with a\n-- particular stream.\n--\n{-# INLINEABLE copyArray2DAsync #-}\ncopyArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Maybe Stream\n -> IO ()\ncopyArray2DAsync !w !h !src !sw !dst !dw !mst =\n memcpy2DAsync (useDevicePtr dst) dw (useDevicePtr src) sw w h DeviceToDevice mst\n\n\n--\n-- Memory copy kind\n--\n{# enum cudaMemcpyKind as CopyDirection {}\n with prefix=\"cudaMemcpy\" deriving (Eq, Show) #}\n\n-- |\n-- Copy data between host and device. This is a synchronous operation.\n--\n{-# INLINEABLE memcpy #-}\nmemcpy :: Storable a\n => Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int -- ^ number of elements\n -> CopyDirection\n -> IO ()\nmemcpy !dst !src !n !dir = doMemcpy undefined dst\n where\n doMemcpy :: Storable a' => a' -> Ptr a' -> IO ()\n doMemcpy x _ =\n nothingIfOk =<< cudaMemcpy dst src (fromIntegral n * fromIntegral (sizeOf x)) dir\n\n{-# INLINE cudaMemcpy #-}\n{# fun cudaMemcpy\n { castPtr `Ptr a'\n , castPtr `Ptr a'\n , cIntConv `Int64'\n , cFromEnum `CopyDirection' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy data between the host and device asynchronously, possibly associated\n-- with a particular stream. The host-side memory must be page-locked (allocated\n-- with 'mallocHostArray').\n--\n{-# INLINEABLE memcpyAsync #-}\nmemcpyAsync :: Storable a\n => Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int -- ^ number of elements\n -> CopyDirection\n -> Maybe Stream\n -> IO ()\nmemcpyAsync !dst !src !n !kind !mst = doMemcpy undefined dst\n where\n doMemcpy :: Storable a' => a' -> Ptr a' -> IO ()\n doMemcpy x _ =\n let bytes = fromIntegral n * fromIntegral (sizeOf x) in\n nothingIfOk =<< cudaMemcpyAsync dst src bytes kind (fromMaybe defaultStream mst)\n\n{-# INLINE cudaMemcpyAsync #-}\n{# fun cudaMemcpyAsync\n { castPtr `Ptr a'\n , castPtr `Ptr a'\n , cIntConv `Int64'\n , cFromEnum `CopyDirection'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D memory area between the host and device. This is a synchronous\n-- operation.\n--\n{-# INLINEABLE memcpy2D #-}\nmemcpy2D :: Storable a\n => Ptr a -- ^ destination\n -> Int -- ^ width of destination array\n -> Ptr a -- ^ source\n -> Int -- ^ width of source array\n -> Int -- ^ width to copy\n -> Int -- ^ height to copy\n -> CopyDirection\n -> IO ()\nmemcpy2D !dst !dw !src !sw !w !h !kind = doCopy undefined dst\n where\n doCopy :: Storable a' => a' -> Ptr a' -> IO ()\n doCopy x _ =\n let bytes = fromIntegral (sizeOf x)\n dw' = fromIntegral dw * bytes\n sw' = fromIntegral sw * bytes\n w' = fromIntegral w * bytes\n h' = fromIntegral h\n in\n nothingIfOk =<< cudaMemcpy2D dst dw' src sw' w' h' kind\n\n{-# INLINE cudaMemcpy2D #-}\n{# fun cudaMemcpy2D\n { castPtr `Ptr a'\n , `Int64'\n , castPtr `Ptr a'\n , `Int64'\n , `Int64'\n , `Int64'\n , cFromEnum `CopyDirection'\n }\n -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D memory area between the host and device asynchronously, possibly\n-- associated with a particular stream. The host-side memory must be\n-- page-locked.\n--\n{-# INLINEABLE memcpy2DAsync #-}\nmemcpy2DAsync :: Storable a\n => Ptr a -- ^ destination\n -> Int -- ^ width of destination array\n -> Ptr a -- ^ source\n -> Int -- ^ width of source array\n -> Int -- ^ width to copy\n -> Int -- ^ height to copy\n -> CopyDirection\n -> Maybe Stream\n -> IO ()\nmemcpy2DAsync !dst !dw !src !sw !w !h !kind !mst = doCopy undefined dst\n where\n doCopy :: Storable a' => a' -> Ptr a' -> IO ()\n doCopy x _ =\n let bytes = fromIntegral (sizeOf x)\n dw' = fromIntegral dw * bytes\n sw' = fromIntegral sw * bytes\n w' = fromIntegral w * bytes\n h' = fromIntegral h\n st = fromMaybe defaultStream mst\n in\n nothingIfOk =<< cudaMemcpy2DAsync dst dw' src sw' w' h' kind st\n\n{-# INLINE cudaMemcpy2DAsync #-}\n{# fun cudaMemcpy2DAsync\n { castPtr `Ptr a'\n , `Int64'\n , castPtr `Ptr a'\n , `Int64'\n , `Int64'\n , `Int64'\n , cFromEnum `CopyDirection'\n , useStream `Stream'\n }\n -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Combined Allocation and Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Write a list of storable elements into a newly allocated device array,\n-- returning the device pointer together with the number of elements that were\n-- written. Note that this requires two copy operations: firstly from a Haskell\n-- list into a heap-allocated array, and from there into device memory. The\n-- array should be 'free'd when no longer required.\n--\n{-# INLINEABLE newListArrayLen #-}\nnewListArrayLen :: Storable a => [a] -> IO (DevicePtr a, Int)\nnewListArrayLen !xs =\n F.withArrayLen xs $ \\len p ->\n bracketOnError (mallocArray len) free $ \\d_xs -> do\n pokeArray len p d_xs\n return (d_xs, len)\n\n\n-- |\n-- Write a list of storable elements into a newly allocated device array. This\n-- is 'newListArrayLen' composed with 'fst'.\n--\n{-# INLINEABLE newListArray #-}\nnewListArray :: Storable a => [a] -> IO (DevicePtr a)\nnewListArray !xs = fst `fmap` newListArrayLen xs\n\n\n-- |\n-- Temporarily store a list of elements into a newly allocated device array. An\n-- IO action is applied to the array, the result of which is returned. Similar\n-- to 'newListArray', this requires two marshalling operations of the data.\n--\n-- As with 'allocaArray', the memory is freed once the action completes, so you\n-- should not return the pointer from the action, and be sure that any\n-- asynchronous operations (such as kernel execution) have completed.\n--\n{-# INLINEABLE withListArray #-}\nwithListArray :: Storable a => [a] -> (DevicePtr a -> IO b) -> IO b\nwithListArray !xs = withListArrayLen xs . const\n\n\n-- |\n-- A variant of 'withListArray' which also supplies the number of elements in\n-- the array to the applied function\n--\n{-# INLINEABLE withListArrayLen #-}\nwithListArrayLen :: Storable a => [a] -> (Int -> DevicePtr a -> IO b) -> IO b\nwithListArrayLen !xs !f =\n bracket (newListArrayLen xs) (free . fst) (uncurry . flip $ f)\n--\n-- XXX: Will this attempt to double-free the device array on error (together\n-- with newListArrayLen)?\n--\n\n\n--------------------------------------------------------------------------------\n-- Utility\n--------------------------------------------------------------------------------\n\n-- |\n-- Initialise device memory to a given 8-bit value\n--\n{-# INLINEABLE memset #-}\nmemset :: DevicePtr a -- ^ The device memory\n -> Int64 -- ^ Number of bytes\n -> Int8 -- ^ Value to set for each byte\n -> IO ()\nmemset !dptr !bytes !symbol = nothingIfOk =<< cudaMemset dptr symbol bytes\n\n{-# INLINE cudaMemset #-}\n{# fun unsafe cudaMemset\n { dptr `DevicePtr a'\n , cIntConv `Int8'\n , cIntConv `Int64' } -> `Status' cToEnum #}\n where\n dptr = useDevicePtr . castDevPtr\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Runtime.Marshal\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Memory management for CUDA devices\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Runtime.Marshal (\n\n -- * Host Allocation\n AllocFlag(..),\n mallocHostArray, freeHost,\n\n -- * Device Allocation\n mallocArray, allocaArray, free,\n\n -- * Unified Memory Allocation\n AttachFlag(..),\n mallocManagedArray,\n\n -- * Marshalling\n peekArray, peekArrayAsync, peekArray2D, peekArray2DAsync, peekListArray,\n pokeArray, pokeArrayAsync, pokeArray2D, pokeArray2DAsync, pokeListArray,\n copyArray, copyArrayAsync, copyArray2D, copyArray2DAsync,\n\n -- * Combined Allocation and Marshalling\n newListArray, newListArrayLen,\n withListArray, withListArrayLen,\n\n -- * Utility\n memset\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cudart\" #}\n\n-- Friends\nimport Foreign.CUDA.Ptr\nimport Foreign.CUDA.Runtime.Error\nimport Foreign.CUDA.Runtime.Stream\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Data.Int\nimport Data.Maybe\nimport Control.Exception\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.Storable\nimport qualified Foreign.Marshal as F\n\n#c\ntypedef enum cudaMemHostAlloc_option_enum {\n\/\/ CUDA_MEMHOSTALLOC_OPTION_DEFAULT = cudaHostAllocDefault,\n CUDA_MEMHOSTALLOC_OPTION_DEVICE_MAPPED = cudaHostAllocMapped,\n CUDA_MEMHOSTALLOC_OPTION_PORTABLE = cudaHostAllocPortable,\n CUDA_MEMHOSTALLOC_OPTION_WRITE_COMBINED = cudaHostAllocWriteCombined\n} cudaMemHostAlloc_option;\n#endc\n\n#if CUDART_VERSION >= 6000\n#c\ntypedef enum cudaMemAttachFlags_option_enum {\n CUDA_MEM_ATTACH_OPTION_GLOBAL = cudaMemAttachGlobal,\n CUDA_MEM_ATTACH_OPTION_HOST = cudaMemAttachHost,\n CUDA_MEM_ATTACH_OPTION_SINGLE = cudaMemAttachSingle\n} cudaMemAttachFlags_option;\n#endc\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Host Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Options for host allocation\n--\n{# enum cudaMemHostAlloc_option as AllocFlag\n { underscoreToCase }\n with prefix=\"CUDA_MEMHOSTALLOC_OPTION\" deriving (Eq, Show) #}\n\n\n-- |\n-- Allocate a section of linear memory on the host which is page-locked and\n-- directly accessible from the device. The storage is sufficient to hold the\n-- given number of elements of a storable type. The runtime system automatically\n-- accelerates calls to functions such as 'memcpy' to page-locked memory.\n--\n-- Note that since the amount of pageable memory is thusly reduced, overall\n-- system performance may suffer. This is best used sparingly to allocate\n-- staging areas for data exchange\n--\n{-# INLINEABLE mallocHostArray #-}\nmallocHostArray :: Storable a => [AllocFlag] -> Int -> IO (HostPtr a)\nmallocHostArray !flags = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (HostPtr a')\n doMalloc x !n = resultIfOk =<< cudaHostAlloc (fromIntegral n * fromIntegral (sizeOf x)) flags\n\n{-# INLINE cudaHostAlloc #-}\n{# fun unsafe cudaHostAlloc\n { alloca'- `HostPtr a' hptr*\n , cIntConv `Int64'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n hptr !p = (HostPtr . castPtr) `fmap` peek p\n\n\n-- |\n-- Free page-locked host memory previously allocated with 'mallecHost'\n--\n{-# INLINEABLE freeHost #-}\nfreeHost :: HostPtr a -> IO ()\nfreeHost !p = nothingIfOk =<< cudaFreeHost p\n\n{-# INLINE cudaFreeHost #-}\n{# fun unsafe cudaFreeHost\n { hptr `HostPtr a' } -> `Status' cToEnum #}\n where hptr = castPtr . useHostPtr\n\n\n--------------------------------------------------------------------------------\n-- Device Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a section of linear memory on the device, and return a reference to\n-- it. The memory is sufficient to hold the given number of elements of storable\n-- type. It is suitable aligned, and not cleared.\n--\n{-# INLINEABLE mallocArray #-}\nmallocArray :: Storable a => Int -> IO (DevicePtr a)\nmallocArray = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')\n doMalloc x !n = resultIfOk =<< cudaMalloc (fromIntegral n * fromIntegral (sizeOf x))\n\n{-# INLINE cudaMalloc #-}\n{# fun unsafe cudaMalloc\n { alloca'- `DevicePtr a' dptr*\n , cIntConv `Int64' } -> `Status' cToEnum #}\n where\n -- C-> Haskell doesn't like qualified imports in marshaller specifications\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n dptr !p = (castDevPtr . DevicePtr) `fmap` peek p\n\n\n-- |\n-- Execute a computation, passing a pointer to a temporarily allocated block of\n-- memory sufficient to hold the given number of elements of storable type. The\n-- memory is freed when the computation terminates (normally or via an\n-- exception), so the pointer must not be used after this.\n--\n-- Note that kernel launches can be asynchronous, so you may need to add a\n-- synchronisation point at the end of the computation.\n--\n{-# INLINEABLE allocaArray #-}\nallocaArray :: Storable a => Int -> (DevicePtr a -> IO b) -> IO b\nallocaArray n = bracket (mallocArray n) free\n\n\n-- |\n-- Free previously allocated memory on the device\n--\n{-# INLINEABLE free #-}\nfree :: DevicePtr a -> IO ()\nfree !p = nothingIfOk =<< cudaFree p\n\n{-# INLINE cudaFree #-}\n{# fun unsafe cudaFree\n { dptr `DevicePtr a' } -> `Status' cToEnum #}\n where\n dptr = useDevicePtr . castDevPtr\n\n\n--------------------------------------------------------------------------------\n-- Unified memory allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Options for unified memory allocations\n--\n#if CUDART_VERSION >= 6000\n{# enum cudaMemAttachFlags_option as AttachFlag\n { underscoreToCase }\n with prefix=\"CUDA_MEM_ATTACH_OPTION\" deriving (Eq, Show) #}\n#else\ndata AttachFlag\n#endif\n\n-- |\n-- Allocates memory that will be automatically managed by the Unified Memory\n-- system\n--\n{-# INLINEABLE mallocManagedArray #-}\nmallocManagedArray :: Storable a => [AttachFlag] -> Int -> IO (DevicePtr a)\n#if CUDART_VERSION < 6000\nmallocManagedArray _ _ = requireSDK 6.0 \"mallocManagedArray\"\n#else\nmallocManagedArray !flags = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')\n doMalloc x !n = resultIfOk =<< cudaMallocManaged (fromIntegral n * fromIntegral (sizeOf x)) flags\n\n{-# INLINE cudaMallocManaged #-}\n{# fun unsafe cudaMallocManaged\n { alloca'- `DevicePtr a' dptr*\n , cIntConv `Int64'\n , combineBitMasks `[AttachFlag]' } -> `Status' cToEnum #}\n where\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n dptr !p = (castDevPtr . DevicePtr) `fmap` peek p\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Copy a number of elements from the device to host memory. This is a\n-- synchronous operation.\n--\n{-# INLINEABLE peekArray #-}\npeekArray :: Storable a => Int -> DevicePtr a -> Ptr a -> IO ()\npeekArray !n !dptr !hptr = memcpy hptr (useDevicePtr dptr) n DeviceToHost\n\n\n-- |\n-- Copy memory from the device asynchronously, possibly associated with a\n-- particular stream. The destination memory must be page locked.\n--\n{-# INLINEABLE peekArrayAsync #-}\npeekArrayAsync :: Storable a => Int -> DevicePtr a -> HostPtr a -> Maybe Stream -> IO ()\npeekArrayAsync !n !dptr !hptr !mst =\n memcpyAsync (useHostPtr hptr) (useDevicePtr dptr) n DeviceToHost mst\n\n\n-- |\n-- Copy a 2D memory area from the device to the host. This is a synchronous\n-- operation.\n--\n{-# INLINEABLE peekArray2D #-}\npeekArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Ptr a -- ^ destination array\n -> Int -- ^ destination array width\n -> IO ()\npeekArray2D !w !h !dptr !dw !hptr !hw =\n memcpy2D hptr hw (useDevicePtr dptr) dw w h DeviceToHost\n\n\n-- |\n-- Copy a 2D memory area from the device to the host asynchronously, possibly\n-- associated with a particular stream. The destination array must be page\n-- locked.\n--\n{-# INLINEABLE peekArray2DAsync #-}\npeekArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> HostPtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Maybe Stream\n -> IO ()\npeekArray2DAsync !w !h !dptr !dw !hptr !hw !mst =\n memcpy2DAsync (useHostPtr hptr) hw (useDevicePtr dptr) dw w h DeviceToHost mst\n\n\n-- |\n-- Copy a number of elements from the device into a new Haskell list. Note that\n-- this requires two memory copies: firstly from the device into a heap\n-- allocated array, and from there marshalled into a list\n--\n{-# INLINEABLE peekListArray #-}\npeekListArray :: Storable a => Int -> DevicePtr a -> IO [a]\npeekListArray !n !dptr =\n F.allocaArray n $ \\p -> do\n peekArray n dptr p\n F.peekArray n p\n\n\n-- |\n-- Copy a number of elements onto the device. This is a synchronous operation.\n--\n{-# INLINEABLE pokeArray #-}\npokeArray :: Storable a => Int -> Ptr a -> DevicePtr a -> IO ()\npokeArray !n !hptr !dptr = memcpy (useDevicePtr dptr) hptr n HostToDevice\n\n\n-- |\n-- Copy memory onto the device asynchronously, possibly associated with a\n-- particular stream. The source memory must be page-locked.\n--\n{-# INLINEABLE pokeArrayAsync #-}\npokeArrayAsync :: Storable a => Int -> HostPtr a -> DevicePtr a -> Maybe Stream -> IO ()\npokeArrayAsync !n !hptr !dptr !mst =\n memcpyAsync (useDevicePtr dptr) (useHostPtr hptr) n HostToDevice mst\n\n\n-- |\n-- Copy a 2D memory area onto the device. This is a synchronous operation.\n--\n{-# INLINEABLE pokeArray2D #-}\npokeArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> Ptr a -- ^ source array\n -> Int -- ^ source array width\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> IO ()\npokeArray2D !w !h !hptr !dw !dptr !hw =\n memcpy2D (useDevicePtr dptr) dw hptr hw w h HostToDevice\n\n\n-- |\n-- Copy a 2D memory area onto the device asynchronously, possibly associated\n-- with a particular stream. The source array must be page locked.\n--\n{-# INLINEABLE pokeArray2DAsync #-}\npokeArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> HostPtr a -- ^ source array\n -> Int -- ^ source array width\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Maybe Stream\n -> IO ()\npokeArray2DAsync !w !h !hptr !hw !dptr !dw !mst =\n memcpy2DAsync (useDevicePtr dptr) dw (useHostPtr hptr) hw w h HostToDevice mst\n\n-- |\n-- Write a list of storable elements into a device array. The array must be\n-- sufficiently large to hold the entire list. This requires two marshalling\n-- operations\n--\n{-# INLINEABLE pokeListArray #-}\npokeListArray :: Storable a => [a] -> DevicePtr a -> IO ()\npokeListArray !xs !dptr = F.withArrayLen xs $ \\len p -> pokeArray len p dptr\n\n\n-- |\n-- Copy the given number of elements from the first device array (source) to the\n-- second (destination). The copied areas may not overlap. This operation is\n-- asynchronous with respect to host, but will not overlap other device\n-- operations.\n--\n{-# INLINEABLE copyArray #-}\ncopyArray :: Storable a => Int -> DevicePtr a -> DevicePtr a -> IO ()\ncopyArray !n !src !dst = memcpy (useDevicePtr dst) (useDevicePtr src) n DeviceToDevice\n\n\n-- |\n-- Copy the given number of elements from the first device array (source) to the\n-- second (destination). The copied areas may not overlap. This operation is\n-- asynchronous with respect to the host, and may be associated with a\n-- particular stream.\n--\n{-# INLINEABLE copyArrayAsync #-}\ncopyArrayAsync :: Storable a => Int -> DevicePtr a -> DevicePtr a -> Maybe Stream -> IO ()\ncopyArrayAsync !n !src !dst !mst =\n memcpyAsync (useDevicePtr dst) (useDevicePtr src) n DeviceToDevice mst\n\n\n-- |\n-- Copy a 2D memory area from the first device array (source) to the second\n-- (destination). The copied areas may not overlap. This operation is\n-- asynchronous with respect to the host, but will not overlap other device\n-- operations.\n--\n{-# INLINEABLE copyArray2D #-}\ncopyArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> IO ()\ncopyArray2D !w !h !src !sw !dst !dw =\n memcpy2D (useDevicePtr dst) dw (useDevicePtr src) sw w h DeviceToDevice\n\n\n-- |\n-- Copy a 2D memory area from the first device array (source) to the second\n-- device array (destination). The copied areas may not overlay. This operation\n-- is asynchronous with respect to the host, and may be associated with a\n-- particular stream.\n--\n{-# INLINEABLE copyArray2DAsync #-}\ncopyArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Maybe Stream\n -> IO ()\ncopyArray2DAsync !w !h !src !sw !dst !dw !mst =\n memcpy2DAsync (useDevicePtr dst) dw (useDevicePtr src) sw w h DeviceToDevice mst\n\n\n--\n-- Memory copy kind\n--\n{# enum cudaMemcpyKind as CopyDirection {}\n with prefix=\"cudaMemcpy\" deriving (Eq, Show) #}\n\n-- |\n-- Copy data between host and device. This is a synchronous operation.\n--\n{-# INLINEABLE memcpy #-}\nmemcpy :: Storable a\n => Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int -- ^ number of elements\n -> CopyDirection\n -> IO ()\nmemcpy !dst !src !n !dir = doMemcpy undefined dst\n where\n doMemcpy :: Storable a' => a' -> Ptr a' -> IO ()\n doMemcpy x _ =\n nothingIfOk =<< cudaMemcpy dst src (fromIntegral n * fromIntegral (sizeOf x)) dir\n\n{-# INLINE cudaMemcpy #-}\n{# fun cudaMemcpy\n { castPtr `Ptr a'\n , castPtr `Ptr a'\n , cIntConv `Int64'\n , cFromEnum `CopyDirection' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy data between the host and device asynchronously, possibly associated\n-- with a particular stream. The host-side memory must be page-locked (allocated\n-- with 'mallocHostArray').\n--\n{-# INLINEABLE memcpyAsync #-}\nmemcpyAsync :: Storable a\n => Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int -- ^ number of elements\n -> CopyDirection\n -> Maybe Stream\n -> IO ()\nmemcpyAsync !dst !src !n !kind !mst = doMemcpy undefined dst\n where\n doMemcpy :: Storable a' => a' -> Ptr a' -> IO ()\n doMemcpy x _ =\n let bytes = fromIntegral n * fromIntegral (sizeOf x) in\n nothingIfOk =<< cudaMemcpyAsync dst src bytes kind (fromMaybe defaultStream mst)\n\n{-# INLINE cudaMemcpyAsync #-}\n{# fun cudaMemcpyAsync\n { castPtr `Ptr a'\n , castPtr `Ptr a'\n , cIntConv `Int64'\n , cFromEnum `CopyDirection'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D memory area between the host and device. This is a synchronous\n-- operation.\n--\n{-# INLINEABLE memcpy2D #-}\nmemcpy2D :: Storable a\n => Ptr a -- ^ destination\n -> Int -- ^ width of destination array\n -> Ptr a -- ^ source\n -> Int -- ^ width of source array\n -> Int -- ^ width to copy\n -> Int -- ^ height to copy\n -> CopyDirection\n -> IO ()\nmemcpy2D !dst !dw !src !sw !w !h !kind = doCopy undefined dst\n where\n doCopy :: Storable a' => a' -> Ptr a' -> IO ()\n doCopy x _ =\n let bytes = fromIntegral (sizeOf x)\n dw' = fromIntegral dw * bytes\n sw' = fromIntegral sw * bytes\n w' = fromIntegral w * bytes\n h' = fromIntegral h\n in\n nothingIfOk =<< cudaMemcpy2D dst dw' src sw' w' h' kind\n\n{-# INLINE cudaMemcpy2D #-}\n{# fun cudaMemcpy2D\n { castPtr `Ptr a'\n , `Int64'\n , castPtr `Ptr a'\n , `Int64'\n , `Int64'\n , `Int64'\n , cFromEnum `CopyDirection'\n }\n -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D memory area between the host and device asynchronously, possibly\n-- associated with a particular stream. The host-side memory must be\n-- page-locked.\n--\n{-# INLINEABLE memcpy2DAsync #-}\nmemcpy2DAsync :: Storable a\n => Ptr a -- ^ destination\n -> Int -- ^ width of destination array\n -> Ptr a -- ^ source\n -> Int -- ^ width of source array\n -> Int -- ^ width to copy\n -> Int -- ^ height to copy\n -> CopyDirection\n -> Maybe Stream\n -> IO ()\nmemcpy2DAsync !dst !dw !src !sw !w !h !kind !mst = doCopy undefined dst\n where\n doCopy :: Storable a' => a' -> Ptr a' -> IO ()\n doCopy x _ =\n let bytes = fromIntegral (sizeOf x)\n dw' = fromIntegral dw * bytes\n sw' = fromIntegral sw * bytes\n w' = fromIntegral w * bytes\n h' = fromIntegral h\n st = fromMaybe defaultStream mst\n in\n nothingIfOk =<< cudaMemcpy2DAsync dst dw' src sw' w' h' kind st\n\n{-# INLINE cudaMemcpy2DAsync #-}\n{# fun cudaMemcpy2DAsync\n { castPtr `Ptr a'\n , `Int64'\n , castPtr `Ptr a'\n , `Int64'\n , `Int64'\n , `Int64'\n , cFromEnum `CopyDirection'\n , useStream `Stream'\n }\n -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Combined Allocation and Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Write a list of storable elements into a newly allocated device array,\n-- returning the device pointer together with the number of elements that were\n-- written. Note that this requires two copy operations: firstly from a Haskell\n-- list into a heap-allocated array, and from there into device memory. The\n-- array should be 'free'd when no longer required.\n--\n{-# INLINEABLE newListArrayLen #-}\nnewListArrayLen :: Storable a => [a] -> IO (DevicePtr a, Int)\nnewListArrayLen !xs =\n F.withArrayLen xs $ \\len p ->\n bracketOnError (mallocArray len) free $ \\d_xs -> do\n pokeArray len p d_xs\n return (d_xs, len)\n\n\n-- |\n-- Write a list of storable elements into a newly allocated device array. This\n-- is 'newListArrayLen' composed with 'fst'.\n--\n{-# INLINEABLE newListArray #-}\nnewListArray :: Storable a => [a] -> IO (DevicePtr a)\nnewListArray !xs = fst `fmap` newListArrayLen xs\n\n\n-- |\n-- Temporarily store a list of elements into a newly allocated device array. An\n-- IO action is applied to the array, the result of which is returned. Similar\n-- to 'newListArray', this requires two marshalling operations of the data.\n--\n-- As with 'allocaArray', the memory is freed once the action completes, so you\n-- should not return the pointer from the action, and be sure that any\n-- asynchronous operations (such as kernel execution) have completed.\n--\n{-# INLINEABLE withListArray #-}\nwithListArray :: Storable a => [a] -> (DevicePtr a -> IO b) -> IO b\nwithListArray !xs = withListArrayLen xs . const\n\n\n-- |\n-- A variant of 'withListArray' which also supplies the number of elements in\n-- the array to the applied function\n--\n{-# INLINEABLE withListArrayLen #-}\nwithListArrayLen :: Storable a => [a] -> (Int -> DevicePtr a -> IO b) -> IO b\nwithListArrayLen !xs !f =\n bracket (newListArrayLen xs) (free . fst) (uncurry . flip $ f)\n--\n-- XXX: Will this attempt to double-free the device array on error (together\n-- with newListArrayLen)?\n--\n\n\n--------------------------------------------------------------------------------\n-- Utility\n--------------------------------------------------------------------------------\n\n-- |\n-- Initialise device memory to a given 8-bit value\n--\n{-# INLINEABLE memset #-}\nmemset :: DevicePtr a -- ^ The device memory\n -> Int64 -- ^ Number of bytes\n -> Int8 -- ^ Value to set for each byte\n -> IO ()\nmemset !dptr !bytes !symbol = nothingIfOk =<< cudaMemset dptr symbol bytes\n\n{-# INLINE cudaMemset #-}\n{# fun unsafe cudaMemset\n { dptr `DevicePtr a'\n , cIntConv `Int8'\n , cIntConv `Int64' } -> `Status' cToEnum #}\n where\n dptr = useDevicePtr . castDevPtr\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"658b5da370c254a992a6682d1c8be0e23191902c","subject":"s\/Xine\/xine\/","message":"s\/Xine\/xine\/\n","repos":"joachifm\/hxine,joachifm\/hxine","old_file":"Xine\/Foreign.chs","new_file":"Xine\/Foreign.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\n-- |\n-- Module : Xine.Foreign\n-- Copyright : (c) Joachim Fasting 2010\n-- License : LGPL (see COPYING)\n-- Maintainer : Joachim Fasting \n-- Stability : unstable\n-- Portability : not portable\n--\n-- A simple binding to xine-lib. Low-level bindings.\n-- Made for xine-lib version 1.1.18.1\n\nmodule Xine.Foreign (\n -- * Version information\n xine_get_version_string, xine_get_version, xine_check_version,\n -- * Global engine handling\n Engine, AudioPort, VideoPort, VisualType(..),\n xine_new, xine_init, xine_open_audio_driver, xine_open_video_driver,\n xine_close_audio_driver, xine_close_video_driver, xine_exit,\n -- * Stream handling\n Stream, StreamParam(..), Speed(..), NormalSpeed(..), Zoom(..),\n AspectRatio(..), MRL, EngineParam(..), Affection(..), TrickMode(..),\n xine_stream_new, xine_stream_master_slave, xine_open, xine_play,\n xine_dispose, xine_eject,\n xine_trick_mode, xine_stop, xine_close, xine_engine_set_param,\n xine_engine_get_param, xine_set_param, xine_get_param,\n -- * Information retrieval\n EngineStatus(..), XineError(..),\n xine_get_error, xine_get_status,\n xine_get_audio_lang, xine_get_spu_lang,\n xine_get_pos_length,\n InfoType(..), MetaType(..),\n xine_get_stream_info, xine_get_meta_info\n ) where\n\nimport Control.Monad (liftM)\nimport Data.Bits\nimport Foreign\nimport Foreign.C\n\n#include \n\n-- Define the name of the dynamic library that has to be loaded before any of\n-- the external C functions may be invoked.\n-- The prefix declaration allows us to refer to identifiers while omitting the\n-- prefix. Prefix matching is case insensitive and any underscore characters\n-- between the prefix and the stem of the identifiers are also removed.\n{#context lib=\"xine\" prefix=\"xine\"#}\n\n-- Opaque types used for structures that are never dereferenced on the\n-- Haskell side.\n{#pointer *xine_t as Engine foreign newtype#}\n{#pointer *xine_audio_port_t as AudioPort foreign newtype#}\n{#pointer *xine_video_port_t as VideoPort foreign newtype#}\n{#pointer *xine_stream_t as Stream foreign newtype#}\n\n-- XXX: just a hack. We really want to be able to pass\n-- custom structs to functions. See 'withData', 'xine_open_audio_driver'.\nnewtype Data = Data (Ptr Data)\n\n-- | Media Resource Locator.\n-- Describes the media to read from. Valid MRLs may be plain file names or\n-- one of the following:\n--\n-- * Filesystem:\n--\n-- file:\\\n--\n-- fifo:\\\n--\n-- stdin:\\\/\n--\n-- * CD and DVD:\n--\n-- dvd:\\\/[device_name][\\\/title[.part]]\n--\n-- dvd:\\\/DVD_image_file[\\\/title[.part]]\n--\n-- dvd:\\\/DVD_directory[\\\/title[.part]]\n--\n-- vcd:\\\/\\\/[CD_image_or_device_name][\\@[letter]number]\n--\n-- vcdo:\\\/\\\/track_number\n--\n-- cdda:\\\/[device][\\\/track_number]\n--\n-- * Video devices:\n--\n-- v4l:\\\/\\\/[tuner_device\\\/frequency\n--\n-- v4l2:\\\/\\\/tuner_device\n--\n-- dvb:\\\/\\\/channel_number\n--\n-- dvb:\\\/\\\/channel_name\n--\n-- dvbc:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvbs:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvbt:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvba:\\\/\\\/channel_name:tuning_parameters\n--\n-- pvr:\\\/tmp_files_path!saved_files_path!max_page_age\n--\n-- * Network:\n--\n-- http:\\\/\\\/host\n--\n-- tcp:\\\/\\\/host[:port]\n--\n-- udp:\\\/\\\/host[:port[?iface=interface]]\n--\n-- rtp:\\\/\\\/host[:port[?iface=interface]]\n--\n-- smb:\\\/\\\/\n--\n-- mms:\\\/\\\/host\n--\n-- pnm:\\\/\\\/host\n--\n-- rtsp:\\\/\\\/host\ntype MRL = String\n\n------------------------------------------------------------------------------\n-- Marshalling\n------------------------------------------------------------------------------\n\ncint2bool :: CInt -> Bool\ncint2bool = (\/= 0)\n{-# INLINE cint2bool #-}\n\nint2cint :: Int -> CInt\nint2cint = fromIntegral\n{-# INLINE int2cint #-}\n\ncint2int :: CInt -> Int\ncint2int = fromIntegral\n{-# INLINE cint2int #-}\n\ncuint2int :: CUInt -> Int\ncuint2int = fromIntegral\n{-# INLINE cuint2int #-}\n\ncint2enum :: Enum a => CInt -> a\ncint2enum = toEnum . cint2int\n{-# INLINE cint2enum #-}\n\nenum2cint :: Enum a => a -> CInt\nenum2cint = int2cint . fromEnum\n{-# INLINE enum2cint #-}\n\npeekInt :: Ptr CInt -> IO Int\npeekInt = liftM cint2int . peek\n{-# INLINE peekInt #-}\n\n-- For pointers which may be NULL.\nmaybeForeignPtr_ c x | x == nullPtr = return Nothing\n | otherwise = (Just . c) `liftM` newForeignPtr_ x\n\npeekEngine = liftM Engine . newForeignPtr_\n{-# INLINE peekEngine #-}\n\npeekAudioPort = maybeForeignPtr_ AudioPort\n{-# INLINE peekAudioPort #-}\n\npeekVideoPort = maybeForeignPtr_ VideoPort\n{-# INLINE peekVideoPort #-}\n\npeekStream = maybeForeignPtr_ Stream\n{-# INLINE peekStream #-}\n\n-- XXX: just a temporary hack until we can actually support\n-- passing a custom struct to functions which support it.\nwithData f = f nullPtr\n\n-- Handle strings which may be NULL.\nwithMaybeString :: Maybe String -> (CString -> IO a) -> IO a\nwithMaybeString Nothing f = f nullPtr\nwithMaybeString (Just s) f = withCString s f\n\n------------------------------------------------------------------------------\n-- Version information\n------------------------------------------------------------------------------\n\n-- | Get xine-lib version string.\n--\n-- Header declaration:\n--\n-- const char *xine_get_version_string (void)\n{#fun pure xine_get_version_string {} -> `String' peekCString*#}\n\n-- | Get version as a triple: major, minor, sub\n--\n-- Header declaration:\n--\n-- void xine_get_version (int *major, int *minor, int *sub)\n{#fun pure xine_get_version\n {alloca- `Int' peekInt*,\n alloca- `Int' peekInt*,\n alloca- `Int' peekInt*} -> `()'#}\n\n-- | Compare given version to xine-lib version (major, minor, sub).\n--\n-- Header declaration:\n--\n-- int xine_check_version (int major, int minor, int sub)\n--\n-- returns 1 if compatible, 0 otherwise.\n{#fun pure xine_check_version\n {int2cint `Int',\n int2cint `Int',\n int2cint `Int'} -> `Bool' cint2bool#}\n\n------------------------------------------------------------------------------\n-- Global engine handling\n------------------------------------------------------------------------------\n\n-- | Valid visual types\n{#enum define VisualType {XINE_VISUAL_TYPE_NONE as None\n ,XINE_VISUAL_TYPE_X11 as X11\n ,XINE_VISUAL_TYPE_X11_2 as X11_2\n ,XINE_VISUAL_TYPE_AA as AA\n ,XINE_VISUAL_TYPE_FB as FB\n ,XINE_VISUAL_TYPE_GTK as GTK\n ,XINE_VISUAL_TYPE_DFB as DFB\n ,XINE_VISUAL_TYPE_PM as PM\n ,XINE_VISUAL_TYPE_DIRECTX as DirectX\n ,XINE_VISUAL_TYPE_CACA as CACA\n ,XINE_VISUAL_TYPE_MACOSX as MacOSX\n ,XINE_VISUAL_TYPE_XCB as XCB\n ,XINE_VISUAL_TYPE_RAW as Raw\n }#}\n\nderiving instance Eq VisualType\n\n-- | Pre-init the xine engine.\n--\n-- Header declaration:\n--\n-- xine_t *xine_new (void)\n{#fun xine_new {} -> `Engine' peekEngine*#}\n\n-- | Post-init the xine engine.\n--\n-- Header declaration:\n--\n-- void xine_init (xine_t *self)\n{#fun xine_init {withEngine* `Engine'} -> `()'#}\n\n-- | Initialise audio driver.\n--\n-- Header declaration:\n--\n-- xine_audio_port_t *xine_open_audio_driver (xine_t *self, const char *id,\n-- void *data)\n--\n-- id: identifier of the driver, may be NULL for auto-detection\n--\n-- data: special data struct for ui\/driver communication\n--\n-- May return NULL if the driver failed to load.\n{#fun xine_open_audio_driver\n {withEngine* `Engine'\n ,withMaybeString* `(Maybe String)'\n ,withData- `Data'} -> `(Maybe AudioPort)' peekAudioPort*#}\n\n-- | Initialise video driver.\n--\n-- Header declaration:\n--\n-- xine_video_port_t *xine_open_video_driver (xine_t *self, const char *id,\n-- int visual, void *data)\n--\n-- id: identifier of the driver, may be NULL for auto-detection\n--\n-- data: special data struct for ui\/driver communication\n--\n-- visual : video driver flavor selector\n--\n-- May return NULL if the driver failed to load.\n{#fun xine_open_video_driver\n {withEngine* `Engine'\n ,withMaybeString* `(Maybe String)'\n ,enum2cint `VisualType'\n ,withData- `Data'} -> `(Maybe VideoPort)' peekVideoPort*#}\n\n-- | Close audio port.\n--\n-- Header declaration:\n--\n-- void xine_close_audio_driver (xine_t *self, xine_audio_port_t *driver)\n{#fun xine_close_audio_driver\n {withEngine* `Engine'\n ,withAudioPort* `AudioPort'} -> `()'#}\n\n-- | Close video port.\n--\n-- Header declaration:\n--\n-- void xine_close_video_driver (xine_t *self, xine_video_port_t *driver)\n{#fun xine_close_video_driver\n {withEngine* `Engine'\n ,withVideoPort* `VideoPort'} -> `()'#}\n\n-- | Free all resources, close all plugins, close engine.\n--\n-- Header declaration:\n--\n-- void xine_exit (xine_t *self)\n{#fun xine_exit {withEngine* `Engine'} -> `()'#}\n\n------------------------------------------------------------------------------\n-- Stream handling\n------------------------------------------------------------------------------\n\n-- | Engine parameter enumeration.\n{#enum define EngineParam\n {XINE_ENGINE_PARAM_VERBOSITY as EngineVerbosity}#}\n\n-- | Stream parameter enumeration.\n{#enum define StreamParam\n {XINE_PARAM_SPEED as Speed\n ,XINE_PARAM_AV_OFFSET as AvOffset\n ,XINE_PARAM_AUDIO_CHANNEL_LOGICAL as AudioChannelLogical\n ,XINE_PARAM_SPU_CHANNEL as SpuChannel\n ,XINE_PARAM_AUDIO_VOLUME as AudioVolume\n ,XINE_PARAM_AUDIO_MUTE as AudioMute\n ,XINE_PARAM_AUDIO_COMPR_LEVEL as AudioComprLevel\n ,XINE_PARAM_AUDIO_REPORT_LEVEL as AudioReportLevel\n ,XINE_PARAM_VERBOSITY as Verbosity\n ,XINE_PARAM_SPU_OFFSET as SpuOffset\n ,XINE_PARAM_IGNORE_VIDEO as IgnoreVideo\n ,XINE_PARAM_IGNORE_AUDIO as IgnoreAudio\n ,XINE_PARAM_BROADCASTER_PORT as BroadcasterPort\n ,XINE_PARAM_METRONOM_PREBUFFER as MetronomPrebuffer\n ,XINE_PARAM_EQ_30HZ as Eq30Hz\n ,XINE_PARAM_EQ_60HZ as Eq60Hz\n ,XINE_PARAM_EQ_125HZ as Eq125Hz\n ,XINE_PARAM_EQ_500HZ as Eq500Hz\n ,XINE_PARAM_EQ_1000HZ as Eq1000Hz\n ,XINE_PARAM_EQ_2000HZ as Eq2000Hz\n ,XINE_PARAM_EQ_4000HZ as Eq4000Hz\n ,XINE_PARAM_EQ_8000HZ as Eq8000Hz\n ,XINE_PARAM_EQ_16000HZ as Eq16000Hz\n ,XINE_PARAM_AUDIO_CLOSE_DEVICE as AudioCloseDevice\n ,XINE_PARAM_AUDIO_AMP_MUTE as AmpMute\n ,XINE_PARAM_FINE_SPEED as FineSpeed\n ,XINE_PARAM_EARLY_FINISHED_EVENT as EarlyFinishedEvent\n ,XINE_PARAM_GAPLESS_SWITCH as GaplessSwitch\n ,XINE_PARAM_DELAY_FINISHED_EVENT as DelayFinishedEvent\n ,XINE_PARAM_VO_DEINTERLACE as Deinterlace\n ,XINE_PARAM_VO_ASPECT_RATIO as AspectRatio\n ,XINE_PARAM_VO_HUE as Hue\n ,XINE_PARAM_VO_SATURATION as Saturation\n ,XINE_PARAM_VO_CONTRAST as Contrast\n ,XINE_PARAM_VO_BRIGHTNESS as Brightness\n ,XINE_PARAM_VO_ZOOM_X as ZoomX\n ,XINE_PARAM_VO_ZOOM_Y as ZoomY\n ,XINE_PARAM_VO_PAN_SCAN as PanScan\n ,XINE_PARAM_VO_TVMODE as TvMode\n ,XINE_PARAM_VO_WINDOW_WIDTH as WindowWidth\n ,XINE_PARAM_VO_WINDOW_HEIGHT as WindowHeight\n ,XINE_PARAM_VO_CROP_LEFT as CropLeft\n ,XINE_PARAM_VO_CROP_RIGHT as CropRight\n ,XINE_PARAM_VO_CROP_TOP as CropTop\n ,XINE_PARAM_VO_CROP_BOTTOM as CropBottom\n }#}\n\n-- | Values for XINE_PARAM_SPEED parameter.\n{#enum define Speed\n {XINE_SPEED_PAUSE as Pause\n ,XINE_SPEED_SLOW_4 as Slow4\n ,XINE_SPEED_SLOW_2 as Slow2\n ,XINE_SPEED_NORMAL as Normal\n ,XINE_SPEED_FAST_2 as Fast2\n ,XINE_SPEED_FAST_4 as Fast4\n }#}\n\nderiving instance Eq Speed\n\n-- | Value for XINE_PARAM_FINE_SPEED\n{#enum define NormalSpeed\n {XINE_FINE_SPEED_NORMAL as NormalSpeed}#}\n\n-- | Values for XINE_PARAM_VO_ZOOM_\n{#enum define Zoom\n {XINE_VO_ZOOM_STEP as ZoomStep\n ,XINE_VO_ZOOM_MAX as ZoomMax\n ,XINE_VO_ZOOM_MIN as ZoomMin}#}\n\n-- | Values for XINE_PARAM_VO_ASPECT_RATIO\n{#enum define AspectRatio\n {XINE_VO_ASPECT_AUTO as AspectAuto\n ,XINE_VO_ASPECT_SQUARE as AspectSquare\n ,XINE_VO_ASPECT_4_3 as Aspect43\n ,XINE_VO_ASPECT_ANAMORPHIC as AspectAnamorphic\n ,XINE_VO_ASPECT_DVB as AspectDvb\n ,XINE_VO_ASPECT_NUM_RATIOS as AspectNumRatios\n }#}\n\n-- | Create a new stream for media playback.\n--\n-- Header declaration:\n--\n-- xine_stream_t *xine_stream_new (xine_t *self,\n-- xine_audio_port *ao, xine_video_port_t *vo)\n--\n-- Returns xine_stream_t* if OK, NULL on error (use 'xine_get_error' for\n-- details).\n{#fun xine_stream_new\n {withEngine* `Engine'\n ,withAudioPort* `AudioPort'\n ,withVideoPort* `VideoPort'} -> `(Maybe Stream)' peekStream*#}\n\n-- | Make one stream the slave of another.\n-- Certain operations on the master stream are also applied to the slave\n-- stream.\n--\n-- Header declaration:\n--\n-- int xine_stream_master_slave (xine_stream_t *master, xine_stream_t *slave,\n-- int affection)\n--\n-- returns 1 on success, 0 on failure.\n{#fun xine_stream_master_slave\n {withStream* `Stream'\n ,withStream* `Stream'\n ,combineAffection `[Affection]'} -> `Int' cint2int#}\n\n-- | The affection determines which actions on the master stream\n-- are also to be applied to the slave stream. See 'xine_stream_master_slave'.\n{#enum define Affection\n {XINE_MASTER_SLAVE_PLAY as AffectionPlay\n ,XINE_MASTER_SLAVE_STOP as AffectionStop\n ,XINE_MASTER_SLAVE_SPEED as AffectionSpeed}#}\n\n-- | Affections can be ORed together.\ncombineAffection :: [Affection] -> CInt\ncombineAffection [] = enum2cint AffectionSpeed\ncombineAffection xs = foldr1 (.&.) (map enum2cint xs)\n\n-- | Open a stream.\n--\n-- Header declaration:\n--\n-- int xine_open (xine_stream_t *stream, const char *mrl)\n--\n-- Returns 1 if OK, 0 on error (use 'xine_get_error' for details).\n{#fun xine_open\n {withStream* `Stream'\n ,withCAString* `MRL'} -> `Int' cint2int#}\n\n-- | Play a stream from a given position.\n--\n-- Header declaration:\n--\n-- int xine_play (xine_stream_t *stream, int start_pos, int start_time)\n--\n-- Returns 1 if OK, 0 on error (use 'xine_get_error' for details).\n{#fun xine_play\n {withStream* `Stream'\n ,int2cint `Int'\n ,int2cint `Int'} -> `Int' cint2int#}\n\n-- | Set xine to a trick mode for fast forward, backwards playback,\n-- low latency seeking.\n--\n-- Header declaration:\n--\n-- int xine_trick_mode (xine_stream_t *stream, int mode, int value)\n--\n-- Returns 1 if OK, 0 on error (use 'xine_get_error' for details).\n{#fun xine_trick_mode\n {withStream* `Stream'\n ,enum2cint `TrickMode'\n ,int2cint `Int'} -> `Int' cint2int#}\n\n{#enum define TrickMode\n {XINE_TRICK_MODE_OFF as TrickOff\n ,XINE_TRICK_MODE_SEEK_TO_POSITION as TrickSeekToPosition\n ,XINE_TRICK_MODE_SEEK_TO_TIME as TrickSeekToTime\n ,XINE_TRICK_MODE_FAST_FORWARD as TrickFastForward\n ,XINE_TRICK_MODE_FAST_REWIND as TrickRewind}#}\n\n-- | Stop stream playback.\n-- The stream stays valid for new 'xine_open' or 'xine_play'.\n--\n-- Header declaration:\n--\n-- void xine_stop (xine_stream *stream)\n{#fun xine_stop {withStream* `Stream'} -> `()'#}\n\n-- | Free all stream-related resources.\n-- The stream stays valid for new 'xine_open'.\n--\n-- Header declaration:\n--\n-- void xine_close (xine_stream_t *stream)\n{#fun xine_close {withStream* `Stream'} -> `()'#}\n\n-- | Ask current input plugin to eject media.\n--\n-- Header declaration:\n--\n-- int xine_eject (xine_stream_t *stream)\n{#fun xine_eject {withStream* `Stream'} -> `Int' cint2int#}\n\n-- | Stop playback, dispose all stream-related resources.\n-- The stream is no longer valid after this.\n--\n-- Header declaration:\n--\n-- void xine_dispose (xine_stream_t *stream)\n{#fun xine_dispose {withStream* `Stream'} -> `()'#}\n\n-- | Set engine parameter.\n--\n-- Header declaration:\n--\n-- void xine_engine_set_param (xine_t *self, int param, int value)\n{#fun xine_engine_set_param\n {withEngine* `Engine'\n ,enum2cint `EngineParam'\n ,int2cint `Int'} -> `()'#}\n\n-- | Get engine parameter.\n--\n-- Header declaration:\n--\n-- int xine_engine_get_param(xine_t *self, int param)\n{#fun xine_engine_get_param\n {withEngine* `Engine'\n ,enum2cint `EngineParam'} -> `Int' cint2int#}\n\n-- | Set stream parameter.\n--\n-- Header declaration:\n--\n-- void xine_set_param (xine_stream_t *stream, int param, int value)\n{#fun xine_set_param\n `(Enum a)' =>\n {withStream* `Stream'\n ,enum2cint `StreamParam'\n ,enum2cint `a'} -> `()'#}\n\n-- | Get stream parameter.\n--\n-- Header declaration:\n--\n-- int xine_get_param (xine_stream_t *stream, int param)\n{#fun xine_get_param\n `(Enum a)' =>\n {withStream* `Stream'\n ,enum2cint `StreamParam'} -> `a' cint2enum#}\n\n------------------------------------------------------------------------------\n-- Information retrieval\n------------------------------------------------------------------------------\n\n-- | Engine status codes.\n{#enum define EngineStatus\n {XINE_STATUS_IDLE as Idle\n ,XINE_STATUS_STOP as Stopped\n ,XINE_STATUS_PLAY as Playing\n ,XINE_STATUS_QUIT as Quitting}#}\n\nderiving instance Eq EngineStatus\nderiving instance Show EngineStatus\n\n-- | xine error codes.\n{#enum define XineError\n {XINE_ERROR_NONE as NoError\n ,XINE_ERROR_NO_INPUT_PLUGIN as NoInputPlugin\n ,XINE_ERROR_NO_DEMUX_PLUGIN as NoDemuxPlugin\n ,XINE_ERROR_MALFORMED_MRL as MalformedMrl\n ,XINE_ERROR_INPUT_FAILED as InputFailed}#}\n\nderiving instance Eq XineError\nderiving instance Show XineError\n\n-- | Return last error.\n--\n-- Header declaration:\n--\n-- int xine_get_error (xine_stream_t *stream)\n{#fun xine_get_error\n {withStream* `Stream'} -> `XineError' cint2enum#}\n\n-- | Get current xine engine status.\n--\n-- int xine_get_status (xine_stream_t *stream)\n{#fun xine_get_status\n {withStream* `Stream'} -> `EngineStatus' cint2enum#}\n\n-- | Find the audio language of the given channel (use -1 for\n-- current channel).\n--\n-- Header declaration:\n--\n-- int xine_get_audio_lang (xine_stream_t *stream, int channel,\n-- char *lang)\n--\n-- lang must point to a buffer of at least XINE_LANG_MAX bytes.\n--\n-- Returns 1 on success, 0 on failure.\n{#fun xine_get_audio_lang\n {withStream* `Stream'\n ,int2cint `Int'\n ,allocLangBuf- `String' peekCString*} -> `Int' cint2int#}\n\n-- XXX: read the constant XINE_LANG_MAX\nallocLangBuf = allocaArray0 32\n\n-- | Find the spu language of the given channel (use -1 for\n-- current channel).\n--\n-- Header declaration:\n--\n-- int xine_get_spu_lang (xine_stream_t *stream, int channel,\n-- char *lang)\n--\n-- lang must point to a buffer of at least XINE_LANG_MAX bytes.\n--\n-- Returns 1 on success, 0 on failure.\n{#fun xine_get_spu_lang\n {withStream* `Stream'\n ,int2cint `Int'\n ,allocLangBuf- `String' peekCString*} -> `Int' cint2int#}\n\n-- | Get position\\\/length information.\n--\n-- Header declaration:\n--\n-- int xine_get_pos_length (xine_stream_t *stream, int *pos_stream,\n-- int *pos_time, int *length_time)\n--\n-- Returns 1 on success, 0 on failure.\n{#fun xine_get_pos_length\n {withStream* `Stream'\n ,alloca- `Int' peekInt*\n ,alloca- `Int' peekInt*\n ,alloca- `Int' peekInt*} -> `Int' cint2int#}\n\n-- | Get information about the stream.\n--\n-- Header declaration:\n--\n-- int32_t xine_get_stream_info (xine_stream_t *stream, int info)\n{#fun xine_get_stream_info\n {withStream* `Stream'\n ,enum2cint `InfoType'} -> `Int' cuint2int#}\n\n-- | Get meta information about the stream.\n--\n-- Header declaration:\n--\n-- const char *xine_get_meta_info (xine_stream_t *stream, int info)\n{#fun xine_get_meta_info\n {withStream* `Stream'\n ,enum2cint `MetaType'} -> `String' peekCString*#}\n\n{#enum define InfoType\n {XINE_STREAM_INFO_BITRATE as InfoBitrate\n ,XINE_STREAM_INFO_SEEKABLE as InfoSeekable\n ,XINE_STREAM_INFO_VIDEO_WIDTH as InfoVideoWidth\n ,XINE_STREAM_INFO_VIDEO_HEIGHT as InfoVideoHeight\n ,XINE_STREAM_INFO_VIDEO_RATIO as InfoVideoRatio\n ,XINE_STREAM_INFO_VIDEO_CHANNELS as InfoVideoChannels\n ,XINE_STREAM_INFO_VIDEO_STREAMS as InfoVideoStreams\n ,XINE_STREAM_INFO_VIDEO_BITRATE as InfoVideoBitrate\n ,XINE_STREAM_INFO_VIDEO_FOURCC as InfoVideoFourCC\n ,XINE_STREAM_INFO_VIDEO_HANDLED as InfoVideoHandled\n ,XINE_STREAM_INFO_FRAME_DURATION as InfoFrameDuration\n ,XINE_STREAM_INFO_AUDIO_CHANNELS as InfoAudioChannels\n ,XINE_STREAM_INFO_AUDIO_BITS as InfoAudioBits\n ,XINE_STREAM_INFO_AUDIO_SAMPLERATE as InfoAudioSamplerate\n ,XINE_STREAM_INFO_AUDIO_BITRATE as InfoAudioBitrate\n ,XINE_STREAM_INFO_AUDIO_FOURCC as InfoAudioFourCC\n ,XINE_STREAM_INFO_AUDIO_HANDLED as InfoAudioHandled\n ,XINE_STREAM_INFO_HAS_CHAPTERS as InfoHasChapters\n ,XINE_STREAM_INFO_HAS_VIDEO as InfoHasVideo\n ,XINE_STREAM_INFO_HAS_AUDIO as InfoHasAudio\n ,XINE_STREAM_INFO_IGNORE_VIDEO as InfoIgnoreVideo\n ,XINE_STREAM_INFO_IGNORE_AUDIO as InfoIgnoreAudio\n ,XINE_STREAM_INFO_IGNORE_SPU as InfoIgnoreSpu\n ,XINE_STREAM_INFO_VIDEO_HAS_STILL as InfoVideoHasStill\n ,XINE_STREAM_INFO_MAX_AUDIO_CHANNEL as InfoMaxAudioChannel\n ,XINE_STREAM_INFO_MAX_SPU_CHANNEL as InfoMaxSpuChannel\n ,XINE_STREAM_INFO_AUDIO_MODE as InfoAudioMode\n ,XINE_STREAM_INFO_SKIPPED_FRAMES as InfoSkippedFrames\n ,XINE_STREAM_INFO_DISCARDED_FRAMES as InfoDiscardedFrames\n ,XINE_STREAM_INFO_VIDEO_AFD as InfoVideoAFD\n ,XINE_STREAM_INFO_DVD_TITLE_NUMBER as InfoDvdTitleNumber\n ,XINE_STREAM_INFO_DVD_TITLE_COUNT as InfoDvdTitleCount\n ,XINE_STREAM_INFO_DVD_CHAPTER_NUMBER as InfoDvdChapterNumber\n ,XINE_STREAM_INFO_DVD_CHAPTER_COUNT as InfoDvdChapterCount\n ,XINE_STREAM_INFO_DVD_ANGLE_NUMBER as InfoDvdAngleNumber\n ,XINE_STREAM_INFO_DVD_ANGLE_COUNT as InfoDvdAngleCount}#}\n\n{#enum define MetaType\n {XINE_META_INFO_TITLE as MetaTitle\n ,XINE_META_INFO_COMMENT as MetaComment\n ,XINE_META_INFO_ARTIST as MetaArtist\n ,XINE_META_INFO_GENRE as MetaGenre\n ,XINE_META_INFO_ALBUM as MetaAlbum\n ,XINE_META_INFO_YEAR as MetaYear\n ,XINE_META_INFO_VIDEOCODEC as MetaVideoCodec\n ,XINE_META_INFO_AUDIOCODEC as MetaAudioCodec\n ,XINE_META_INFO_SYSTEMLAYER as MetaSystemLayer\n ,XINE_META_INFO_INPUT_PLUGIN as MetaInputPlugin\n ,XINE_META_INFO_CDINDEX_DISCID as MetaDiscId\n ,XINE_META_INFO_TRACK_NUMBER as MetaTrackNumber\n ,XINE_META_INFO_COMPOSER as MetaComposer\n ,XINE_META_INFO_PUBLISHER as MetaPublisher\n ,XINE_META_INFO_LICENSE as MetaLicense\n ,XINE_META_INFO_ARRANGER as MetaArranger\n ,XINE_META_INFO_LYRICIST as MetaLyricist\n ,XINE_META_INFO_CONDUCTOR as MetaConductor\n ,XINE_META_INFO_PERFORMER as MetaPerformer\n ,XINE_META_INFO_ENSEMBLE as MetaEnsemble\n ,XINE_META_INFO_OPUS as MetaOpus\n ,XINE_META_INFO_PART as MetaPart\n ,XINE_META_INFO_PARTNUMBER as MetaPartNumber\n ,XINE_META_INFO_LOCATION as MetaLocation}#}\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\n-- |\n-- Module : Xine.Foreign\n-- Copyright : (c) Joachim Fasting 2010\n-- License : LGPL (see COPYING)\n-- Maintainer : Joachim Fasting \n-- Stability : unstable\n-- Portability : not portable\n--\n-- A simple binding to xine-lib. Low-level bindings.\n-- Made for xine-lib version 1.1.18.1\n\nmodule Xine.Foreign (\n -- * Version information\n xine_get_version_string, xine_get_version, xine_check_version,\n -- * Global engine handling\n Engine, AudioPort, VideoPort, VisualType(..),\n xine_new, xine_init, xine_open_audio_driver, xine_open_video_driver,\n xine_close_audio_driver, xine_close_video_driver, xine_exit,\n -- * Stream handling\n Stream, StreamParam(..), Speed(..), NormalSpeed(..), Zoom(..),\n AspectRatio(..), MRL, EngineParam(..), Affection(..), TrickMode(..),\n xine_stream_new, xine_stream_master_slave, xine_open, xine_play,\n xine_dispose, xine_eject,\n xine_trick_mode, xine_stop, xine_close, xine_engine_set_param,\n xine_engine_get_param, xine_set_param, xine_get_param,\n -- * Information retrieval\n EngineStatus(..), XineError(..),\n xine_get_error, xine_get_status,\n xine_get_audio_lang, xine_get_spu_lang,\n xine_get_pos_length,\n InfoType(..), MetaType(..),\n xine_get_stream_info, xine_get_meta_info\n ) where\n\nimport Control.Monad (liftM)\nimport Data.Bits\nimport Foreign\nimport Foreign.C\n\n#include \n\n-- Define the name of the dynamic library that has to be loaded before any of\n-- the external C functions may be invoked.\n-- The prefix declaration allows us to refer to identifiers while omitting the\n-- prefix. Prefix matching is case insensitive and any underscore characters\n-- between the prefix and the stem of the identifiers are also removed.\n{#context lib=\"xine\" prefix=\"xine\"#}\n\n-- Opaque types used for structures that are never dereferenced on the\n-- Haskell side.\n{#pointer *xine_t as Engine foreign newtype#}\n{#pointer *xine_audio_port_t as AudioPort foreign newtype#}\n{#pointer *xine_video_port_t as VideoPort foreign newtype#}\n{#pointer *xine_stream_t as Stream foreign newtype#}\n\n-- XXX: just a hack. We really want to be able to pass\n-- custom structs to functions. See 'withData', 'xine_open_audio_driver'.\nnewtype Data = Data (Ptr Data)\n\n-- | Media Resource Locator.\n-- Describes the media to read from. Valid MRLs may be plain file names or\n-- one of the following:\n--\n-- * Filesystem:\n--\n-- file:\\\n--\n-- fifo:\\\n--\n-- stdin:\\\/\n--\n-- * CD and DVD:\n--\n-- dvd:\\\/[device_name][\\\/title[.part]]\n--\n-- dvd:\\\/DVD_image_file[\\\/title[.part]]\n--\n-- dvd:\\\/DVD_directory[\\\/title[.part]]\n--\n-- vcd:\\\/\\\/[CD_image_or_device_name][\\@[letter]number]\n--\n-- vcdo:\\\/\\\/track_number\n--\n-- cdda:\\\/[device][\\\/track_number]\n--\n-- * Video devices:\n--\n-- v4l:\\\/\\\/[tuner_device\\\/frequency\n--\n-- v4l2:\\\/\\\/tuner_device\n--\n-- dvb:\\\/\\\/channel_number\n--\n-- dvb:\\\/\\\/channel_name\n--\n-- dvbc:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvbs:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvbt:\\\/\\\/channel_name:tuning_parameters\n--\n-- dvba:\\\/\\\/channel_name:tuning_parameters\n--\n-- pvr:\\\/tmp_files_path!saved_files_path!max_page_age\n--\n-- * Network:\n--\n-- http:\\\/\\\/host\n--\n-- tcp:\\\/\\\/host[:port]\n--\n-- udp:\\\/\\\/host[:port[?iface=interface]]\n--\n-- rtp:\\\/\\\/host[:port[?iface=interface]]\n--\n-- smb:\\\/\\\/\n--\n-- mms:\\\/\\\/host\n--\n-- pnm:\\\/\\\/host\n--\n-- rtsp:\\\/\\\/host\ntype MRL = String\n\n------------------------------------------------------------------------------\n-- Marshalling\n------------------------------------------------------------------------------\n\ncint2bool :: CInt -> Bool\ncint2bool = (\/= 0)\n{-# INLINE cint2bool #-}\n\nint2cint :: Int -> CInt\nint2cint = fromIntegral\n{-# INLINE int2cint #-}\n\ncint2int :: CInt -> Int\ncint2int = fromIntegral\n{-# INLINE cint2int #-}\n\ncuint2int :: CUInt -> Int\ncuint2int = fromIntegral\n{-# INLINE cuint2int #-}\n\ncint2enum :: Enum a => CInt -> a\ncint2enum = toEnum . cint2int\n{-# INLINE cint2enum #-}\n\nenum2cint :: Enum a => a -> CInt\nenum2cint = int2cint . fromEnum\n{-# INLINE enum2cint #-}\n\npeekInt :: Ptr CInt -> IO Int\npeekInt = liftM cint2int . peek\n{-# INLINE peekInt #-}\n\n-- For pointers which may be NULL.\nmaybeForeignPtr_ c x | x == nullPtr = return Nothing\n | otherwise = (Just . c) `liftM` newForeignPtr_ x\n\npeekEngine = liftM Engine . newForeignPtr_\n{-# INLINE peekEngine #-}\n\npeekAudioPort = maybeForeignPtr_ AudioPort\n{-# INLINE peekAudioPort #-}\n\npeekVideoPort = maybeForeignPtr_ VideoPort\n{-# INLINE peekVideoPort #-}\n\npeekStream = maybeForeignPtr_ Stream\n{-# INLINE peekStream #-}\n\n-- XXX: just a temporary hack until we can actually support\n-- passing a custom struct to functions which support it.\nwithData f = f nullPtr\n\n-- Handle strings which may be NULL.\nwithMaybeString :: Maybe String -> (CString -> IO a) -> IO a\nwithMaybeString Nothing f = f nullPtr\nwithMaybeString (Just s) f = withCString s f\n\n------------------------------------------------------------------------------\n-- Version information\n------------------------------------------------------------------------------\n\n-- | Get xine-lib version string.\n--\n-- Header declaration:\n--\n-- const char *xine_get_version_string (void)\n{#fun pure xine_get_version_string {} -> `String' peekCString*#}\n\n-- | Get version as a triple: major, minor, sub\n--\n-- Header declaration:\n--\n-- void xine_get_version (int *major, int *minor, int *sub)\n{#fun pure xine_get_version\n {alloca- `Int' peekInt*,\n alloca- `Int' peekInt*,\n alloca- `Int' peekInt*} -> `()'#}\n\n-- | Compare given version to xine-lib version (major, minor, sub).\n--\n-- Header declaration:\n--\n-- int xine_check_version (int major, int minor, int sub)\n--\n-- returns 1 if compatible, 0 otherwise.\n{#fun pure xine_check_version\n {int2cint `Int',\n int2cint `Int',\n int2cint `Int'} -> `Bool' cint2bool#}\n\n------------------------------------------------------------------------------\n-- Global engine handling\n------------------------------------------------------------------------------\n\n-- | Valid visual types\n{#enum define VisualType {XINE_VISUAL_TYPE_NONE as None\n ,XINE_VISUAL_TYPE_X11 as X11\n ,XINE_VISUAL_TYPE_X11_2 as X11_2\n ,XINE_VISUAL_TYPE_AA as AA\n ,XINE_VISUAL_TYPE_FB as FB\n ,XINE_VISUAL_TYPE_GTK as GTK\n ,XINE_VISUAL_TYPE_DFB as DFB\n ,XINE_VISUAL_TYPE_PM as PM\n ,XINE_VISUAL_TYPE_DIRECTX as DirectX\n ,XINE_VISUAL_TYPE_CACA as CACA\n ,XINE_VISUAL_TYPE_MACOSX as MacOSX\n ,XINE_VISUAL_TYPE_XCB as XCB\n ,XINE_VISUAL_TYPE_RAW as Raw\n }#}\n\n-- | Pre-init the Xine engine.\n--\n-- Header declaration:\n--\n-- xine_t *xine_new (void)\n{#fun xine_new {} -> `Engine' peekEngine*#}\n\n-- | Post-init the Xine engine.\n--\n-- Header declaration:\n--\n-- void xine_init (xine_t *self)\n{#fun xine_init {withEngine* `Engine'} -> `()'#}\n\n-- | Initialise audio driver.\n--\n-- Header declaration:\n--\n-- xine_audio_port_t *xine_open_audio_driver (xine_t *self, const char *id,\n-- void *data)\n--\n-- id: identifier of the driver, may be NULL for auto-detection\n--\n-- data: special data struct for ui\/driver communication\n--\n-- May return NULL if the driver failed to load.\n{#fun xine_open_audio_driver\n {withEngine* `Engine'\n ,withMaybeString* `(Maybe String)'\n ,withData- `Data'} -> `(Maybe AudioPort)' peekAudioPort*#}\n\n-- | Initialise video driver.\n--\n-- Header declaration:\n--\n-- xine_video_port_t *xine_open_video_driver (xine_t *self, const char *id,\n-- int visual, void *data)\n--\n-- id: identifier of the driver, may be NULL for auto-detection\n--\n-- data: special data struct for ui\/driver communication\n--\n-- visual : video driver flavor selector\n--\n-- May return NULL if the driver failed to load.\n{#fun xine_open_video_driver\n {withEngine* `Engine'\n ,withMaybeString* `(Maybe String)'\n ,enum2cint `VisualType'\n ,withData- `Data'} -> `(Maybe VideoPort)' peekVideoPort*#}\n\n-- | Close audio port.\n--\n-- Header declaration:\n--\n-- void xine_close_audio_driver (xine_t *self, xine_audio_port_t *driver)\n{#fun xine_close_audio_driver\n {withEngine* `Engine'\n ,withAudioPort* `AudioPort'} -> `()'#}\n\n-- | Close video port.\n--\n-- Header declaration:\n--\n-- void xine_close_video_driver (xine_t *self, xine_video_port_t *driver)\n{#fun xine_close_video_driver\n {withEngine* `Engine'\n ,withVideoPort* `VideoPort'} -> `()'#}\n\n-- | Free all resources, close all plugins, close engine.\n--\n-- Header declaration:\n--\n-- void xine_exit (xine_t *self)\n{#fun xine_exit {withEngine* `Engine'} -> `()'#}\n\n------------------------------------------------------------------------------\n-- Stream handling\n------------------------------------------------------------------------------\n\n-- | Engine parameter enumeration.\n{#enum define EngineParam\n {XINE_ENGINE_PARAM_VERBOSITY as EngineVerbosity}#}\n\n-- | Stream parameter enumeration.\n{#enum define StreamParam\n {XINE_PARAM_SPEED as Speed\n ,XINE_PARAM_AV_OFFSET as AvOffset\n ,XINE_PARAM_AUDIO_CHANNEL_LOGICAL as AudioChannelLogical\n ,XINE_PARAM_SPU_CHANNEL as SpuChannel\n ,XINE_PARAM_AUDIO_VOLUME as AudioVolume\n ,XINE_PARAM_AUDIO_MUTE as AudioMute\n ,XINE_PARAM_AUDIO_COMPR_LEVEL as AudioComprLevel\n ,XINE_PARAM_AUDIO_REPORT_LEVEL as AudioReportLevel\n ,XINE_PARAM_VERBOSITY as Verbosity\n ,XINE_PARAM_SPU_OFFSET as SpuOffset\n ,XINE_PARAM_IGNORE_VIDEO as IgnoreVideo\n ,XINE_PARAM_IGNORE_AUDIO as IgnoreAudio\n ,XINE_PARAM_BROADCASTER_PORT as BroadcasterPort\n ,XINE_PARAM_METRONOM_PREBUFFER as MetronomPrebuffer\n ,XINE_PARAM_EQ_30HZ as Eq30Hz\n ,XINE_PARAM_EQ_60HZ as Eq60Hz\n ,XINE_PARAM_EQ_125HZ as Eq125Hz\n ,XINE_PARAM_EQ_500HZ as Eq500Hz\n ,XINE_PARAM_EQ_1000HZ as Eq1000Hz\n ,XINE_PARAM_EQ_2000HZ as Eq2000Hz\n ,XINE_PARAM_EQ_4000HZ as Eq4000Hz\n ,XINE_PARAM_EQ_8000HZ as Eq8000Hz\n ,XINE_PARAM_EQ_16000HZ as Eq16000Hz\n ,XINE_PARAM_AUDIO_CLOSE_DEVICE as AudioCloseDevice\n ,XINE_PARAM_AUDIO_AMP_MUTE as AmpMute\n ,XINE_PARAM_FINE_SPEED as FineSpeed\n ,XINE_PARAM_EARLY_FINISHED_EVENT as EarlyFinishedEvent\n ,XINE_PARAM_GAPLESS_SWITCH as GaplessSwitch\n ,XINE_PARAM_DELAY_FINISHED_EVENT as DelayFinishedEvent\n ,XINE_PARAM_VO_DEINTERLACE as Deinterlace\n ,XINE_PARAM_VO_ASPECT_RATIO as AspectRatio\n ,XINE_PARAM_VO_HUE as Hue\n ,XINE_PARAM_VO_SATURATION as Saturation\n ,XINE_PARAM_VO_CONTRAST as Contrast\n ,XINE_PARAM_VO_BRIGHTNESS as Brightness\n ,XINE_PARAM_VO_ZOOM_X as ZoomX\n ,XINE_PARAM_VO_ZOOM_Y as ZoomY\n ,XINE_PARAM_VO_PAN_SCAN as PanScan\n ,XINE_PARAM_VO_TVMODE as TvMode\n ,XINE_PARAM_VO_WINDOW_WIDTH as WindowWidth\n ,XINE_PARAM_VO_WINDOW_HEIGHT as WindowHeight\n ,XINE_PARAM_VO_CROP_LEFT as CropLeft\n ,XINE_PARAM_VO_CROP_RIGHT as CropRight\n ,XINE_PARAM_VO_CROP_TOP as CropTop\n ,XINE_PARAM_VO_CROP_BOTTOM as CropBottom\n }#}\n\n-- | Values for XINE_PARAM_SPEED parameter.\n{#enum define Speed\n {XINE_SPEED_PAUSE as Pause\n ,XINE_SPEED_SLOW_4 as Slow4\n ,XINE_SPEED_SLOW_2 as Slow2\n ,XINE_SPEED_NORMAL as Normal\n ,XINE_SPEED_FAST_2 as Fast2\n ,XINE_SPEED_FAST_4 as Fast4\n }#}\n\nderiving instance Eq Speed\n\n-- | Value for XINE_PARAM_FINE_SPEED\n{#enum define NormalSpeed\n {XINE_FINE_SPEED_NORMAL as NormalSpeed}#}\n\n-- | Values for XINE_PARAM_VO_ZOOM_\n{#enum define Zoom\n {XINE_VO_ZOOM_STEP as ZoomStep\n ,XINE_VO_ZOOM_MAX as ZoomMax\n ,XINE_VO_ZOOM_MIN as ZoomMin}#}\n\n-- | Values for XINE_PARAM_VO_ASPECT_RATIO\n{#enum define AspectRatio\n {XINE_VO_ASPECT_AUTO as AspectAuto\n ,XINE_VO_ASPECT_SQUARE as AspectSquare\n ,XINE_VO_ASPECT_4_3 as Aspect43\n ,XINE_VO_ASPECT_ANAMORPHIC as AspectAnamorphic\n ,XINE_VO_ASPECT_DVB as AspectDvb\n ,XINE_VO_ASPECT_NUM_RATIOS as AspectNumRatios\n }#}\n\n-- | Create a new stream for media playback.\n--\n-- Header declaration:\n--\n-- xine_stream_t *xine_stream_new (xine_t *self,\n-- xine_audio_port *ao, xine_video_port_t *vo)\n--\n-- Returns xine_stream_t* if OK, NULL on error (use 'xine_get_error' for\n-- details).\n{#fun xine_stream_new\n {withEngine* `Engine'\n ,withAudioPort* `AudioPort'\n ,withVideoPort* `VideoPort'} -> `(Maybe Stream)' peekStream*#}\n\n-- | Make one stream the slave of another.\n-- Certain operations on the master stream are also applied to the slave\n-- stream.\n--\n-- Header declaration:\n--\n-- int xine_stream_master_slave (xine_stream_t *master, xine_stream_t *slave,\n-- int affection)\n--\n-- returns 1 on success, 0 on failure.\n{#fun xine_stream_master_slave\n {withStream* `Stream'\n ,withStream* `Stream'\n ,combineAffection `[Affection]'} -> `Int' cint2int#}\n\n-- | The affection determines which actions on the master stream\n-- are also to be applied to the slave stream. See 'xine_stream_master_slave'.\n{#enum define Affection\n {XINE_MASTER_SLAVE_PLAY as AffectionPlay\n ,XINE_MASTER_SLAVE_STOP as AffectionStop\n ,XINE_MASTER_SLAVE_SPEED as AffectionSpeed}#}\n\n-- | Affections can be ORed together.\ncombineAffection :: [Affection] -> CInt\ncombineAffection [] = enum2cint AffectionSpeed\ncombineAffection xs = foldr1 (.&.) (map enum2cint xs)\n\n-- | Open a stream.\n--\n-- Header declaration:\n--\n-- int xine_open (xine_stream_t *stream, const char *mrl)\n--\n-- Returns 1 if OK, 0 on error (use 'xine_get_error' for details).\n{#fun xine_open\n {withStream* `Stream'\n ,withCAString* `MRL'} -> `Int' cint2int#}\n\n-- | Play a stream from a given position.\n--\n-- Header declaration:\n--\n-- int xine_play (xine_stream_t *stream, int start_pos, int start_time)\n--\n-- Returns 1 if OK, 0 on error (use 'xine_get_error' for details).\n{#fun xine_play\n {withStream* `Stream'\n ,int2cint `Int'\n ,int2cint `Int'} -> `Int' cint2int#}\n\n-- | Set xine to a trick mode for fast forward, backwards playback,\n-- low latency seeking.\n--\n-- Header declaration:\n--\n-- int xine_trick_mode (xine_stream_t *stream, int mode, int value)\n--\n-- Returns 1 if OK, 0 on error (use 'xine_get_error' for details).\n{#fun xine_trick_mode\n {withStream* `Stream'\n ,enum2cint `TrickMode'\n ,int2cint `Int'} -> `Int' cint2int#}\n\n{#enum define TrickMode\n {XINE_TRICK_MODE_OFF as TrickOff\n ,XINE_TRICK_MODE_SEEK_TO_POSITION as TrickSeekToPosition\n ,XINE_TRICK_MODE_SEEK_TO_TIME as TrickSeekToTime\n ,XINE_TRICK_MODE_FAST_FORWARD as TrickFastForward\n ,XINE_TRICK_MODE_FAST_REWIND as TrickRewind}#}\n\n-- | Stop stream playback.\n-- The stream stays valid for new 'xine_open' or 'xine_play'.\n--\n-- Header declaration:\n--\n-- void xine_stop (xine_stream *stream)\n{#fun xine_stop {withStream* `Stream'} -> `()'#}\n\n-- | Free all stream-related resources.\n-- The stream stays valid for new 'xine_open'.\n--\n-- Header declaration:\n--\n-- void xine_close (xine_stream_t *stream)\n{#fun xine_close {withStream* `Stream'} -> `()'#}\n\n-- | Ask current input plugin to eject media.\n--\n-- Header declaration:\n--\n-- int xine_eject (xine_stream_t *stream)\n{#fun xine_eject {withStream* `Stream'} -> `Int' cint2int#}\n\n-- | Stop playback, dispose all stream-related resources.\n-- The stream is no longer valid after this.\n--\n-- Header declaration:\n--\n-- void xine_dispose (xine_stream_t *stream)\n{#fun xine_dispose {withStream* `Stream'} -> `()'#}\n\n-- | Set engine parameter.\n--\n-- Header declaration:\n--\n-- void xine_engine_set_param (xine_t *self, int param, int value)\n{#fun xine_engine_set_param\n {withEngine* `Engine'\n ,enum2cint `EngineParam'\n ,int2cint `Int'} -> `()'#}\n\n-- | Get engine parameter.\n--\n-- Header declaration:\n--\n-- int xine_engine_get_param(xine_t *self, int param)\n{#fun xine_engine_get_param\n {withEngine* `Engine'\n ,enum2cint `EngineParam'} -> `Int' cint2int#}\n\n-- | Set stream parameter.\n--\n-- Header declaration:\n--\n-- void xine_set_param (xine_stream_t *stream, int param, int value)\n{#fun xine_set_param\n `(Enum a)' =>\n {withStream* `Stream'\n ,enum2cint `StreamParam'\n ,enum2cint `a'} -> `()'#}\n\n-- | Get stream parameter.\n--\n-- Header declaration:\n--\n-- int xine_get_param (xine_stream_t *stream, int param)\n{#fun xine_get_param\n `(Enum a)' =>\n {withStream* `Stream'\n ,enum2cint `StreamParam'} -> `a' cint2enum#}\n\n------------------------------------------------------------------------------\n-- Information retrieval\n------------------------------------------------------------------------------\n\n-- | Engine status codes.\n{#enum define EngineStatus\n {XINE_STATUS_IDLE as Idle\n ,XINE_STATUS_STOP as Stopped\n ,XINE_STATUS_PLAY as Playing\n ,XINE_STATUS_QUIT as Quitting}#}\n\nderiving instance Eq EngineStatus\nderiving instance Show EngineStatus\n\n-- | Xine error codes.\n{#enum define XineError\n {XINE_ERROR_NONE as NoError\n ,XINE_ERROR_NO_INPUT_PLUGIN as NoInputPlugin\n ,XINE_ERROR_NO_DEMUX_PLUGIN as NoDemuxPlugin\n ,XINE_ERROR_MALFORMED_MRL as MalformedMrl\n ,XINE_ERROR_INPUT_FAILED as InputFailed}#}\n\nderiving instance Eq XineError\nderiving instance Show XineError\n\n-- | Return last error.\n--\n-- Header declaration:\n--\n-- int xine_get_error (xine_stream_t *stream)\n{#fun xine_get_error\n {withStream* `Stream'} -> `XineError' cint2enum#}\n\n-- | Get current xine engine status.\n--\n-- int xine_get_status (xine_stream_t *stream)\n{#fun xine_get_status\n {withStream* `Stream'} -> `EngineStatus' cint2enum#}\n\n-- | Find the audio language of the given channel (use -1 for\n-- current channel).\n--\n-- Header declaration:\n--\n-- int xine_get_audio_lang (xine_stream_t *stream, int channel,\n-- char *lang)\n--\n-- lang must point to a buffer of at least XINE_LANG_MAX bytes.\n--\n-- Returns 1 on success, 0 on failure.\n{#fun xine_get_audio_lang\n {withStream* `Stream'\n ,int2cint `Int'\n ,allocLangBuf- `String' peekCString*} -> `Int' cint2int#}\n\n-- XXX: read the constant XINE_LANG_MAX\nallocLangBuf = allocaArray0 32\n\n-- | Find the spu language of the given channel (use -1 for\n-- current channel).\n--\n-- Header declaration:\n--\n-- int xine_get_spu_lang (xine_stream_t *stream, int channel,\n-- char *lang)\n--\n-- lang must point to a buffer of at least XINE_LANG_MAX bytes.\n--\n-- Returns 1 on success, 0 on failure.\n{#fun xine_get_spu_lang\n {withStream* `Stream'\n ,int2cint `Int'\n ,allocLangBuf- `String' peekCString*} -> `Int' cint2int#}\n\n-- | Get position\\\/length information.\n--\n-- Header declaration:\n--\n-- int xine_get_pos_length (xine_stream_t *stream, int *pos_stream,\n-- int *pos_time, int *length_time)\n--\n-- Returns 1 on success, 0 on failure.\n{#fun xine_get_pos_length\n {withStream* `Stream'\n ,alloca- `Int' peekInt*\n ,alloca- `Int' peekInt*\n ,alloca- `Int' peekInt*} -> `Int' cint2int#}\n\n-- | Get information about the stream.\n--\n-- Header declaration:\n--\n-- int32_t xine_get_stream_info (xine_stream_t *stream, int info)\n{#fun xine_get_stream_info\n {withStream* `Stream'\n ,enum2cint `InfoType'} -> `Int' cuint2int#}\n\n-- | Get meta information about the stream.\n--\n-- Header declaration:\n--\n-- const char *xine_get_meta_info (xine_stream_t *stream, int info)\n{#fun xine_get_meta_info\n {withStream* `Stream'\n ,enum2cint `MetaType'} -> `String' peekCString*#}\n\n{#enum define InfoType\n {XINE_STREAM_INFO_BITRATE as InfoBitrate\n ,XINE_STREAM_INFO_SEEKABLE as InfoSeekable\n ,XINE_STREAM_INFO_VIDEO_WIDTH as InfoVideoWidth\n ,XINE_STREAM_INFO_VIDEO_HEIGHT as InfoVideoHeight\n ,XINE_STREAM_INFO_VIDEO_RATIO as InfoVideoRatio\n ,XINE_STREAM_INFO_VIDEO_CHANNELS as InfoVideoChannels\n ,XINE_STREAM_INFO_VIDEO_STREAMS as InfoVideoStreams\n ,XINE_STREAM_INFO_VIDEO_BITRATE as InfoVideoBitrate\n ,XINE_STREAM_INFO_VIDEO_FOURCC as InfoVideoFourCC\n ,XINE_STREAM_INFO_VIDEO_HANDLED as InfoVideoHandled\n ,XINE_STREAM_INFO_FRAME_DURATION as InfoFrameDuration\n ,XINE_STREAM_INFO_AUDIO_CHANNELS as InfoAudioChannels\n ,XINE_STREAM_INFO_AUDIO_BITS as InfoAudioBits\n ,XINE_STREAM_INFO_AUDIO_SAMPLERATE as InfoAudioSamplerate\n ,XINE_STREAM_INFO_AUDIO_BITRATE as InfoAudioBitrate\n ,XINE_STREAM_INFO_AUDIO_FOURCC as InfoAudioFourCC\n ,XINE_STREAM_INFO_AUDIO_HANDLED as InfoAudioHandled\n ,XINE_STREAM_INFO_HAS_CHAPTERS as InfoHasChapters\n ,XINE_STREAM_INFO_HAS_VIDEO as InfoHasVideo\n ,XINE_STREAM_INFO_HAS_AUDIO as InfoHasAudio\n ,XINE_STREAM_INFO_IGNORE_VIDEO as InfoIgnoreVideo\n ,XINE_STREAM_INFO_IGNORE_AUDIO as InfoIgnoreAudio\n ,XINE_STREAM_INFO_IGNORE_SPU as InfoIgnoreSpu\n ,XINE_STREAM_INFO_VIDEO_HAS_STILL as InfoVideoHasStill\n ,XINE_STREAM_INFO_MAX_AUDIO_CHANNEL as InfoMaxAudioChannel\n ,XINE_STREAM_INFO_MAX_SPU_CHANNEL as InfoMaxSpuChannel\n ,XINE_STREAM_INFO_AUDIO_MODE as InfoAudioMode\n ,XINE_STREAM_INFO_SKIPPED_FRAMES as InfoSkippedFrames\n ,XINE_STREAM_INFO_DISCARDED_FRAMES as InfoDiscardedFrames\n ,XINE_STREAM_INFO_VIDEO_AFD as InfoVideoAFD\n ,XINE_STREAM_INFO_DVD_TITLE_NUMBER as InfoDvdTitleNumber\n ,XINE_STREAM_INFO_DVD_TITLE_COUNT as InfoDvdTitleCount\n ,XINE_STREAM_INFO_DVD_CHAPTER_NUMBER as InfoDvdChapterNumber\n ,XINE_STREAM_INFO_DVD_CHAPTER_COUNT as InfoDvdChapterCount\n ,XINE_STREAM_INFO_DVD_ANGLE_NUMBER as InfoDvdAngleNumber\n ,XINE_STREAM_INFO_DVD_ANGLE_COUNT as InfoDvdAngleCount}#}\n\n{#enum define MetaType\n {XINE_META_INFO_TITLE as MetaTitle\n ,XINE_META_INFO_COMMENT as MetaComment\n ,XINE_META_INFO_ARTIST as MetaArtist\n ,XINE_META_INFO_GENRE as MetaGenre\n ,XINE_META_INFO_ALBUM as MetaAlbum\n ,XINE_META_INFO_YEAR as MetaYear\n ,XINE_META_INFO_VIDEOCODEC as MetaVideoCodec\n ,XINE_META_INFO_AUDIOCODEC as MetaAudioCodec\n ,XINE_META_INFO_SYSTEMLAYER as MetaSystemLayer\n ,XINE_META_INFO_INPUT_PLUGIN as MetaInputPlugin\n ,XINE_META_INFO_CDINDEX_DISCID as MetaDiscId\n ,XINE_META_INFO_TRACK_NUMBER as MetaTrackNumber\n ,XINE_META_INFO_COMPOSER as MetaComposer\n ,XINE_META_INFO_PUBLISHER as MetaPublisher\n ,XINE_META_INFO_LICENSE as MetaLicense\n ,XINE_META_INFO_ARRANGER as MetaArranger\n ,XINE_META_INFO_LYRICIST as MetaLyricist\n ,XINE_META_INFO_CONDUCTOR as MetaConductor\n ,XINE_META_INFO_PERFORMER as MetaPerformer\n ,XINE_META_INFO_ENSEMBLE as MetaEnsemble\n ,XINE_META_INFO_OPUS as MetaOpus\n ,XINE_META_INFO_PART as MetaPart\n ,XINE_META_INFO_PARTNUMBER as MetaPartNumber\n ,XINE_META_INFO_LOCATION as MetaLocation}#}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"540cdc169c6112d7d902be464d323f51509bc8d4","subject":"fix for 7.8.4","message":"fix for 7.8.4\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/OGRFeature.chs","new_file":"src\/GDAL\/Internal\/OGRFeature.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGRFeature (\n OGRFeature (..)\n , OGRFeatureDef (..)\n , OGRField (..)\n , OGRTimeZone (..)\n , Fid (..)\n , FieldType (..)\n , Field (..)\n , Feature (..)\n , FeatureH (..)\n , FieldDefnH (..)\n , FeatureDefnH (..)\n , Justification (..)\n\n , FeatureDef (..)\n , GeomFieldDef (..)\n , FieldDef (..)\n , fieldTypedAs\n , (.:)\n , (.=)\n , aGeom\n , aNullableGeom\n , theGeom\n , theNullableGeom\n , feature\n\n\n , featureToHandle\n , featureFromHandle\n , getFid\n\n , withFieldDefnH\n , fieldDefFromHandle\n , featureDefFromHandle\n , fieldDefsFromFeatureDefnH\n , geomFieldDefsFromFeatureDefnH\n#if SUPPORTS_MULTI_GEOM_FIELDS\n , GeomFieldDefnH (..)\n , withGeomFieldDefnH\n#endif\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\" #}\n\nimport Control.Applicative ((<$>), (<*>), pure)\nimport Control.Monad (liftM, liftM2, (>=>), (<=<), when, void, join)\nimport Control.Monad.Catch (bracket)\n\nimport Data.ByteString (ByteString)\nimport Data.ByteString.Char8 (packCStringLen)\nimport Data.ByteString.Unsafe (unsafeUseAsCStringLen)\nimport qualified Data.HashMap.Strict as HM\nimport Data.Int (Int32, Int64)\nimport Data.Monoid (mempty, (<>))\nimport Data.Proxy (Proxy(Proxy))\n\nimport Data.Text (Text)\nimport Data.Time.LocalTime (\n LocalTime(..)\n , TimeOfDay(..)\n , TimeZone(..)\n , minutesToTimeZone\n , utc\n )\nimport Data.Time ()\nimport Data.Time.Calendar (Day, fromGregorian, toGregorian)\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport qualified Data.Vector as V\n\nimport Foreign.C.Types (\n CInt(..)\n , CDouble(..)\n , CChar(..)\n , CUChar(..)\n , CLong(..)\n )\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (copyBytes, toBool)\nimport Foreign.Ptr (Ptr, castPtr, nullPtr)\nimport Foreign.Storable (Storable, sizeOf, peek, peekElemOff)\n#if GDAL_VERSION_MAJOR >= 2\nimport Foreign.C.Types (CLLong(..))\nimport Foreign.Marshal.Utils (fromBool)\n#endif\n\n\nimport GDAL.Internal.Util (\n toEnumC\n , fromEnumC\n , peekEncodedCString\n , useAsEncodedCString\n )\n{#import GDAL.Internal.OSR #}\n{#import GDAL.Internal.CPLError #}\n{#import GDAL.Internal.OGRGeometry #}\n{#import GDAL.Internal.OGRError #}\n\n#include \"gdal.h\"\n#include \"ogr_core.h\"\n#include \"ogr_api.h\"\n#include \"cpl_string.h\"\n\nnewtype Fid = Fid { unFid :: Int64 }\n deriving (Eq, Show, Num)\n\nclass OGRField a where\n fieldDef :: Proxy a -> FieldDef\n toField :: a -> Field\n fromField :: Field -> Either Text a\n\n(.:) :: OGRField a => Feature -> Text -> Either Text a\nfeat .: name =\n maybe (Left (\"fromFeature: field '\"<>name<>\"' not present\"))\n fromField\n (HM.lookup name (fFields feat))\n\n(.=) :: OGRField a => Text -> a -> (Text, Field)\nname .= value = (name, toField value)\n\nclass OGRFeature a where\n toFeature :: a -> Feature\n fromFeature :: Feature -> Either Text a\n\ntheGeom :: Feature -> Either Text Geometry\ntheGeom = maybe (Left \"Feature has no geometry\") Right . fGeom\n\ntheNullableGeom :: Feature -> Either Text (Maybe Geometry)\ntheNullableGeom = Right . fGeom\n\naGeom :: Feature -> Text -> Either Text Geometry\nfeat `aGeom` name =\n maybe (Left (\"fromFeature: geometry field '\"<>name<>\"' not present\"))\n (maybe (Left (\"fromFeature: geometry '\"<>name<>\"' is NULL\")) Right)\n (HM.lookup name (fGeoms feat))\n\naNullableGeom :: Feature -> Text -> Either Text (Maybe Geometry)\nfeat `aNullableGeom` name =\n maybe (Left (\"fromFeature: geometry field '\"<>name<>\"' not present\"))\n Right\n (HM.lookup name (fGeoms feat))\n\nclass OGRFeature a => OGRFeatureDef a where\n featureDef :: Proxy a -> FeatureDef\n\nfieldTypedAs :: forall a. OGRField a => Text -> a -> (Text, FieldDef)\nname `fieldTypedAs` _ = (name, fieldDef (Proxy :: Proxy a))\n\n{#enum FieldType {} omit (OFTMaxType) deriving (Eq,Show,Read,Bounded) #}\n\n{#enum Justification {}\n omit (JustifyUndefined)\n with prefix = \"OJ\"\n add prefix = \"Justify\"\n deriving (Eq,Show,Read,Bounded) #}\n\ndata Field\n = OGRInteger !Int32\n | OGRIntegerList !(St.Vector Int32)\n#if SUPPORTS_64_BIT_INT_FIELDS\n | OGRInteger64 !Int64\n | OGRInteger64List !(St.Vector Int64)\n#endif\n | OGRReal !Double\n | OGRRealList !(St.Vector Double)\n | OGRString !Text\n | OGRStringList !(V.Vector Text)\n | OGRBinary !ByteString\n | OGRDateTime !LocalTime !OGRTimeZone\n | OGRDate !Day\n | OGRTime !TimeOfDay\n | OGRNullField\n deriving (Show, Eq)\n\ndata OGRTimeZone\n = UnknownTimeZone\n | LocalTimeZone\n | KnownTimeZone !TimeZone\n deriving (Eq, Show)\n\ndata FieldDef\n = FieldDef {\n fldType :: !FieldType\n , fldWidth :: !(Maybe Int)\n , fldPrec :: !(Maybe Int)\n , fldJust :: !(Maybe Justification)\n , fldNullable :: !Bool\n } deriving (Show, Eq)\n\ndata GeomFieldDef\n = GeomFieldDef {\n gfdType :: !GeometryType\n , gfdSrs :: !(Maybe SpatialReference)\n , gfdNullable :: !Bool\n } deriving (Show, Eq)\n\ntype Map a = HM.HashMap Text a\n\ndata Feature\n = Feature {\n fFields :: !(Map Field)\n , fGeom :: !(Maybe Geometry)\n , fGeoms :: !(Map (Maybe Geometry))\n } deriving (Show, Eq)\n\nfeature :: Geometry -> [(Text,Field)] -> Feature\nfeature g fs =\n Feature { fFields = HM.fromList fs\n , fGeom = Just g\n , fGeoms = mempty\n }\n\ninstance OGRFeature Feature where\n toFeature = id\n fromFeature = Right\n\ndata FeatureDef\n = FeatureDef {\n fdName :: !Text\n , fdFields :: !FieldDefs\n , fdGeom :: !GeomFieldDef\n , fdGeoms :: !GeomFieldDefs\n } deriving (Show, Eq)\n\ntype FieldDefs = V.Vector (Text, FieldDef)\ntype GeomFieldDefs = V.Vector (Text, GeomFieldDef)\n\n\n{#pointer FeatureH newtype#}\n{#pointer FieldDefnH newtype#}\n{#pointer FeatureDefnH newtype#}\n\nderiving instance Eq FeatureH\n\nnullFeatureH :: FeatureH\nnullFeatureH = FeatureH nullPtr\n\n\nwithFieldDefnH :: Text -> FieldDef -> (FieldDefnH -> IO a) -> IO a\nwithFieldDefnH fldName FieldDef{..} f =\n useAsEncodedCString fldName $ \\pName ->\n bracket ({#call unsafe OGR_Fld_Create as ^#} pName (fromEnumC fldType))\n ({#call unsafe OGR_Fld_Destroy as ^#}) (\\p -> populate p >> f p)\n where\n populate h = do\n case fldWidth of\n Just w -> {#call unsafe OGR_Fld_SetWidth as ^#} h (fromIntegral w)\n Nothing -> return ()\n case fldPrec of\n Just p -> {#call unsafe OGR_Fld_SetPrecision as ^#} h (fromIntegral p)\n Nothing -> return ()\n case fldJust of\n Just j -> {#call unsafe OGR_Fld_SetJustify as ^#} h (fromEnumC j)\n Nothing -> return ()\n#if SUPPORTS_NULLABLE_FIELD_DEFS\n {#call unsafe OGR_Fld_SetNullable as ^#} h (fromBool fldNullable)\n#endif\n\nfieldDefFromHandle :: FieldDefnH -> IO FieldDef\nfieldDefFromHandle p =\n FieldDef\n <$> liftM toEnumC ({#call unsafe OGR_Fld_GetType as ^#} p)\n <*> liftM iToMaybe ({#call unsafe OGR_Fld_GetWidth as ^#} p)\n <*> liftM iToMaybe ({#call unsafe OGR_Fld_GetPrecision as ^#} p)\n <*> liftM jToMaybe ({#call unsafe OGR_Fld_GetJustify as ^#} p)\n#if SUPPORTS_NULLABLE_FIELD_DEFS\n <*> liftM toBool ({#call unsafe OGR_Fld_IsNullable as ^#} p)\n#else\n <*> pure True\n#endif\n where\n iToMaybe = (\\v -> if v==0 then Nothing else Just (fromIntegral v))\n jToMaybe = (\\j -> if j==0 then Nothing else Just (toEnumC j))\n\nfeatureDefFromHandle :: GeomFieldDef -> FeatureDefnH -> IO FeatureDef\nfeatureDefFromHandle gfd p = do\n#if SUPPORTS_MULTI_GEOM_FIELDS\n gfields <- geomFieldDefsFromFeatureDefnH p\n let (gfd', gfields')\n -- should not happen but just in case\n | V.null gfields = (gfd, gfields)\n -- ignore layer definition since it doesn't carry correct nullability\n -- info\n | otherwise = (snd (V.unsafeHead gfields), V.unsafeTail gfields)\n#else\n let (gfd', gfields') = (gfd, mempty)\n#endif\n FeatureDef\n <$> ({#call unsafe OGR_FD_GetName as ^#} p >>= peekEncodedCString)\n <*> fieldDefsFromFeatureDefnH p\n <*> pure gfd'\n <*> pure gfields'\n\nfieldDefsFromFeatureDefnH :: FeatureDefnH -> IO (V.Vector (Text, FieldDef))\nfieldDefsFromFeatureDefnH p = do\n nFields <- {#call unsafe OGR_FD_GetFieldCount as ^#} p\n V.generateM (fromIntegral nFields) $ \\i -> do\n fDef <- {#call unsafe OGR_FD_GetFieldDefn as ^#} p (fromIntegral i)\n liftM2 (,) (getFieldName fDef) (fieldDefFromHandle fDef)\n\n\ngeomFieldDefsFromFeatureDefnH\n :: FeatureDefnH -> IO (V.Vector (Text, GeomFieldDef))\n\n#if SUPPORTS_MULTI_GEOM_FIELDS\n\n{#pointer GeomFieldDefnH newtype#}\n\ngeomFieldDefsFromFeatureDefnH p = do\n nFields <- {#call unsafe OGR_FD_GetGeomFieldCount as ^#} p\n V.generateM (fromIntegral nFields) $\n gFldDef <=< ({#call unsafe OGR_FD_GetGeomFieldDefn as ^#} p . fromIntegral)\n where\n gFldDef g = do\n name <- {#call unsafe OGR_GFld_GetNameRef as ^#} g >>= peekEncodedCString\n gDef <- GeomFieldDef\n <$> liftM toEnumC ({#call unsafe OGR_GFld_GetType as ^#} g)\n <*> ({#call unsafe OGR_GFld_GetSpatialRef as ^#} g >>=\n maybeNewSpatialRefBorrowedHandle)\n#if SUPPORTS_NULLABLE_FIELD_DEFS\n <*> liftM toBool ({#call unsafe OGR_GFld_IsNullable as ^#} g)\n#else\n <*> pure True\n#endif\n return (name, gDef)\n\nwithGeomFieldDefnH :: Text -> GeomFieldDef -> (GeomFieldDefnH -> IO a) -> IO a\nwithGeomFieldDefnH gfdName GeomFieldDef{..} f =\n useAsEncodedCString gfdName $ \\pName ->\n bracket ({#call unsafe OGR_GFld_Create as ^#} pName (fromEnumC gfdType))\n ({#call unsafe OGR_GFld_Destroy as ^#}) (\\p -> populate p >> f p)\n where\n populate p = do\n withMaybeSpatialReference gfdSrs $\n {#call unsafe OGR_GFld_SetSpatialRef as ^#} p\n#if SUPPORTS_NULLABLE_FIELD_DEFS\n {#call unsafe OGR_GFld_SetNullable as ^#} p (fromBool gfdNullable)\n#endif\n\n#else\ngeomFieldDefsFromFeatureDefnH = const (return mempty)\n#endif -- SUPPORTS_MULTI_GEOM_FIELDS\n\nnullFID :: Fid\nnullFID = Fid ({#const OGRNullFID#})\n\nfeatureToHandle\n :: OGRFeature f\n => FeatureDefnH -> Maybe Fid -> f -> (FeatureH -> IO a) -> IO a\nfeatureToHandle fdH fId ft act =\n bracket ({#call unsafe OGR_F_Create as ^#} fdH)\n ({#call unsafe OGR_F_Destroy as ^#}) $ \\pF -> do\n case fId of\n Just (Fid fid) ->\n void $ {#call unsafe OGR_F_SetFID as ^#} pF (fromIntegral fid)\n Nothing -> return ()\n fieldDefs <- fieldDefsFromFeatureDefnH fdH\n flip imapM_ fieldDefs $ \\ix (name, _) -> do\n case HM.lookup name fFields of\n Just f -> setField f ix pF\n Nothing -> return ()\n case fGeom of\n Just g -> void $ withGeometry g ({#call unsafe OGR_F_SetGeometry as ^#} pF)\n Nothing -> return ()\n when (not (HM.null fGeoms)) $ do\n#if SUPPORTS_MULTI_GEOM_FIELDS\n geomFieldDefs <- geomFieldDefsFromFeatureDefnH fdH\n flip imapM_ (V.tail geomFieldDefs) $ \\ix (name, _) -> do\n case join (HM.lookup name fGeoms) of\n Just g ->\n void $ withGeometry g ({#call unsafe OGR_F_SetGeomField as ^#} pF (ix+1))\n Nothing ->\n return ()\n#else\n throwBindingException MultipleGeomFieldsNotSupported\n#endif\n act pF\n where Feature {..} = toFeature ft\n\nimapM :: (Monad m, Num a) => (a -> b -> m c) -> V.Vector b -> m (V.Vector c)\nimapM f v = V.mapM (uncurry f) (V.zip (V.enumFromN 0 (V.length v)) v)\n\nimapM_ :: (Monad m, Num a) => (a -> b -> m ()) -> V.Vector b -> m ()\nimapM_ f v = V.mapM_ (uncurry f) (V.zip (V.enumFromN 0 (V.length v)) v)\n\ngetFid :: FeatureH -> IO (Maybe Fid)\ngetFid pF = do\n mFid <- liftM fromIntegral ({#call unsafe OGR_F_GetFID as ^#} pF)\n return (if mFid == nullFID then Nothing else Just mFid)\n\nfeatureFromHandle\n :: OGRFeature a\n => FeatureDef -> IO FeatureH -> IO (Maybe (Maybe Fid, a))\nfeatureFromHandle FeatureDef{..} act =\n bracket act {#call unsafe OGR_F_Destroy as ^#} $ \\pF -> do\n if (pF == nullFeatureH)\n then return Nothing\n else do\n fid <- getFid pF\n fields <- flip imapM fdFields $ \\i (fldName, fd) -> do\n isSet <- liftM toBool ({#call unsafe OGR_F_IsFieldSet as ^#} pF i)\n if isSet\n then getField (fldType fd) i pF >>=\n maybe (throwBindingException (FieldParseError fldName))\n (\\f -> return (fldName, f))\n else return (fldName, OGRNullField)\n geomRef <- {#call unsafe OGR_F_StealGeometry as ^#} pF\n geom <- if geomRef \/= nullPtr\n then liftM Just (newGeometryHandle geomRef)\n else return Nothing\n#if SUPPORTS_MULTI_GEOM_FIELDS\n geoms <- flip imapM fdGeoms $ \\ix (gfdName, _) -> do\n pG <- {#call unsafe OGR_F_GetGeomFieldRef as ^#} pF (ix + 1)\n g <- if pG \/= nullPtr\n then liftM Just (cloneGeometry pG)\n else return Nothing\n return (gfdName, g)\n#else\n let geoms = mempty\n#endif\n either (throwBindingException . FromFeatureError)\n (\\f -> return (Just (fid,f)))\n (fromFeature Feature {\n fFields = HM.fromList (V.toList fields)\n , fGeom = geom\n , fGeoms = HM.fromList (V.toList geoms)\n })\n\n\n-- ############################################################################\n-- setField\n-- ############################################################################\n\nsetField :: Field -> CInt -> FeatureH -> IO ()\n\nsetField (OGRInteger v) ix f =\n {#call unsafe OGR_F_SetFieldInteger as ^#} f (fromIntegral ix) (fromIntegral v)\n\nsetField (OGRIntegerList v) ix f =\n St.unsafeWith v $\n {#call unsafe OGR_F_SetFieldIntegerList as ^#} f (fromIntegral ix)\n (fromIntegral (St.length v)) . castPtr\n\n#if SUPPORTS_64_BIT_INT_FIELDS\nsetField (OGRInteger64 v) ix f =\n {#call unsafe OGR_F_SetFieldInteger64 as ^#} f (fromIntegral ix) (fromIntegral v)\n\nsetField (OGRInteger64List v) ix f =\n St.unsafeWith v $\n {#call unsafe OGR_F_SetFieldInteger64List as ^#} f (fromIntegral ix)\n (fromIntegral (St.length v)) . castPtr\n#endif\n\nsetField (OGRReal v) ix f =\n {#call unsafe OGR_F_SetFieldDouble as ^#} f (fromIntegral ix) (realToFrac v)\n\nsetField (OGRRealList v) ix f =\n St.unsafeWith v $\n {#call unsafe OGR_F_SetFieldDoubleList as ^#} f (fromIntegral ix)\n (fromIntegral (St.length v)) . castPtr\n\nsetField (OGRString v) ix f = useAsEncodedCString v $\n {#call unsafe OGR_F_SetFieldString as ^#} f (fromIntegral ix)\n\nsetField (OGRStringList v) ix f =\n bracket createList {#call unsafe CSLDestroy as ^#} $\n {#call unsafe OGR_F_SetFieldStringList as ^#} f (fromIntegral ix)\n where\n createList = V.foldM' folder nullPtr v\n folder acc k =\n useAsEncodedCString k $ {#call unsafe CSLAddString as ^#} acc\n\nsetField (OGRBinary v) ix f = unsafeUseAsCStringLen v $ \\(p,l) ->\n {#call unsafe OGR_F_SetFieldBinary as ^#}\n f (fromIntegral ix) (fromIntegral l) (castPtr p)\n\nsetField (OGRDateTime (LocalTime day (TimeOfDay h mn s)) tz) ix f =\n {#call unsafe OGR_F_SetFieldDateTime as ^#} f (fromIntegral ix)\n (fromIntegral y) (fromIntegral m) (fromIntegral d)\n (fromIntegral h) (fromIntegral mn) (truncate s) (fromOGRTimeZone tz)\n where (y, m, d) = toGregorian day\n\nsetField (OGRDate day) ix f =\n {#call unsafe OGR_F_SetFieldDateTime as ^#} f (fromIntegral ix)\n (fromIntegral y) (fromIntegral m) (fromIntegral d) 0 0 0 (fromOGRTimeZone tz)\n where (y, m, d) = toGregorian day\n tz = UnknownTimeZone\n\nsetField (OGRTime (TimeOfDay h mn s)) ix f =\n {#call unsafe OGR_F_SetFieldDateTime as ^#} f (fromIntegral ix) 0 0 0\n (fromIntegral h) (fromIntegral mn) (truncate s) (fromOGRTimeZone tz)\n where tz = UnknownTimeZone\n\nsetField OGRNullField ix f = {#call unsafe OGR_F_UnsetField as ^#} f ix\n\n-- ############################################################################\n-- getField\n-- ############################################################################\n\ngetField :: FieldType -> CInt -> FeatureH -> IO (Maybe Field)\n\ngetField OFTInteger ix f =\n liftM (Just . OGRInteger . fromIntegral)\n ({#call unsafe OGR_F_GetFieldAsInteger as ^#} f ix)\n\ngetField OFTIntegerList ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsIntegerList as ^#} f ix lenP\n nElems <- peekIntegral lenP\n if nElems == 0\n then return (Just (OGRIntegerList mempty))\n else do\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CInt) (nElems * sizeOf (undefined :: CInt))\n liftM (Just . OGRIntegerList) (St.unsafeFreeze (Stm.unsafeCast vec))\n\n#if SUPPORTS_64_BIT_INT_FIELDS\ngetField OFTInteger64 ix f\n = liftM (Just . OGRInteger64 . fromIntegral)\n ({#call unsafe OGR_F_GetFieldAsInteger64 as ^#} f ix)\n\ngetField OFTInteger64List ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsInteger64List as ^#} f ix lenP\n nElems <- peekIntegral lenP\n if nElems == 0\n then return (Just (OGRInteger64List mempty))\n else do\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CLLong) (nElems * sizeOf (undefined :: CLLong))\n liftM (Just . OGRInteger64List) (St.unsafeFreeze (Stm.unsafeCast vec))\n#endif\n\ngetField OFTReal ix f\n = liftM (Just . OGRReal . realToFrac)\n ({#call unsafe OGR_F_GetFieldAsDouble as ^#} f ix)\n\ngetField OFTRealList ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsDoubleList as ^#} f ix lenP\n nElems <- peekIntegral lenP\n if nElems == 0\n then return (Just (OGRRealList mempty))\n else do\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CDouble) (nElems * sizeOf (undefined :: CDouble))\n liftM (Just . OGRRealList) (St.unsafeFreeze (Stm.unsafeCast vec))\n\ngetField OFTString ix f = liftM (Just . OGRString)\n (({#call unsafe OGR_F_GetFieldAsString as ^#} f ix) >>= peekEncodedCString)\n\ngetField OFTWideString ix f = getField OFTString ix f\n\ngetField OFTStringList ix f = liftM (Just . OGRStringList) $ do\n ptr <- {#call unsafe OGR_F_GetFieldAsStringList as ^#} f ix\n nElems <- liftM fromIntegral ({#call unsafe CSLCount as ^#} ptr)\n V.generateM nElems (peekElemOff ptr >=> peekEncodedCString)\n\ngetField OFTWideStringList ix f = getField OFTStringList ix f\n\ngetField OFTBinary ix f = alloca $ \\lenP -> do\n buf <- liftM castPtr ({#call unsafe OGR_F_GetFieldAsBinary as ^#} f ix lenP)\n nElems <- peekIntegral lenP\n liftM (Just . OGRBinary) (packCStringLen (buf, nElems))\n\ngetField OFTDateTime ix f =\n liftM (fmap (uncurry OGRDateTime)) (getDateTime ix f)\n\ngetField OFTDate ix f =\n liftM (fmap (\\(LocalTime d _,_) -> OGRDate d)) (getDateTime ix f)\n\ngetField OFTTime ix f =\n liftM (fmap (\\(LocalTime _ t,_) -> OGRTime t)) (getDateTime ix f)\n\n\ngetDateTime :: CInt -> FeatureH -> IO (Maybe (LocalTime, OGRTimeZone))\ngetDateTime ix f\n = alloca $ \\y -> alloca $ \\m -> alloca $ \\d ->\n alloca $ \\h -> alloca $ \\mn -> alloca $ \\s -> alloca $ \\pTz -> do\n ret <- {#call unsafe OGR_F_GetFieldAsDateTime as ^#} f ix y m d h mn s pTz\n if ret == 0\n then return Nothing\n else do\n day <- fromGregorian <$> peekIntegral y\n <*> peekIntegral m\n <*> peekIntegral d\n tod <- TimeOfDay <$> peekIntegral h\n <*> peekIntegral mn\n <*> peekIntegral s\n iTz <- peekIntegral pTz\n return (Just (LocalTime day tod, toOGRTimezone iTz))\n\ntoOGRTimezone :: CInt -> OGRTimeZone\ntoOGRTimezone tz =\n case tz of\n 0 -> UnknownTimeZone\n 1 -> LocalTimeZone\n 100 -> KnownTimeZone utc\n n -> KnownTimeZone (minutesToTimeZone ((fromIntegral n - 100) * 15))\n\nfromOGRTimeZone :: OGRTimeZone -> CInt\nfromOGRTimeZone UnknownTimeZone = 0\nfromOGRTimeZone LocalTimeZone = 1\nfromOGRTimeZone (KnownTimeZone tz) = truncate ((mins \/ 15) + 100)\n where mins = fromIntegral (timeZoneMinutes tz) :: Double\n\npeekIntegral :: (Storable a, Integral a, Num b) => Ptr a -> IO b\npeekIntegral = liftM fromIntegral . peek\n\ngetFieldName :: FieldDefnH -> IO Text\ngetFieldName =\n {#call unsafe OGR_Fld_GetNameRef as ^#} >=> peekEncodedCString\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGRFeature (\n OGRFeature (..)\n , OGRFeatureDef (..)\n , OGRField (..)\n , OGRTimeZone (..)\n , Fid (..)\n , FieldType (..)\n , Field (..)\n , Feature (..)\n , FeatureH (..)\n , FieldDefnH (..)\n , FeatureDefnH (..)\n , Justification (..)\n\n , FeatureDef (..)\n , GeomFieldDef (..)\n , FieldDef (..)\n , fieldTypedAs\n , (.:)\n , (.=)\n , aGeom\n , aNullableGeom\n , theGeom\n , theNullableGeom\n , feature\n\n\n , featureToHandle\n , featureFromHandle\n , getFid\n\n , withFieldDefnH\n , fieldDefFromHandle\n , featureDefFromHandle\n , fieldDefsFromFeatureDefnH\n , geomFieldDefsFromFeatureDefnH\n#if SUPPORTS_MULTI_GEOM_FIELDS\n , GeomFieldDefnH (..)\n , withGeomFieldDefnH\n#endif\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\" #}\n\nimport Control.Applicative ((<$>), (<*>), pure)\nimport Control.Monad (liftM, liftM2, (>=>), (<=<), when, void)\nimport Control.Monad.Catch (bracket)\n\nimport Data.ByteString (ByteString)\nimport Data.ByteString.Char8 (packCStringLen)\nimport Data.ByteString.Unsafe (unsafeUseAsCStringLen)\nimport qualified Data.HashMap.Strict as HM\nimport Data.Int (Int32, Int64)\nimport Data.Monoid (mempty, (<>))\nimport Data.Proxy (Proxy(Proxy))\n\nimport Data.Text (Text)\nimport Data.Time.LocalTime (\n LocalTime(..)\n , TimeOfDay(..)\n , TimeZone(..)\n , minutesToTimeZone\n , utc\n )\nimport Data.Time ()\nimport Data.Time.Calendar (Day, fromGregorian, toGregorian)\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport qualified Data.Vector as V\n\nimport Foreign.C.Types (\n CInt(..)\n , CDouble(..)\n , CChar(..)\n , CUChar(..)\n , CLong(..)\n )\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (copyBytes, toBool)\nimport Foreign.Ptr (Ptr, castPtr, nullPtr)\nimport Foreign.Storable (Storable, sizeOf, peek, peekElemOff)\n#if GDAL_VERSION_MAJOR >= 2\nimport Foreign.C.Types (CLLong(..))\nimport Foreign.Marshal.Utils (fromBool)\n#endif\n\n\nimport GDAL.Internal.Util (\n toEnumC\n , fromEnumC\n , peekEncodedCString\n , useAsEncodedCString\n )\n{#import GDAL.Internal.OSR #}\n{#import GDAL.Internal.CPLError #}\n{#import GDAL.Internal.OGRGeometry #}\n{#import GDAL.Internal.OGRError #}\n\n#include \"gdal.h\"\n#include \"ogr_core.h\"\n#include \"ogr_api.h\"\n#include \"cpl_string.h\"\n\nnewtype Fid = Fid { unFid :: Int64 }\n deriving (Eq, Show, Num)\n\nclass OGRField a where\n fieldDef :: Proxy a -> FieldDef\n toField :: a -> Field\n fromField :: Field -> Either Text a\n\n(.:) :: OGRField a => Feature -> Text -> Either Text a\nfeat .: name =\n maybe (Left (\"fromFeature: field '\"<>name<>\"' not present\"))\n fromField\n (HM.lookup name (fFields feat))\n\n(.=) :: OGRField a => Text -> a -> (Text, Field)\nname .= value = (name, toField value)\n\nclass OGRFeature a where\n toFeature :: a -> Feature\n fromFeature :: Feature -> Either Text a\n\ntheGeom :: Feature -> Either Text Geometry\ntheGeom = maybe (Left \"Feature has no geometry\") Right . fGeom\n\ntheNullableGeom :: Feature -> Either Text (Maybe Geometry)\ntheNullableGeom = Right . fGeom\n\naGeom :: Feature -> Text -> Either Text Geometry\nfeat `aGeom` name =\n maybe (Left (\"fromFeature: geometry field '\"<>name<>\"' not present\"))\n (maybe (Left (\"fromFeature: geometry '\"<>name<>\"' is NULL\")) Right)\n (HM.lookup name (fGeoms feat))\n\naNullableGeom :: Feature -> Text -> Either Text (Maybe Geometry)\nfeat `aNullableGeom` name =\n maybe (Left (\"fromFeature: geometry field '\"<>name<>\"' not present\"))\n Right\n (HM.lookup name (fGeoms feat))\n\nclass OGRFeature a => OGRFeatureDef a where\n featureDef :: Proxy a -> FeatureDef\n\nfieldTypedAs :: forall a. OGRField a => Text -> a -> (Text, FieldDef)\nname `fieldTypedAs` _ = (name, fieldDef (Proxy :: Proxy a))\n\n{#enum FieldType {} omit (OFTMaxType) deriving (Eq,Show,Read,Bounded) #}\n\n{#enum Justification {}\n omit (JustifyUndefined)\n with prefix = \"OJ\"\n add prefix = \"Justify\"\n deriving (Eq,Show,Read,Bounded) #}\n\ndata Field\n = OGRInteger !Int32\n | OGRIntegerList !(St.Vector Int32)\n#if SUPPORTS_64_BIT_INT_FIELDS\n | OGRInteger64 !Int64\n | OGRInteger64List !(St.Vector Int64)\n#endif\n | OGRReal !Double\n | OGRRealList !(St.Vector Double)\n | OGRString !Text\n | OGRStringList !(V.Vector Text)\n | OGRBinary !ByteString\n | OGRDateTime !LocalTime !OGRTimeZone\n | OGRDate !Day\n | OGRTime !TimeOfDay\n | OGRNullField\n deriving (Show, Eq)\n\ndata OGRTimeZone\n = UnknownTimeZone\n | LocalTimeZone\n | KnownTimeZone !TimeZone\n deriving (Eq, Show)\n\ndata FieldDef\n = FieldDef {\n fldType :: !FieldType\n , fldWidth :: !(Maybe Int)\n , fldPrec :: !(Maybe Int)\n , fldJust :: !(Maybe Justification)\n , fldNullable :: !Bool\n } deriving (Show, Eq)\n\ndata GeomFieldDef\n = GeomFieldDef {\n gfdType :: !GeometryType\n , gfdSrs :: !(Maybe SpatialReference)\n , gfdNullable :: !Bool\n } deriving (Show, Eq)\n\ntype Map a = HM.HashMap Text a\n\ndata Feature\n = Feature {\n fFields :: !(Map Field)\n , fGeom :: !(Maybe Geometry)\n , fGeoms :: !(Map (Maybe Geometry))\n } deriving (Show, Eq)\n\nfeature :: Geometry -> [(Text,Field)] -> Feature\nfeature g fs =\n Feature { fFields = HM.fromList fs\n , fGeom = Just g\n , fGeoms = mempty\n }\n\ninstance OGRFeature Feature where\n toFeature = id\n fromFeature = Right\n\ndata FeatureDef\n = FeatureDef {\n fdName :: !Text\n , fdFields :: !FieldDefs\n , fdGeom :: !GeomFieldDef\n , fdGeoms :: !GeomFieldDefs\n } deriving (Show, Eq)\n\ntype FieldDefs = V.Vector (Text, FieldDef)\ntype GeomFieldDefs = V.Vector (Text, GeomFieldDef)\n\n\n{#pointer FeatureH newtype#}\n{#pointer FieldDefnH newtype#}\n{#pointer FeatureDefnH newtype#}\n\nderiving instance Eq FeatureH\n\nnullFeatureH :: FeatureH\nnullFeatureH = FeatureH nullPtr\n\n\nwithFieldDefnH :: Text -> FieldDef -> (FieldDefnH -> IO a) -> IO a\nwithFieldDefnH fldName FieldDef{..} f =\n useAsEncodedCString fldName $ \\pName ->\n bracket ({#call unsafe OGR_Fld_Create as ^#} pName (fromEnumC fldType))\n ({#call unsafe OGR_Fld_Destroy as ^#}) (\\p -> populate p >> f p)\n where\n populate h = do\n case fldWidth of\n Just w -> {#call unsafe OGR_Fld_SetWidth as ^#} h (fromIntegral w)\n Nothing -> return ()\n case fldPrec of\n Just p -> {#call unsafe OGR_Fld_SetPrecision as ^#} h (fromIntegral p)\n Nothing -> return ()\n case fldJust of\n Just j -> {#call unsafe OGR_Fld_SetJustify as ^#} h (fromEnumC j)\n Nothing -> return ()\n#if SUPPORTS_NULLABLE_FIELD_DEFS\n {#call unsafe OGR_Fld_SetNullable as ^#} h (fromBool fldNullable)\n#endif\n\nfieldDefFromHandle :: FieldDefnH -> IO FieldDef\nfieldDefFromHandle p =\n FieldDef\n <$> liftM toEnumC ({#call unsafe OGR_Fld_GetType as ^#} p)\n <*> liftM iToMaybe ({#call unsafe OGR_Fld_GetWidth as ^#} p)\n <*> liftM iToMaybe ({#call unsafe OGR_Fld_GetPrecision as ^#} p)\n <*> liftM jToMaybe ({#call unsafe OGR_Fld_GetJustify as ^#} p)\n#if SUPPORTS_NULLABLE_FIELD_DEFS\n <*> liftM toBool ({#call unsafe OGR_Fld_IsNullable as ^#} p)\n#else\n <*> pure True\n#endif\n where\n iToMaybe = (\\v -> if v==0 then Nothing else Just (fromIntegral v))\n jToMaybe = (\\j -> if j==0 then Nothing else Just (toEnumC j))\n\nfeatureDefFromHandle :: GeomFieldDef -> FeatureDefnH -> IO FeatureDef\nfeatureDefFromHandle gfd p = do\n#if SUPPORTS_MULTI_GEOM_FIELDS\n gfields <- geomFieldDefsFromFeatureDefnH p\n let (gfd', gfields')\n -- should not happen but just in case\n | V.null gfields = (gfd, gfields)\n -- ignore layer definition since it doesn't carry correct nullability\n -- info\n | otherwise = (snd (V.unsafeHead gfields), V.unsafeTail gfields)\n#else\n let (gfd', gfields') = (gfd, mempty)\n#endif\n FeatureDef\n <$> ({#call unsafe OGR_FD_GetName as ^#} p >>= peekEncodedCString)\n <*> fieldDefsFromFeatureDefnH p\n <*> pure gfd'\n <*> pure gfields'\n\nfieldDefsFromFeatureDefnH :: FeatureDefnH -> IO (V.Vector (Text, FieldDef))\nfieldDefsFromFeatureDefnH p = do\n nFields <- {#call unsafe OGR_FD_GetFieldCount as ^#} p\n V.generateM (fromIntegral nFields) $ \\i -> do\n fDef <- {#call unsafe OGR_FD_GetFieldDefn as ^#} p (fromIntegral i)\n liftM2 (,) (getFieldName fDef) (fieldDefFromHandle fDef)\n\n\ngeomFieldDefsFromFeatureDefnH\n :: FeatureDefnH -> IO (V.Vector (Text, GeomFieldDef))\n\n#if SUPPORTS_MULTI_GEOM_FIELDS\n\n{#pointer GeomFieldDefnH newtype#}\n\ngeomFieldDefsFromFeatureDefnH p = do\n nFields <- {#call unsafe OGR_FD_GetGeomFieldCount as ^#} p\n V.generateM (fromIntegral nFields) $\n gFldDef <=< ({#call unsafe OGR_FD_GetGeomFieldDefn as ^#} p . fromIntegral)\n where\n gFldDef g = do\n name <- {#call unsafe OGR_GFld_GetNameRef as ^#} g >>= peekEncodedCString\n gDef <- GeomFieldDef\n <$> liftM toEnumC ({#call unsafe OGR_GFld_GetType as ^#} g)\n <*> ({#call unsafe OGR_GFld_GetSpatialRef as ^#} g >>=\n maybeNewSpatialRefBorrowedHandle)\n#if SUPPORTS_NULLABLE_FIELD_DEFS\n <*> liftM toBool ({#call unsafe OGR_GFld_IsNullable as ^#} g)\n#else\n <*> pure True\n#endif\n return (name, gDef)\n\nwithGeomFieldDefnH :: Text -> GeomFieldDef -> (GeomFieldDefnH -> IO a) -> IO a\nwithGeomFieldDefnH gfdName GeomFieldDef{..} f =\n useAsEncodedCString gfdName $ \\pName ->\n bracket ({#call unsafe OGR_GFld_Create as ^#} pName (fromEnumC gfdType))\n ({#call unsafe OGR_GFld_Destroy as ^#}) (\\p -> populate p >> f p)\n where\n populate p = do\n withMaybeSpatialReference gfdSrs $\n {#call unsafe OGR_GFld_SetSpatialRef as ^#} p\n#if SUPPORTS_NULLABLE_FIELD_DEFS\n {#call unsafe OGR_GFld_SetNullable as ^#} p (fromBool gfdNullable)\n#endif\n\n#else\ngeomFieldDefsFromFeatureDefnH = const (return mempty)\n#endif -- SUPPORTS_MULTI_GEOM_FIELDS\n\nnullFID :: Fid\nnullFID = Fid ({#const OGRNullFID#})\n\nfeatureToHandle\n :: OGRFeature f\n => FeatureDefnH -> Maybe Fid -> f -> (FeatureH -> IO a) -> IO a\nfeatureToHandle fdH fId ft act =\n bracket ({#call unsafe OGR_F_Create as ^#} fdH)\n ({#call unsafe OGR_F_Destroy as ^#}) $ \\pF -> do\n case fId of\n Just (Fid fid) ->\n void $ {#call unsafe OGR_F_SetFID as ^#} pF (fromIntegral fid)\n Nothing -> return ()\n fieldDefs <- fieldDefsFromFeatureDefnH fdH\n flip imapM_ fieldDefs $ \\ix (name, _) -> do\n case HM.lookup name fFields of\n Just f -> setField f ix pF\n Nothing -> return ()\n case fGeom of\n Just g -> void $ withGeometry g ({#call unsafe OGR_F_SetGeometry as ^#} pF)\n Nothing -> return ()\n when (not (HM.null fGeoms)) $ do\n#if SUPPORTS_MULTI_GEOM_FIELDS\n geomFieldDefs <- geomFieldDefsFromFeatureDefnH fdH\n flip imapM_ (V.tail geomFieldDefs) $ \\ix (name, _) -> do\n case join (HM.lookup name fGeoms) of\n Just g ->\n void $ withGeometry g ({#call unsafe OGR_F_SetGeomField as ^#} pF (ix+1))\n Nothing ->\n return ()\n#else\n throwBindingException MultipleGeomFieldsNotSupported\n#endif\n act pF\n where Feature {..} = toFeature ft\n\nimapM :: (Monad m, Num a) => (a -> b -> m c) -> V.Vector b -> m (V.Vector c)\nimapM f v = V.mapM (uncurry f) (V.zip (V.enumFromN 0 (V.length v)) v)\n\nimapM_ :: (Monad m, Num a) => (a -> b -> m ()) -> V.Vector b -> m ()\nimapM_ f v = V.mapM_ (uncurry f) (V.zip (V.enumFromN 0 (V.length v)) v)\n\ngetFid :: FeatureH -> IO (Maybe Fid)\ngetFid pF = do\n mFid <- liftM fromIntegral ({#call unsafe OGR_F_GetFID as ^#} pF)\n return (if mFid == nullFID then Nothing else Just mFid)\n\nfeatureFromHandle\n :: OGRFeature a\n => FeatureDef -> IO FeatureH -> IO (Maybe (Maybe Fid, a))\nfeatureFromHandle FeatureDef{..} act =\n bracket act {#call unsafe OGR_F_Destroy as ^#} $ \\pF -> do\n if (pF == nullFeatureH)\n then return Nothing\n else do\n fid <- getFid pF\n fields <- flip imapM fdFields $ \\i (fldName, fd) -> do\n isSet <- liftM toBool ({#call unsafe OGR_F_IsFieldSet as ^#} pF i)\n if isSet\n then getField (fldType fd) i pF >>=\n maybe (throwBindingException (FieldParseError fldName))\n (\\f -> return (fldName, f))\n else return (fldName, OGRNullField)\n geomRef <- {#call unsafe OGR_F_StealGeometry as ^#} pF\n geom <- if geomRef \/= nullPtr\n then liftM Just (newGeometryHandle geomRef)\n else return Nothing\n#if SUPPORTS_MULTI_GEOM_FIELDS\n geoms <- flip imapM fdGeoms $ \\ix (gfdName, _) -> do\n pG <- {#call unsafe OGR_F_GetGeomFieldRef as ^#} pF (ix + 1)\n g <- if pG \/= nullPtr\n then liftM Just (cloneGeometry pG)\n else return Nothing\n return (gfdName, g)\n#else\n let geoms = mempty\n#endif\n either (throwBindingException . FromFeatureError)\n (\\f -> return (Just (fid,f)))\n (fromFeature Feature {\n fFields = HM.fromList (V.toList fields)\n , fGeom = geom\n , fGeoms = HM.fromList (V.toList geoms)\n })\n\n\n-- ############################################################################\n-- setField\n-- ############################################################################\n\nsetField :: Field -> CInt -> FeatureH -> IO ()\n\nsetField (OGRInteger v) ix f =\n {#call unsafe OGR_F_SetFieldInteger as ^#} f (fromIntegral ix) (fromIntegral v)\n\nsetField (OGRIntegerList v) ix f =\n St.unsafeWith v $\n {#call unsafe OGR_F_SetFieldIntegerList as ^#} f (fromIntegral ix)\n (fromIntegral (St.length v)) . castPtr\n\n#if SUPPORTS_64_BIT_INT_FIELDS\nsetField (OGRInteger64 v) ix f =\n {#call unsafe OGR_F_SetFieldInteger64 as ^#} f (fromIntegral ix) (fromIntegral v)\n\nsetField (OGRInteger64List v) ix f =\n St.unsafeWith v $\n {#call unsafe OGR_F_SetFieldInteger64List as ^#} f (fromIntegral ix)\n (fromIntegral (St.length v)) . castPtr\n#endif\n\nsetField (OGRReal v) ix f =\n {#call unsafe OGR_F_SetFieldDouble as ^#} f (fromIntegral ix) (realToFrac v)\n\nsetField (OGRRealList v) ix f =\n St.unsafeWith v $\n {#call unsafe OGR_F_SetFieldDoubleList as ^#} f (fromIntegral ix)\n (fromIntegral (St.length v)) . castPtr\n\nsetField (OGRString v) ix f = useAsEncodedCString v $\n {#call unsafe OGR_F_SetFieldString as ^#} f (fromIntegral ix)\n\nsetField (OGRStringList v) ix f =\n bracket createList {#call unsafe CSLDestroy as ^#} $\n {#call unsafe OGR_F_SetFieldStringList as ^#} f (fromIntegral ix)\n where\n createList = V.foldM' folder nullPtr v\n folder acc k =\n useAsEncodedCString k $ {#call unsafe CSLAddString as ^#} acc\n\nsetField (OGRBinary v) ix f = unsafeUseAsCStringLen v $ \\(p,l) ->\n {#call unsafe OGR_F_SetFieldBinary as ^#}\n f (fromIntegral ix) (fromIntegral l) (castPtr p)\n\nsetField (OGRDateTime (LocalTime day (TimeOfDay h mn s)) tz) ix f =\n {#call unsafe OGR_F_SetFieldDateTime as ^#} f (fromIntegral ix)\n (fromIntegral y) (fromIntegral m) (fromIntegral d)\n (fromIntegral h) (fromIntegral mn) (truncate s) (fromOGRTimeZone tz)\n where (y, m, d) = toGregorian day\n\nsetField (OGRDate day) ix f =\n {#call unsafe OGR_F_SetFieldDateTime as ^#} f (fromIntegral ix)\n (fromIntegral y) (fromIntegral m) (fromIntegral d) 0 0 0 (fromOGRTimeZone tz)\n where (y, m, d) = toGregorian day\n tz = UnknownTimeZone\n\nsetField (OGRTime (TimeOfDay h mn s)) ix f =\n {#call unsafe OGR_F_SetFieldDateTime as ^#} f (fromIntegral ix) 0 0 0\n (fromIntegral h) (fromIntegral mn) (truncate s) (fromOGRTimeZone tz)\n where tz = UnknownTimeZone\n\nsetField OGRNullField ix f = {#call unsafe OGR_F_UnsetField as ^#} f ix\n\n-- ############################################################################\n-- getField\n-- ############################################################################\n\ngetField :: FieldType -> CInt -> FeatureH -> IO (Maybe Field)\n\ngetField OFTInteger ix f =\n liftM (Just . OGRInteger . fromIntegral)\n ({#call unsafe OGR_F_GetFieldAsInteger as ^#} f ix)\n\ngetField OFTIntegerList ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsIntegerList as ^#} f ix lenP\n nElems <- peekIntegral lenP\n if nElems == 0\n then return (Just (OGRIntegerList mempty))\n else do\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CInt) (nElems * sizeOf (undefined :: CInt))\n liftM (Just . OGRIntegerList) (St.unsafeFreeze (Stm.unsafeCast vec))\n\n#if SUPPORTS_64_BIT_INT_FIELDS\ngetField OFTInteger64 ix f\n = liftM (Just . OGRInteger64 . fromIntegral)\n ({#call unsafe OGR_F_GetFieldAsInteger64 as ^#} f ix)\n\ngetField OFTInteger64List ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsInteger64List as ^#} f ix lenP\n nElems <- peekIntegral lenP\n if nElems == 0\n then return (Just (OGRInteger64List mempty))\n else do\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CLLong) (nElems * sizeOf (undefined :: CLLong))\n liftM (Just . OGRInteger64List) (St.unsafeFreeze (Stm.unsafeCast vec))\n#endif\n\ngetField OFTReal ix f\n = liftM (Just . OGRReal . realToFrac)\n ({#call unsafe OGR_F_GetFieldAsDouble as ^#} f ix)\n\ngetField OFTRealList ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsDoubleList as ^#} f ix lenP\n nElems <- peekIntegral lenP\n if nElems == 0\n then return (Just (OGRRealList mempty))\n else do\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CDouble) (nElems * sizeOf (undefined :: CDouble))\n liftM (Just . OGRRealList) (St.unsafeFreeze (Stm.unsafeCast vec))\n\ngetField OFTString ix f = liftM (Just . OGRString)\n (({#call unsafe OGR_F_GetFieldAsString as ^#} f ix) >>= peekEncodedCString)\n\ngetField OFTWideString ix f = getField OFTString ix f\n\ngetField OFTStringList ix f = liftM (Just . OGRStringList) $ do\n ptr <- {#call unsafe OGR_F_GetFieldAsStringList as ^#} f ix\n nElems <- liftM fromIntegral ({#call unsafe CSLCount as ^#} ptr)\n V.generateM nElems (peekElemOff ptr >=> peekEncodedCString)\n\ngetField OFTWideStringList ix f = getField OFTStringList ix f\n\ngetField OFTBinary ix f = alloca $ \\lenP -> do\n buf <- liftM castPtr ({#call unsafe OGR_F_GetFieldAsBinary as ^#} f ix lenP)\n nElems <- peekIntegral lenP\n liftM (Just . OGRBinary) (packCStringLen (buf, nElems))\n\ngetField OFTDateTime ix f =\n liftM (fmap (uncurry OGRDateTime)) (getDateTime ix f)\n\ngetField OFTDate ix f =\n liftM (fmap (\\(LocalTime d _,_) -> OGRDate d)) (getDateTime ix f)\n\ngetField OFTTime ix f =\n liftM (fmap (\\(LocalTime _ t,_) -> OGRTime t)) (getDateTime ix f)\n\n\ngetDateTime :: CInt -> FeatureH -> IO (Maybe (LocalTime, OGRTimeZone))\ngetDateTime ix f\n = alloca $ \\y -> alloca $ \\m -> alloca $ \\d ->\n alloca $ \\h -> alloca $ \\mn -> alloca $ \\s -> alloca $ \\pTz -> do\n ret <- {#call unsafe OGR_F_GetFieldAsDateTime as ^#} f ix y m d h mn s pTz\n if ret == 0\n then return Nothing\n else do\n day <- fromGregorian <$> peekIntegral y\n <*> peekIntegral m\n <*> peekIntegral d\n tod <- TimeOfDay <$> peekIntegral h\n <*> peekIntegral mn\n <*> peekIntegral s\n iTz <- peekIntegral pTz\n return (Just (LocalTime day tod, toOGRTimezone iTz))\n\ntoOGRTimezone :: CInt -> OGRTimeZone\ntoOGRTimezone tz =\n case tz of\n 0 -> UnknownTimeZone\n 1 -> LocalTimeZone\n 100 -> KnownTimeZone utc\n n -> KnownTimeZone (minutesToTimeZone ((fromIntegral n - 100) * 15))\n\nfromOGRTimeZone :: OGRTimeZone -> CInt\nfromOGRTimeZone UnknownTimeZone = 0\nfromOGRTimeZone LocalTimeZone = 1\nfromOGRTimeZone (KnownTimeZone tz) = truncate ((mins \/ 15) + 100)\n where mins = fromIntegral (timeZoneMinutes tz) :: Double\n\npeekIntegral :: (Storable a, Integral a, Num b) => Ptr a -> IO b\npeekIntegral = liftM fromIntegral . peek\n\ngetFieldName :: FieldDefnH -> IO Text\ngetFieldName =\n {#call unsafe OGR_Fld_GetNameRef as ^#} >=> peekEncodedCString\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"34bfd7138945e837c645fbb6c2748122bf2e888c","subject":"Add writeAttr for Enums. This is needed for MessageDialog.","message":"Add writeAttr for Enums.\nThis is needed for MessageDialog.\n","repos":"vincenthz\/webkit","old_file":"glib\/System\/Glib\/Properties.chs","new_file":"glib\/System\/Glib\/Properties.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GObject Properties\n--\n-- Author : Duncan Coutts\n--\n-- Created: 16 April 2005\n--\n-- Version $Revision: 1.8 $ from $Date: 2005\/08\/29 11:15:58 $\n--\n-- Copyright (C) 2005 Duncan Coutts\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Functions for getting and setting GObject properties\n--\nmodule System.Glib.Properties (\n -- * per-type functions for getting and setting GObject properties\n objectSetPropertyInt,\n objectGetPropertyInt,\n objectSetPropertyUInt,\n objectGetPropertyUInt,\n objectSetPropertyBool,\n objectGetPropertyBool,\n objectSetPropertyEnum,\n objectGetPropertyEnum,\n objectSetPropertyFlags,\n objectGetPropertyFlags,\n objectSetPropertyFloat,\n objectGetPropertyFloat,\n objectSetPropertyDouble,\n objectGetPropertyDouble,\n objectSetPropertyString,\n objectGetPropertyString,\n objectSetPropertyMaybeString,\n objectGetPropertyMaybeString, \n objectSetPropertyBoxedOpaque,\n objectGetPropertyBoxedOpaque,\n objectSetPropertyBoxedStorable,\n objectGetPropertyBoxedStorable,\n objectSetPropertyGObject,\n objectGetPropertyGObject,\n\n -- * constructors for attributes backed by GObject properties\n newAttrFromIntProperty,\n readAttrFromIntProperty,\n newAttrFromUIntProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n newAttrFromFloatProperty,\n newAttrFromDoubleProperty,\n newAttrFromEnumProperty,\n readAttrFromEnumProperty,\n writeAttrFromEnumProperty,\n newAttrFromFlagsProperty,\n newAttrFromStringProperty,\n readAttrFromStringProperty,\n writeAttrFromStringProperty,\n writeAttrFromMaybeStringProperty,\n newAttrFromMaybeStringProperty,\n newAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n ) where\n\nimport Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags, fromFlags, toFlags)\nimport System.Glib.UTFString\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\nimport System.Glib.GObject\t(makeNewGObject)\nimport qualified System.Glib.GTypeConstants as GType\nimport System.Glib.GType\nimport System.Glib.GValueTypes\nimport System.Glib.Attributes\t(Attr, ReadAttr, WriteAttr, ReadWriteAttr,\n\t\t\t\tnewAttr, readAttr, writeAttr)\n\n{# context lib=\"glib\" prefix=\"g\" #}\n\nobjectSetPropertyInternal :: GObjectClass gobj => GType -> (GValue -> a -> IO ()) -> String -> gobj -> a -> IO ()\nobjectSetPropertyInternal gtype valueSet prop obj val =\n withCString prop $ \\propPtr ->\n allocaGValue $ \\gvalue -> do\n valueInit gvalue gtype\n valueSet gvalue val\n {# call g_object_set_property #}\n (toGObject obj)\n propPtr\n gvalue\n\nobjectGetPropertyInternal :: GObjectClass gobj => GType -> (GValue -> IO a) -> String -> gobj -> IO a\nobjectGetPropertyInternal gtype valueGet prop obj =\n withCString prop $ \\propPtr ->\n allocaGValue $ \\gvalue -> do\n valueInit gvalue gtype\n {# call unsafe g_object_get_property #}\n (toGObject obj)\n propPtr\n gvalue\n valueGet gvalue\n\nobjectSetPropertyInt :: GObjectClass gobj => String -> gobj -> Int -> IO ()\nobjectSetPropertyInt = objectSetPropertyInternal GType.int valueSetInt\n\nobjectGetPropertyInt :: GObjectClass gobj => String -> gobj -> IO Int\nobjectGetPropertyInt = objectGetPropertyInternal GType.int valueGetInt\n\nobjectSetPropertyUInt :: GObjectClass gobj => String -> gobj -> Int -> IO ()\nobjectSetPropertyUInt = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral v))\n\nobjectGetPropertyUInt :: GObjectClass gobj => String -> gobj -> IO Int\nobjectGetPropertyUInt = objectGetPropertyInternal GType.uint (\\gv -> liftM fromIntegral $ valueGetUInt gv)\n\nobjectSetPropertyBool :: GObjectClass gobj => String -> gobj -> Bool -> IO ()\nobjectSetPropertyBool = objectSetPropertyInternal GType.bool valueSetBool\n\nobjectGetPropertyBool :: GObjectClass gobj => String -> gobj -> IO Bool\nobjectGetPropertyBool = objectGetPropertyInternal GType.bool valueGetBool\n\nobjectSetPropertyEnum :: (GObjectClass gobj, Enum enum) => GType -> String -> gobj -> enum -> IO ()\nobjectSetPropertyEnum gtype = objectSetPropertyInternal gtype valueSetEnum\n\nobjectGetPropertyEnum :: (GObjectClass gobj, Enum enum) => GType -> String -> gobj -> IO enum\nobjectGetPropertyEnum gtype = objectGetPropertyInternal gtype valueGetEnum\n\nobjectSetPropertyFlags :: (GObjectClass gobj, Flags flag) => String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags = objectSetPropertyInternal GType.flags valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => String -> gobj -> IO [flag]\nobjectGetPropertyFlags = objectGetPropertyInternal GType.flags valueGetFlags\n\nobjectSetPropertyFloat :: GObjectClass gobj => String -> gobj -> Float -> IO ()\nobjectSetPropertyFloat = objectSetPropertyInternal GType.float valueSetFloat\n\nobjectGetPropertyFloat :: GObjectClass gobj => String -> gobj -> IO Float\nobjectGetPropertyFloat = objectGetPropertyInternal GType.float valueGetFloat\n\nobjectSetPropertyDouble :: GObjectClass gobj => String -> gobj -> Double -> IO ()\nobjectSetPropertyDouble = objectSetPropertyInternal GType.double valueSetDouble\n\nobjectGetPropertyDouble :: GObjectClass gobj => String -> gobj -> IO Double\nobjectGetPropertyDouble = objectGetPropertyInternal GType.double valueGetDouble\n\nobjectSetPropertyString :: GObjectClass gobj => String -> gobj -> String -> IO ()\nobjectSetPropertyString = objectSetPropertyInternal GType.string valueSetString\n\nobjectGetPropertyString :: GObjectClass gobj => String -> gobj -> IO String\nobjectGetPropertyString = objectGetPropertyInternal GType.string valueGetString\n\nobjectSetPropertyMaybeString :: GObjectClass gobj => String -> gobj -> Maybe String -> IO ()\nobjectSetPropertyMaybeString = objectSetPropertyInternal GType.string valueSetMaybeString\n\nobjectGetPropertyMaybeString :: GObjectClass gobj => String -> gobj -> IO (Maybe String)\nobjectGetPropertyMaybeString = objectGetPropertyInternal GType.string valueGetMaybeString\n\nobjectSetPropertyBoxedOpaque :: GObjectClass gobj => (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> GType -> String -> gobj -> boxed -> IO ()\nobjectSetPropertyBoxedOpaque with gtype = objectSetPropertyInternal gtype (valueSetBoxed with)\n\nobjectGetPropertyBoxedOpaque :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> GType -> String -> gobj -> IO boxed\nobjectGetPropertyBoxedOpaque peek gtype = objectGetPropertyInternal gtype (valueGetBoxed peek)\n\nobjectSetPropertyBoxedStorable :: (GObjectClass gobj, Storable boxed) => GType -> String -> gobj -> boxed -> IO ()\nobjectSetPropertyBoxedStorable = objectSetPropertyBoxedOpaque with\n\nobjectGetPropertyBoxedStorable :: (GObjectClass gobj, Storable boxed) => GType -> String -> gobj -> IO boxed\nobjectGetPropertyBoxedStorable = objectGetPropertyBoxedOpaque peek\n\nobjectSetPropertyGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> gobj' -> IO ()\nobjectSetPropertyGObject gtype = objectSetPropertyInternal gtype valueSetGObject\n\nobjectGetPropertyGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO gobj'\nobjectGetPropertyGObject gtype = objectGetPropertyInternal gtype valueGetGObject\n\n\n-- Convenience functions to make attribute implementations in the other modules\n-- shorter and more easily extensible.\n--\n\nnewAttrFromIntProperty :: GObjectClass gobj => String -> Attr gobj Int\nnewAttrFromIntProperty propName =\n newAttr (objectGetPropertyInt propName) (objectSetPropertyInt propName)\n\nreadAttrFromIntProperty :: GObjectClass gobj => String -> ReadAttr gobj Int\nreadAttrFromIntProperty propName =\n readAttr (objectGetPropertyInt propName)\n\nnewAttrFromUIntProperty :: GObjectClass gobj => String -> Attr gobj Int\nnewAttrFromUIntProperty propName =\n newAttr (objectGetPropertyUInt propName) (objectSetPropertyUInt propName)\n\nwriteAttrFromUIntProperty :: GObjectClass gobj => String -> WriteAttr gobj Int\nwriteAttrFromUIntProperty propName =\n writeAttr (objectSetPropertyUInt propName)\n\nnewAttrFromBoolProperty :: GObjectClass gobj => String -> Attr gobj Bool\nnewAttrFromBoolProperty propName =\n newAttr (objectGetPropertyBool propName) (objectSetPropertyBool propName)\n\nnewAttrFromFloatProperty :: GObjectClass gobj => String -> Attr gobj Float\nnewAttrFromFloatProperty propName =\n newAttr (objectGetPropertyFloat propName) (objectSetPropertyFloat propName)\n\nnewAttrFromDoubleProperty :: GObjectClass gobj => String -> Attr gobj Double\nnewAttrFromDoubleProperty propName =\n newAttr (objectGetPropertyDouble propName) (objectSetPropertyDouble propName)\n\nnewAttrFromEnumProperty :: (GObjectClass gobj, Enum enum) => String -> GType -> Attr gobj enum\nnewAttrFromEnumProperty propName gtype =\n newAttr (objectGetPropertyEnum gtype propName) (objectSetPropertyEnum gtype propName)\n\nreadAttrFromEnumProperty :: (GObjectClass gobj, Enum enum) => String -> GType -> ReadAttr gobj enum\nreadAttrFromEnumProperty propName gtype =\n readAttr (objectGetPropertyEnum gtype propName)\n\nwriteAttrFromEnumProperty :: (GObjectClass gobj, Enum enum) => String -> GType -> WriteAttr gobj enum\nwriteAttrFromEnumProperty propName gtype =\n writeAttr (objectSetPropertyEnum gtype propName)\n\nnewAttrFromFlagsProperty :: (GObjectClass gobj, Flags flag) => String -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName =\n newAttr (objectGetPropertyFlags propName) (objectSetPropertyFlags propName)\n\nnewAttrFromStringProperty :: GObjectClass gobj => String -> Attr gobj String\nnewAttrFromStringProperty propName =\n newAttr (objectGetPropertyString propName) (objectSetPropertyString propName)\n\nreadAttrFromStringProperty :: GObjectClass gobj => String -> ReadAttr gobj String\nreadAttrFromStringProperty propName =\n readAttr (objectGetPropertyString propName)\n\nwriteAttrFromStringProperty :: GObjectClass gobj => String -> WriteAttr gobj String\nwriteAttrFromStringProperty propName =\n writeAttr (objectSetPropertyString propName)\n\nwriteAttrFromMaybeStringProperty :: GObjectClass gobj => String -> WriteAttr gobj (Maybe String)\nwriteAttrFromMaybeStringProperty propName =\n writeAttr (objectSetPropertyMaybeString propName)\n\nnewAttrFromMaybeStringProperty :: GObjectClass gobj => String -> Attr gobj (Maybe String)\nnewAttrFromMaybeStringProperty propName =\n newAttr (objectGetPropertyMaybeString propName) (objectSetPropertyMaybeString propName)\n\nnewAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> String -> GType -> Attr gobj boxed\nnewAttrFromBoxedOpaqueProperty peek with propName gtype =\n newAttr (objectGetPropertyBoxedOpaque peek gtype propName) (objectSetPropertyBoxedOpaque with gtype propName)\n\nwriteAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> String -> GType -> WriteAttr gobj boxed\nwriteAttrFromBoxedOpaqueProperty with propName gtype =\n writeAttr (objectSetPropertyBoxedOpaque with gtype propName)\n\nnewAttrFromBoxedStorableProperty :: (GObjectClass gobj, Storable boxed) => String -> GType -> Attr gobj boxed\nnewAttrFromBoxedStorableProperty propName gtype =\n newAttr (objectGetPropertyBoxedStorable gtype propName) (objectSetPropertyBoxedStorable gtype propName)\n\nnewAttrFromObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj gobj' gobj''\nnewAttrFromObjectProperty propName gtype =\n newAttr (objectGetPropertyGObject gtype propName) (objectSetPropertyGObject gtype propName)\n\nwriteAttrFromObjectProperty :: (GObjectClass gobj, GObjectClass gobj') => String -> GType -> WriteAttr gobj gobj'\nwriteAttrFromObjectProperty propName gtype =\n writeAttr (objectSetPropertyGObject gtype propName)\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GObject Properties\n--\n-- Author : Duncan Coutts\n--\n-- Created: 16 April 2005\n--\n-- Version $Revision: 1.8 $ from $Date: 2005\/08\/29 11:15:58 $\n--\n-- Copyright (C) 2005 Duncan Coutts\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Functions for getting and setting GObject properties\n--\nmodule System.Glib.Properties (\n -- * per-type functions for getting and setting GObject properties\n objectSetPropertyInt,\n objectGetPropertyInt,\n objectSetPropertyUInt,\n objectGetPropertyUInt,\n objectSetPropertyBool,\n objectGetPropertyBool,\n objectSetPropertyEnum,\n objectGetPropertyEnum,\n objectSetPropertyFlags,\n objectGetPropertyFlags,\n objectSetPropertyFloat,\n objectGetPropertyFloat,\n objectSetPropertyDouble,\n objectGetPropertyDouble,\n objectSetPropertyString,\n objectGetPropertyString,\n objectSetPropertyMaybeString,\n objectGetPropertyMaybeString, \n objectSetPropertyBoxedOpaque,\n objectGetPropertyBoxedOpaque,\n objectSetPropertyBoxedStorable,\n objectGetPropertyBoxedStorable,\n objectSetPropertyGObject,\n objectGetPropertyGObject,\n\n -- * constructors for attributes backed by GObject properties\n newAttrFromIntProperty,\n readAttrFromIntProperty,\n newAttrFromUIntProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n newAttrFromFloatProperty,\n newAttrFromDoubleProperty,\n newAttrFromEnumProperty,\n readAttrFromEnumProperty,\n newAttrFromFlagsProperty,\n newAttrFromStringProperty,\n readAttrFromStringProperty,\n writeAttrFromStringProperty,\n writeAttrFromMaybeStringProperty,\n newAttrFromMaybeStringProperty,\n newAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n ) where\n\nimport Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags, fromFlags, toFlags)\nimport System.Glib.UTFString\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\nimport System.Glib.GObject\t(makeNewGObject)\nimport qualified System.Glib.GTypeConstants as GType\nimport System.Glib.GType\nimport System.Glib.GValueTypes\nimport System.Glib.Attributes\t(Attr, ReadAttr, WriteAttr, ReadWriteAttr,\n\t\t\t\tnewAttr, readAttr, writeAttr)\n\n{# context lib=\"glib\" prefix=\"g\" #}\n\nobjectSetPropertyInternal :: GObjectClass gobj => GType -> (GValue -> a -> IO ()) -> String -> gobj -> a -> IO ()\nobjectSetPropertyInternal gtype valueSet prop obj val =\n withCString prop $ \\propPtr ->\n allocaGValue $ \\gvalue -> do\n valueInit gvalue gtype\n valueSet gvalue val\n {# call g_object_set_property #}\n (toGObject obj)\n propPtr\n gvalue\n\nobjectGetPropertyInternal :: GObjectClass gobj => GType -> (GValue -> IO a) -> String -> gobj -> IO a\nobjectGetPropertyInternal gtype valueGet prop obj =\n withCString prop $ \\propPtr ->\n allocaGValue $ \\gvalue -> do\n valueInit gvalue gtype\n {# call unsafe g_object_get_property #}\n (toGObject obj)\n propPtr\n gvalue\n valueGet gvalue\n\nobjectSetPropertyInt :: GObjectClass gobj => String -> gobj -> Int -> IO ()\nobjectSetPropertyInt = objectSetPropertyInternal GType.int valueSetInt\n\nobjectGetPropertyInt :: GObjectClass gobj => String -> gobj -> IO Int\nobjectGetPropertyInt = objectGetPropertyInternal GType.int valueGetInt\n\nobjectSetPropertyUInt :: GObjectClass gobj => String -> gobj -> Int -> IO ()\nobjectSetPropertyUInt = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral v))\n\nobjectGetPropertyUInt :: GObjectClass gobj => String -> gobj -> IO Int\nobjectGetPropertyUInt = objectGetPropertyInternal GType.uint (\\gv -> liftM fromIntegral $ valueGetUInt gv)\n\nobjectSetPropertyBool :: GObjectClass gobj => String -> gobj -> Bool -> IO ()\nobjectSetPropertyBool = objectSetPropertyInternal GType.bool valueSetBool\n\nobjectGetPropertyBool :: GObjectClass gobj => String -> gobj -> IO Bool\nobjectGetPropertyBool = objectGetPropertyInternal GType.bool valueGetBool\n\nobjectSetPropertyEnum :: (GObjectClass gobj, Enum enum) => GType -> String -> gobj -> enum -> IO ()\nobjectSetPropertyEnum gtype = objectSetPropertyInternal gtype valueSetEnum\n\nobjectGetPropertyEnum :: (GObjectClass gobj, Enum enum) => GType -> String -> gobj -> IO enum\nobjectGetPropertyEnum gtype = objectGetPropertyInternal gtype valueGetEnum\n\nobjectSetPropertyFlags :: (GObjectClass gobj, Flags flag) => String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags = objectSetPropertyInternal GType.flags valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => String -> gobj -> IO [flag]\nobjectGetPropertyFlags = objectGetPropertyInternal GType.flags valueGetFlags\n\nobjectSetPropertyFloat :: GObjectClass gobj => String -> gobj -> Float -> IO ()\nobjectSetPropertyFloat = objectSetPropertyInternal GType.float valueSetFloat\n\nobjectGetPropertyFloat :: GObjectClass gobj => String -> gobj -> IO Float\nobjectGetPropertyFloat = objectGetPropertyInternal GType.float valueGetFloat\n\nobjectSetPropertyDouble :: GObjectClass gobj => String -> gobj -> Double -> IO ()\nobjectSetPropertyDouble = objectSetPropertyInternal GType.double valueSetDouble\n\nobjectGetPropertyDouble :: GObjectClass gobj => String -> gobj -> IO Double\nobjectGetPropertyDouble = objectGetPropertyInternal GType.double valueGetDouble\n\nobjectSetPropertyString :: GObjectClass gobj => String -> gobj -> String -> IO ()\nobjectSetPropertyString = objectSetPropertyInternal GType.string valueSetString\n\nobjectGetPropertyString :: GObjectClass gobj => String -> gobj -> IO String\nobjectGetPropertyString = objectGetPropertyInternal GType.string valueGetString\n\nobjectSetPropertyMaybeString :: GObjectClass gobj => String -> gobj -> Maybe String -> IO ()\nobjectSetPropertyMaybeString = objectSetPropertyInternal GType.string valueSetMaybeString\n\nobjectGetPropertyMaybeString :: GObjectClass gobj => String -> gobj -> IO (Maybe String)\nobjectGetPropertyMaybeString = objectGetPropertyInternal GType.string valueGetMaybeString\n\nobjectSetPropertyBoxedOpaque :: GObjectClass gobj => (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> GType -> String -> gobj -> boxed -> IO ()\nobjectSetPropertyBoxedOpaque with gtype = objectSetPropertyInternal gtype (valueSetBoxed with)\n\nobjectGetPropertyBoxedOpaque :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> GType -> String -> gobj -> IO boxed\nobjectGetPropertyBoxedOpaque peek gtype = objectGetPropertyInternal gtype (valueGetBoxed peek)\n\nobjectSetPropertyBoxedStorable :: (GObjectClass gobj, Storable boxed) => GType -> String -> gobj -> boxed -> IO ()\nobjectSetPropertyBoxedStorable = objectSetPropertyBoxedOpaque with\n\nobjectGetPropertyBoxedStorable :: (GObjectClass gobj, Storable boxed) => GType -> String -> gobj -> IO boxed\nobjectGetPropertyBoxedStorable = objectGetPropertyBoxedOpaque peek\n\nobjectSetPropertyGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> gobj' -> IO ()\nobjectSetPropertyGObject gtype = objectSetPropertyInternal gtype valueSetGObject\n\nobjectGetPropertyGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO gobj'\nobjectGetPropertyGObject gtype = objectGetPropertyInternal gtype valueGetGObject\n\n\n-- Convenience functions to make attribute implementations in the other modules\n-- shorter and more easily extensible.\n--\n\nnewAttrFromIntProperty :: GObjectClass gobj => String -> Attr gobj Int\nnewAttrFromIntProperty propName =\n newAttr (objectGetPropertyInt propName) (objectSetPropertyInt propName)\n\nreadAttrFromIntProperty :: GObjectClass gobj => String -> ReadAttr gobj Int\nreadAttrFromIntProperty propName =\n readAttr (objectGetPropertyInt propName)\n\nnewAttrFromUIntProperty :: GObjectClass gobj => String -> Attr gobj Int\nnewAttrFromUIntProperty propName =\n newAttr (objectGetPropertyUInt propName) (objectSetPropertyUInt propName)\n\nwriteAttrFromUIntProperty :: GObjectClass gobj => String -> WriteAttr gobj Int\nwriteAttrFromUIntProperty propName =\n writeAttr (objectSetPropertyUInt propName)\n\nnewAttrFromBoolProperty :: GObjectClass gobj => String -> Attr gobj Bool\nnewAttrFromBoolProperty propName =\n newAttr (objectGetPropertyBool propName) (objectSetPropertyBool propName)\n\nnewAttrFromFloatProperty :: GObjectClass gobj => String -> Attr gobj Float\nnewAttrFromFloatProperty propName =\n newAttr (objectGetPropertyFloat propName) (objectSetPropertyFloat propName)\n\nnewAttrFromDoubleProperty :: GObjectClass gobj => String -> Attr gobj Double\nnewAttrFromDoubleProperty propName =\n newAttr (objectGetPropertyDouble propName) (objectSetPropertyDouble propName)\n\nnewAttrFromEnumProperty :: (GObjectClass gobj, Enum enum) => String -> GType -> Attr gobj enum\nnewAttrFromEnumProperty propName gtype =\n newAttr (objectGetPropertyEnum gtype propName) (objectSetPropertyEnum gtype propName)\n\nreadAttrFromEnumProperty :: (GObjectClass gobj, Enum enum) => String -> GType -> ReadAttr gobj enum\nreadAttrFromEnumProperty propName gtype =\n readAttr (objectGetPropertyEnum gtype propName)\n\nnewAttrFromFlagsProperty :: (GObjectClass gobj, Flags flag) => String -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName =\n newAttr (objectGetPropertyFlags propName) (objectSetPropertyFlags propName)\n\nnewAttrFromStringProperty :: GObjectClass gobj => String -> Attr gobj String\nnewAttrFromStringProperty propName =\n newAttr (objectGetPropertyString propName) (objectSetPropertyString propName)\n\nreadAttrFromStringProperty :: GObjectClass gobj => String -> ReadAttr gobj String\nreadAttrFromStringProperty propName =\n readAttr (objectGetPropertyString propName)\n\nwriteAttrFromStringProperty :: GObjectClass gobj => String -> WriteAttr gobj String\nwriteAttrFromStringProperty propName =\n writeAttr (objectSetPropertyString propName)\n\nwriteAttrFromMaybeStringProperty :: GObjectClass gobj => String -> WriteAttr gobj (Maybe String)\nwriteAttrFromMaybeStringProperty propName =\n writeAttr (objectSetPropertyMaybeString propName)\n\nnewAttrFromMaybeStringProperty :: GObjectClass gobj => String -> Attr gobj (Maybe String)\nnewAttrFromMaybeStringProperty propName =\n newAttr (objectGetPropertyMaybeString propName) (objectSetPropertyMaybeString propName)\n\nnewAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> String -> GType -> Attr gobj boxed\nnewAttrFromBoxedOpaqueProperty peek with propName gtype =\n newAttr (objectGetPropertyBoxedOpaque peek gtype propName) (objectSetPropertyBoxedOpaque with gtype propName)\n\nwriteAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> String -> GType -> WriteAttr gobj boxed\nwriteAttrFromBoxedOpaqueProperty with propName gtype =\n writeAttr (objectSetPropertyBoxedOpaque with gtype propName)\n\nnewAttrFromBoxedStorableProperty :: (GObjectClass gobj, Storable boxed) => String -> GType -> Attr gobj boxed\nnewAttrFromBoxedStorableProperty propName gtype =\n newAttr (objectGetPropertyBoxedStorable gtype propName) (objectSetPropertyBoxedStorable gtype propName)\n\nnewAttrFromObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj gobj' gobj''\nnewAttrFromObjectProperty propName gtype =\n newAttr (objectGetPropertyGObject gtype propName) (objectSetPropertyGObject gtype propName)\n\nwriteAttrFromObjectProperty :: (GObjectClass gobj, GObjectClass gobj') => String -> GType -> WriteAttr gobj gobj'\nwriteAttrFromObjectProperty propName gtype =\n writeAttr (objectSetPropertyGObject gtype propName)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"30f45b88a17377a6216da8e27b44ac2eec43596e","subject":"Remove Gtk.Signals from GtkInternals.chs","message":"Remove Gtk.Signals from GtkInternals.chs","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/GtkInternals.chs","new_file":"gtk\/Graphics\/UI\/GtkInternals.chs","new_contents":"{-# OPTIONS_HADDOCK hide #-}\n-- -*-haskell-*-\n-- Internal functions for the GIMP Toolkit (GTK) Binding for Haskell\n--\n-- Author : Axel Simon\n--\n-- Copyright (C) 2010 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- #hide\n\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- This file contains functions that are needed by other library wrappers that build\n-- on Gtk2Hs. An application should not need this function nor include this file.\n--\nmodule Graphics.UI.GtkInternals (\n module Graphics.UI.Gtk.Types,\n module Graphics.UI.Gtk.General.DNDTypes,\n module Graphics.UI.Gtk.Multiline.Types,\n ) where\n\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.General.DNDTypes#} (mkTargetList)\n{#import Graphics.UI.Gtk.Multiline.Types#} \n","old_contents":"{-# OPTIONS_HADDOCK hide #-}\n-- -*-haskell-*-\n-- Internal functions for the GIMP Toolkit (GTK) Binding for Haskell\n--\n-- Author : Axel Simon\n--\n-- Copyright (C) 2010 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- #hide\n\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- This file contains functions that are needed by other library wrappers that build\n-- on Gtk2Hs. An application should not need this function nor include this file.\n--\nmodule Graphics.UI.GtkInternals (\n module Graphics.UI.Gtk.Types,\n module Graphics.UI.Gtk.General.DNDTypes,\n module Graphics.UI.Gtk.Multiline.Types,\n module Graphics.UI.Gtk.Signals,\n ) where\n\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.General.DNDTypes#} (mkTargetList)\n{#import Graphics.UI.Gtk.Multiline.Types#} \n{#import Graphics.UI.Gtk.Signals#}","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"049a9ad7b6d2676cd7dd5f86550312f3a779981e","subject":"Remove Gtk.Signals from GtkInternals.chs","message":"Remove Gtk.Signals from GtkInternals.chs\n","repos":"gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"gtk\/Graphics\/UI\/GtkInternals.chs","new_file":"gtk\/Graphics\/UI\/GtkInternals.chs","new_contents":"{-# OPTIONS_HADDOCK hide #-}\n-- -*-haskell-*-\n-- Internal functions for the GIMP Toolkit (GTK) Binding for Haskell\n--\n-- Author : Axel Simon\n--\n-- Copyright (C) 2010 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- #hide\n\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- This file contains functions that are needed by other library wrappers that build\n-- on Gtk2Hs. An application should not need this function nor include this file.\n--\nmodule Graphics.UI.GtkInternals (\n module Graphics.UI.Gtk.Types,\n module Graphics.UI.Gtk.General.DNDTypes,\n module Graphics.UI.Gtk.Multiline.Types,\n ) where\n\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.General.DNDTypes#} (mkTargetList)\n{#import Graphics.UI.Gtk.Multiline.Types#} \n","old_contents":"{-# OPTIONS_HADDOCK hide #-}\n-- -*-haskell-*-\n-- Internal functions for the GIMP Toolkit (GTK) Binding for Haskell\n--\n-- Author : Axel Simon\n--\n-- Copyright (C) 2010 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- #hide\n\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- This file contains functions that are needed by other library wrappers that build\n-- on Gtk2Hs. An application should not need this function nor include this file.\n--\nmodule Graphics.UI.GtkInternals (\n module Graphics.UI.Gtk.Types,\n module Graphics.UI.Gtk.General.DNDTypes,\n module Graphics.UI.Gtk.Multiline.Types,\n module Graphics.UI.Gtk.Signals,\n ) where\n\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.General.DNDTypes#} (mkTargetList)\n{#import Graphics.UI.Gtk.Multiline.Types#} \n{#import Graphics.UI.Gtk.Signals#}","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"45fdade14f8d7fa8c2a6f794235835a96c47ab71","subject":"Make the setting of handlers more efficient in IO.parse","message":"Make the setting of handlers more efficient in IO.parse\n\nIgnore-this: d1cf0752eb1ca9e028ee6253c6163c5d\n\ndarcs-hash:20090306112543-ed7c9-8795c33e97ce02a620f50e3c40ebb97007e737b0.gz\n","repos":"the-real-blackh\/hexpat,the-real-blackh\/hexpat,the-real-blackh\/hexpat","old_file":"Text\/XML\/Expat\/IO.chs","new_file":"Text\/XML\/Expat\/IO.chs","new_contents":"-- hexpat, a Haskell wrapper for expat\n-- Copyright (C) 2008 Evan Martin \n\n-- |This module wraps the Expat API directly with IO operations\n-- everywhere. Basic usage is:\n--\n-- (1) Make a new parser: 'newParser'.\n--\n-- (2) Set up callbacks on the parser: 'setStartElementHandler', etc.\n--\n-- (3) Feed data into the parser: 'parse' or 'parseChunk'.\n\nmodule Text.XML.Expat.IO (\n -- ** Parser Setup\n Parser, newParser,\n\n -- ** Parsing\n parse, Encoding(..),\n\n -- ** Parser Callbacks\n StartElementHandler, EndElementHandler, CharacterDataHandler,\n setStartElementHandler, setEndElementHandler, setCharacterDataHandler,\n\n -- ** Lower-level Parsing Interface\n parseChunk,\n\n -- ** Helpers\n encodingToString\n) where\n\nimport Control.Exception (bracket)\nimport C2HS\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Lazy as BSL\nimport qualified Data.ByteString.Internal as BSI\nimport Data.IORef\n\n#include \n\n-- Expat functions start with \"XML\", but C2HS appears to ignore our \"as\"\n-- definitions if they only differ from the symbol in case. So we write out\n-- XML_* in most cases anyway... :(\n{#context lib = \"expat\" prefix = \"XML\"#}\n\n-- |Opaque parser type.\ntype ParserPtr = Ptr ()\ndata Parser = Parser\n (ForeignPtr ())\n (IORef CStartElementHandler) \n (IORef CEndElementHandler) \n (IORef CCharacterDataHandler) \n\nwithParser :: Parser -> (ParserPtr -> IO a) -> IO a\nwithParser (Parser fp _ _ _) = withForeignPtr fp\n\n-- |Encoding types available for the document encoding.\ndata Encoding = ASCII | UTF8 | UTF16 | ISO88591\nencodingToString :: Encoding -> String\nencodingToString ASCII = \"US-ASCII\"\nencodingToString UTF8 = \"UTF-8\"\nencodingToString UTF16 = \"UTF-16\"\nencodingToString ISO88591 = \"ISO-8859-1\"\n\nwithOptEncoding :: Maybe Encoding -> (CString -> IO a) -> IO a\nwithOptEncoding Nothing f = f nullPtr\nwithOptEncoding (Just enc) f = withCString (encodingToString enc) f\n\n{#fun unsafe XML_ParserCreate as parserCreate\n {withOptEncoding* `Maybe Encoding'} -> `ParserPtr' id#}\nforeign import ccall \"&XML_ParserFree\" parserFree :: FunPtr (ParserPtr -> IO ())\n\n-- |Create a 'Parser'. The encoding parameter, if provided, overrides the\n-- document's encoding declaration.\nnewParser :: Maybe Encoding -> IO Parser\nnewParser enc = do\n ptr <- parserCreate enc\n fptr <- newForeignPtr parserFree ptr\n nullStartH <- newIORef nullCStartElementHandler\n nullEndH <- newIORef nullCEndElementHandler\n nullCharH <- newIORef nullCCharacterDataHandler\n return $ Parser fptr nullStartH nullEndH nullCharH\n\n-- ByteString.useAsCStringLen is almost what we need, but C2HS wants a CInt\n-- instead of an Int.\nwithBStringLen :: BS.ByteString -> ((CString, CInt) -> IO a) -> IO a\nwithBStringLen bs f = do\n BS.useAsCStringLen bs $ \\(str, len) -> f (str, fromIntegral len)\n\nunStatus :: CInt -> Bool\nunStatus 0 = False\nunStatus 1 = True\n-- |@parseChunk data False@ feeds \/strict\/ ByteString data into a\n-- 'Parser'. The end of the data is indicated by passing @True@ for the\n-- final parameter. @parse@ returns @False@ on a parse error.\nparseChunk :: Parser\n -> BS.ByteString\n -> Bool\n -> IO Bool\nparseChunk parser xml final = do\n withHandlers parser $ doParseChunk parser xml final\n\nwithHandlers :: Parser -> IO a -> IO a\nwithHandlers parser@(Parser fp startRef endRef charRef) code = do\n bracket\n (do\n cStartH <- mkCStartElementHandler =<< readIORef startRef\n cEndH <- mkCEndElementHandler =<< readIORef endRef\n cCharH <- mkCCharacterDataHandler =<< readIORef charRef\n withParser parser $ \\p -> do\n {#call unsafe XML_SetStartElementHandler as ^#} p cStartH\n {#call unsafe XML_SetEndElementHandler as ^#} p cEndH\n {#call unsafe XML_SetCharacterDataHandler as ^#} p cCharH\n return (cStartH, cEndH, cCharH))\n (\\(cStartH, cEndH, cCharH) -> do\n freeHaskellFunPtr cStartH\n freeHaskellFunPtr cEndH\n freeHaskellFunPtr cCharH)\n (\\_ -> code)\n\n{#fun XML_Parse as doParseChunk\n {withParser* `Parser', withBStringLen* `BS.ByteString' &, `Bool'}\n -> `Bool' unStatus#}\n\n-- |@parse data@ feeds \/lazy\/ bytestring data into a parser and returns\n-- @True@ if there was no parse error.\nparse :: Parser -> BSL.ByteString -> IO Bool\nparse parser bs = withHandlers parser $ feedChunk (BSL.toChunks bs)\n where\n feedChunk [] = return True\n feedChunk [chunk] = parseChunk parser chunk True\n feedChunk (c:cs) = do ok <- doParseChunk parser c False\n if ok then feedChunk cs\n else return False\n\n-- |The type of the \\\"element started\\\" callback. The first parameter is\n-- the element name; the second are the (attribute, value) pairs.\ntype StartElementHandler = BS.ByteString -> [(BS.ByteString,BS.ByteString)] -> IO ()\n-- |The type of the \\\"element ended\\\" callback. The parameter is\n-- the element name.\ntype EndElementHandler = BS.ByteString -> IO ()\n-- |The type of the \\\"character data\\\" callback. The parameter is\n-- the character data processed. This callback may be called more than once\n-- while processing a single conceptual block of text.\ntype CharacterDataHandler = BS.ByteString -> IO ()\n\ntype CStartElementHandler = Ptr () -> CString -> Ptr CString -> IO ()\nnullCStartElementHandler _ _ _ = return ()\n\nforeign import ccall \"wrapper\"\n mkCStartElementHandler :: CStartElementHandler\n -> IO (FunPtr CStartElementHandler)\nwrapStartElementHandler :: StartElementHandler -> CStartElementHandler\nwrapStartElementHandler handler = h where\n h ptr cname cattrs = do\n name <- peekByteString cname\n cattrlist <- peekArray0 nullPtr cattrs\n attrlist <- mapM peekByteString cattrlist\n handler name (pairwise attrlist)\n-- |Attach a StartElementHandler to a Parser.\nsetStartElementHandler :: Parser -> StartElementHandler -> IO ()\nsetStartElementHandler parser@(Parser _ startRef _ _) handler = do\n withParser parser $ \\p -> do\n writeIORef startRef $ wrapStartElementHandler handler\n\ntype CEndElementHandler = Ptr () -> CString -> IO ()\nnullCEndElementHandler _ _ = return ()\n\nforeign import ccall \"wrapper\"\n mkCEndElementHandler :: CEndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler :: EndElementHandler -> CEndElementHandler\nwrapEndElementHandler handler = h where\n h ptr cname = do\n name <- peekByteString cname\n handler name\n\n-- |Attach an EndElementHandler to a Parser.\nsetEndElementHandler :: Parser -> EndElementHandler -> IO ()\nsetEndElementHandler parser@(Parser _ _ endRef _) handler = do\n withParser parser $ \\p -> do\n writeIORef endRef $ wrapEndElementHandler handler\n\ntype CCharacterDataHandler = Ptr () -> CString -> CInt -> IO ()\nnullCCharacterDataHandler _ _ _ = return ()\n\nforeign import ccall \"wrapper\"\n mkCCharacterDataHandler :: CCharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler :: CharacterDataHandler -> CCharacterDataHandler\nwrapCharacterDataHandler handler = h where\n h ptr cdata len = do\n data_ <- peekByteStringLen (cdata, fromIntegral len)\n handler data_\n\n-- |Attach an CharacterDataHandler to a Parser.\nsetCharacterDataHandler :: Parser -> CharacterDataHandler -> IO ()\nsetCharacterDataHandler parser@(Parser _ _ _ charRef) handler = do\n withParser parser $ \\p -> do\n writeIORef charRef $ wrapCharacterDataHandler handler\n\npairwise (x1:x2:xs) = (x1,x2) : pairwise xs\npairwise [] = []\n\npeekByteString :: CString -> IO BS.ByteString\n{-# INLINE peekByteString #-}\npeekByteString cstr = do\n len <- BSI.c_strlen cstr\n peekByteStringLen (castPtr cstr, len)\n\npeekByteStringLen :: (CString, CSize) -> IO BS.ByteString \n{-# INLINE peekByteStringLen #-}\npeekByteStringLen (cstr, len) =\n BSI.create (fromIntegral len) $ \\ptr ->\n BSI.memcpy ptr (castPtr cstr) len\n\n","old_contents":"-- hexpat, a Haskell wrapper for expat\n-- Copyright (C) 2008 Evan Martin \n\n-- |This module wraps the Expat API directly with IO operations\n-- everywhere. Basic usage is:\n--\n-- (1) Make a new parser: 'newParser'.\n--\n-- (2) Set up callbacks on the parser: 'setStartElementHandler', etc.\n--\n-- (3) Feed data into the parser: 'parse' or 'parseChunk'.\n\nmodule Text.XML.Expat.IO (\n -- ** Parser Setup\n Parser, newParser,\n\n -- ** Parsing\n parse, Encoding(..),\n\n -- ** Parser Callbacks\n StartElementHandler, EndElementHandler, CharacterDataHandler,\n setStartElementHandler, setEndElementHandler, setCharacterDataHandler,\n\n -- ** Lower-level Parsing Interface\n parseChunk,\n\n -- ** Helpers\n encodingToString\n) where\n\nimport Control.Exception (bracket)\nimport C2HS\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Lazy as BSL\nimport qualified Data.ByteString.Internal as BSI\nimport Data.IORef\n\n#include \n\n-- Expat functions start with \"XML\", but C2HS appears to ignore our \"as\"\n-- definitions if they only differ from the symbol in case. So we write out\n-- XML_* in most cases anyway... :(\n{#context lib = \"expat\" prefix = \"XML\"#}\n\n-- |Opaque parser type.\ntype ParserPtr = Ptr ()\ndata Parser = Parser\n (ForeignPtr ())\n (IORef CStartElementHandler) \n (IORef CEndElementHandler) \n (IORef CCharacterDataHandler) \n\nwithParser :: Parser -> (ParserPtr -> IO a) -> IO a\nwithParser (Parser fp _ _ _) = withForeignPtr fp\n\n-- |Encoding types available for the document encoding.\ndata Encoding = ASCII | UTF8 | UTF16 | ISO88591\nencodingToString :: Encoding -> String\nencodingToString ASCII = \"US-ASCII\"\nencodingToString UTF8 = \"UTF-8\"\nencodingToString UTF16 = \"UTF-16\"\nencodingToString ISO88591 = \"ISO-8859-1\"\n\nwithOptEncoding :: Maybe Encoding -> (CString -> IO a) -> IO a\nwithOptEncoding Nothing f = f nullPtr\nwithOptEncoding (Just enc) f = withCString (encodingToString enc) f\n\n{#fun unsafe XML_ParserCreate as parserCreate\n {withOptEncoding* `Maybe Encoding'} -> `ParserPtr' id#}\nforeign import ccall \"&XML_ParserFree\" parserFree :: FunPtr (ParserPtr -> IO ())\n\n-- |Create a 'Parser'. The encoding parameter, if provided, overrides the\n-- document's encoding declaration.\nnewParser :: Maybe Encoding -> IO Parser\nnewParser enc = do\n ptr <- parserCreate enc\n fptr <- newForeignPtr parserFree ptr\n nullStartH <- newIORef nullCStartElementHandler\n nullEndH <- newIORef nullCEndElementHandler\n nullCharH <- newIORef nullCCharacterDataHandler\n return $ Parser fptr nullStartH nullEndH nullCharH\n\n-- ByteString.useAsCStringLen is almost what we need, but C2HS wants a CInt\n-- instead of an Int.\nwithBStringLen :: BS.ByteString -> ((CString, CInt) -> IO a) -> IO a\nwithBStringLen bs f = do\n BS.useAsCStringLen bs $ \\(str, len) -> f (str, fromIntegral len)\n\nunStatus :: CInt -> Bool\nunStatus 0 = False\nunStatus 1 = True\n-- |@parseChunk data False@ feeds \/strict\/ ByteString data into a\n-- 'Parser'. The end of the data is indicated by passing @True@ for the\n-- final parameter. @parse@ returns @False@ on a parse error.\nparseChunk :: Parser\n -> BS.ByteString\n -> Bool\n -> IO Bool\nparseChunk parser@(Parser fp startRef endRef charRef) xml final = do\n bracket\n (do\n cStartH <- mkCStartElementHandler =<< readIORef startRef\n cEndH <- mkCEndElementHandler =<< readIORef endRef\n cCharH <- mkCCharacterDataHandler =<< readIORef charRef\n withParser parser $ \\p -> do\n {#call unsafe XML_SetStartElementHandler as ^#} p cStartH\n {#call unsafe XML_SetEndElementHandler as ^#} p cEndH\n {#call unsafe XML_SetCharacterDataHandler as ^#} p cCharH\n return (cStartH, cEndH, cCharH))\n (\\(cStartH, cEndH, cCharH) -> do\n freeHaskellFunPtr cStartH\n freeHaskellFunPtr cEndH\n freeHaskellFunPtr cCharH)\n (\\_ -> doParseChunk parser xml final)\n\n{#fun XML_Parse as doParseChunk\n {withParser* `Parser', withBStringLen* `BS.ByteString' &, `Bool'}\n -> `Bool' unStatus#}\n\n-- |@parse data@ feeds \/lazy\/ bytestring data into a parser and returns\n-- @True@ if there was no parse error.\nparse :: Parser -> BSL.ByteString -> IO Bool\nparse parser bs = feedChunk (BSL.toChunks bs) where\n feedChunk [] = return True\n feedChunk [chunk] = parseChunk parser chunk True\n feedChunk (c:cs) = do ok <- parseChunk parser c False\n if ok then feedChunk cs\n else return False\n\n-- |The type of the \\\"element started\\\" callback. The first parameter is\n-- the element name; the second are the (attribute, value) pairs.\ntype StartElementHandler = BS.ByteString -> [(BS.ByteString,BS.ByteString)] -> IO ()\n-- |The type of the \\\"element ended\\\" callback. The parameter is\n-- the element name.\ntype EndElementHandler = BS.ByteString -> IO ()\n-- |The type of the \\\"character data\\\" callback. The parameter is\n-- the character data processed. This callback may be called more than once\n-- while processing a single conceptual block of text.\ntype CharacterDataHandler = BS.ByteString -> IO ()\n\ntype CStartElementHandler = Ptr () -> CString -> Ptr CString -> IO ()\nnullCStartElementHandler _ _ _ = return ()\n\nforeign import ccall \"wrapper\"\n mkCStartElementHandler :: CStartElementHandler\n -> IO (FunPtr CStartElementHandler)\nwrapStartElementHandler :: StartElementHandler -> CStartElementHandler\nwrapStartElementHandler handler = h where\n h ptr cname cattrs = do\n name <- peekByteString cname\n cattrlist <- peekArray0 nullPtr cattrs\n attrlist <- mapM peekByteString cattrlist\n handler name (pairwise attrlist)\n-- |Attach a StartElementHandler to a Parser.\nsetStartElementHandler :: Parser -> StartElementHandler -> IO ()\nsetStartElementHandler parser@(Parser _ startRef _ _) handler = do\n withParser parser $ \\p -> do\n writeIORef startRef $ wrapStartElementHandler handler\n\ntype CEndElementHandler = Ptr () -> CString -> IO ()\nnullCEndElementHandler _ _ = return ()\n\nforeign import ccall \"wrapper\"\n mkCEndElementHandler :: CEndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler :: EndElementHandler -> CEndElementHandler\nwrapEndElementHandler handler = h where\n h ptr cname = do\n name <- peekByteString cname\n handler name\n\n-- |Attach an EndElementHandler to a Parser.\nsetEndElementHandler :: Parser -> EndElementHandler -> IO ()\nsetEndElementHandler parser@(Parser _ _ endRef _) handler = do\n withParser parser $ \\p -> do\n writeIORef endRef $ wrapEndElementHandler handler\n\ntype CCharacterDataHandler = Ptr () -> CString -> CInt -> IO ()\nnullCCharacterDataHandler _ _ _ = return ()\n\nforeign import ccall \"wrapper\"\n mkCCharacterDataHandler :: CCharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler :: CharacterDataHandler -> CCharacterDataHandler\nwrapCharacterDataHandler handler = h where\n h ptr cdata len = do\n data_ <- peekByteStringLen (cdata, fromIntegral len)\n handler data_\n\n-- |Attach an CharacterDataHandler to a Parser.\nsetCharacterDataHandler :: Parser -> CharacterDataHandler -> IO ()\nsetCharacterDataHandler parser@(Parser _ _ _ charRef) handler = do\n withParser parser $ \\p -> do\n writeIORef charRef $ wrapCharacterDataHandler handler\n\npairwise (x1:x2:xs) = (x1,x2) : pairwise xs\npairwise [] = []\n\npeekByteString :: CString -> IO BS.ByteString\n{-# INLINE peekByteString #-}\npeekByteString cstr = do\n len <- BSI.c_strlen cstr\n peekByteStringLen (castPtr cstr, len)\n\npeekByteStringLen :: (CString, CSize) -> IO BS.ByteString \n{-# INLINE peekByteStringLen #-}\npeekByteStringLen (cstr, len) =\n BSI.create (fromIntegral len) $ \\ptr ->\n BSI.memcpy ptr (castPtr cstr) len\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"eace3210cf91c5591f020aa0a696c310bba3322a","subject":"export functions","message":"export functions\n","repos":"adamwalker\/haskell_cudd,maweki\/haskell_cudd","old_file":"CuddExplicitDeref.chs","new_file":"CuddExplicitDeref.chs","new_contents":"module CuddExplicitDeref (\n bzero,\n bone,\n bvar,\n band,\n bor,\n bnand,\n bnor,\n bxor,\n bxnor,\n bnot,\n bite,\n bexists,\n bforall,\n deref,\n setVarMap,\n mapVars,\n DDNode,\n STDdManager,\n leq,\n CuddExplicitDeref.shift,\n ref,\n largestCube,\n makePrime,\n supportIndices,\n indicesToCube,\n computeCube,\n nodesToCube,\n readSize,\n satCube,\n compose,\n andAbstract,\n xorExistAbstract,\n leqUnless,\n equivDC,\n xeqy,\n debugCheck,\n checkKeys\n ) where\n\nimport Foreign hiding (void)\nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Control.Monad.ST.Lazy\nimport Control.Monad\n\nimport CuddC\nimport CuddInternal hiding (deref)\n\nnewtype DDNode s u = DDNode {unDDNode :: Ptr CDdNode} deriving (Ord, Eq, Show)\n\narg0 :: (Ptr CDdManager -> IO (Ptr CDdNode)) -> STDdManager s u -> ST s (DDNode s u)\narg0 f (STDdManager m) = liftM DDNode $ unsafeIOToST $ f m\n\narg1 :: (Ptr CDdManager -> Ptr CDdNode -> IO (Ptr CDdNode)) -> STDdManager s u -> DDNode s u -> ST s (DDNode s u)\narg1 f (STDdManager m) (DDNode x) = liftM DDNode $ unsafeIOToST $ f m x\n\narg2 :: (Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)) -> STDdManager s u -> DDNode s u -> DDNode s u -> ST s (DDNode s u)\narg2 f (STDdManager m) (DDNode x) (DDNode y) = liftM DDNode $ unsafeIOToST $ f m x y\n \narg3 :: (Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)) -> STDdManager s u -> DDNode s u -> DDNode s u -> DDNode s u -> ST s (DDNode s u)\narg3 f (STDdManager m) (DDNode x) (DDNode y) (DDNode z) = liftM DDNode $ unsafeIOToST $ f m x y z\n\nbzero (STDdManager m) = DDNode $ unsafePerformIO $ c_cuddReadLogicZero m\nbone (STDdManager m) = DDNode $ unsafePerformIO $ c_cuddReadOne m\n\nband = arg2 c_cuddBddAnd\nbor = arg2 c_cuddBddOr\nbnand = arg2 c_cuddBddNand\nbnor = arg2 c_cuddBddNor\nbxor = arg2 c_cuddBddXor\nbxnor = arg2 c_cuddBddXnor\nbite = arg3 c_cuddBddIte\nbexists = arg2 c_cuddBddExistAbstract\nbforall = arg2 c_cuddBddUnivAbstract\n\nandAbstract = arg3 c_cuddBddAndAbstract\nxorExistAbstract = arg3 c_cuddBddXorExistAbstract\n\nbnot (DDNode x) = DDNode $ unsafePerformIO $ c_cuddNot x\nbvar (STDdManager m) i = liftM DDNode $ unsafeIOToST $ c_cuddBddIthVar m (fromIntegral i)\n\nderef :: STDdManager s u -> DDNode s u -> ST s ()\nderef (STDdManager m) (DDNode x) = unsafeIOToST $ c_cuddIterDerefBdd m x\n\nsetVarMap :: STDdManager s u -> [DDNode s u] -> [DDNode s u] -> ST s ()\nsetVarMap (STDdManager m) xs ys = unsafeIOToST $ \n withArrayLen (map unDDNode xs) $ \\xl xp -> \n withArrayLen (map unDDNode ys) $ \\yl yp -> do\n when (xl \/= yl) (error \"setVarMap: lengths not equal\")\n void $ c_cuddSetVarMap m xp yp (fromIntegral xl)\n\nmapVars :: STDdManager s u -> DDNode s u -> ST s (DDNode s u)\nmapVars (STDdManager m) (DDNode x) = liftM DDNode $ unsafeIOToST $ c_cuddBddVarMap m x\n\nleq :: STDdManager s u -> DDNode s u -> DDNode s u -> ST s Bool\nleq (STDdManager m) (DDNode x) (DDNode y) = liftM (==1) $ unsafeIOToST $ c_cuddBddLeq m x y\n\nshift :: STDdManager s u -> [DDNode s u] -> [DDNode s u] -> DDNode s u -> ST s (DDNode s u)\nshift (STDdManager m) nodesx nodesy (DDNode x) = unsafeIOToST $ \n withArrayLen (map unDDNode nodesx) $ \\lx xp -> \n withArrayLen (map unDDNode nodesy) $ \\ly yp -> do\n when (lx \/= ly) $ error \"CuddExplicitDeref: shift: lengths not equal\"\n res <- c_cuddBddSwapVariables m x xp yp (fromIntegral lx)\n return $ DDNode res\n\nref :: DDNode s u -> ST s ()\nref (DDNode x) = unsafeIOToST $ cuddRef x\n\nlargestCube :: STDdManager s u -> DDNode s u -> ST s (DDNode s u, Int)\nlargestCube (STDdManager m) (DDNode x) = unsafeIOToST $ \n alloca $ \\lp -> do\n res <- c_cuddLargestCube m x lp \n l <- peek lp\n return (DDNode res, fromIntegral l)\n\nmakePrime :: STDdManager s u -> DDNode s u -> DDNode s u -> ST s (DDNode s u)\nmakePrime = arg2 c_cuddBddMakePrime\n\nsupportIndices :: STDdManager s u -> DDNode s u -> ST s [Int]\nsupportIndices (STDdManager m) (DDNode x) = unsafeIOToST $\n alloca $ \\arrp -> do\n sz <- c_cuddSupportIndices m x arrp\n aaddr <- peek arrp\n res <- peekArray (fromIntegral sz) aaddr\n return $ map fromIntegral res\n\nindicesToCube :: STDdManager s u -> [Int] -> ST s (DDNode s u)\nindicesToCube (STDdManager m) indices = unsafeIOToST $\n withArrayLen (map fromIntegral indices) $ \\sz pt -> do\n res <- c_cuddIndicesToCube m pt (fromIntegral sz)\n return $ DDNode res\n\ncomputeCube :: STDdManager s u -> [DDNode s u] -> [Bool] -> ST s (DDNode s u)\ncomputeCube (STDdManager m) nodes phases = unsafeIOToST $ \n withArrayLen (map unDDNode nodes) $ \\szn ptn -> \n withArrayLen (map (fromIntegral . fromBool) phases) $ \\szp ptp -> do\n when (szn \/= szp) $ error \"computeCube: lists are different lengths\"\n res <- c_cuddBddComputeCube m ptn ptp (fromIntegral szn)\n return $ DDNode res\n\nnodesToCube :: STDdManager s u -> [DDNode s u] -> ST s (DDNode s u)\nnodesToCube (STDdManager m) nodes = unsafeIOToST $\n withArrayLen (map unDDNode nodes) $ \\sz pt -> do\n res <- c_cuddBddComputeCube m pt nullPtr (fromIntegral sz)\n return $ DDNode res\n\nreadSize :: STDdManager s u -> ST s Int\nreadSize (STDdManager m) = liftM fromIntegral $ unsafeIOToST $ c_cuddReadSize m\n\nsatCube :: STDdManager s u -> DDNode s u -> ST s [Int]\nsatCube ma@(STDdManager m) (DDNode x) = unsafeIOToST $ do\n size <- liftM fromIntegral $ c_cuddReadSize m\n allocaArray size $ \\resptr -> do\n c_cuddBddToCubeArray m x resptr\n res <- peekArray size resptr\n return $ map fromIntegral res\n\ncompose :: STDdManager s u -> DDNode s u -> DDNode s u -> Int -> ST s (DDNode s u)\ncompose (STDdManager m) (DDNode f) (DDNode g) v = liftM DDNode $ unsafeIOToST $ c_cuddBddCompose m f g (fromIntegral v)\n\narg3Bool :: (Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> Ptr CDdNode -> IO CInt) -> STDdManager s u -> DDNode s u -> DDNode s u -> DDNode s u -> ST s Bool\narg3Bool f (STDdManager m) (DDNode x) (DDNode y) (DDNode z) = liftM (==1) $ unsafeIOToST $ f m x y z\n\nleqUnless, equivDC :: STDdManager s u -> DDNode s u -> DDNode s u -> DDNode s u -> ST s Bool\nleqUnless = arg3Bool c_cuddBddLeqUnless\nequivDC = arg3Bool c_cuddEquivDC\n\nxeqy :: STDdManager s u -> [DDNode s u] -> [DDNode s u] -> ST s (DDNode s u)\nxeqy (STDdManager m) xs ys = unsafeIOToST $ \n withArrayLen (map unDDNode xs) $ \\xl xp -> \n withArrayLen (map unDDNode ys) $ \\yl yp -> do\n when (xl \/= yl) (error \"xeqy: lengths not equal\")\n res <- c_cuddXeqy m (fromIntegral xl) xp yp\n return $ DDNode res\n\ndebugCheck :: STDdManager s u -> ST s ()\ndebugCheck (STDdManager m) = unsafeIOToST $ c_cuddDebugCheck m\n\ncheckKeys :: STDdManager s u -> ST s ()\ncheckKeys (STDdManager m) = unsafeIOToST $ c_cuddCheckKeys m\n\n{-\nrefCount :: STDdManager s u -> STDdNode s u -> ST s (DdNode s u)\n\nunRefCount :: STDdManager s u -> DdNode s u -> ST s (STDdNode s u)\n-}\n","old_contents":"module CuddExplicitDeref (\n bzero,\n bone,\n bvar,\n band,\n bor,\n bnand,\n bnor,\n bxor,\n bxnor,\n bnot,\n bite,\n bexists,\n bforall,\n deref,\n setVarMap,\n mapVars,\n DDNode,\n STDdManager,\n leq,\n CuddExplicitDeref.shift,\n ref,\n largestCube,\n makePrime,\n supportIndices,\n indicesToCube,\n computeCube,\n nodesToCube,\n readSize,\n satCube,\n compose,\n andAbstract,\n xorExistAbstract,\n leqUnless,\n equivDC,\n xeqy\n ) where\n\nimport Foreign hiding (void)\nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Control.Monad.ST.Lazy\nimport Control.Monad\n\nimport CuddC\nimport CuddInternal hiding (deref)\n\nnewtype DDNode s u = DDNode {unDDNode :: Ptr CDdNode} deriving (Ord, Eq, Show)\n\narg0 :: (Ptr CDdManager -> IO (Ptr CDdNode)) -> STDdManager s u -> ST s (DDNode s u)\narg0 f (STDdManager m) = liftM DDNode $ unsafeIOToST $ f m\n\narg1 :: (Ptr CDdManager -> Ptr CDdNode -> IO (Ptr CDdNode)) -> STDdManager s u -> DDNode s u -> ST s (DDNode s u)\narg1 f (STDdManager m) (DDNode x) = liftM DDNode $ unsafeIOToST $ f m x\n\narg2 :: (Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)) -> STDdManager s u -> DDNode s u -> DDNode s u -> ST s (DDNode s u)\narg2 f (STDdManager m) (DDNode x) (DDNode y) = liftM DDNode $ unsafeIOToST $ f m x y\n \narg3 :: (Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> Ptr CDdNode -> IO (Ptr CDdNode)) -> STDdManager s u -> DDNode s u -> DDNode s u -> DDNode s u -> ST s (DDNode s u)\narg3 f (STDdManager m) (DDNode x) (DDNode y) (DDNode z) = liftM DDNode $ unsafeIOToST $ f m x y z\n\nbzero (STDdManager m) = DDNode $ unsafePerformIO $ c_cuddReadLogicZero m\nbone (STDdManager m) = DDNode $ unsafePerformIO $ c_cuddReadOne m\n\nband = arg2 c_cuddBddAnd\nbor = arg2 c_cuddBddOr\nbnand = arg2 c_cuddBddNand\nbnor = arg2 c_cuddBddNor\nbxor = arg2 c_cuddBddXor\nbxnor = arg2 c_cuddBddXnor\nbite = arg3 c_cuddBddIte\nbexists = arg2 c_cuddBddExistAbstract\nbforall = arg2 c_cuddBddUnivAbstract\n\nandAbstract = arg3 c_cuddBddAndAbstract\nxorExistAbstract = arg3 c_cuddBddXorExistAbstract\n\nbnot (DDNode x) = DDNode $ unsafePerformIO $ c_cuddNot x\nbvar (STDdManager m) i = liftM DDNode $ unsafeIOToST $ c_cuddBddIthVar m (fromIntegral i)\n\nderef :: STDdManager s u -> DDNode s u -> ST s ()\nderef (STDdManager m) (DDNode x) = unsafeIOToST $ c_cuddIterDerefBdd m x\n\nsetVarMap :: STDdManager s u -> [DDNode s u] -> [DDNode s u] -> ST s ()\nsetVarMap (STDdManager m) xs ys = unsafeIOToST $ \n withArrayLen (map unDDNode xs) $ \\xl xp -> \n withArrayLen (map unDDNode ys) $ \\yl yp -> do\n when (xl \/= yl) (error \"setVarMap: lengths not equal\")\n void $ c_cuddSetVarMap m xp yp (fromIntegral xl)\n\nmapVars :: STDdManager s u -> DDNode s u -> ST s (DDNode s u)\nmapVars (STDdManager m) (DDNode x) = liftM DDNode $ unsafeIOToST $ c_cuddBddVarMap m x\n\nleq :: STDdManager s u -> DDNode s u -> DDNode s u -> ST s Bool\nleq (STDdManager m) (DDNode x) (DDNode y) = liftM (==1) $ unsafeIOToST $ c_cuddBddLeq m x y\n\nshift :: STDdManager s u -> [DDNode s u] -> [DDNode s u] -> DDNode s u -> ST s (DDNode s u)\nshift (STDdManager m) nodesx nodesy (DDNode x) = unsafeIOToST $ \n withArrayLen (map unDDNode nodesx) $ \\lx xp -> \n withArrayLen (map unDDNode nodesy) $ \\ly yp -> do\n when (lx \/= ly) $ error \"CuddExplicitDeref: shift: lengths not equal\"\n res <- c_cuddBddSwapVariables m x xp yp (fromIntegral lx)\n return $ DDNode res\n\nref :: DDNode s u -> ST s ()\nref (DDNode x) = unsafeIOToST $ cuddRef x\n\nlargestCube :: STDdManager s u -> DDNode s u -> ST s (DDNode s u, Int)\nlargestCube (STDdManager m) (DDNode x) = unsafeIOToST $ \n alloca $ \\lp -> do\n res <- c_cuddLargestCube m x lp \n l <- peek lp\n return (DDNode res, fromIntegral l)\n\nmakePrime :: STDdManager s u -> DDNode s u -> DDNode s u -> ST s (DDNode s u)\nmakePrime = arg2 c_cuddBddMakePrime\n\nsupportIndices :: STDdManager s u -> DDNode s u -> ST s [Int]\nsupportIndices (STDdManager m) (DDNode x) = unsafeIOToST $\n alloca $ \\arrp -> do\n sz <- c_cuddSupportIndices m x arrp\n aaddr <- peek arrp\n res <- peekArray (fromIntegral sz) aaddr\n return $ map fromIntegral res\n\nindicesToCube :: STDdManager s u -> [Int] -> ST s (DDNode s u)\nindicesToCube (STDdManager m) indices = unsafeIOToST $\n withArrayLen (map fromIntegral indices) $ \\sz pt -> do\n res <- c_cuddIndicesToCube m pt (fromIntegral sz)\n return $ DDNode res\n\ncomputeCube :: STDdManager s u -> [DDNode s u] -> [Bool] -> ST s (DDNode s u)\ncomputeCube (STDdManager m) nodes phases = unsafeIOToST $ \n withArrayLen (map unDDNode nodes) $ \\szn ptn -> \n withArrayLen (map (fromIntegral . fromBool) phases) $ \\szp ptp -> do\n when (szn \/= szp) $ error \"computeCube: lists are different lengths\"\n res <- c_cuddBddComputeCube m ptn ptp (fromIntegral szn)\n return $ DDNode res\n\nnodesToCube :: STDdManager s u -> [DDNode s u] -> ST s (DDNode s u)\nnodesToCube (STDdManager m) nodes = unsafeIOToST $\n withArrayLen (map unDDNode nodes) $ \\sz pt -> do\n res <- c_cuddBddComputeCube m pt nullPtr (fromIntegral sz)\n return $ DDNode res\n\nreadSize :: STDdManager s u -> ST s Int\nreadSize (STDdManager m) = liftM fromIntegral $ unsafeIOToST $ c_cuddReadSize m\n\nsatCube :: STDdManager s u -> DDNode s u -> ST s [Int]\nsatCube ma@(STDdManager m) (DDNode x) = unsafeIOToST $ do\n size <- liftM fromIntegral $ c_cuddReadSize m\n allocaArray size $ \\resptr -> do\n c_cuddBddToCubeArray m x resptr\n res <- peekArray size resptr\n return $ map fromIntegral res\n\ncompose :: STDdManager s u -> DDNode s u -> DDNode s u -> Int -> ST s (DDNode s u)\ncompose (STDdManager m) (DDNode f) (DDNode g) v = liftM DDNode $ unsafeIOToST $ c_cuddBddCompose m f g (fromIntegral v)\n\narg3Bool :: (Ptr CDdManager -> Ptr CDdNode -> Ptr CDdNode -> Ptr CDdNode -> IO CInt) -> STDdManager s u -> DDNode s u -> DDNode s u -> DDNode s u -> ST s Bool\narg3Bool f (STDdManager m) (DDNode x) (DDNode y) (DDNode z) = liftM (==1) $ unsafeIOToST $ f m x y z\n\nleqUnless, equivDC :: STDdManager s u -> DDNode s u -> DDNode s u -> DDNode s u -> ST s Bool\nleqUnless = arg3Bool c_cuddBddLeqUnless\nequivDC = arg3Bool c_cuddEquivDC\n\nxeqy :: STDdManager s u -> [DDNode s u] -> [DDNode s u] -> ST s (DDNode s u)\nxeqy (STDdManager m) xs ys = unsafeIOToST $ \n withArrayLen (map unDDNode xs) $ \\xl xp -> \n withArrayLen (map unDDNode ys) $ \\yl yp -> do\n when (xl \/= yl) (error \"xeqy: lengths not equal\")\n res <- c_cuddXeqy m (fromIntegral xl) xp yp\n return $ DDNode res\n\ndebugCheck :: STDdManager s u -> ST s ()\ndebugCheck (STDdManager m) = unsafeIOToST $ c_cuddDebugCheck m\n\ncheckKeys :: STDdManager s u -> ST s ()\ncheckKeys (STDdManager m) = unsafeIOToST $ c_cuddCheckKeys m\n\n{-\nrefCount :: STDdManager s u -> STDdNode s u -> ST s (DdNode s u)\n\nunRefCount :: STDdManager s u -> DdNode s u -> ST s (STDdNode s u)\n-}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"2fd76d225bd9480ccb66cd54375b1a927ab1bf99","subject":"Make the setting of handlers more efficient in IO.parse","message":"Make the setting of handlers more efficient in IO.parse\n\nIgnore-this: d1cf0752eb1ca9e028ee6253c6163c5d\n\ndarcs-hash:20090306112543-ed7c9-8795c33e97ce02a620f50e3c40ebb97007e737b0.gz\n","repos":"sol\/hexpat,sol\/hexpat","old_file":"Text\/XML\/Expat\/IO.chs","new_file":"Text\/XML\/Expat\/IO.chs","new_contents":"-- hexpat, a Haskell wrapper for expat\n-- Copyright (C) 2008 Evan Martin \n\n-- |This module wraps the Expat API directly with IO operations\n-- everywhere. Basic usage is:\n--\n-- (1) Make a new parser: 'newParser'.\n--\n-- (2) Set up callbacks on the parser: 'setStartElementHandler', etc.\n--\n-- (3) Feed data into the parser: 'parse' or 'parseChunk'.\n\nmodule Text.XML.Expat.IO (\n -- ** Parser Setup\n Parser, newParser,\n\n -- ** Parsing\n parse, Encoding(..),\n\n -- ** Parser Callbacks\n StartElementHandler, EndElementHandler, CharacterDataHandler,\n setStartElementHandler, setEndElementHandler, setCharacterDataHandler,\n\n -- ** Lower-level Parsing Interface\n parseChunk,\n\n -- ** Helpers\n encodingToString\n) where\n\nimport Control.Exception (bracket)\nimport C2HS\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Lazy as BSL\nimport qualified Data.ByteString.Internal as BSI\nimport Data.IORef\n\n#include \n\n-- Expat functions start with \"XML\", but C2HS appears to ignore our \"as\"\n-- definitions if they only differ from the symbol in case. So we write out\n-- XML_* in most cases anyway... :(\n{#context lib = \"expat\" prefix = \"XML\"#}\n\n-- |Opaque parser type.\ntype ParserPtr = Ptr ()\ndata Parser = Parser\n (ForeignPtr ())\n (IORef CStartElementHandler) \n (IORef CEndElementHandler) \n (IORef CCharacterDataHandler) \n\nwithParser :: Parser -> (ParserPtr -> IO a) -> IO a\nwithParser (Parser fp _ _ _) = withForeignPtr fp\n\n-- |Encoding types available for the document encoding.\ndata Encoding = ASCII | UTF8 | UTF16 | ISO88591\nencodingToString :: Encoding -> String\nencodingToString ASCII = \"US-ASCII\"\nencodingToString UTF8 = \"UTF-8\"\nencodingToString UTF16 = \"UTF-16\"\nencodingToString ISO88591 = \"ISO-8859-1\"\n\nwithOptEncoding :: Maybe Encoding -> (CString -> IO a) -> IO a\nwithOptEncoding Nothing f = f nullPtr\nwithOptEncoding (Just enc) f = withCString (encodingToString enc) f\n\n{#fun unsafe XML_ParserCreate as parserCreate\n {withOptEncoding* `Maybe Encoding'} -> `ParserPtr' id#}\nforeign import ccall \"&XML_ParserFree\" parserFree :: FunPtr (ParserPtr -> IO ())\n\n-- |Create a 'Parser'. The encoding parameter, if provided, overrides the\n-- document's encoding declaration.\nnewParser :: Maybe Encoding -> IO Parser\nnewParser enc = do\n ptr <- parserCreate enc\n fptr <- newForeignPtr parserFree ptr\n nullStartH <- newIORef nullCStartElementHandler\n nullEndH <- newIORef nullCEndElementHandler\n nullCharH <- newIORef nullCCharacterDataHandler\n return $ Parser fptr nullStartH nullEndH nullCharH\n\n-- ByteString.useAsCStringLen is almost what we need, but C2HS wants a CInt\n-- instead of an Int.\nwithBStringLen :: BS.ByteString -> ((CString, CInt) -> IO a) -> IO a\nwithBStringLen bs f = do\n BS.useAsCStringLen bs $ \\(str, len) -> f (str, fromIntegral len)\n\nunStatus :: CInt -> Bool\nunStatus 0 = False\nunStatus 1 = True\n-- |@parseChunk data False@ feeds \/strict\/ ByteString data into a\n-- 'Parser'. The end of the data is indicated by passing @True@ for the\n-- final parameter. @parse@ returns @False@ on a parse error.\nparseChunk :: Parser\n -> BS.ByteString\n -> Bool\n -> IO Bool\nparseChunk parser xml final = do\n withHandlers parser $ doParseChunk parser xml final\n\nwithHandlers :: Parser -> IO a -> IO a\nwithHandlers parser@(Parser fp startRef endRef charRef) code = do\n bracket\n (do\n cStartH <- mkCStartElementHandler =<< readIORef startRef\n cEndH <- mkCEndElementHandler =<< readIORef endRef\n cCharH <- mkCCharacterDataHandler =<< readIORef charRef\n withParser parser $ \\p -> do\n {#call unsafe XML_SetStartElementHandler as ^#} p cStartH\n {#call unsafe XML_SetEndElementHandler as ^#} p cEndH\n {#call unsafe XML_SetCharacterDataHandler as ^#} p cCharH\n return (cStartH, cEndH, cCharH))\n (\\(cStartH, cEndH, cCharH) -> do\n freeHaskellFunPtr cStartH\n freeHaskellFunPtr cEndH\n freeHaskellFunPtr cCharH)\n (\\_ -> code)\n\n{#fun XML_Parse as doParseChunk\n {withParser* `Parser', withBStringLen* `BS.ByteString' &, `Bool'}\n -> `Bool' unStatus#}\n\n-- |@parse data@ feeds \/lazy\/ bytestring data into a parser and returns\n-- @True@ if there was no parse error.\nparse :: Parser -> BSL.ByteString -> IO Bool\nparse parser bs = withHandlers parser $ feedChunk (BSL.toChunks bs)\n where\n feedChunk [] = return True\n feedChunk [chunk] = parseChunk parser chunk True\n feedChunk (c:cs) = do ok <- doParseChunk parser c False\n if ok then feedChunk cs\n else return False\n\n-- |The type of the \\\"element started\\\" callback. The first parameter is\n-- the element name; the second are the (attribute, value) pairs.\ntype StartElementHandler = BS.ByteString -> [(BS.ByteString,BS.ByteString)] -> IO ()\n-- |The type of the \\\"element ended\\\" callback. The parameter is\n-- the element name.\ntype EndElementHandler = BS.ByteString -> IO ()\n-- |The type of the \\\"character data\\\" callback. The parameter is\n-- the character data processed. This callback may be called more than once\n-- while processing a single conceptual block of text.\ntype CharacterDataHandler = BS.ByteString -> IO ()\n\ntype CStartElementHandler = Ptr () -> CString -> Ptr CString -> IO ()\nnullCStartElementHandler _ _ _ = return ()\n\nforeign import ccall \"wrapper\"\n mkCStartElementHandler :: CStartElementHandler\n -> IO (FunPtr CStartElementHandler)\nwrapStartElementHandler :: StartElementHandler -> CStartElementHandler\nwrapStartElementHandler handler = h where\n h ptr cname cattrs = do\n name <- peekByteString cname\n cattrlist <- peekArray0 nullPtr cattrs\n attrlist <- mapM peekByteString cattrlist\n handler name (pairwise attrlist)\n-- |Attach a StartElementHandler to a Parser.\nsetStartElementHandler :: Parser -> StartElementHandler -> IO ()\nsetStartElementHandler parser@(Parser _ startRef _ _) handler = do\n withParser parser $ \\p -> do\n writeIORef startRef $ wrapStartElementHandler handler\n\ntype CEndElementHandler = Ptr () -> CString -> IO ()\nnullCEndElementHandler _ _ = return ()\n\nforeign import ccall \"wrapper\"\n mkCEndElementHandler :: CEndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler :: EndElementHandler -> CEndElementHandler\nwrapEndElementHandler handler = h where\n h ptr cname = do\n name <- peekByteString cname\n handler name\n\n-- |Attach an EndElementHandler to a Parser.\nsetEndElementHandler :: Parser -> EndElementHandler -> IO ()\nsetEndElementHandler parser@(Parser _ _ endRef _) handler = do\n withParser parser $ \\p -> do\n writeIORef endRef $ wrapEndElementHandler handler\n\ntype CCharacterDataHandler = Ptr () -> CString -> CInt -> IO ()\nnullCCharacterDataHandler _ _ _ = return ()\n\nforeign import ccall \"wrapper\"\n mkCCharacterDataHandler :: CCharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler :: CharacterDataHandler -> CCharacterDataHandler\nwrapCharacterDataHandler handler = h where\n h ptr cdata len = do\n data_ <- peekByteStringLen (cdata, fromIntegral len)\n handler data_\n\n-- |Attach an CharacterDataHandler to a Parser.\nsetCharacterDataHandler :: Parser -> CharacterDataHandler -> IO ()\nsetCharacterDataHandler parser@(Parser _ _ _ charRef) handler = do\n withParser parser $ \\p -> do\n writeIORef charRef $ wrapCharacterDataHandler handler\n\npairwise (x1:x2:xs) = (x1,x2) : pairwise xs\npairwise [] = []\n\npeekByteString :: CString -> IO BS.ByteString\n{-# INLINE peekByteString #-}\npeekByteString cstr = do\n len <- BSI.c_strlen cstr\n peekByteStringLen (castPtr cstr, len)\n\npeekByteStringLen :: (CString, CSize) -> IO BS.ByteString \n{-# INLINE peekByteStringLen #-}\npeekByteStringLen (cstr, len) =\n BSI.create (fromIntegral len) $ \\ptr ->\n BSI.memcpy ptr (castPtr cstr) len\n\n","old_contents":"-- hexpat, a Haskell wrapper for expat\n-- Copyright (C) 2008 Evan Martin \n\n-- |This module wraps the Expat API directly with IO operations\n-- everywhere. Basic usage is:\n--\n-- (1) Make a new parser: 'newParser'.\n--\n-- (2) Set up callbacks on the parser: 'setStartElementHandler', etc.\n--\n-- (3) Feed data into the parser: 'parse' or 'parseChunk'.\n\nmodule Text.XML.Expat.IO (\n -- ** Parser Setup\n Parser, newParser,\n\n -- ** Parsing\n parse, Encoding(..),\n\n -- ** Parser Callbacks\n StartElementHandler, EndElementHandler, CharacterDataHandler,\n setStartElementHandler, setEndElementHandler, setCharacterDataHandler,\n\n -- ** Lower-level Parsing Interface\n parseChunk,\n\n -- ** Helpers\n encodingToString\n) where\n\nimport Control.Exception (bracket)\nimport C2HS\nimport qualified Data.ByteString as BS\nimport qualified Data.ByteString.Lazy as BSL\nimport qualified Data.ByteString.Internal as BSI\nimport Data.IORef\n\n#include \n\n-- Expat functions start with \"XML\", but C2HS appears to ignore our \"as\"\n-- definitions if they only differ from the symbol in case. So we write out\n-- XML_* in most cases anyway... :(\n{#context lib = \"expat\" prefix = \"XML\"#}\n\n-- |Opaque parser type.\ntype ParserPtr = Ptr ()\ndata Parser = Parser\n (ForeignPtr ())\n (IORef CStartElementHandler) \n (IORef CEndElementHandler) \n (IORef CCharacterDataHandler) \n\nwithParser :: Parser -> (ParserPtr -> IO a) -> IO a\nwithParser (Parser fp _ _ _) = withForeignPtr fp\n\n-- |Encoding types available for the document encoding.\ndata Encoding = ASCII | UTF8 | UTF16 | ISO88591\nencodingToString :: Encoding -> String\nencodingToString ASCII = \"US-ASCII\"\nencodingToString UTF8 = \"UTF-8\"\nencodingToString UTF16 = \"UTF-16\"\nencodingToString ISO88591 = \"ISO-8859-1\"\n\nwithOptEncoding :: Maybe Encoding -> (CString -> IO a) -> IO a\nwithOptEncoding Nothing f = f nullPtr\nwithOptEncoding (Just enc) f = withCString (encodingToString enc) f\n\n{#fun unsafe XML_ParserCreate as parserCreate\n {withOptEncoding* `Maybe Encoding'} -> `ParserPtr' id#}\nforeign import ccall \"&XML_ParserFree\" parserFree :: FunPtr (ParserPtr -> IO ())\n\n-- |Create a 'Parser'. The encoding parameter, if provided, overrides the\n-- document's encoding declaration.\nnewParser :: Maybe Encoding -> IO Parser\nnewParser enc = do\n ptr <- parserCreate enc\n fptr <- newForeignPtr parserFree ptr\n nullStartH <- newIORef nullCStartElementHandler\n nullEndH <- newIORef nullCEndElementHandler\n nullCharH <- newIORef nullCCharacterDataHandler\n return $ Parser fptr nullStartH nullEndH nullCharH\n\n-- ByteString.useAsCStringLen is almost what we need, but C2HS wants a CInt\n-- instead of an Int.\nwithBStringLen :: BS.ByteString -> ((CString, CInt) -> IO a) -> IO a\nwithBStringLen bs f = do\n BS.useAsCStringLen bs $ \\(str, len) -> f (str, fromIntegral len)\n\nunStatus :: CInt -> Bool\nunStatus 0 = False\nunStatus 1 = True\n-- |@parseChunk data False@ feeds \/strict\/ ByteString data into a\n-- 'Parser'. The end of the data is indicated by passing @True@ for the\n-- final parameter. @parse@ returns @False@ on a parse error.\nparseChunk :: Parser\n -> BS.ByteString\n -> Bool\n -> IO Bool\nparseChunk parser@(Parser fp startRef endRef charRef) xml final = do\n bracket\n (do\n cStartH <- mkCStartElementHandler =<< readIORef startRef\n cEndH <- mkCEndElementHandler =<< readIORef endRef\n cCharH <- mkCCharacterDataHandler =<< readIORef charRef\n withParser parser $ \\p -> do\n {#call unsafe XML_SetStartElementHandler as ^#} p cStartH\n {#call unsafe XML_SetEndElementHandler as ^#} p cEndH\n {#call unsafe XML_SetCharacterDataHandler as ^#} p cCharH\n return (cStartH, cEndH, cCharH))\n (\\(cStartH, cEndH, cCharH) -> do\n freeHaskellFunPtr cStartH\n freeHaskellFunPtr cEndH\n freeHaskellFunPtr cCharH)\n (\\_ -> doParseChunk parser xml final)\n\n{#fun XML_Parse as doParseChunk\n {withParser* `Parser', withBStringLen* `BS.ByteString' &, `Bool'}\n -> `Bool' unStatus#}\n\n-- |@parse data@ feeds \/lazy\/ bytestring data into a parser and returns\n-- @True@ if there was no parse error.\nparse :: Parser -> BSL.ByteString -> IO Bool\nparse parser bs = feedChunk (BSL.toChunks bs) where\n feedChunk [] = return True\n feedChunk [chunk] = parseChunk parser chunk True\n feedChunk (c:cs) = do ok <- parseChunk parser c False\n if ok then feedChunk cs\n else return False\n\n-- |The type of the \\\"element started\\\" callback. The first parameter is\n-- the element name; the second are the (attribute, value) pairs.\ntype StartElementHandler = BS.ByteString -> [(BS.ByteString,BS.ByteString)] -> IO ()\n-- |The type of the \\\"element ended\\\" callback. The parameter is\n-- the element name.\ntype EndElementHandler = BS.ByteString -> IO ()\n-- |The type of the \\\"character data\\\" callback. The parameter is\n-- the character data processed. This callback may be called more than once\n-- while processing a single conceptual block of text.\ntype CharacterDataHandler = BS.ByteString -> IO ()\n\ntype CStartElementHandler = Ptr () -> CString -> Ptr CString -> IO ()\nnullCStartElementHandler _ _ _ = return ()\n\nforeign import ccall \"wrapper\"\n mkCStartElementHandler :: CStartElementHandler\n -> IO (FunPtr CStartElementHandler)\nwrapStartElementHandler :: StartElementHandler -> CStartElementHandler\nwrapStartElementHandler handler = h where\n h ptr cname cattrs = do\n name <- peekByteString cname\n cattrlist <- peekArray0 nullPtr cattrs\n attrlist <- mapM peekByteString cattrlist\n handler name (pairwise attrlist)\n-- |Attach a StartElementHandler to a Parser.\nsetStartElementHandler :: Parser -> StartElementHandler -> IO ()\nsetStartElementHandler parser@(Parser _ startRef _ _) handler = do\n withParser parser $ \\p -> do\n writeIORef startRef $ wrapStartElementHandler handler\n\ntype CEndElementHandler = Ptr () -> CString -> IO ()\nnullCEndElementHandler _ _ = return ()\n\nforeign import ccall \"wrapper\"\n mkCEndElementHandler :: CEndElementHandler\n -> IO (FunPtr CEndElementHandler)\nwrapEndElementHandler :: EndElementHandler -> CEndElementHandler\nwrapEndElementHandler handler = h where\n h ptr cname = do\n name <- peekByteString cname\n handler name\n\n-- |Attach an EndElementHandler to a Parser.\nsetEndElementHandler :: Parser -> EndElementHandler -> IO ()\nsetEndElementHandler parser@(Parser _ _ endRef _) handler = do\n withParser parser $ \\p -> do\n writeIORef endRef $ wrapEndElementHandler handler\n\ntype CCharacterDataHandler = Ptr () -> CString -> CInt -> IO ()\nnullCCharacterDataHandler _ _ _ = return ()\n\nforeign import ccall \"wrapper\"\n mkCCharacterDataHandler :: CCharacterDataHandler\n -> IO (FunPtr CCharacterDataHandler)\nwrapCharacterDataHandler :: CharacterDataHandler -> CCharacterDataHandler\nwrapCharacterDataHandler handler = h where\n h ptr cdata len = do\n data_ <- peekByteStringLen (cdata, fromIntegral len)\n handler data_\n\n-- |Attach an CharacterDataHandler to a Parser.\nsetCharacterDataHandler :: Parser -> CharacterDataHandler -> IO ()\nsetCharacterDataHandler parser@(Parser _ _ _ charRef) handler = do\n withParser parser $ \\p -> do\n writeIORef charRef $ wrapCharacterDataHandler handler\n\npairwise (x1:x2:xs) = (x1,x2) : pairwise xs\npairwise [] = []\n\npeekByteString :: CString -> IO BS.ByteString\n{-# INLINE peekByteString #-}\npeekByteString cstr = do\n len <- BSI.c_strlen cstr\n peekByteStringLen (castPtr cstr, len)\n\npeekByteStringLen :: (CString, CSize) -> IO BS.ByteString \n{-# INLINE peekByteStringLen #-}\npeekByteStringLen (cstr, len) =\n BSI.create (fromIntegral len) $ \\ptr ->\n BSI.memcpy ptr (castPtr cstr) len\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"b86719b391c2aef0a5dffaedfa0d3bf5b3cad4e8","subject":"mtrFindGroup mtrDissolveGroup","message":"mtrFindGroup mtrDissolveGroup\n","repos":"maweki\/haskell_cudd,adamwalker\/haskell_cudd","old_file":"MTR.chs","new_file":"MTR.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls, CPP #-}\n\nmodule MTR where\n\nimport System.IO\nimport Foreign\nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Control.Monad\n\n#include \n#include \n\ndata CMtrNode \nnewtype MtrNode = MtrNode (Ptr CMtrNode)\n\nforeign import ccall unsafe \"mtr.h Mtr_AllocNode\"\n c_mtrAllocNode :: IO (Ptr CMtrNode)\n\nmtrAllocNode :: IO (MtrNode) \nmtrAllocNode = liftM MtrNode c_mtrAllocNode\n\nforeign import ccall unsafe \"mtr.h Mtr_CreateFirstChild\"\n c_mtrCreateFirstChild :: Ptr CMtrNode -> IO (Ptr CMtrNode)\n\nmtrCreateFirstChild :: MtrNode -> IO (MtrNode)\nmtrCreateFirstChild (MtrNode p) = liftM MtrNode $ c_mtrCreateFirstChild p\n\nforeign import ccall unsafe \"mtr.h Mtr_CreateLastChild\"\n c_mtrCreateLastChild :: Ptr CMtrNode -> IO (Ptr CMtrNode)\n\nmtrCreateLastChild :: MtrNode -> IO (MtrNode)\nmtrCreateLastChild (MtrNode p) = liftM MtrNode $ c_mtrCreateLastChild p\n\nforeign import ccall unsafe \"mtr.h Mtr_DeallocNode\"\n c_mtrDeallocNode :: Ptr CMtrNode -> IO ()\n\nmtrDeallocNode :: MtrNode -> IO ()\nmtrDeallocNode (MtrNode p) = c_mtrDeallocNode p\n\nforeign import ccall unsafe \"mtr.h Mtr_MakeFirstChild\"\n c_mtrMakeFirstChild :: Ptr CMtrNode -> Ptr CMtrNode -> IO ()\n\nmtrMakeFirstChild :: MtrNode -> MtrNode -> IO ()\nmtrMakeFirstChild (MtrNode p) (MtrNode c) = c_mtrMakeFirstChild p c\n\nforeign import ccall unsafe \"mtr.h Mtr_MakeLastChild\"\n c_mtrMakeLastChild :: Ptr CMtrNode -> Ptr CMtrNode -> IO ()\n\nmtrMakeLastChild :: MtrNode -> MtrNode -> IO ()\nmtrMakeLastChild (MtrNode p) (MtrNode c) = c_mtrMakeLastChild p c\n\nforeign import ccall unsafe \"mtr.h Mtr_MakeNextSibling\"\n c_mtrMakeNextSibling :: Ptr CMtrNode -> Ptr CMtrNode -> IO ()\n\nmtrMakeNextSibling :: MtrNode -> MtrNode -> IO ()\nmtrMakeNextSibling (MtrNode f) (MtrNode s) = c_mtrMakeNextSibling f s\n\nforeign import ccall unsafe \"mtr.h Mtr_PrintGroups\"\n c_mtrPrintGroups :: Ptr CMtrNode -> CInt -> IO ()\n\nmtrPrintGroups :: MtrNode -> Int -> IO ()\nmtrPrintGroups (MtrNode c) s = c_mtrPrintGroups c (fromIntegral s)\n\nforeign import ccall unsafe \"mtr.h Mtr_PrintTree\"\n c_mtrPrintTree :: Ptr CMtrNode -> IO ()\n\nmtrPrintTree :: MtrNode -> IO ()\nmtrPrintTree (MtrNode c) = c_mtrPrintTree c\n\nforeign import ccall unsafe \"mtr.h Mtr_MakeGroup\"\n c_mtrMakeGroup :: Ptr CMtrNode -> CInt -> CInt -> CInt -> IO (Ptr CMtrNode)\n\nmtrMakeGroup :: MtrNode -> Int -> Int -> Int -> IO (MtrNode)\nmtrMakeGroup (MtrNode r) l s f = liftM MtrNode $ c_mtrMakeGroup r (fromIntegral l) (fromIntegral s) (fromIntegral f)\n\nforeign import ccall unsafe \"mtr.h Mtr_InitGroupTree\"\n c_mtrInitGroupTree :: CInt -> CInt -> IO (Ptr CMtrNode)\n\nmtrInitGroupTree :: Int -> Int -> IO (MtrNode)\nmtrInitGroupTree l s = liftM MtrNode $ c_mtrInitGroupTree (fromIntegral l) (fromIntegral s)\n\nforeign import ccall unsafe \"mtr.h Mtr_FindGroup\"\n c_mtrFindGroup :: Ptr CMtrNode -> CUInt -> CUInt -> IO (Ptr CMtrNode)\n\nmtrFindGroup :: MtrNode -> Int -> Int -> IO MtrNode\nmtrFindGroup (MtrNode m) x y = liftM MtrNode $ c_mtrFindGroup m (fromIntegral x) (fromIntegral y)\n\nforeign import ccall unsafe \"mtr.h Mtr_DissolveGroup\"\n c_mtrDissolveGroup :: Ptr CMtrNode -> IO ()\n\nmtrDissolveGroup :: MtrNode -> IO ()\nmtrDissolveGroup (MtrNode m) = c_mtrDissolveGroup m\n\n#c\nenum MTR_TYPES {\n MTRDefault = MTR_DEFAULT,\n MTRTerminal = MTR_TERMINAL,\n MTRSoft = MTR_SOFT,\n MTRFixed = MTR_FIXED,\n MTRNewNode = MTR_NEWNODE\n};\n#endc\n\n{#enum MTR_TYPES as MTRType {underscoreToCase} deriving (Show, Eq) #}\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls, CPP #-}\n\nmodule MTR where\n\nimport System.IO\nimport Foreign\nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Control.Monad\n\n#include \n#include \n\ndata CMtrNode \nnewtype MtrNode = MtrNode (Ptr CMtrNode)\n\nforeign import ccall unsafe \"mtr.h Mtr_AllocNode\"\n c_mtrAllocNode :: IO (Ptr CMtrNode)\n\nmtrAllocNode :: IO (MtrNode) \nmtrAllocNode = liftM MtrNode c_mtrAllocNode\n\nforeign import ccall unsafe \"mtr.h Mtr_CreateFirstChild\"\n c_mtrCreateFirstChild :: Ptr CMtrNode -> IO (Ptr CMtrNode)\n\nmtrCreateFirstChild :: MtrNode -> IO (MtrNode)\nmtrCreateFirstChild (MtrNode p) = liftM MtrNode $ c_mtrCreateFirstChild p\n\nforeign import ccall unsafe \"mtr.h Mtr_CreateLastChild\"\n c_mtrCreateLastChild :: Ptr CMtrNode -> IO (Ptr CMtrNode)\n\nmtrCreateLastChild :: MtrNode -> IO (MtrNode)\nmtrCreateLastChild (MtrNode p) = liftM MtrNode $ c_mtrCreateLastChild p\n\nforeign import ccall unsafe \"mtr.h Mtr_DeallocNode\"\n c_mtrDeallocNode :: Ptr CMtrNode -> IO ()\n\nmtrDeallocNode :: MtrNode -> IO ()\nmtrDeallocNode (MtrNode p) = c_mtrDeallocNode p\n\nforeign import ccall unsafe \"mtr.h Mtr_MakeFirstChild\"\n c_mtrMakeFirstChild :: Ptr CMtrNode -> Ptr CMtrNode -> IO ()\n\nmtrMakeFirstChild :: MtrNode -> MtrNode -> IO ()\nmtrMakeFirstChild (MtrNode p) (MtrNode c) = c_mtrMakeFirstChild p c\n\nforeign import ccall unsafe \"mtr.h Mtr_MakeLastChild\"\n c_mtrMakeLastChild :: Ptr CMtrNode -> Ptr CMtrNode -> IO ()\n\nmtrMakeLastChild :: MtrNode -> MtrNode -> IO ()\nmtrMakeLastChild (MtrNode p) (MtrNode c) = c_mtrMakeLastChild p c\n\nforeign import ccall unsafe \"mtr.h Mtr_MakeNextSibling\"\n c_mtrMakeNextSibling :: Ptr CMtrNode -> Ptr CMtrNode -> IO ()\n\nmtrMakeNextSibling :: MtrNode -> MtrNode -> IO ()\nmtrMakeNextSibling (MtrNode f) (MtrNode s) = c_mtrMakeNextSibling f s\n\nforeign import ccall unsafe \"mtr.h Mtr_PrintGroups\"\n c_mtrPrintGroups :: Ptr CMtrNode -> CInt -> IO ()\n\nmtrPrintGroups :: MtrNode -> Int -> IO ()\nmtrPrintGroups (MtrNode c) s = c_mtrPrintGroups c (fromIntegral s)\n\nforeign import ccall unsafe \"mtr.h Mtr_PrintTree\"\n c_mtrPrintTree :: Ptr CMtrNode -> IO ()\n\nmtrPrintTree :: MtrNode -> IO ()\nmtrPrintTree (MtrNode c) = c_mtrPrintTree c\n\nforeign import ccall unsafe \"mtr.h Mtr_MakeGroup\"\n c_mtrMakeGroup :: Ptr CMtrNode -> CInt -> CInt -> CInt -> IO (Ptr CMtrNode)\n\nmtrMakeGroup :: MtrNode -> Int -> Int -> Int -> IO (MtrNode)\nmtrMakeGroup (MtrNode r) l s f = liftM MtrNode $ c_mtrMakeGroup r (fromIntegral l) (fromIntegral s) (fromIntegral f)\n\nforeign import ccall unsafe \"mtr.h Mtr_InitGroupTree\"\n c_mtrInitGroupTree :: CInt -> CInt -> IO (Ptr CMtrNode)\n\nmtrInitGroupTree :: Int -> Int -> IO (MtrNode)\nmtrInitGroupTree l s = liftM MtrNode $ c_mtrInitGroupTree (fromIntegral l) (fromIntegral s)\n\n#c\nenum MTR_TYPES {\n MTRDefault = MTR_DEFAULT,\n MTRTerminal = MTR_TERMINAL,\n MTRSoft = MTR_SOFT,\n MTRFixed = MTR_FIXED,\n MTRNewNode = MTR_NEWNODE\n};\n#endc\n\n{#enum MTR_TYPES as MTRType {underscoreToCase} deriving (Show, Eq) #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"838f470cac38405eb2d3c8773935e750a16334ce","subject":"Exported and,or and not from imagemath","message":"Exported and,or and not from imagemath\n","repos":"BeautifulDestinations\/CV,aleator\/CV,TomMD\/CV,aleator\/CV","old_file":"CV\/ImageMath.chs","new_file":"CV\/ImageMath.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ScopedTypeVariables, FlexibleContexts#-}\n#include \"cvWrapLEO.h\"\n\n-- | Mathematical and statistical operations for images. See also module\n-- \"CV.ImageMathOp\" which contains handy operators for some of these.\nmodule CV.ImageMath(\n -- * Operations for two images\n add\n, sub\n, absDiff\n, mul\n, CV.ImageMath.div\n, CV.ImageMath.min\n, CV.ImageMath.max\n, maskedMerge\n, averageImages\n, CV.ImageMath.atan2\n -- * Operations for one image\n, subMean\n, subMeanAbs\n, CV.ImageMath.sqrt\n, CV.ImageMath.log\n, CV.ImageMath.abs\n, CV.ImageMath.atan\n, invert\n -- * Operations for a scalar and an image\n, addS\n, subS\n, subRS\n, mulS\n-- TODO: divS is missing, is it needed?\n-- , divS\n, minS\n, maxS\n -- * Pixelwise logical operations\n, CV.ImageMath.not\n, CV.ImageMath.and\n, CV.ImageMath.or\n, CV.ImageMath.notOp\n, CV.ImageMath.andOp\n, CV.ImageMath.orOp\n -- * Comparison operations\n, lessThan\n, moreThan\n, less2Than\n, more2Than\n, lessEq2Than \n, moreEq2Than\n -- * Image statistics\n, CV.ImageMath.sum\n, average\n, averageMask\n, stdDeviation\n, stdDeviationMask\n, findMinMax\n, findMinMaxLoc\n, findMinMaxMask\n, imageMinMax -- TODO: merge with findMinMax \/ replace binding?\n, minValue\n, maxValue\n, imageAvgSdv -- TODO: merge with average and stdDeviation \/ replace binding?\n -- * Misc (to be moved?)\n, gaussianImage -- TODO: move to other module?\n, fadedEdgeImage -- TODO: move to other module?\n, fadeToCenter -- TODO: move to other module?\n, maximalCoveringCircle -- TODO: move to other module?\n, limitToOp -- TODO: remove? needed in Morphology; export operations at end?\n-- TODO: add section \"Image operations\" and add the bare operations there for combining with others?\n) where\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.ForeignPtr\nimport Foreign.Ptr\n\nimport CV.Bindings.Types\nimport CV.Bindings.Core\nimport CV.Image\nimport CV.ImageOp\n\n-- import C2HSTools\n{#import CV.Image#}\nimport Foreign.Marshal\nimport Foreign.Storable\nimport Foreign.Ptr\nimport System.IO.Unsafe\nimport Control.Applicative ((<$>))\n\nmkBinaryImageOpIO f = \\a -> \\b ->\n withGenImage a $ \\ia ->\n withGenImage b $ \\ib ->\n withCloneValue a $ \\clone ->\n withGenImage clone $ \\cl -> do\n f ia ib cl\n return clone\n\nmkBinaryImageOp\n :: (Ptr () -> Ptr () -> Ptr () -> IO a)\n -> CV.Image.Image c1 d1\n -> CV.Image.Image c1 d1\n -> CV.Image.Image c1 d1\n\nmkBinaryImageOp f = \\a -> \\b -> unsafePerformIO $\n withGenImage a $ \\ia ->\n withGenImage b $ \\ib ->\n withCloneValue a $ \\clone ->\n withGenImage clone $ \\cl -> do\n f ia ib cl\n return clone\n\n\n-- I just can't think of a proper name for this\n -- Friday Evening\nabcNullPtr f = \\a b c -> f a b c nullPtr\n\naddOp imageToBeAdded = ImgOp $ \\target ->\n withGenImage target $ \\ctarget ->\n withGenImage imageToBeAdded $ \\cadd ->\n {#call cvAdd#} ctarget cadd ctarget nullPtr\n\n-- | Calculates the per-pixel sum of two images.\nadd = mkBinaryImageOp $ abcNullPtr {#call cvAdd#}\n\n-- | Calculates the per-pixel difference of two images.\nsub = mkBinaryImageOp $ abcNullPtr {#call cvSub#}\n\nsubFrom what = ImgOp $ \\from ->\n withGenImage from $ \\ifrom ->\n withGenImage what $ \\iwhat ->\n {#call cvSub#} ifrom iwhat ifrom nullPtr\n\nlogOp :: ImageOperation GrayScale D32\nlogOp = ImgOp $ \\i -> withGenImage i (\\img -> {#call cvLog#} img img)\n\n-- | Calculates the natural logarithm of every pixel.\nlog = unsafeOperate logOp\n\nsqrtOp :: ImageOperation GrayScale D32\nsqrtOp = ImgOp $ \\i -> withGenImage i (\\img -> {#call sqrtImage#} img img)\n\n-- | Calculates the square root of every pixel.\nsqrt = unsafeOperate sqrtOp\n\n-- | Operation to limit image with another image; same as 'ImageMath.min'.\nlimitToOp what = ImgOp $ \\from ->\n withGenImage from $ \\ifrom ->\n withGenImage what $ \\iwhat ->\n {#call cvMin#} ifrom iwhat ifrom\n\n-- | Limit image with another image; same as 'ImageMath.min'.\nlimitTo x y = unsafeOperate (limitToOp x) y\n\n-- | Calculates the per-pixel product of two images.\nmul = mkBinaryImageOp\n (\\a b c -> {#call cvMul#} a b c 1)\n\n-- | Calculates the per-pixel division of two images.\ndiv = mkBinaryImageOp\n (\\a b c -> {#call cvDiv#} a b c 1)\n\n-- | Calculates the per-pixel minimum of two images.\nmin = mkBinaryImageOp {#call cvMin#}\n\n-- | Calculates the per-pixel maximum of two images.\nmax = mkBinaryImageOp {#call cvMax#}\n\n-- | Calculates the per-pixel absolute difference of two images.\nabsDiff = mkBinaryImageOp {#call cvAbsDiff#}\n\n-- | Calculates the atan of every pixel.\natan :: Image GrayScale D32 -> Image GrayScale D32\natan i = unsafePerformIO $ do\n let (w,h) = getSize i\n res <- create (w,h)\n withImage i $ \\s ->\n withImage res $ \\r -> do\n {#call calculateAtan#} s r\n return res\n\n-- | Calculates the atan2 of pixel values in two images.\natan2 :: Image GrayScale D32 -> Image GrayScale D32 -> Image GrayScale D32\natan2 a b = unsafePerformIO $ do\n res <- create (getSize a)\n withImage a $ \\c_a ->\n withImage b $ \\c_b ->\n withImage res $ \\c_res -> do\n {#call calculateAtan2#} c_a c_b c_res\n return res\n\n\n-- Operation that subtracts image mean from image\nsubtractMeanAbsOp = ImgOp $ \\image -> do\n av <- average' image\n withGenImage image $ \\i ->\n {#call wrapAbsDiffS#} i (realToFrac av) i -- TODO: check C datatype sizes\n\n-- | Calculates the absolute difference of every pixel to image mean.\n-- See also 'ImageMath.subMean'.\nsubMeanAbs = unsafeOperate subtractMeanAbsOp\n\n-- | Logical inversion of image (ie. invert, but stay on [0..1] range;\n-- multiply by @-1@ and add @1@).\ninvert i = addS 1 $ mulS (-1) i\n\nnotOp :: ImageOperation GrayScale D8\nnotOp = ImgOp $ \\image -> withGenImage image $ \\i -> {#call cvNot#} i i\n\nnot :: Image GrayScale D8 -> Image GrayScale D8\nnot = unsafeOperate notOp\n\nandOp :: Image GrayScale D8 -> Mask -> ImageOperation GrayScale D8\nandOp image0 mask = ImgOp $ \\image1 -> \n withGenImage image0 $ \\ci0 ->\n withGenImage image1 $ \\ci1 -> \n withMask mask $ \\cmask -> \n {#call cvAnd#} ci0 ci1 ci1 cmask\n\nand :: Image GrayScale D8 -> Image GrayScale D8 -> Mask -> Image GrayScale D8 \nand i j mask = unsafeOperate (andOp i mask) j\n\norOp :: Image GrayScale D8 -> Mask -> ImageOperation GrayScale D8\norOp image0 mask = ImgOp $ \\image1 -> \n withGenImage image0 $ \\ci0 ->\n withGenImage image1 $ \\ci1 -> \n withMask mask $ \\cmask -> \n {#call cvOr#} ci0 ci1 ci1 cmask\n\nor :: Image GrayScale D8 -> Image GrayScale D8 -> Mask -> Image GrayScale D8 \nor i j mask = unsafeOperate (orOp i mask) j\n\nabsOp = ImgOp $ \\image -> do\n withGenImage image $ \\i ->\n {#call wrapAbsDiffS#} i 0 i\n\n-- | Calculates the absolute value of every pixel.\nabs = unsafeOperate absOp\n\nsubtractMeanOp :: ImageOperation GrayScale D32\nsubtractMeanOp = ImgOp $ \\image -> do\n let s = CV.ImageMath.sum image\n let mean = s \/ (fromIntegral $ getArea image )\n let (ImgOp subop) = subRSOp (realToFrac mean)\n subop image\n\n-- | Calculates the (non-absolute) difference of every pixel to image mean.\n-- See also 'ImageMath.subMeanAbs'.\nsubMean = unsafeOperate subtractMeanOp\n\nsubRSOp :: D32 -> ImageOperation GrayScale D32\nsubRSOp scalar = ImgOp $ \\a ->\n withGenImage a $ \\ia -> do\n {#call wrapSubRS#} ia (realToFrac scalar) ia\n\n-- | Subtracts a scalar from every pixel, scalar on right.\nsubRS s a= unsafeOperate (subRSOp s) a\n\nsubSOp scalar = ImgOp $ \\a ->\n withGenImage a $ \\ia -> do\n {#call wrapSubS#} ia (realToFrac scalar) ia\n\n-- | Subtracts a scalar from every pixel, scalar on left.\nsubS a s = unsafeOperate (subSOp s) a\n\n-- Multiply the image with scalar\nmulSOp :: D32 -> ImageOperation GrayScale D32\nmulSOp scalar = ImgOp $ \\a ->\n withGenImage a $ \\ia -> do\n {#call cvConvertScale#} ia ia s 0\n return ()\n where s = realToFrac scalar\n -- I've heard this will lose information\n\n-- | Multiplies every pixel by a scalar.\nmulS s = unsafeOperate $ mulSOp s\n\nmkImgScalarOp op scalar = ImgOp $ \\a ->\n withGenImage a $ \\ia -> do\n op ia (realToFrac scalar) ia\n return ()\n\n-- TODO: Relax the addition so it works on multiple image depths\naddSOp :: D32 -> ImageOperation GrayScale D32\naddSOp = mkImgScalarOp $ {#call wrapAddS#}\n\n-- | Adds a scalar to every pixel.\naddS s = unsafeOperate $ addSOp s\n\nminSOp = mkImgScalarOp $ {#call cvMinS#}\n\n-- | Calculates the per-pixel minimum between an image and a scalar.\nminS :: Float -> Image c d -> Image c d\nminS s = unsafeOperate $ minSOp s\n\nmaxSOp = mkImgScalarOp $ {#call cvMaxS#}\n\n-- | Calculates the per-pixel maximum between an image and a scalar.\nmaxS :: Float -> Image c d -> Image c d\nmaxS s = unsafeOperate $ maxSOp s\n\n\n-- Comparison operators\ncmpEQ = 0\ncmpGT = 1\ncmpGE = 2\ncmpLT = 3\ncmpLE = 4\ncmpNE = 5\n\n-- TODO: For some reason the below was going through 8U images. Investigate\nmkCmpOp :: CInt -> D32 -> (Image GrayScale D32 -> Image GrayScale D8)\nmkCmpOp cmp = \\scalar a -> unsafePerformIO $\n withGenImage a $ \\ia -> do\n new <- create (getSize a) --8UC1\n withGenImage new $ \\cl -> do\n {#call cvCmpS#} ia (realToFrac scalar) cl cmp\n --imageTo32F new\n return new\n\n-- TODO: For some reason the below was going through 8U images. Investigate\nmkCmp2Op :: (CreateImage (Image GrayScale d)) =>\n CInt -> (Image GrayScale d -> Image GrayScale d -> Image GrayScale D8)\nmkCmp2Op cmp = \\imgA imgB -> unsafePerformIO $ do\n withGenImage imgA $ \\ia -> do\n withGenImage imgB $ \\ib -> do\n new <- create (getSize imgA) -- 8U\n withGenImage new $ \\cl -> do\n {#call cvCmp#} ia ib cl cmp\n return new\n --imageTo32F new\n\n-- | Compares each pixel to a scalar, and produces a binary image where the\n-- pixel value is less than the scalar. For example, @(lessThan s I)@ has\n-- white pixels where value of I is less than s. Notice that the order of\n-- operands is opposite to the intuitive interpretation of @s ``lessThan`` I@.\nlessThan :: D32 -> Image GrayScale D32 -> Image GrayScale D8\nlessThan = mkCmpOp cmpLT\n\n-- | Compares each pixel to a scalar, and produces a binary image where the\n-- pixel value is greater than the scalar. For example, @(moreThan s I)@ has\n-- white pixels where value of I is greater than s. Notice that the order of\n-- operands is opposite to the intuitive interpretation of @s ``moreThan`` I@.\nmoreThan :: D32 -> Image GrayScale D32 -> Image GrayScale D8\nmoreThan = mkCmpOp cmpGT\n\n-- | Compares two images and produces a binary image that has white pixels in\n-- those positions where the comparison is true. For example,\n-- @(less2Than A B)@ has white pixels where value of A is less than value of\n-- B. Notice that these functions follow the intuitive order of operands,\n-- unlike 'lessThan' and 'moreThan'.\nless2Than,lessEq2Than,more2Than, moreEq2Than\n :: (CreateImage (Image GrayScale d)) => Image GrayScale d -> Image GrayScale d -> Image GrayScale D8\n\nless2Than = mkCmp2Op cmpLT\nlessEq2Than = mkCmp2Op cmpLE\nmoreEq2Than = mkCmp2Op cmpGE\nmore2Than = mkCmp2Op cmpGT\n\n-- Statistics\n\naverage' :: Image GrayScale D32 -> IO D32\naverage' img = withGenImage img $ \\image -> \n {#call wrapAvg#} image nullPtr >>= return . realToFrac\n\n-- | Calculates the average pixel value in whole image.\naverage :: Image GrayScale D32 -> D32\naverage = realToFrac.unsafePerformIO.average'\n\n-- | Calculates the average value for pixels that have non-zero mask value.\naverageMask :: Image GrayScale D32 -> Image GrayScale D8 -> D32\naverageMask img mask = unsafePerformIO $\n withGenImage img $ \\c_image -> \n withGenImage mask $ \\c_mask -> \n {#call wrapAvg#} c_image c_mask >>= return . realToFrac\n\n-- | Calculates the sum of pixel values in whole image\n-- (notice that OpenCV automatically casts the result to double).\nsum :: Image GrayScale D32 -> D32\nsum img = realToFrac $ unsafePerformIO $ withGenImage img $ \\image ->\n {#call wrapSum#} image\n\n-- | Calculates the average of multiple images by adding the pixel values and\n-- dividing the resulting values by number of images.\naverageImages is = ( (1\/(fromIntegral $ length is)) `mulS`) (foldl1 add is)\n\n-- sum img = unsafePerformIO $ withGenImage img $ \\image ->\n-- {#call wrapSum#} image\n\nstdDeviation' img = withGenImage img {#call wrapStdDev#}\n\n-- | Calculates the standard deviation of pixel values in whole image.\nstdDeviation :: Image GrayScale D32 -> D32\nstdDeviation = realToFrac . unsafePerformIO . stdDeviation'\n\n-- | Calculates the standard deviation of values for pixels that have non-zero\n-- mask value.\nstdDeviationMask img mask = unsafePerformIO $\n withGenImage img $ \\i ->\n withGenImage mask $ \\m ->\n {#call wrapStdDevMask#} i m\n\n\npeekFloatConv :: (Storable a, RealFloat a, RealFloat b) => Ptr a -> IO b\npeekFloatConv a = fmap realToFrac (peek a)\n\n\n{#fun wrapMinMax as findMinMax'\n { withGenBareImage* `BareImage'\n , withGenBareImage* `BareImage'\n , alloca- `D32' peekFloatConv*\n , alloca- `D32' peekFloatConv*} -- TODO: Check datatype sizes used in C!\n -> `()'#}\n\n-- | Finds the minimum and maximum pixel value in the image and the locations\n-- where these values were found.\nfindMinMaxLoc img = unsafePerformIO $\n\t alloca $ \\(ptrintmaxx :: Ptr CInt)->\n\t alloca $ \\(ptrintmaxy :: Ptr CInt)->\n alloca $ \\(ptrintminx :: Ptr CInt)->\n alloca $ \\(ptrintminy :: Ptr CInt)->\n alloca $ \\(ptrintmin :: Ptr CDouble)->\n alloca $ \\(ptrintmax :: Ptr CDouble)->\n withImage img $ \\cimg -> do {\n {#call wrapMinMaxLoc#} cimg ptrintminx ptrintminy ptrintmaxx ptrintmaxy ptrintmin ptrintmax;\n\t\t minx <- fromIntegral <$> peek ptrintminx;\n\t\t miny <- fromIntegral <$> peek ptrintminy;\n\t\t maxx <- fromIntegral <$> peek ptrintmaxx;\n\t\t maxy <- fromIntegral <$> peek ptrintmaxy;\n\t\t maxval <- realToFrac <$> peek ptrintmax;\n\t\t minval <- realToFrac <$> peek ptrintmin;\n return (((minx,miny),minval),((maxx,maxy),maxval));}\n\n-- TODO: create one function findMinMaxLoc' which takes also mask and base\n-- findMinMax, findMinMaxLoc and findMinMaxMask (findMinMaxLocMask?) on it\n\n-- findMinMax and findMinMaxLoc using the new bindings of cvMinMaxLoc...\n-- do these really work also with D8 images? depends on fractional instance?\n-- maybe create a new class or add a function to some existing class that\n-- allows to get a pixel value from float..\n\n-- | Finds the minimum and maximum pixel value in the image.\nimageMinMax :: (Fractional d) => Image GrayScale d -> (d,d)\nimageMinMax image = unsafePerformIO $ do\n withImage image $ \\pimage -> do\n let\n minval :: CDouble\n minval = 0\n maxval :: CDouble\n maxval = 0\n with minval $ \\pminval ->\n with maxval $ \\pmaxval -> do\n c'cvMinMaxLoc (castPtr pimage) pminval pmaxval nullPtr nullPtr nullPtr\n minv <- peek pminval\n maxv <- peek pmaxval\n return ((realToFrac minv), (realToFrac maxv))\n\n-- | Finds the minimum and maximum pixel value in the image.\nimageMinMaxLoc :: (Fractional d) => Image GrayScale d -> (((Int,Int),d), ((Int,Int),d))\nimageMinMaxLoc image = unsafePerformIO $ do\n withImage image $ \\pimage -> do\n let\n minval :: CDouble\n minval = 0\n maxval :: CDouble\n maxval = 0\n minloc :: C'CvPoint\n minloc = C'CvPoint 0 0\n maxloc :: C'CvPoint\n maxloc = C'CvPoint 0 0\n with minval $ \\pminval ->\n with maxval $ \\pmaxval ->\n with minloc $ \\pminloc ->\n with maxloc $ \\pmaxloc -> do\n c'cvMinMaxLoc (castPtr pimage) pminval pmaxval pminloc pmaxloc nullPtr\n minv <- peek pminval\n (C'CvPoint minx miny) <- peek pminloc\n maxv <- peek pmaxval\n (C'CvPoint maxx maxy) <- peek pmaxloc\n return $\n (((fromIntegral minx, fromIntegral miny), realToFrac minv),\n ((fromIntegral maxx, fromIntegral maxy), realToFrac maxv))\n\n-- TODO: enable using a mask\n-- | Calculates the average and standard deviation of pixel values in the image\n-- in one operation.\nimageAvgSdv :: (Fractional d) => Image GrayScale d -> (d,d)\nimageAvgSdv i = unsafePerformIO $ do\n withImage i $ \\i_ptr -> do\n let\n avg = (C'CvScalar 0 0 0 0)\n sdv = (C'CvScalar 0 0 0 0)\n with avg $ \\avg_ptr ->\n with sdv $ \\sdv_ptr -> do\n c'cvAvgSdv (castPtr i_ptr) avg_ptr sdv_ptr nullPtr\n (C'CvScalar a1 _ _ _) <- peek avg_ptr\n (C'CvScalar s1 _ _ _) <- peek sdv_ptr\n return (realToFrac a1, realToFrac s1)\n\n-- | Finds the minimum and maximum pixel value in the image.\nfindMinMax i = unsafePerformIO $ do\n nullp <- newForeignPtr_ nullPtr\n (findMinMax' (unS i) (BareImage nullp))\n\n-- | Finds the minimum and maximum value for pixels with non-zero mask value.\nfindMinMaxMask i mask = unsafePerformIO (findMinMax' i mask)\n\n-- let a = getAllPixels i in (minimum a,maximum a)\n\n-- | Utility functions for getting the maximum or minimum pixel value of the \n-- image; equal to @snd . findMinMax@ and @fst . findMinMax@.\nmaxValue,minValue :: Image GrayScale D32 -> D32\nmaxValue = snd.findMinMax\nminValue = fst.findMinMax\n\n-- | Render image of 2D gaussian curve with standard deviation of (stdX,stdY) to image size (w,h)\n-- The origin\/center of curve is in center of the image.\ngaussianImage :: (Int,Int) -> (Double,Double) -> Image GrayScale D32\ngaussianImage (w,h) (stdX,stdY) = unsafePerformIO $ do\n dst <- create (w,h) -- 32F_C1\n withImage dst $ \\d-> do\n {#call render_gaussian#} d (realToFrac stdX) (realToFrac stdY)\n return dst\n\n-- | Produce white image with 'edgeW' amount of edges fading to black.\nfadedEdgeImage (w,h) edgeW = unsafePerformIO $\u00a0creatingImage ({#call fadedEdges#} w h edgeW)\n\n-- | Produce image where pixel is coloured according to distance from the edge.\nfadeToCenter (w,h) = unsafePerformIO $\u00a0creatingImage ({#call rectangularDistance#} w h )\n\n-- TODO: Fix C-code of masked_merge to accept D8 input for the mask\n-- | Merge two images according to a mask. Result is @R = A*m + B*(m-1)@.\nmaskedMerge :: Image GrayScale D8 -> Image GrayScale D32 -> Image GrayScale D32 -> Image GrayScale D32\nmaskedMerge mask img img2 = unsafePerformIO $ do\n res <- create (getSize img) -- 32FC1\n withImage img $ \\cimg ->\n withImage img2 $ \\cimg2 ->\n withImage res $ \\cres ->\n withImage (unsafeImageTo32F mask) $ \\cmask ->\n {#call masked_merge#} cimg cmask cimg2 cres\n return res\n\n-- | Given a distance map and a circle, return the biggest circle with radius less\n-- than given in the distance map that fully covers the previous one.\nmaximalCoveringCircle distMap (x,y,r)\n = unsafePerformIO $\n withImage distMap $ \\c_distmap ->\n alloca $ \\(ptr_int_max_x :: Ptr CInt) ->\n alloca $ \\(ptr_int_max_y :: Ptr CInt) ->\n alloca $ \\(ptr_double_max_r :: Ptr CDouble) ->\n do\n {#call maximal_covering_circle#} x y r c_distmap ptr_int_max_x ptr_int_max_y ptr_double_max_r\n max_x <- fromIntegral <$> peek ptr_int_max_x\n max_y <- fromIntegral <$> peek ptr_int_max_y\n max_r <- realToFrac <$> peek ptr_double_max_r\n return (max_x,max_y,max_r)\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ScopedTypeVariables, FlexibleContexts#-}\n#include \"cvWrapLEO.h\"\n\n-- | Mathematical and statistical operations for images. See also module\n-- \"CV.ImageMathOp\" which contains handy operators for some of these.\nmodule CV.ImageMath(\n -- * Operations for two images\n add\n, sub\n, absDiff\n, mul\n, CV.ImageMath.div\n, CV.ImageMath.min\n, CV.ImageMath.max\n, maskedMerge\n, averageImages\n, CV.ImageMath.atan2\n -- * Operations for one image\n, subMean\n, subMeanAbs\n, CV.ImageMath.sqrt\n, CV.ImageMath.log\n, CV.ImageMath.abs\n, CV.ImageMath.atan\n, invert\n -- * Operations for a scalar and an image\n, addS\n, subS\n, subRS\n, mulS\n-- TODO: divS is missing, is it needed?\n-- , divS\n, minS\n, maxS\n -- * Comparison operations\n, lessThan\n, moreThan\n, less2Than\n, more2Than\n, lessEq2Than \n, moreEq2Than\n -- * Image statistics\n, CV.ImageMath.sum\n, average\n, averageMask\n, stdDeviation\n, stdDeviationMask\n, findMinMax\n, findMinMaxLoc\n, findMinMaxMask\n, imageMinMax -- TODO: merge with findMinMax \/ replace binding?\n, minValue\n, maxValue\n, imageAvgSdv -- TODO: merge with average and stdDeviation \/ replace binding?\n -- * Misc (to be moved?)\n, gaussianImage -- TODO: move to other module?\n, fadedEdgeImage -- TODO: move to other module?\n, fadeToCenter -- TODO: move to other module?\n, maximalCoveringCircle -- TODO: move to other module?\n, limitToOp -- TODO: remove? needed in Morphology; export operations at end?\n-- TODO: add section \"Image operations\" and add the bare operations there for combining with others?\n) where\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.ForeignPtr\nimport Foreign.Ptr\n\nimport CV.Bindings.Types\nimport CV.Bindings.Core\nimport CV.Image\nimport CV.ImageOp\n\n-- import C2HSTools\n{#import CV.Image#}\nimport Foreign.Marshal\nimport Foreign.Storable\nimport Foreign.Ptr\nimport System.IO.Unsafe\nimport Control.Applicative ((<$>))\n\nmkBinaryImageOpIO f = \\a -> \\b ->\n withGenImage a $ \\ia ->\n withGenImage b $ \\ib ->\n withCloneValue a $ \\clone ->\n withGenImage clone $ \\cl -> do\n f ia ib cl\n return clone\n\nmkBinaryImageOp\n :: (Ptr () -> Ptr () -> Ptr () -> IO a)\n -> CV.Image.Image c1 d1\n -> CV.Image.Image c1 d1\n -> CV.Image.Image c1 d1\n\nmkBinaryImageOp f = \\a -> \\b -> unsafePerformIO $\n withGenImage a $ \\ia ->\n withGenImage b $ \\ib ->\n withCloneValue a $ \\clone ->\n withGenImage clone $ \\cl -> do\n f ia ib cl\n return clone\n\n\n-- I just can't think of a proper name for this\n -- Friday Evening\nabcNullPtr f = \\a b c -> f a b c nullPtr\n\naddOp imageToBeAdded = ImgOp $ \\target ->\n withGenImage target $ \\ctarget ->\n withGenImage imageToBeAdded $ \\cadd ->\n {#call cvAdd#} ctarget cadd ctarget nullPtr\n\n-- | Calculates the per-pixel sum of two images.\nadd = mkBinaryImageOp $ abcNullPtr {#call cvAdd#}\n\n-- | Calculates the per-pixel difference of two images.\nsub = mkBinaryImageOp $ abcNullPtr {#call cvSub#}\n\nsubFrom what = ImgOp $ \\from ->\n withGenImage from $ \\ifrom ->\n withGenImage what $ \\iwhat ->\n {#call cvSub#} ifrom iwhat ifrom nullPtr\n\nlogOp :: ImageOperation GrayScale D32\nlogOp = ImgOp $ \\i -> withGenImage i (\\img -> {#call cvLog#} img img)\n\n-- | Calculates the natural logarithm of every pixel.\nlog = unsafeOperate logOp\n\nsqrtOp :: ImageOperation GrayScale D32\nsqrtOp = ImgOp $ \\i -> withGenImage i (\\img -> {#call sqrtImage#} img img)\n\n-- | Calculates the square root of every pixel.\nsqrt = unsafeOperate sqrtOp\n\n-- | Operation to limit image with another image; same as 'ImageMath.min'.\nlimitToOp what = ImgOp $ \\from ->\n withGenImage from $ \\ifrom ->\n withGenImage what $ \\iwhat ->\n {#call cvMin#} ifrom iwhat ifrom\n\n-- | Limit image with another image; same as 'ImageMath.min'.\nlimitTo x y = unsafeOperate (limitToOp x) y\n\n-- | Calculates the per-pixel product of two images.\nmul = mkBinaryImageOp\n (\\a b c -> {#call cvMul#} a b c 1)\n\n-- | Calculates the per-pixel division of two images.\ndiv = mkBinaryImageOp\n (\\a b c -> {#call cvDiv#} a b c 1)\n\n-- | Calculates the per-pixel minimum of two images.\nmin = mkBinaryImageOp {#call cvMin#}\n\n-- | Calculates the per-pixel maximum of two images.\nmax = mkBinaryImageOp {#call cvMax#}\n\n-- | Calculates the per-pixel absolute difference of two images.\nabsDiff = mkBinaryImageOp {#call cvAbsDiff#}\n\n-- | Calculates the atan of every pixel.\natan :: Image GrayScale D32 -> Image GrayScale D32\natan i = unsafePerformIO $ do\n let (w,h) = getSize i\n res <- create (w,h)\n withImage i $ \\s ->\n withImage res $ \\r -> do\n {#call calculateAtan#} s r\n return res\n\n-- | Calculates the atan2 of pixel values in two images.\natan2 :: Image GrayScale D32 -> Image GrayScale D32 -> Image GrayScale D32\natan2 a b = unsafePerformIO $ do\n res <- create (getSize a)\n withImage a $ \\c_a ->\n withImage b $ \\c_b ->\n withImage res $ \\c_res -> do\n {#call calculateAtan2#} c_a c_b c_res\n return res\n\n\n-- Operation that subtracts image mean from image\nsubtractMeanAbsOp = ImgOp $ \\image -> do\n av <- average' image\n withGenImage image $ \\i ->\n {#call wrapAbsDiffS#} i (realToFrac av) i -- TODO: check C datatype sizes\n\n-- | Calculates the absolute difference of every pixel to image mean.\n-- See also 'ImageMath.subMean'.\nsubMeanAbs = unsafeOperate subtractMeanAbsOp\n\n-- | Logical inversion of image (ie. invert, but stay on [0..1] range;\n-- multiply by @-1@ and add @1@).\ninvert i = addS 1 $ mulS (-1) i\n\nnotOp :: ImageOperation GrayScale D8\nnotOp = ImgOp $ \\image -> withGenImage image $ \\i -> {#call cvNot#} i i\n\nnot :: Image GrayScale D8 -> Image GrayScale D8\nnot = unsafeOperate notOp\n\nandOp :: Image GrayScale D8 -> Mask -> ImageOperation GrayScale D8\nandOp image0 mask = ImgOp $ \\image1 -> \n withGenImage image0 $ \\ci0 ->\n withGenImage image1 $ \\ci1 -> \n withMask mask $ \\cmask -> \n {#call cvAnd#} ci0 ci1 ci1 cmask\n\nand :: Image GrayScale D8 -> Image GrayScale D8 -> Mask -> Image GrayScale D8 \nand i j mask = unsafeOperate (andOp i mask) j\n\norOp :: Image GrayScale D8 -> Mask -> ImageOperation GrayScale D8\norOp image0 mask = ImgOp $ \\image1 -> \n withGenImage image0 $ \\ci0 ->\n withGenImage image1 $ \\ci1 -> \n withMask mask $ \\cmask -> \n {#call cvOr#} ci0 ci1 ci1 cmask\n\nor :: Image GrayScale D8 -> Image GrayScale D8 -> Mask -> Image GrayScale D8 \nor i j mask = unsafeOperate (orOp i mask) j\n\nabsOp = ImgOp $ \\image -> do\n withGenImage image $ \\i ->\n {#call wrapAbsDiffS#} i 0 i\n\n-- | Calculates the absolute value of every pixel.\nabs = unsafeOperate absOp\n\nsubtractMeanOp :: ImageOperation GrayScale D32\nsubtractMeanOp = ImgOp $ \\image -> do\n let s = CV.ImageMath.sum image\n let mean = s \/ (fromIntegral $ getArea image )\n let (ImgOp subop) = subRSOp (realToFrac mean)\n subop image\n\n-- | Calculates the (non-absolute) difference of every pixel to image mean.\n-- See also 'ImageMath.subMeanAbs'.\nsubMean = unsafeOperate subtractMeanOp\n\nsubRSOp :: D32 -> ImageOperation GrayScale D32\nsubRSOp scalar = ImgOp $ \\a ->\n withGenImage a $ \\ia -> do\n {#call wrapSubRS#} ia (realToFrac scalar) ia\n\n-- | Subtracts a scalar from every pixel, scalar on right.\nsubRS s a= unsafeOperate (subRSOp s) a\n\nsubSOp scalar = ImgOp $ \\a ->\n withGenImage a $ \\ia -> do\n {#call wrapSubS#} ia (realToFrac scalar) ia\n\n-- | Subtracts a scalar from every pixel, scalar on left.\nsubS a s = unsafeOperate (subSOp s) a\n\n-- Multiply the image with scalar\nmulSOp :: D32 -> ImageOperation GrayScale D32\nmulSOp scalar = ImgOp $ \\a ->\n withGenImage a $ \\ia -> do\n {#call cvConvertScale#} ia ia s 0\n return ()\n where s = realToFrac scalar\n -- I've heard this will lose information\n\n-- | Multiplies every pixel by a scalar.\nmulS s = unsafeOperate $ mulSOp s\n\nmkImgScalarOp op scalar = ImgOp $ \\a ->\n withGenImage a $ \\ia -> do\n op ia (realToFrac scalar) ia\n return ()\n\n-- TODO: Relax the addition so it works on multiple image depths\naddSOp :: D32 -> ImageOperation GrayScale D32\naddSOp = mkImgScalarOp $ {#call wrapAddS#}\n\n-- | Adds a scalar to every pixel.\naddS s = unsafeOperate $ addSOp s\n\nminSOp = mkImgScalarOp $ {#call cvMinS#}\n\n-- | Calculates the per-pixel minimum between an image and a scalar.\nminS :: Float -> Image c d -> Image c d\nminS s = unsafeOperate $ minSOp s\n\nmaxSOp = mkImgScalarOp $ {#call cvMaxS#}\n\n-- | Calculates the per-pixel maximum between an image and a scalar.\nmaxS :: Float -> Image c d -> Image c d\nmaxS s = unsafeOperate $ maxSOp s\n\n\n-- Comparison operators\ncmpEQ = 0\ncmpGT = 1\ncmpGE = 2\ncmpLT = 3\ncmpLE = 4\ncmpNE = 5\n\n-- TODO: For some reason the below was going through 8U images. Investigate\nmkCmpOp :: CInt -> D32 -> (Image GrayScale D32 -> Image GrayScale D8)\nmkCmpOp cmp = \\scalar a -> unsafePerformIO $\n withGenImage a $ \\ia -> do\n new <- create (getSize a) --8UC1\n withGenImage new $ \\cl -> do\n {#call cvCmpS#} ia (realToFrac scalar) cl cmp\n --imageTo32F new\n return new\n\n-- TODO: For some reason the below was going through 8U images. Investigate\nmkCmp2Op :: (CreateImage (Image GrayScale d)) =>\n CInt -> (Image GrayScale d -> Image GrayScale d -> Image GrayScale D8)\nmkCmp2Op cmp = \\imgA imgB -> unsafePerformIO $ do\n withGenImage imgA $ \\ia -> do\n withGenImage imgB $ \\ib -> do\n new <- create (getSize imgA) -- 8U\n withGenImage new $ \\cl -> do\n {#call cvCmp#} ia ib cl cmp\n return new\n --imageTo32F new\n\n-- | Compares each pixel to a scalar, and produces a binary image where the\n-- pixel value is less than the scalar. For example, @(lessThan s I)@ has\n-- white pixels where value of I is less than s. Notice that the order of\n-- operands is opposite to the intuitive interpretation of @s ``lessThan`` I@.\nlessThan :: D32 -> Image GrayScale D32 -> Image GrayScale D8\nlessThan = mkCmpOp cmpLT\n\n-- | Compares each pixel to a scalar, and produces a binary image where the\n-- pixel value is greater than the scalar. For example, @(moreThan s I)@ has\n-- white pixels where value of I is greater than s. Notice that the order of\n-- operands is opposite to the intuitive interpretation of @s ``moreThan`` I@.\nmoreThan :: D32 -> Image GrayScale D32 -> Image GrayScale D8\nmoreThan = mkCmpOp cmpGT\n\n-- | Compares two images and produces a binary image that has white pixels in\n-- those positions where the comparison is true. For example,\n-- @(less2Than A B)@ has white pixels where value of A is less than value of\n-- B. Notice that these functions follow the intuitive order of operands,\n-- unlike 'lessThan' and 'moreThan'.\nless2Than,lessEq2Than,more2Than, moreEq2Than\n :: (CreateImage (Image GrayScale d)) => Image GrayScale d -> Image GrayScale d -> Image GrayScale D8\n\nless2Than = mkCmp2Op cmpLT\nlessEq2Than = mkCmp2Op cmpLE\nmoreEq2Than = mkCmp2Op cmpGE\nmore2Than = mkCmp2Op cmpGT\n\n-- Statistics\n\naverage' :: Image GrayScale D32 -> IO D32\naverage' img = withGenImage img $ \\image -> \n {#call wrapAvg#} image nullPtr >>= return . realToFrac\n\n-- | Calculates the average pixel value in whole image.\naverage :: Image GrayScale D32 -> D32\naverage = realToFrac.unsafePerformIO.average'\n\n-- | Calculates the average value for pixels that have non-zero mask value.\naverageMask :: Image GrayScale D32 -> Image GrayScale D8 -> D32\naverageMask img mask = unsafePerformIO $\n withGenImage img $ \\c_image -> \n withGenImage mask $ \\c_mask -> \n {#call wrapAvg#} c_image c_mask >>= return . realToFrac\n\n-- | Calculates the sum of pixel values in whole image\n-- (notice that OpenCV automatically casts the result to double).\nsum :: Image GrayScale D32 -> D32\nsum img = realToFrac $ unsafePerformIO $ withGenImage img $ \\image ->\n {#call wrapSum#} image\n\n-- | Calculates the average of multiple images by adding the pixel values and\n-- dividing the resulting values by number of images.\naverageImages is = ( (1\/(fromIntegral $ length is)) `mulS`) (foldl1 add is)\n\n-- sum img = unsafePerformIO $ withGenImage img $ \\image ->\n-- {#call wrapSum#} image\n\nstdDeviation' img = withGenImage img {#call wrapStdDev#}\n\n-- | Calculates the standard deviation of pixel values in whole image.\nstdDeviation :: Image GrayScale D32 -> D32\nstdDeviation = realToFrac . unsafePerformIO . stdDeviation'\n\n-- | Calculates the standard deviation of values for pixels that have non-zero\n-- mask value.\nstdDeviationMask img mask = unsafePerformIO $\n withGenImage img $ \\i ->\n withGenImage mask $ \\m ->\n {#call wrapStdDevMask#} i m\n\n\npeekFloatConv :: (Storable a, RealFloat a, RealFloat b) => Ptr a -> IO b\npeekFloatConv a = fmap realToFrac (peek a)\n\n\n{#fun wrapMinMax as findMinMax'\n { withGenBareImage* `BareImage'\n , withGenBareImage* `BareImage'\n , alloca- `D32' peekFloatConv*\n , alloca- `D32' peekFloatConv*} -- TODO: Check datatype sizes used in C!\n -> `()'#}\n\n-- | Finds the minimum and maximum pixel value in the image and the locations\n-- where these values were found.\nfindMinMaxLoc img = unsafePerformIO $\n\t alloca $ \\(ptrintmaxx :: Ptr CInt)->\n\t alloca $ \\(ptrintmaxy :: Ptr CInt)->\n alloca $ \\(ptrintminx :: Ptr CInt)->\n alloca $ \\(ptrintminy :: Ptr CInt)->\n alloca $ \\(ptrintmin :: Ptr CDouble)->\n alloca $ \\(ptrintmax :: Ptr CDouble)->\n withImage img $ \\cimg -> do {\n {#call wrapMinMaxLoc#} cimg ptrintminx ptrintminy ptrintmaxx ptrintmaxy ptrintmin ptrintmax;\n\t\t minx <- fromIntegral <$> peek ptrintminx;\n\t\t miny <- fromIntegral <$> peek ptrintminy;\n\t\t maxx <- fromIntegral <$> peek ptrintmaxx;\n\t\t maxy <- fromIntegral <$> peek ptrintmaxy;\n\t\t maxval <- realToFrac <$> peek ptrintmax;\n\t\t minval <- realToFrac <$> peek ptrintmin;\n return (((minx,miny),minval),((maxx,maxy),maxval));}\n\n-- TODO: create one function findMinMaxLoc' which takes also mask and base\n-- findMinMax, findMinMaxLoc and findMinMaxMask (findMinMaxLocMask?) on it\n\n-- findMinMax and findMinMaxLoc using the new bindings of cvMinMaxLoc...\n-- do these really work also with D8 images? depends on fractional instance?\n-- maybe create a new class or add a function to some existing class that\n-- allows to get a pixel value from float..\n\n-- | Finds the minimum and maximum pixel value in the image.\nimageMinMax :: (Fractional d) => Image GrayScale d -> (d,d)\nimageMinMax image = unsafePerformIO $ do\n withImage image $ \\pimage -> do\n let\n minval :: CDouble\n minval = 0\n maxval :: CDouble\n maxval = 0\n with minval $ \\pminval ->\n with maxval $ \\pmaxval -> do\n c'cvMinMaxLoc (castPtr pimage) pminval pmaxval nullPtr nullPtr nullPtr\n minv <- peek pminval\n maxv <- peek pmaxval\n return ((realToFrac minv), (realToFrac maxv))\n\n-- | Finds the minimum and maximum pixel value in the image.\nimageMinMaxLoc :: (Fractional d) => Image GrayScale d -> (((Int,Int),d), ((Int,Int),d))\nimageMinMaxLoc image = unsafePerformIO $ do\n withImage image $ \\pimage -> do\n let\n minval :: CDouble\n minval = 0\n maxval :: CDouble\n maxval = 0\n minloc :: C'CvPoint\n minloc = C'CvPoint 0 0\n maxloc :: C'CvPoint\n maxloc = C'CvPoint 0 0\n with minval $ \\pminval ->\n with maxval $ \\pmaxval ->\n with minloc $ \\pminloc ->\n with maxloc $ \\pmaxloc -> do\n c'cvMinMaxLoc (castPtr pimage) pminval pmaxval pminloc pmaxloc nullPtr\n minv <- peek pminval\n (C'CvPoint minx miny) <- peek pminloc\n maxv <- peek pmaxval\n (C'CvPoint maxx maxy) <- peek pmaxloc\n return $\n (((fromIntegral minx, fromIntegral miny), realToFrac minv),\n ((fromIntegral maxx, fromIntegral maxy), realToFrac maxv))\n\n-- TODO: enable using a mask\n-- | Calculates the average and standard deviation of pixel values in the image\n-- in one operation.\nimageAvgSdv :: (Fractional d) => Image GrayScale d -> (d,d)\nimageAvgSdv i = unsafePerformIO $ do\n withImage i $ \\i_ptr -> do\n let\n avg = (C'CvScalar 0 0 0 0)\n sdv = (C'CvScalar 0 0 0 0)\n with avg $ \\avg_ptr ->\n with sdv $ \\sdv_ptr -> do\n c'cvAvgSdv (castPtr i_ptr) avg_ptr sdv_ptr nullPtr\n (C'CvScalar a1 _ _ _) <- peek avg_ptr\n (C'CvScalar s1 _ _ _) <- peek sdv_ptr\n return (realToFrac a1, realToFrac s1)\n\n-- | Finds the minimum and maximum pixel value in the image.\nfindMinMax i = unsafePerformIO $ do\n nullp <- newForeignPtr_ nullPtr\n (findMinMax' (unS i) (BareImage nullp))\n\n-- | Finds the minimum and maximum value for pixels with non-zero mask value.\nfindMinMaxMask i mask = unsafePerformIO (findMinMax' i mask)\n\n-- let a = getAllPixels i in (minimum a,maximum a)\n\n-- | Utility functions for getting the maximum or minimum pixel value of the \n-- image; equal to @snd . findMinMax@ and @fst . findMinMax@.\nmaxValue,minValue :: Image GrayScale D32 -> D32\nmaxValue = snd.findMinMax\nminValue = fst.findMinMax\n\n-- | Render image of 2D gaussian curve with standard deviation of (stdX,stdY) to image size (w,h)\n-- The origin\/center of curve is in center of the image.\ngaussianImage :: (Int,Int) -> (Double,Double) -> Image GrayScale D32\ngaussianImage (w,h) (stdX,stdY) = unsafePerformIO $ do\n dst <- create (w,h) -- 32F_C1\n withImage dst $ \\d-> do\n {#call render_gaussian#} d (realToFrac stdX) (realToFrac stdY)\n return dst\n\n-- | Produce white image with 'edgeW' amount of edges fading to black.\nfadedEdgeImage (w,h) edgeW = unsafePerformIO $\u00a0creatingImage ({#call fadedEdges#} w h edgeW)\n\n-- | Produce image where pixel is coloured according to distance from the edge.\nfadeToCenter (w,h) = unsafePerformIO $\u00a0creatingImage ({#call rectangularDistance#} w h )\n\n-- TODO: Fix C-code of masked_merge to accept D8 input for the mask\n-- | Merge two images according to a mask. Result is @R = A*m + B*(m-1)@.\nmaskedMerge :: Image GrayScale D8 -> Image GrayScale D32 -> Image GrayScale D32 -> Image GrayScale D32\nmaskedMerge mask img img2 = unsafePerformIO $ do\n res <- create (getSize img) -- 32FC1\n withImage img $ \\cimg ->\n withImage img2 $ \\cimg2 ->\n withImage res $ \\cres ->\n withImage (unsafeImageTo32F mask) $ \\cmask ->\n {#call masked_merge#} cimg cmask cimg2 cres\n return res\n\n-- | Given a distance map and a circle, return the biggest circle with radius less\n-- than given in the distance map that fully covers the previous one.\nmaximalCoveringCircle distMap (x,y,r)\n = unsafePerformIO $\n withImage distMap $ \\c_distmap ->\n alloca $ \\(ptr_int_max_x :: Ptr CInt) ->\n alloca $ \\(ptr_int_max_y :: Ptr CInt) ->\n alloca $ \\(ptr_double_max_r :: Ptr CDouble) ->\n do\n {#call maximal_covering_circle#} x y r c_distmap ptr_int_max_x ptr_int_max_y ptr_double_max_r\n max_x <- fromIntegral <$> peek ptr_int_max_x\n max_y <- fromIntegral <$> peek ptr_int_max_y\n max_r <- realToFrac <$> peek ptr_double_max_r\n return (max_x,max_y,max_r)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"c31c36808b9249d7bc77b55c8eb861eeceb13771","subject":"Some work on commit.h","message":"Some work on commit.h\n","repos":"norm2782\/hgit2","old_file":"Git2.chs","new_file":"Git2.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\n#include \"git2.h\"\n\nmodule Git2 where\n\nimport Data.ByteString\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\nimport System.IO.Unsafe\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype CPtr = Ptr ()\ntype Ptr2Int = CPtr -> IO CInt\n\nnewtype ObjDB = ObjDB CPtr\nnewtype Repository = Repository CPtr\nnewtype Index = Index CPtr\nnewtype Blob = Blob CPtr\nnewtype ObjID = ObjID CPtr\nnewtype Commit = Commit CPtr\nnewtype Signature = Signature CPtr\n\ndefaultPort :: String\ndefaultPort = \"9418\" -- TODO: Import from net.h?\n\n{#enum define Direction { GIT_DIR_FETCH as Fetch\n , GIT_DIR_PUSH as Push}#}\n\n{-\n#define GIT_STATUS_CURRENT 0\n\/** Flags for index status *\/\n#define GIT_STATUS_INDEX_NEW (1 << 0)\n#define GIT_STATUS_INDEX_MODIFIED (1 << 1)\n#define GIT_STATUS_INDEX_DELETED (1 << 2)\n\n\/** Flags for worktree status *\/\n#define GIT_STATUS_WT_NEW (1 << 3)\n#define GIT_STATUS_WT_MODIFIED (1 << 4)\n#define GIT_STATUS_WT_DELETED (1 << 5)\n\n\/\/ TODO Ignored files not handled yet\n#define GIT_STATUS_IGNORED (1 << 6)\n-}\n\n{-\n{#enum define Status { GIT_STATUS_CURRENT as Current\n , GIT_STATUS_INDEX_NEW as NewIndex\n , GIT_STATUS_INDEX_MODIFIED as ModifiedIndex\n , GIT_STATUS_INDEX_DELETED as DeletedIndex\n , GIT_STATUS_WT_NEW as NewWorkTree\n , GIT_STATUS_WT_MODIFIED as ModifiedWorkTree\n , GIT_STATUS_WT_DELETED as DeletedWorkTree\n , GIT_STATUS_IGNORED as Ignored}#}\n-}\n\n{#enum git_otype as OType {underscoreToCase}#}\n{#enum git_rtype as RType {underscoreToCase}#}\n{#enum git_repository_pathid as RepositoryPathID {underscoreToCase}#}\n{#enum git_error as GitError {underscoreToCase}#}\n{#enum git_odb_streammode as ODBStreamMode {underscoreToCase}#}\n\nderiving instance Show GitError\n\n-------------------------------------------------------------------------------\n-- BEGIN: blob.h\n-------------------------------------------------------------------------------\n\n{-\n\/**\n * Get a read-only buffer with the raw content of a blob.\n *\n * A pointer to the raw content of a blob is returned;\n * this pointer is owned internally by the object and shall\n * not be free'd. The pointer may be invalidated at a later\n * time.\n *\n * @param blob pointer to the blob\n * @return the pointer; NULL if the blob has no contents\n *\/\nGIT_EXTERN(const void *) git_blob_rawcontent(git_blob *blob);\n-}\n-- TODO: Could the next two be made \"pure\"\n-- TODO: Figure out what this function should return...\nrawBlobContent :: Blob -> IO CPtr\nrawBlobContent (Blob b) = {#call git_blob_rawcontent#} b\n\nrawBlobSize :: Blob -> IO Int\nrawBlobSize (Blob b) = return . fromIntegral =<< {#call git_blob_rawsize#} b\n\nblobFromFile :: ObjID -> Repository -> String -> IO (Maybe GitError)\nblobFromFile (ObjID obj) (Repository repo) path = do\n pathStr <- newCString path\n res <- {#call git_blob_create_fromfile #} obj repo pathStr\n retMaybeRes res\n\nretMaybeRes :: CInt -> IO (Maybe GitError)\nretMaybeRes res | res == 0 = return Nothing\n | otherwise = return $ Just . toEnum . fromIntegral $ res\n\nblobFromBuffer :: ObjID -> Repository -> CPtr -> IO (Maybe GitError)\nblobFromBuffer (ObjID objId) (Repository repo) buf = do\n res <- {#call git_blob_create_frombuffer#} objId repo buf\n (fromIntegral $ sizeOf buf)\n retMaybeRes res\n\n-------------------------------------------------------------------------------\n-- END: blob.h\n-------------------------------------------------------------------------------\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: commit.h\n-------------------------------------------------------------------------------\n\ncommitId :: Commit -> ObjID\ncommitId (Commit c) = unsafePerformIO $\n return . ObjID =<< {#call unsafe git_commit_id#} c\n\nshortCommitMsg :: Commit -> String\nshortCommitMsg (Commit c) = unsafePerformIO $\n peekCString =<< {#call unsafe git_commit_message_short#} c\n\ncommitMsg :: Commit -> String\ncommitMsg (Commit c) = unsafePerformIO $\n peekCString =<< {#call unsafe git_commit_message#} c\n\ncommitTime :: Commit -> TimeT\ncommitTime (Commit c) = unsafePerformIO $\n return =<< {#call unsafe git_commit_time#} c\n\ntimeOffset :: Commit -> Int\ntimeOffset (Commit c) = unsafePerformIO $\n return . fromIntegral =<< {#call unsafe git_commit_time_offset#} c\n\ncommitter :: Commit -> Signature\ncommitter (Commit c) = unsafePerformIO $\n return . Signature =<< {#call unsafe git_commit_committer#} c\n\nauthor :: Commit -> Signature\nauthor (Commit c) = unsafePerformIO $\n return . Signature =<< {#call unsafe git_commit_author#} c\n\n{-\n\/**\n * Get the tree pointed to by a commit.\n *\n * @param tree_out pointer where to store the tree object\n * @param commit a previously loaded commit.\n * @return 0 on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_commit_tree(git_tree **tree_out, git_commit *commit);\n\n\/**\n * Get the id of the tree pointed to by a commit. This differs from\n * `git_commit_tree` in that no attempts are made to fetch an object\n * from the ODB.\n *\n * @param commit a previously loaded commit.\n * @return the id of tree pointed to by commit.\n *\/\nGIT_EXTERN(const git_oid *) git_commit_tree_oid(git_commit *commit);\n\n\/**\n * Get the number of parents of this commit\n *\n * @param commit a previously loaded commit.\n * @return integer of count of parents\n *\/\nGIT_EXTERN(unsigned int) git_commit_parentcount(git_commit *commit);\n\n\/**\n * Get the specified parent of the commit.\n *\n * @param parent Pointer where to store the parent commit\n * @param commit a previously loaded commit.\n * @param n the position of the parent (from 0 to `parentcount`)\n * @return 0 on success; error code otherwise\n *\/\nGIT_EXTERN(int) git_commit_parent(git_commit **parent, git_commit *commit, unsigned int n);\n\n\/**\n * Get the oid of a specified parent for a commit. This is different from\n * `git_commit_parent`, which will attempt to load the parent commit from\n * the ODB.\n *\n * @param commit a previously loaded commit.\n * @param n the position of the parent (from 0 to `parentcount`)\n * @return the id of the parent, NULL on error.\n *\/\nGIT_EXTERN(const git_oid *) git_commit_parent_oid(git_commit *commit, unsigned int n);\n\n\/**\n * Create a new commit in the repository using `git_object`\n * instances as parameters.\n *\n * @param oid Pointer where to store the OID of the\n *\tnewly created commit\n *\n * @param repo Repository where to store the commit\n *\n * @param update_ref If not NULL, name of the reference that\n *\twill be updated to point to this commit. If the reference\n *\tis not direct, it will be resolved to a direct reference.\n *\tUse \"HEAD\" to update the HEAD of the current branch and\n *\tmake it point to this commit\n *\n * @param author Signature representing the author and the authory\n *\ttime of this commit\n *\n * @param committer Signature representing the committer and the\n * commit time of this commit\n *\n * @param message Full message for this commit\n *\n * @param tree An instance of a `git_tree` object that will\n * be used as the tree for the commit. This tree object must\n * also be owned by the given `repo`.\n *\n * @param parent_count Number of parents for this commit\n *\n * @param parents[] Array of `parent_count` pointers to `git_commit`\n * objects that will be used as the parents for this commit. This\n * array may be NULL if `parent_count` is 0 (root commit). All the\n * given commits must be owned by the `repo`.\n *\n * @return 0 on success; error code otherwise\n *\tThe created commit will be written to the Object Database and\n *\tthe given reference will be updated to point to it\n *\/\nGIT_EXTERN(int) git_commit_create(\n\t\tgit_oid *oid,\n\t\tgit_repository *repo,\n\t\tconst char *update_ref,\n\t\tconst git_signature *author,\n\t\tconst git_signature *committer,\n\t\tconst char *message,\n\t\tconst git_tree *tree,\n\t\tint parent_count,\n\t\tconst git_commit *parents[]);\n\n\/**\n * Create a new commit in the repository using a variable\n * argument list.\n *\n * The parents for the commit are specified as a variable\n * list of pointers to `const git_commit *`. Note that this\n * is a convenience method which may not be safe to export\n * for certain languages or compilers\n *\n * All other parameters remain the same\n *\n * @see git_commit_create\n *\/\nGIT_EXTERN(int) git_commit_create_v(\n\t\tgit_oid *oid,\n\t\tgit_repository *repo,\n\t\tconst char *update_ref,\n\t\tconst git_signature *author,\n\t\tconst git_signature *committer,\n\t\tconst char *message,\n\t\tconst git_tree *tree,\n\t\tint parent_count,\n\t\t...);\n-}\n\n-------------------------------------------------------------------------------\n-- END: commit.h\n-------------------------------------------------------------------------------\n\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: repositoy.h\n-------------------------------------------------------------------------------\n\nrepoIs :: Ptr2Int -> Repository -> IO Bool\nrepoIs ffi (Repository ptr) = return . toBool =<< ffi ptr\n\nopenRepo :: String -> IO (Either GitError Repository)\nopenRepo path = alloca $ \\pprepo -> do\n pstr <- newCString path\n res <- {#call git_repository_open#} pprepo pstr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nopenRepoObjDir :: String -> String -> String -> String\n -> IO (Either GitError Repository)\nopenRepoObjDir dir objDir idxFile workTree = alloca $ \\pprepo -> do\n dirStr <- newCString dir\n objDStr <- newCString objDir\n idxFStr <- newCString idxFile\n wtrStr <- newCString workTree\n res <- {#call git_repository_open2#} pprepo dirStr objDStr idxFStr wtrStr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nopenRepoObjDb :: String -> ObjDB -> String -> String\n -> IO (Either GitError Repository)\nopenRepoObjDb dir (ObjDB db) idxFile workTree = alloca $ \\pprepo -> do\n dirStr <- newCString dir\n idxFStr <- newCString idxFile\n wtrStr <- newCString workTree\n res <- {#call git_repository_open3#} pprepo dirStr db idxFStr wtrStr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\ndiscover :: String -> Bool -> String -> IO (Either GitError String)\ndiscover startPath acrossFs ceilingDirs = alloca $ \\path -> do\n spStr <- newCString startPath\n cdsStr <- newCString ceilingDirs\n res <- {#call git_repository_discover#} path (fromIntegral $ sizeOf path)\n spStr (fromBool acrossFs) cdsStr\n retEither res $ fmap Right $ peekCString path\n\ndatabase :: Repository -> IO ObjDB\ndatabase (Repository r) = return . ObjDB =<< {#call git_repository_database#} r\n\nindex :: Repository -> IO (Either GitError Index)\nindex (Repository r) = alloca $ \\idx -> do\n res <- {#call git_repository_index#} idx r\n retEither res $ fmap (Right . Index) $ peek idx\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\ninit :: String -> Bool -> IO (Either GitError Repository)\ninit path isBare = alloca $ \\pprepo -> do\n pstr <- newCString path\n res <- {#call git_repository_init#} pprepo pstr (fromBool isBare)\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nretEither :: CInt -> IO (Either GitError a) -> IO (Either GitError a)\nretEither res f | res == 0 = f\n | otherwise = return . Left . toEnum . fromIntegral $ res\n\nisHeadDetached :: Repository -> IO Bool\nisHeadDetached = repoIs {#call git_repository_head_detached#}\n\nisHeadOrphan :: Repository -> IO Bool\nisHeadOrphan = repoIs {#call git_repository_head_orphan#}\n\nisEmpty :: Repository -> IO Bool\nisEmpty = repoIs {#call git_repository_is_empty#}\n\npath :: Repository -> RepositoryPathID -> IO String\npath (Repository r) pathID = peekCString =<< {#call git_repository_path#} r p\n where p = fromIntegral $ fromEnum pathID\n\nisBare :: Repository -> IO Bool\nisBare = repoIs {#call git_repository_is_bare#}\n\n-------------------------------------------------------------------------------\n-- END: repository.h\n-------------------------------------------------------------------------------\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE StandaloneDeriving #-}\n\n#include \"git2.h\"\n\nmodule Git2 where\n\nimport Data.ByteString\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\ntype OffT = {#type git_off_t#}\ntype TimeT = {#type git_time_t#}\ntype CPtr = Ptr ()\ntype Ptr2Int = CPtr -> IO CInt\n\nnewtype ObjDB = ObjDB CPtr\nnewtype Repository = Repository CPtr\nnewtype Index = Index CPtr\nnewtype Blob = Blob CPtr\nnewtype ObjID = ObjID CPtr\n\ndefaultPort :: String\ndefaultPort = \"9418\" -- TODO: Import from net.h?\n\n{#enum define Direction { GIT_DIR_FETCH as Fetch\n , GIT_DIR_PUSH as Push}#}\n\n{-\n#define GIT_STATUS_CURRENT 0\n\/** Flags for index status *\/\n#define GIT_STATUS_INDEX_NEW (1 << 0)\n#define GIT_STATUS_INDEX_MODIFIED (1 << 1)\n#define GIT_STATUS_INDEX_DELETED (1 << 2)\n\n\/** Flags for worktree status *\/\n#define GIT_STATUS_WT_NEW (1 << 3)\n#define GIT_STATUS_WT_MODIFIED (1 << 4)\n#define GIT_STATUS_WT_DELETED (1 << 5)\n\n\/\/ TODO Ignored files not handled yet\n#define GIT_STATUS_IGNORED (1 << 6)\n-}\n\n{-\n{#enum define Status { GIT_STATUS_CURRENT as Current\n , GIT_STATUS_INDEX_NEW as NewIndex\n , GIT_STATUS_INDEX_MODIFIED as ModifiedIndex\n , GIT_STATUS_INDEX_DELETED as DeletedIndex\n , GIT_STATUS_WT_NEW as NewWorkTree\n , GIT_STATUS_WT_MODIFIED as ModifiedWorkTree\n , GIT_STATUS_WT_DELETED as DeletedWorkTree\n , GIT_STATUS_IGNORED as Ignored}#}\n-}\n\n{#enum git_otype as OType {underscoreToCase}#}\n{#enum git_rtype as RType {underscoreToCase}#}\n{#enum git_repository_pathid as RepositoryPathID {underscoreToCase}#}\n{#enum git_error as GitError {underscoreToCase}#}\n{#enum git_odb_streammode as ODBStreamMode {underscoreToCase}#}\n\nderiving instance Show GitError\n\n-------------------------------------------------------------------------------\n-- BEGIN: blob.h\n-------------------------------------------------------------------------------\n\n{-\n\/**\n * Get a read-only buffer with the raw content of a blob.\n *\n * A pointer to the raw content of a blob is returned;\n * this pointer is owned internally by the object and shall\n * not be free'd. The pointer may be invalidated at a later\n * time.\n *\n * @param blob pointer to the blob\n * @return the pointer; NULL if the blob has no contents\n *\/\nGIT_EXTERN(const void *) git_blob_rawcontent(git_blob *blob);\n-}\n-- TODO: Could the next two be made \"pure\"\n-- TODO: Figure out what this function should return...\nrawBlobContent :: Blob -> IO CPtr\nrawBlobContent (Blob b) = {#call git_blob_rawcontent#} b\n\nrawBlobSize :: Blob -> IO Int\nrawBlobSize (Blob b) = return . fromIntegral =<< {#call git_blob_rawsize#} b\n\nblobFromFile :: ObjID -> Repository -> String -> IO (Maybe GitError)\nblobFromFile (ObjID obj) (Repository repo) path = do\n pathStr <- newCString path\n res <- {#call git_blob_create_fromfile #} obj repo pathStr\n retMaybeRes res\n\nretMaybeRes :: CInt -> IO (Maybe GitError)\nretMaybeRes res | res == 0 = return Nothing\n | otherwise = return $ Just . toEnum . fromIntegral $ res\n\nblobFromBuffer :: ObjID -> Repository -> CPtr -> Int -> IO (Maybe GitError)\nblobFromBuffer (ObjID objid) (Repository repo) buf n = do\n res <- {#call git_blob_create_frombuffer#} objid repo buf (fromIntegral n)\n retMaybeRes res\n\n-------------------------------------------------------------------------------\n-- END: blob.h\n-------------------------------------------------------------------------------\n\n\n\n-------------------------------------------------------------------------------\n-- BEGIN: repositoy.h\n-------------------------------------------------------------------------------\n\nrepoIs :: Ptr2Int -> Repository -> IO Bool\nrepoIs ffi (Repository ptr) = return . toBool =<< ffi ptr\n\nopenRepo :: String -> IO (Either GitError Repository)\nopenRepo path = alloca $ \\pprepo -> do\n pstr <- newCString path\n res <- {#call git_repository_open#} pprepo pstr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nopenRepoObjDir :: String -> String -> String -> String\n -> IO (Either GitError Repository)\nopenRepoObjDir dir objDir idxFile workTree = alloca $ \\pprepo -> do\n dirStr <- newCString dir\n objDStr <- newCString objDir\n idxFStr <- newCString idxFile\n wtrStr <- newCString workTree\n res <- {#call git_repository_open2#} pprepo dirStr objDStr idxFStr wtrStr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nopenRepoObjDb :: String -> ObjDB -> String -> String\n -> IO (Either GitError Repository)\nopenRepoObjDb dir (ObjDB db) idxFile workTree = alloca $ \\pprepo -> do\n dirStr <- newCString dir\n idxFStr <- newCString idxFile\n wtrStr <- newCString workTree\n res <- {#call git_repository_open3#} pprepo dirStr db idxFStr wtrStr\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\ndiscover :: String -> Bool -> String -> IO (Either GitError String)\ndiscover startPath acrossFs ceilingDirs = alloca $ \\path -> do\n spStr <- newCString startPath\n cdsStr <- newCString ceilingDirs\n res <- {#call git_repository_discover#} path (fromIntegral $ sizeOf path)\n spStr (fromBool acrossFs) cdsStr\n retEither res $ fmap Right $ peekCString path\n\ndatabase :: Repository -> IO ObjDB\ndatabase (Repository r) = return . ObjDB =<< {#call git_repository_database#} r\n\nindex :: Repository -> IO (Either GitError Index)\nindex (Repository r) = alloca $ \\idx -> do\n res <- {#call git_repository_index#} idx r\n retEither res $ fmap (Right . Index) $ peek idx\n\nfree :: Repository -> IO ()\nfree (Repository r) = {#call git_repository_free#} r\n\ninit :: String -> Bool -> IO (Either GitError Repository)\ninit path isBare = alloca $ \\pprepo -> do\n pstr <- newCString path\n res <- {#call git_repository_init#} pprepo pstr (fromBool isBare)\n retEither res $ fmap (Right . Repository) $ peek pprepo\n\nretEither :: CInt -> IO (Either GitError a) -> IO (Either GitError a)\nretEither res f | res == 0 = f\n | otherwise = return . Left . toEnum . fromIntegral $ res\n\nisHeadDetached :: Repository -> IO Bool\nisHeadDetached = repoIs {#call git_repository_head_detached#}\n\nisHeadOrphan :: Repository -> IO Bool\nisHeadOrphan = repoIs {#call git_repository_head_orphan#}\n\nisEmpty :: Repository -> IO Bool\nisEmpty = repoIs {#call git_repository_is_empty#}\n\npath :: Repository -> RepositoryPathID -> IO String\npath (Repository r) pathID = peekCString =<< {#call git_repository_path#} r p\n where p = fromIntegral $ fromEnum pathID\n\nisBare :: Repository -> IO Bool\nisBare = repoIs {#call git_repository_is_bare#}\n\n-------------------------------------------------------------------------------\n-- END: repository.h\n-------------------------------------------------------------------------------\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"d322638289ed44c8d65c58c0f0ac50988c2b4099","subject":"Fix a bug with error handling.","message":"Fix a bug with error handling.\n\nAccording to the standard, Initialized can be\ncalled before Init and Finalized can be called\nafter Finalize. So we cannot call checkError on\nthem. This was an issue when running it with\nOpen MPI.\n\nSo the following comment in the code also applies in this case:\n 242 -- XXX can't call checkError on finalize, because\n 243 -- checkError calls Internal.errorClass and Internal.errorString.\n 244 -- These cannot be called after finalize (at least on OpenMPI).\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Control\/Parallel\/MPI\/Internal.chs","new_file":"src\/Control\/Parallel\/MPI\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n#include \n#include \"init_wrapper.h\"\n#include \"comparison_result.h\"\n#include \"error_classes.h\"\n#include \"thread_support.h\"\n-----------------------------------------------------------------------------\n{- |\nModule : Control.Parallel.MPI.Internal\nCopyright : (c) 2010 Bernie Pope, Dmitry Astapov\nLicense : BSD-style\nMaintainer : florbitous@gmail.com\nStability : experimental\nPortability : ghc\n\nThis module contains low-level Haskell bindings to core MPI functions.\nAll Haskell functions correspond to MPI functions or values with the similar\nname (i.e. @commRank@ is the binding for @MPI_Comm_rank@ etc)\n\nNote that most of this module is re-exported by\n\"Control.Parallel.MPI\", so if you are not interested in writing\nlow-level code, you should probably import \"Control.Parallel.MPI\" and\neither \"Control.Parallel.MPI.Storable\" or \"Control.Parallel.MPI.Serializable\".\n-}\n-----------------------------------------------------------------------------\nmodule Control.Parallel.MPI.Internal\n (\n\n -- * MPI runtime management.\n -- ** Initialization, finalization, termination.\n init, finalize, initialized, finalized, abort,\n -- ** Multi-threaded environment support.\n ThreadSupport (..), initThread, queryThread, isThreadMain,\n\n -- ** Runtime attributes.\n getProcessorName, Version (..), getVersion, Implementation(..), getImplementation, universeSize,\n\n -- ** Info objects\n Info, infoNull, infoCreate, infoSet, infoDelete, infoGet,\n\n -- * Requests and statuses.\n Request, Status (..), getCount, test, testPtr, cancel, cancelPtr, wait, waitPtr, waitall, requestNull, \n\n -- * Process management.\n -- ** Communicators.\n Comm, commWorld, commSelf, commNull, commTestInter,\n commSize, commRemoteSize, \n commRank, \n commCompare, commFree, commGroup, commGetAttr,\n\n -- ** Process groups.\n Group, groupEmpty, groupRank, groupSize, groupUnion,\n groupIntersection, groupDifference, groupCompare, groupExcl,\n groupIncl, groupTranslateRanks,\n -- ** Comparisons.\n ComparisonResult (..),\n\n -- ** Dynamic process management\n commGetParent, commSpawn, commSpawnSimple, argvNull, errcodesIgnore,\n openPort, closePort, commAccept, commConnect, commDisconnect,\n\n -- * Error handling.\n Errhandler, errorsAreFatal, errorsReturn, errorsThrowExceptions, commSetErrhandler, commGetErrhandler,\n ErrorClass (..), MPIError(..), mpiUndefined,\n\n -- * Ranks.\n Rank, rankId, toRank, fromRank, anySource, theRoot, procNull,\n\n -- * Data types.\n Datatype, char, wchar, short, int, long, longLong, unsignedChar, unsignedShort, unsigned, unsignedLong, unsignedLongLong, float, double, longDouble, byte, packed, typeSize,\n\n -- * Point-to-point operations.\n -- ** Tags.\n Tag, toTag, fromTag, anyTag, unitTag, tagUpperBound,\n\n -- ** Blocking operations.\n BufferPtr, Count, -- XXX: what will break if we don't export those?\n send, ssend, rsend, recv,\n -- ** Non-blocking operations.\n isend, issend, irecv,\n isendPtr, issendPtr, irecvPtr,\n\n\n -- * Collective operations.\n -- ** One-to-all.\n bcast, scatter, scatterv,\n -- ** All-to-one.\n gather, gatherv, reduce,\n -- ** All-to-all.\n allgather, allgatherv,\n alltoall, alltoallv,\n allreduce, \n reduceScatterBlock,\n reduceScatter,\n barrier,\n\n -- ** Reduction operations.\n Operation, maxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp,\n opCreate, opFree,\n\n -- * Timing.\n wtime, wtick, wtimeIsGlobal, wtimeIsGlobalKey\n\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Data.Maybe (fromMaybe)\nimport Control.Monad (liftM, unless)\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception\n\n{# context prefix = \"MPI\" #}\n\n-- | Pointer to memory buffer that either holds data to be sent or is\n-- used to receive some data. You would\n-- probably have to use 'castPtr' to pass some actual pointers to\n-- API functions.\ntype BufferPtr = Ptr ()\n\n-- | Count of elements in the send\/receive buffer\ntype Count = CInt\n\n{- |\nHaskell enum that contains MPI constants\n@MPI_IDENT@, @MPI_CONGRUENT@, @MPI_SIMILAR@ and @MPI_UNEQUAL@.\n\nThose are used to compare communicators ('commCompare') and\nprocess groups ('groupCompare'). Refer to those\nfunctions for description of comparison rules.\n-}\n{# enum ComparisonResult {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- Which Haskell type will be used as Comm depends on the MPI\n-- implementation that was selected during compilation. It could be\n-- CInt, Ptr (), Ptr CInt or something else.\ntype MPIComm = {# type MPI_Comm #}\n\n{- | Abstract type representing MPI communicator handle. Different MPI\n implementations use different C types to implement this, so\n concrete Haskell type behind @Comm@ is hidden from user.\n\n In any MPI program you have predefined communicator 'commWorld'\n which includes all running processes. You could create new\n communicators with TODO\n-}\nnewtype Comm = MkComm { fromComm :: MPIComm } deriving Eq\npeekComm ptr = MkComm <$> peek ptr\nwithComm comm f = alloca $ \\ptr -> do poke ptr (fromComm comm)\n f (castPtr ptr)\n\nforeign import ccall \"&mpi_comm_world\" commWorld_ :: Ptr MPIComm\nforeign import ccall \"&mpi_comm_self\" commSelf_ :: Ptr MPIComm\n\n-- | Predefined handle for communicator that includes all running\n-- processes. Similar to @MPI_Comm_world@\ncommWorld :: Comm\ncommWorld = MkComm <$> unsafePerformIO $ peek commWorld_\n\n-- | Predefined handle for communicator that includes only current\n-- process. Similar to @MPI_Comm_self@\ncommSelf :: Comm\ncommSelf = MkComm <$> unsafePerformIO $ peek commSelf_\n\nforeign import ccall \"&mpi_max_processor_name\" max_processor_name_ :: Ptr CInt\nforeign import ccall \"&mpi_max_port_name\" max_port_name_ :: Ptr CInt\nforeign import ccall \"&mpi_max_error_string\" max_error_string_ :: Ptr CInt\n\n-- | Max length of \"processor name\" as returned by 'getProcessorName'\nmaxProcessorName :: CInt\nmaxProcessorName = unsafePerformIO $ peek max_processor_name_\n\n-- | Max length of \"port name\" as returned by 'openPort'\nmaxPortName :: CInt\nmaxPortName = unsafePerformIO $ peek max_port_name_\n\n-- | Max length of error description as returned by 'errorString'\nmaxErrorString :: CInt\nmaxErrorString = unsafePerformIO $ peek max_error_string_\n\n-- | Initialize the MPI environment. The MPI environment must be intialized by each\n-- MPI process before any other MPI function is called. Note that\n-- the environment may also be initialized by the functions 'initThread', 'mpi',\n-- and 'mpiWorld'. It is an error to attempt to initialize the environment more\n-- than once for a given MPI program execution. The only MPI functions that may\n-- be called before the MPI environment is initialized are 'getVersion',\n-- 'initialized' and 'finalized'. This function corresponds to @MPI_Init@.\n{# fun unsafe init_wrapper as init {} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been initialized. Returns @True@ if the\n-- environment has been initialized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Initialized@.\n{# fun unsafe Initialized as ^ {alloca- `Bool' peekBool*} -> `()' discard*- #}\n\n-- | Determine if the MPI environment has been finalized. Returns @True@ if the\n-- environment has been finalized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Finalized@.\n{# fun unsafe Finalized as ^ {alloca- `Bool' peekBool*} -> `()' discard*- #}\n\n-- | Initialize the MPI environment with a \/required\/ level of thread support.\n-- See the documentation for 'init' for more information about MPI initialization.\n-- The \/provided\/ level of thread support is returned in the result.\n-- There is no guarantee that provided will be greater than or equal to required.\n-- The level of provided thread support depends on the underlying MPI implementation,\n-- and may also depend on information provided when the program is executed\n-- (for example, by supplying appropriate arguments to @mpiexec@).\n-- If the required level of support cannot be provided then it will try to\n-- return the least supported level greater than what was required.\n-- If that cannot be satisfied then it will return the highest supported level\n-- provided by the MPI implementation. See the documentation for 'ThreadSupport'\n-- for information about what levels are available and their relative ordering.\n-- This function corresponds to @MPI_Init_thread@.\n{# fun unsafe init_wrapper_thread as initThread\n {cFromEnum `ThreadSupport', alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\n-- | Returns the current provided level of thread support. This will be the value\n-- returned as \\\"provided level of support\\\" by 'initThread' as well. This function\n-- corresponds to @MPI_Query_thread@.\n{# fun unsafe Query_thread as ^ {alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\n-- | This function can be called by a thread to find out whether it is the main thread (the\n-- thread that called 'init' or 'initThread'.\n{# fun unsafe Is_thread_main as ^\n {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Terminate the MPI execution environment.\n-- Once 'finalize' is called no other MPI functions may be called except\n-- 'getVersion', 'initialized' and 'finalized', however non-MPI computations\n-- may continue. Each process must complete\n-- any pending communication that it initiated before calling 'finalize'.\n-- Note: the error code returned\n-- by 'finalize' is not checked. This function corresponds to @MPI_Finalize@.\n{# fun unsafe Finalize as ^ {} -> `()' discard*- #}\ndiscard _ = return ()\n-- XXX can't call checkError on finalize, because\n-- checkError calls Internal.errorClass and Internal.errorString.\n-- These cannot be called after finalize (at least on OpenMPI).\n\n-- | Return the name of the current processing host. From this value it\n-- must be possible to identify a specific piece of hardware on which\n-- the code is running.\ngetProcessorName :: IO String\ngetProcessorName = do\n allocaBytes (fromIntegral maxProcessorName) $ \\ptr -> do\n len <- getProcessorName' ptr\n peekCStringLen (ptr, cIntConv len)\n where\n getProcessorName' = {# fun unsafe Get_processor_name as getProcessorName_\n {id `Ptr CChar', alloca- `CInt' peekIntConv*} -> `()' checkError*- #}\n\n-- | MPI implementation version\ndata Version =\n Version { version :: Int, subversion :: Int }\n deriving (Eq, Ord)\n\ninstance Show Version where\n show v = show (version v) ++ \".\" ++ show (subversion v)\n\n-- | Which MPI version the code is running on.\ngetVersion :: IO Version\ngetVersion = do\n (version, subversion) <- getVersion'\n return $ Version version subversion\n where\n getVersion' = {# fun unsafe Get_version as getVersion_\n {alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Supported MPI implementations\ndata Implementation = MPICH2 | OpenMPI deriving (Eq,Show)\n\n-- | Which MPI implementation was used during linking\ngetImplementation :: Implementation\ngetImplementation =\n#ifdef MPICH2\n MPICH2\n#else\n OpenMPI\n#endif\n\n-- | Return the number of processes involved in a communicator. For 'commWorld'\n-- it returns the total number of processes available. If the communicator is\n-- and intra-communicator it returns the number of processes in the local group.\n-- This function corresponds to @MPI_Comm_size@.\n{# fun unsafe Comm_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n-- | For intercommunicators, returns size of the remote process group.\n-- Corresponds to @MPI_Comm_remote_size@.\n{# fun unsafe Comm_remote_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n{- | Check whether the given communicator is intercommunicator - that\n is, communicator connecting two different groups of processes.\n\nRefer to MPI Report v2.2, Section 5.2 \"Communicator Argument\" for\nmore details.\n-}\n{# fun unsafe Comm_test_inter as ^\n {fromComm `Comm', alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Look up MPI communicator argument by the given numeric key.\n-- Lookup of some standard MPI arguments is provided by convenience\n-- functions 'tagUpperBound' and 'wtimeIsGlobal'.\ncommGetAttr :: Storable e => Comm -> Int -> IO (Maybe e)\ncommGetAttr comm key = do\n isInitialized <- initialized\n if isInitialized then do\n alloca $ \\ptr -> do\n found <- commGetAttr' comm key (castPtr ptr)\n if found then do ptr2 <- peek ptr\n Just <$> peek ptr2\n else return Nothing\n else return Nothing\n where\n commGetAttr' = {# fun unsafe Comm_get_attr as commGetAttr_\n {fromComm `Comm', cIntConv `Int', id `Ptr ()', alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Maximum tag value supported by the current MPI implementation. Corresponds to the value of standard MPI\n-- attribute @MPI_TAG_UB@.\n--\n-- When called before 'init' or 'initThread' would return 0.\ntagUpperBound :: Int\ntagUpperBound =\n let key = unsafePerformIO (peek tagUB_)\n in fromMaybe 0 $ unsafePerformIO (commGetAttr commWorld key)\n\nforeign import ccall unsafe \"&mpi_tag_ub\" tagUB_ :: Ptr Int\n\n{- | True if clocks at all processes in\n'commWorld' are synchronized, False otherwise. The expectation is that\nthe variation in time, as measured by calls to 'wtime', will be less then one half the\nround-trip time for an MPI message of length zero. \n\nCommunicators other than 'commWorld' could have different clocks.\nYou could find it out by querying attribute 'wtimeIsGlobalKey' with 'commGetAttr'.\n\nWhen wtimeIsGlobal is called before 'init' or 'initThread' it would return False.\n-}\nwtimeIsGlobal :: Bool\nwtimeIsGlobal =\n fromMaybe False $ unsafePerformIO (commGetAttr commWorld wtimeIsGlobalKey)\n\nforeign import ccall unsafe \"&mpi_wtime_is_global\" wtimeIsGlobal_ :: Ptr Int\n\n-- | Numeric key for standard MPI communicator attribute @MPI_WTIME_IS_GLOBAL@.\n-- To be used with 'commGetAttr'.\nwtimeIsGlobalKey :: Int\nwtimeIsGlobalKey = unsafePerformIO (peek wtimeIsGlobal_)\n\n{- | \nMany ``dynamic'' MPI applications are expected to exist in a static runtime environment, in which resources have been allocated before the application is run. When a user (or possibly a batch system) runs one of these quasi-static applications, she will usually specify a number of processes to start and a total number of processes that are expected. An application simply needs to know how many slots there are, i.e., how many processes it should spawn.\n\nThis attribute indicates the total number of processes that are expected.\n\nWhen universeSize is called before 'init' or 'initThread' it would return False.\n-}\nuniverseSize :: Comm -> IO (Maybe Int)\nuniverseSize c =\n commGetAttr c universeSizeKey\n\nforeign import ccall unsafe \"&mpi_universe_size\" universeSize_ :: Ptr Int\n\n-- | Numeric key for recommended MPI communicator attribute @MPI_UNIVERSE_SIZE@.\n-- To be used with 'commGetAttr'.\nuniverseSizeKey :: Int\nuniverseSizeKey = unsafePerformIO (peek universeSize_)\n\n-- | Return the rank of the calling process for the given\n-- communicator. If it is an intercommunicator, returns rank of the\n-- process in the local group.\n{# fun unsafe Comm_rank as ^\n {fromComm `Comm', alloca- `Rank' peekIntConv* } -> `()' checkError*- #}\n\n{- | Compares two communicators.\n\n* If they are handles for the same MPI communicator object, result is 'Identical';\n\n* If both communicators are identical in constituents and rank\n order, result is `Congruent';\n\n* If they have the same members, but with different ranks, then\n result is 'Similar';\n\n* Otherwise, result is 'Unequal'.\n\n-}\n{# fun unsafe Comm_compare as ^\n {fromComm `Comm', fromComm `Comm', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- | Test for an incomming message, without actually receiving it.\n-- If a message has been sent from @Rank@ to the current process with @Tag@ on the\n-- communicator @Comm@ then 'probe' will return the 'Status' of the message. Otherwise\n-- it will block the current process until such a matching message is sent.\n-- This allows the current process to check for an incoming message and decide\n-- how to receive it, based on the information in the 'Status'.\n-- This function corresponds to @MPI_Probe@.\n-- The most common usecase is to call @probe@ first and then use 'getCount' to find out size of incoming message.\n-- However since different implementations provide additional fields in @Status@, we cannot deserialize Status into Haskell land\n-- and serialize it back without losing information. Hence the use of Ptr Status.\n{# fun Probe as ^\n {fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Status'} -> `()' checkError*- #}\n{- probe :: Rank -- ^ Rank of the sender.\n -> Tag -- ^ Tag of the sent message.\n -> Comm -- ^ Communicator.\n -> IO Status -- ^ Information about the incoming message (but not the content of the message). -}\n\n{-| Returns the number of entries received. (we count entries, each of\ntype @Datatype@, not bytes.) The datatype argument should match the\nargument provided by the receive call that set the status variable. -}\ngetCount :: Comm -> Rank -> Tag -> Datatype -> IO Int\ngetCount comm rank tag datatype =\n alloca $ \\statusPtr -> do\n probe rank tag comm statusPtr\n cnt <- getCount' statusPtr datatype\n return $ fromIntegral cnt\n where\n getCount' = {# fun unsafe Get_count as getCount_\n {castPtr `Ptr Status', fromDatatype `Datatype', alloca- `CInt' peekIntConv*} -> `()' checkError*- #}\n\n\n{-| Send the values (as specified by @BufferPtr@, @Count@, @Datatype@) to\n the process specified by (@Comm@, @Rank@, @Tag@). Caller will\n block until data is copied from the send buffer by the MPI\n-}\n{# fun unsafe Send as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{-| Variant of 'send' that would terminate only when receiving side\nactually starts receiving data. \n-}\n{# fun unsafe Ssend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{-| Variant of 'send' that expects the relevant 'recv' to be already\nstarted, otherwise this call could terminate with MPI error.\n-}\n{# fun unsafe Rsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n-- | Receives data from the process\n-- specified by (@Comm@, @Rank@, @Tag@) and stores it into buffer specified\n-- by (@BufferPtr@, @Count@, @Datatype@).\n{# fun unsafe Recv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast* } -> `()' checkError*- #}\n-- | Send the values (as specified by @BufferPtr@, @Count@, @Datatype@) to\n-- the process specified by (@Comm@, @Rank@, @Tag@) in non-blocking mode.\n-- \n-- Use 'probe' or 'test' to check the status of the operation,\n-- 'cancel' to terminate it or 'wait' to block until it completes.\n-- Operation would be considered complete as soon as MPI finishes\n-- copying the data from the send buffer. \n{# fun unsafe Isend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n-- | Variant of the 'isend' that would be considered complete only when\n-- receiving side actually starts receiving data. \n{# fun unsafe Issend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n-- | Non-blocking variant of 'recv'. Receives data from the process\n-- specified by (@Comm@, @Rank@, @Tag@) and stores it into buffer specified\n-- by (@BufferPtr@, @Count@, @Datatype@).\n{# fun Irecv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n\n-- | Like 'isend', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun unsafe Isend as isendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'issend', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun unsafe Issend as issendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'irecv', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun Irecv as irecvPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Broadcast data from one member to all members of the communicator.\n{# fun unsafe Bcast as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocks until all processes on the communicator call this function.\n-- This function corresponds to @MPI_Barrier@.\n{# fun unsafe Barrier as ^ {fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocking test for the completion of a send of receive.\n-- See 'test' for a non-blocking variant.\n-- This function corresponds to @MPI_Wait@. Request pointer could\n-- be changed to point to @requestNull@. See @wait@ for variant that does not mutate request value.\n{# fun unsafe Wait as waitPtr\n {castPtr `Ptr Request', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Same as @waitPtr@, but does not change Haskell @Request@ value to point to @procNull@.\n-- Usually, this is harmless - your request just would be considered inactive.\nwait request = withRequest request waitPtr\n\n-- | Takes pointer to the array of Requests of given size, 'wait's on all of them,\n-- populates array of Statuses of the same size. This function corresponds to @MPI_Waitall@\n{# fun unsafe Waitall as ^\n { id `Count', castPtr `Ptr Request', castPtr `Ptr Status'} -> `()' checkError*- #}\n-- TODO: Make this Storable Array instead of Ptr ?\n\n-- | Non-blocking test for the completion of a send or receive.\n-- Returns @Nothing@ if the request is not complete, otherwise\n-- it returns @Just status@.\n--\n-- Note that while MPI would modify\n-- request to be @requestNull@ if the operation is complete,\n-- Haskell value would not be changed. So, if you got (Just status)\n-- as a result, consider your request to be @requestNull@. Or use @testPtr@.\n--\n-- See 'wait' for a blocking variant.\n-- This function corresponds to @MPI_Test@.\ntest :: Request -> IO (Maybe Status)\ntest request = withRequest request testPtr\n\n-- | Analogous to 'test' but uses pointer to @Request@. If request is completed, pointer would be \n-- set to point to @requestNull@.\ntestPtr :: Ptr Request -> IO (Maybe Status)\ntestPtr reqPtr = do\n (flag, status) <- testPtr' reqPtr\n request' <- peek reqPtr\n if flag\n then do if request' == requestNull\n then return $ Just status\n else error \"testPtr: request modified, but not set to MPI_REQUEST_NULL!\"\n else return Nothing\n where testPtr' = {# fun unsafe Test as testPtr_\n {castPtr `Ptr Request', alloca- `Bool' peekBool*, allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Cancel a pending communication request.\n-- This function corresponds to @MPI_Cancel@. Sets pointer to point to @requestNull@.\n{# fun unsafe Cancel as cancelPtr\n {castPtr `Ptr Request'} -> `()' checkError*- #}\n\n\n-- | Same as @cancelPtr@, but does not change Haskell @Request@ value to point to @procNull@.\n-- Usually, this is harmless - your request just would be considered inactive.\ncancel request = withRequest request cancelPtr\n\nwithRequest req f = do alloca $ \\ptr -> do poke ptr req\n f (castPtr ptr)\n\n-- | Scatter data from one member to all members of\n-- a group.\n{# fun unsafe Scatter as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Gather data from all members of a group to one\n-- member.\n{# fun unsafe Gather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- Note: We pass counts\/displs as Ptr CInt so that caller could supply nullPtr here\n-- which would be impossible if we marshal arrays ourselves here.\n\n-- | A variation of 'scatter' which allows to use data segments of\n-- different length.\n{# fun unsafe Scatterv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'gather' which allows to use data segments of\n-- different length.\n{# fun unsafe Gatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'gather' where all members of\n-- a group receive the result.\n{# fun unsafe Allgather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'allgather' that allows to use data segments of\n-- different length.\n{# fun unsafe Allgatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Scatter\/Gather data from all\n-- members to all members of a group (also called complete exchange)\n{# fun unsafe Alltoall as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variant of 'alltoall' allows to use data segments of different length.\n{# fun unsafe Alltoallv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\n\n-- | Applies predefined or user-defined reduction operations to data,\n-- and delivers result to the single process.\n{# fun Reduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Applies predefined or user-defined reduction operations to data,\n-- and delivers result to all members of the group.\n{# fun Allreduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A combined reduction and scatter operation - result is split and\n-- parts are distributed among the participating processes.\n--\n-- See 'reduceScatter' for variant that allows to specify personal\n-- block size for each process.\n--\n-- Note that this call is not supported with some MPI implementations,\n-- like OpenMPI <= 1.5 and would cause a run-time 'error' in that case.\n#if 0\n{# fun Reduce_scatter_block as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n#else\nreduceScatterBlock :: BufferPtr -> BufferPtr -> Count -> Datatype -> Operation -> Comm -> IO ()\nreduceScatterBlock = error \"reduceScatterBlock is not supported by OpenMPI\"\n#endif\n\n-- | A combined reduction and scatter operation - result is split and\n-- parts are distributed among the participating processes.\n{# fun Reduce_scatter as ^\n { id `BufferPtr', id `BufferPtr', id `Ptr CInt', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n\n-- TODO: In the following haddock block, mention SCAN and EXSCAN once\n-- they are implemented \n\n{- | Binds a user-dened reduction operation to an 'Operation' handle that can\nsubsequently be used in 'reduce', 'allreduce', and 'reduceScatter'.\nThe user-defined operation is assumed to be associative. \n\nIf second argument to @opCreate@ is @True@, then the operation should be both commutative and associative. If\nit is not commutative, then the order of operands is fixed and is defined to be in ascending,\nprocess rank order, beginning with process zero. The order of evaluation can be changed,\ntaking advantage of the associativity of the operation. If operation\nis commutative then the order\nof evaluation can be changed, taking advantage of commutativity and\nassociativity.\n\nUser-defined operation accepts four arguments, @invec@, @inoutvec@,\n@len@ and @datatype@:\n\n[@invec@] first input vector\n\n[@inoutvec@] second input vector, which is also the output vector\n\n[@len@] length of both vectors\n\n[@datatype@] type of the elements in both vectors.\n\nFunction is expected to apply reduction operation to the elements\nof @invec@ and @inoutvec@ in pariwise manner:\n\n@\ninoutvec[i] = op invec[i] inoutvec[i]\n@\n\nFull example with user-defined function that mimics standard operation\n'sumOp':\n\n@\nimport \"Control.Parallel.MPI.Fast\"\n\nforeign import ccall \\\"wrapper\\\" \n wrap :: (Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()) \n -> IO (FunPtr (Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()))\nreduceUserOpTest myRank = do\n numProcs <- commSize commWorld\n userSumPtr <- wrap userSum\n mySumOp <- opCreate True userSumPtr\n (src :: StorableArray Int Double) <- newListArray (0,99) [0..99]\n if myRank \/= root\n then reduceSend commWorld root sumOp src\n else do\n (result :: StorableArray Int Double) <- intoNewArray_ (0,99) $ reduceRecv commWorld root mySumOp src\n recvMsg <- getElems result\n freeHaskellFunPtr userSumPtr\n where\n userSum :: Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()\n userSum inPtr inoutPtr lenPtr _ = do\n len <- peek lenPtr\n let offs = sizeOf ( undefined :: CDouble )\n let loop 0 _ _ = return ()\n loop n inPtr inoutPtr = do\n a <- peek inPtr\n b <- peek inoutPtr\n poke inoutPtr (a+b)\n loop (n-1) (plusPtr inPtr offs) (plusPtr inoutPtr offs)\n loop len inPtr inoutPtr\n@\n-}\n{# fun unsafe Op_create as ^\n {castFunPtr `FunPtr (Ptr t -> Ptr t -> Ptr CInt -> Ptr Datatype -> IO ())', cFromEnum `Bool', alloca- `Operation' peekOperation*} -> `()' checkError*- #}\n\n{- | Free the handle for user-defined reduction operation created by 'opCreate'\n-}\n{# fun Op_free as ^ {withOperation* `Operation'} -> `()' checkError*- #}\n\n{- | Returns a \nfloating-point number of seconds, representing elapsed wallclock\ntime since some time in the past.\n\nThe \\\"time in the past\\\" is guaranteed not to change during the life of the process.\nThe user is responsible for converting large numbers of seconds to other units if they are\npreferred. The time is local to the node that calls @wtime@, but see 'wtimeIsGlobal'.\n-}\n{# fun unsafe Wtime as ^ {} -> `Double' realToFrac #}\n\n{- | Returns the resolution of 'wtime' in seconds. That is, it returns,\nas a double precision value, the number of seconds between successive clock ticks. For\nexample, if the clock is implemented by the hardware as a counter that is incremented\nevery millisecond, the value returned by @wtick@ should be 10^(-3).\n-}\n{# fun unsafe Wtick as ^ {} -> `Double' realToFrac #}\n\n-- | Return the process group from a communicator. With\n-- intercommunicator, returns the local group.\n{# fun unsafe Comm_group as ^\n {fromComm `Comm', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Returns the rank of the calling process in the given group. This function corresponds to @MPI_Group_rank@.\ngroupRank :: Group -> Rank\ngroupRank = unsafePerformIO <$> groupRank'\n where groupRank' = {# fun unsafe Group_rank as groupRank_\n {fromGroup `Group', alloca- `Rank' peekIntConv*} -> `()' checkError*- #}\n\n-- | Returns the size of a group. This function corresponds to @MPI_Group_size@.\ngroupSize :: Group -> Int\ngroupSize = unsafePerformIO <$> groupSize'\n where groupSize' = {# fun unsafe Group_size as groupSize_\n {fromGroup `Group', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Constructs the union of two groups: all the members of the first group, followed by all the members of the \n-- second group that do not appear in the first group. This function corresponds to @MPI_Group_union@.\ngroupUnion :: Group -> Group -> Group\ngroupUnion g1 g2 = unsafePerformIO $ groupUnion' g1 g2\n where groupUnion' = {# fun unsafe Group_union as groupUnion_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Constructs a new group which is the intersection of two groups. This function corresponds to @MPI_Group_intersection@.\ngroupIntersection :: Group -> Group -> Group\ngroupIntersection g1 g2 = unsafePerformIO $ groupIntersection' g1 g2\n where groupIntersection' = {# fun unsafe Group_intersection as groupIntersection_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Constructs a new group which contains all the elements of the first group which are not in the second group. \n-- This function corresponds to @MPI_Group_difference@.\ngroupDifference :: Group -> Group -> Group\ngroupDifference g1 g2 = unsafePerformIO $ groupDifference' g1 g2\n where groupDifference' = {# fun unsafe Group_difference as groupDifference_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Compares two groups. Returns 'MPI_IDENT' if the order and members of the two groups are the same,\n-- 'MPI_SIMILAR' if only the members are the same, and 'MPI_UNEQUAL' otherwise.\ngroupCompare :: Group -> Group -> ComparisonResult\ngroupCompare g1 g2 = unsafePerformIO $ groupCompare' g1 g2\n where\n groupCompare' = {# fun unsafe Group_compare as groupCompare_\n {fromGroup `Group', fromGroup `Group', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- Technically it might make better sense to make the second argument a Set rather than a list\n-- but the order is significant in the groupIncl function (the other function, not this one).\n-- For the sake of keeping their types in sync, a list is used instead.\n{- | Create a new @Group@ from the given one. Exclude processes\nwith given @Rank@s from the new @Group@. Processes in new @Group@ will\nhave ranks @[0...]@.\n-}\n{# fun unsafe Group_excl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n{- | Create a new @Group@ from the given one. Include only processes\nwith given @Rank@s in the new @Group@. Processes in new @Group@ will\nhave ranks @[0...]@.\n-}\n{# fun unsafe Group_incl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n{- | Given two @Group@s and list of @Rank@s of some processes in the\nfirst @Group@, return @Rank@s of those processes in the second\n@Group@. If there are no corresponding @Rank@ in the second @Group@,\n'mpiUndefined' is returned.\n\nThis function is important for determining the relative numbering of the same processes\nin two different groups. For instance, if one knows the ranks of certain processes in the group\nof 'commWorld', one might want to know their ranks in a subset of that group.\nNote that 'procNull' is a valid rank for input to @groupTranslateRanks@, which\nreturns 'procNull' as the translated rank.\n-}\ngroupTranslateRanks :: Group -> [Rank] -> Group -> [Rank]\ngroupTranslateRanks group1 ranks group2 =\n unsafePerformIO $ do\n let (rankIntList :: [Int]) = map fromEnum ranks\n withArrayLen rankIntList $ \\size ranksPtr ->\n allocaArray size $ \\resultPtr -> do\n groupTranslateRanks' group1 (cFromEnum size) (castPtr ranksPtr) group2 resultPtr\n map toRank <$> peekArray size resultPtr\n where\n groupTranslateRanks' = {# fun unsafe Group_translate_ranks as groupTranslateRanks_\n {fromGroup `Group', id `CInt', id `Ptr CInt', fromGroup `Group', id `Ptr CInt'} -> `()' checkError*- #}\n\nwithRanksAsInts ranks f = withArrayLen (map fromEnum ranks) $ \\size ptr -> f (cIntConv size, castPtr ptr)\n\n{- | If a process was started with 'commSpawn', @commGetParent@\nreturns the parent intercommunicator of the current process. This\nparent intercommunicator is created implicitly inside of 'init' and\nis the same intercommunicator returned by 'commSpawn' in the\nparents. If the process was not spawned, @commGetParent@ returns\n'commNull'. After the parent communicator is freed or disconnected,\n@commGetParent@ returns 'commNull'. -} \n\n{# fun unsafe Comm_get_parent as ^\n {alloca- `Comm' peekComm*} -> `()' checkError*- #}\n\nwithT = with\n{# fun unsafe Comm_spawn as ^\n { `String' \n , withT* `Ptr CChar'\n , id `Count'\n , fromInfo `Info'\n , fromRank `Rank'\n , fromComm `Comm'\n , alloca- `Comm' peekComm*\n , id `Ptr CInt'} -> `()' checkError*- #}\n\nforeign import ccall unsafe \"&mpi_argv_null\" mpiArgvNull_ :: Ptr (Ptr CChar)\nforeign import ccall unsafe \"&mpi_errcodes_ignore\" mpiErrcodesIgnore_ :: Ptr (Ptr CInt)\nargvNull = unsafePerformIO $ peek mpiArgvNull_\nerrcodesIgnore = unsafePerformIO $ peek mpiErrcodesIgnore_\n\n{-| Simplified version of `commSpawn' that does not support argument passing and spawn error code checking. -}\ncommSpawnSimple rank program maxprocs =\n commSpawn program argvNull maxprocs infoNull rank commSelf errcodesIgnore\n\n{-| Opens up a port (network address) on the server where clients\n can establish connections using @commConnect@.\n\nRefer to MPI Report v2.2, Section 10.4 \"Establishing communication\"\nfor more details on client\/server programming with MPI. -}\nopenPort :: Info -> IO String\nopenPort info = do\n allocaBytes (fromIntegral maxPortName) $ \\ptr -> do\n openPort' info ptr\n peekCStringLen (ptr, fromIntegral maxPortName)\n where\n openPort' = {# fun unsafe Open_port as openPort_\n {fromInfo `Info', id `Ptr CChar'} -> `()' checkError*- #}\n\n-- | Closes the specified port on the server.\n{# fun unsafe Close_port as ^\n {`String'} -> `()' checkError*- #}\n\n{-| @commAccept@ allows a connection from a client. The intercommunicator\n object returned can be used to communicate with the client. -}\n{# fun unsafe Comm_accept as ^\n { `String'\n , fromInfo `Info'\n , fromRank `Rank'\n , fromComm `Comm'\n , alloca- `Comm' peekComm*} -> `()' checkError*- #}\n\n{-| @commConnect@ creates a connection to the server. The intercommunicator \n object returned can be used to communicate with the server. -}\n{# fun unsafe Comm_connect as ^\n { `String'\n , fromInfo `Info'\n , fromRank `Rank'\n , fromComm `Comm'\n , alloca- `Comm' peekComm*} -> `()' checkError*- #}\n\n-- | Free a communicator object.\n{# fun Comm_free as ^ {withComm* `Comm'} -> `()' checkError*- #}\n\n-- | Stop pending communication and deallocate a communicator object.\n{# fun Comm_disconnect as ^ {withComm* `Comm'} -> `()' checkError*- #}\n\nforeign import ccall \"&mpi_undefined\" mpiUndefined_ :: Ptr Int\n\n-- | Predefined constant that might be returned as @Rank@ by calls\n-- like 'groupTranslateRanks'. Corresponds to @MPI_UNDEFINED@. Please\n-- refer to \\\"MPI Report Constant And Predefined Handle Index\\\" for a\n-- list of situations where @mpiUndefined@ could appear.\nmpiUndefined :: Int\nmpiUndefined = unsafePerformIO $ peek mpiUndefined_\n\n-- | Return the number of bytes used to store an MPI @Datatype@.\ntypeSize :: Datatype -> Int\ntypeSize = unsafePerformIO . typeSize'\n where\n typeSize' =\n {# fun unsafe Type_size as typeSize_\n {fromDatatype `Datatype', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n{# fun unsafe Error_class as ^\n { id `CInt', alloca- `CInt' peek*} -> `CInt' id #}\n\n-- | Set the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_set_errhandler@.\n{# fun unsafe Comm_set_errhandler as ^\n {fromComm `Comm', fromErrhandler `Errhandler'} -> `()' checkError*- #}\n\n-- | Get the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_get_errhandler@.\n{# fun unsafe Comm_get_errhandler as ^\n {fromComm `Comm', alloca- `Errhandler' peekErrhandler*} -> `()' checkError*- #}\n\n-- | Tries to terminate all MPI processes in its communicator argument.\n-- The second argument is an error code which \/may\/ be used as the return status\n-- of the MPI process, but this is not guaranteed. On systems where 'Int' has a larger\n-- range than 'CInt', the error code will be clipped to fit into the range of 'CInt'.\n-- This function corresponds to @MPI_Abort@.\nabort :: Comm -> Int -> IO ()\nabort comm code =\n abort' comm (toErrorCode code)\n where\n toErrorCode :: Int -> CInt\n toErrorCode i\n -- Assumes Int always has range at least as big as CInt.\n | i < (fromIntegral (minBound :: CInt)) = minBound\n | i > (fromIntegral (maxBound :: CInt)) = maxBound\n | otherwise = cIntConv i\n\n abort' = {# fun unsafe Abort as abort_ {fromComm `Comm', id `CInt'} -> `()' checkError*- #}\n\n\ntype MPIDatatype = {# type MPI_Datatype #}\n\n-- | Haskell datatype used to represent @MPI_Datatype@. \n-- Please refer to Chapter 4 of MPI Report v. 2.2 for a description\n-- of various datatypes.\nnewtype Datatype = MkDatatype { fromDatatype :: MPIDatatype }\n\nforeign import ccall unsafe \"&mpi_char\" char_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_wchar\" wchar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_short\" short_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_int\" int_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long\" long_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_long\" longLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_char\" unsignedChar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_short\" unsignedShort_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned\" unsigned_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long\" unsignedLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long_long\" unsignedLongLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_float\" float_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_double\" double_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_double\" longDouble_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_byte\" byte_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_packed\" packed_ :: Ptr MPIDatatype\n\nchar, wchar, short, int, long, longLong, unsignedChar, unsignedShort :: Datatype\nunsigned, unsignedLong, unsignedLongLong, float, double, longDouble :: Datatype\nbyte, packed :: Datatype\n\nchar = MkDatatype <$> unsafePerformIO $ peek char_\nwchar = MkDatatype <$> unsafePerformIO $ peek wchar_\nshort = MkDatatype <$> unsafePerformIO $ peek short_\nint = MkDatatype <$> unsafePerformIO $ peek int_\nlong = MkDatatype <$> unsafePerformIO $ peek long_\nlongLong = MkDatatype <$> unsafePerformIO $ peek longLong_\nunsignedChar = MkDatatype <$> unsafePerformIO $ peek unsignedChar_\nunsignedShort = MkDatatype <$> unsafePerformIO $ peek unsignedShort_\nunsigned = MkDatatype <$> unsafePerformIO $ peek unsigned_\nunsignedLong = MkDatatype <$> unsafePerformIO $ peek unsignedLong_\nunsignedLongLong = MkDatatype <$> unsafePerformIO $ peek unsignedLongLong_\nfloat = MkDatatype <$> unsafePerformIO $ peek float_\ndouble = MkDatatype <$> unsafePerformIO $ peek double_\nlongDouble = MkDatatype <$> unsafePerformIO $ peek longDouble_\nbyte = MkDatatype <$> unsafePerformIO $ peek byte_\npacked = MkDatatype <$> unsafePerformIO $ peek packed_\n\ntype MPIErrhandler = {# type MPI_Errhandler #}\n\n-- | Haskell datatype that represents values usable as @MPI_Errhandler@\nnewtype Errhandler = MkErrhandler { fromErrhandler :: MPIErrhandler } deriving Storable\npeekErrhandler ptr = MkErrhandler <$> peek ptr\n\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr MPIErrhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr MPIErrhandler\n\n-- | Predefined @Errhandler@ that will terminate the process on any\n-- MPI error\nerrorsAreFatal :: Errhandler\nerrorsAreFatal = MkErrhandler <$> unsafePerformIO $ peek errorsAreFatal_\n\n-- | Predefined @Errhandler@ that will convert errors into Haskell\n-- exceptions. Mimics the semantics of @MPI_Errors_return@\nerrorsReturn :: Errhandler\nerrorsReturn = MkErrhandler <$> unsafePerformIO $ peek errorsReturn_\n\n-- | Same as 'errorsReturn', but with a more meaningful name.\nerrorsThrowExceptions :: Errhandler\nerrorsThrowExceptions = errorsReturn\n\n{# enum ErrorClass {underscoreToCase} deriving (Eq,Ord,Show,Typeable) #}\n\n-- XXX Should this be a ForeinPtr?\n-- there is a MPI_Group_free function, which we should probably\n-- call when the group is no longer referenced.\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIGroup = {# type MPI_Group #}\n\n-- | Haskell datatype representing MPI process groups.\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\npeekGroup ptr = MkGroup <$> peek ptr\n\nforeign import ccall \"&mpi_group_empty\" groupEmpty_ :: Ptr MPIGroup\n-- | A predefined group without any members. Corresponds to @MPI_GROUP_EMPTY@.\ngroupEmpty :: Group\ngroupEmpty = MkGroup <$> unsafePerformIO $ peek groupEmpty_\n\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIOperation = {# type MPI_Op #}\n\n{- | Abstract type representing handle for MPI reduction operation\n(that can be used with 'reduce', 'allreduce', and 'reduceScatter').\n-}\nnewtype Operation = MkOperation { fromOperation :: MPIOperation } deriving Storable\npeekOperation ptr = MkOperation <$> peek ptr\nwithOperation op f = alloca $ \\ptr -> do poke ptr (fromOperation op)\n f (castPtr ptr)\n\nforeign import ccall unsafe \"&mpi_max\" maxOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_min\" minOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_sum\" sumOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_prod\" prodOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_land\" landOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_band\" bandOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lor\" lorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bor\" borOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lxor\" lxorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bxor\" bxorOp_ :: Ptr MPIOperation\n-- foreign import ccall \"mpi_maxloc\" maxlocOp :: MPIOperation\n-- foreign import ccall \"mpi_minloc\" minlocOp :: MPIOperation\n-- foreign import ccall \"mpi_replace\" replaceOp :: MPIOperation\n-- TODO: support for those requires better support for pair datatypes\n\n-- | Predefined reduction operation: maximum\nmaxOp :: Operation\nmaxOp = MkOperation <$> unsafePerformIO $ peek maxOp_\n\n-- | Predefined reduction operation: minimum\nminOp :: Operation\nminOp = MkOperation <$> unsafePerformIO $ peek minOp_\n\n-- | Predefined reduction operation: (+)\nsumOp :: Operation\nsumOp = MkOperation <$> unsafePerformIO $ peek sumOp_\n\n-- | Predefined reduction operation: (*)\nprodOp :: Operation\nprodOp = MkOperation <$> unsafePerformIO $ peek prodOp_\n\n-- | Predefined reduction operation: logical \\\"and\\\"\nlandOp :: Operation\nlandOp = MkOperation <$> unsafePerformIO $ peek landOp_\n\n-- | Predefined reduction operation: bit-wise \\\"and\\\"\nbandOp :: Operation\nbandOp = MkOperation <$> unsafePerformIO $ peek bandOp_\n\n-- | Predefined reduction operation: logical \\\"or\\\"\nlorOp :: Operation\nlorOp = MkOperation <$> unsafePerformIO $ peek lorOp_\n\n-- | Predefined reduction operation: bit-wise \\\"or\\\"\nborOp :: Operation\nborOp = MkOperation <$> unsafePerformIO $ peek borOp_\n\n-- | Predefined reduction operation: logical \\\"xor\\\"\nlxorOp :: Operation\nlxorOp = MkOperation <$> unsafePerformIO $ peek lxorOp_\n\n-- | Predefined reduction operation: bit-wise \\\"xor\\\"\nbxorOp :: Operation\nbxorOp = MkOperation <$> unsafePerformIO $ peek bxorOp_\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIInfo = {# type MPI_Info #}\n\n{- | Abstract type representing handle for MPI Info object\n-}\nnewtype Info = MkInfo { fromInfo :: MPIInfo } deriving Storable\npeekInfo ptr = MkInfo <$> peek ptr\n\nforeign import ccall \"&mpi_info_null\" infoNull_ :: Ptr MPIInfo\n\n-- | Predefined info object that has no info\ninfoNull :: Info\ninfoNull = unsafePerformIO $ peekInfo infoNull_\n\n{-| Creates new empty info object -}\n{# fun unsafe Info_create as ^\n {alloca- `Info' peekInfo*} -> `()' checkError*- #}\n\n{-| Adds specified (key, value) pair to info object -}\n{# fun unsafe Info_set as ^\n {fromInfo `Info', `String', `String'} -> `()' checkError*- #}\n\n{-| Deletes the specified key from info object -}\n{# fun unsafe Info_delete as ^\n {fromInfo `Info', `String'} -> `()' checkError*- #}\n\n{-| Gets the specified key -}\ninfoGet :: Info -> String -> IO (Maybe String)\ninfoGet info key = do\n (len, found) <- infoGetValuelen' info key \n -- len+1 is required to allow for the terminating \\NULL\n if found\/=0 then allocaBytes (fromIntegral len + 1)\n (\\bufferPtr -> do\n found <- infoGet' info key (len+1) bufferPtr\n if found\/=0 then Just <$> peekCStringLen (bufferPtr, fromIntegral len)\n else return Nothing)\n else return Nothing\n\ninfoGetValuelen' = {# fun unsafe Info_get_valuelen as infoGetValuelen_\n {fromInfo `Info', `String', alloca- `CInt' peek*, alloca- `CInt' peek* } -> `()' checkError*- #}\n\ninfoGet' = {# fun unsafe Info_get as infoGet_\n {fromInfo `Info', `String', id `CInt', castPtr `Ptr CChar', alloca- `CInt' peek*} -> `()' checkError*- #}\n\n\n{- | Haskell datatype that represents values which\n could be used as MPI rank designations. Low-level MPI calls require\n that you use 32-bit non-negative integer values as ranks, so any\n non-numeric Haskell Ranks should provide a sensible instances of\n 'Enum'.\n\nAttempt to supply a value that does not fit into 32 bits will cause a\nrun-time 'error'.\n-}\nnewtype Rank = MkRank { rankId :: CInt -- ^ Extract numeric value of the 'Rank'\n }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Rank where\n (MkRank x) + (MkRank y) = MkRank (x+y)\n (MkRank x) * (MkRank y) = MkRank (x*y)\n abs (MkRank x) = MkRank (abs x)\n signum (MkRank x) = MkRank (signum x)\n fromInteger x\n | x > ( fromIntegral (maxBound :: CInt)) = error \"Rank value does not fit into 32 bits\"\n | x < 0 = error \"Negative Rank value\"\n | otherwise = MkRank (fromIntegral x)\n\nforeign import ccall \"&mpi_any_source\" anySource_ :: Ptr CInt\nforeign import ccall \"&mpi_root\" theRoot_ :: Ptr CInt\nforeign import ccall \"&mpi_proc_null\" procNull_ :: Ptr CInt\nforeign import ccall \"&mpi_request_null\" requestNull_ :: Ptr MPIRequest\nforeign import ccall \"&mpi_comm_null\" commNull_ :: Ptr MPIComm\n\n-- | Predefined rank number that allows reception of point-to-point messages\n-- regardless of their source. Corresponds to @MPI_ANY_SOURCE@\nanySource :: Rank\nanySource = toRank $ unsafePerformIO $ peek anySource_\n\n-- | Predefined rank number that specifies root process during\n-- operations involving intercommunicators. Corresponds to @MPI_ROOT@\ntheRoot :: Rank\ntheRoot = toRank $ unsafePerformIO $ peek theRoot_\n\n-- | Predefined rank number that specifies non-root processes during\n-- operations involving intercommunicators. Corresponds to @MPI_PROC_NULL@\nprocNull :: Rank\nprocNull = toRank $ unsafePerformIO $ peek procNull_\n\n-- | Predefined request handle value that specifies non-existing or finished request.\n-- Corresponds to @MPI_REQUEST_NULL@\nrequestNull :: Request\nrequestNull = unsafePerformIO $ peekRequest requestNull_\n\n-- | Predefined communicator handle value that specifies non-existing or destroyed (inter-)communicator.\n-- Corresponds to @MPI_COMM_NULL@\ncommNull :: Comm\ncommNull = unsafePerformIO $ peekComm commNull_\n\ninstance Show Rank where\n show = show . rankId\n\n-- | Map arbitrary 'Enum' value to 'Rank'\ntoRank :: Enum a => a -> Rank\ntoRank x = MkRank { rankId = cIntConv (fromEnum x) }\n\n-- | Map 'Rank' to arbitrary 'Enum'\nfromRank :: Enum a => Rank -> a\nfromRank = toEnum . cIntConv . rankId\n\ntype MPIRequest = {# type MPI_Request #}\n{-| Haskell representation of the @MPI_Request@ type. Returned by\nnon-blocking communication operations, could be further processed with\n'probe', 'test', 'cancel' or 'wait'. -}\nnewtype Request = MkRequest MPIRequest deriving (Storable,Eq)\npeekRequest ptr = MkRequest <$> peek ptr\n\n{-\nThis module provides Haskell representation of the @MPI_Status@ type\n(request status).\n\nField `status_error' should be used with care:\n\\\"The error field in status is not needed for calls that return only\none status, such as @MPI_WAIT@, since that would only duplicate the\ninformation returned by the function itself. The current design avoids\nthe additional overhead of setting it, in such cases. The field is\nneeded for calls that return multiple statuses, since each request may\nhave had a different failure.\\\"\n(this is a quote from )\n\nThis means that, for example, during the call to @MPI_Wait@\nimplementation is free to leave this field filled with whatever\ngarbage got there during memory allocation. Haskell FFI is not\nblanking out freshly allocated memory, so beware!\n-}\n\n-- | Haskell structure that holds fields of @MPI_Status@.\ndata Status =\n Status\n { status_source :: Rank -- ^ rank of the source process\n , status_tag :: Tag -- ^ tag assigned at source\n , status_error :: CInt -- ^ error code, if any\n }\n deriving (Eq, Ord, Show)\n\ninstance Storable Status where\n sizeOf _ = {#sizeof MPI_Status #}\n alignment _ = 4\n peek p = Status\n <$> liftM (MkRank . cIntConv) ({#get MPI_Status->MPI_SOURCE #} p)\n <*> liftM (MkTag . cIntConv) ({#get MPI_Status->MPI_TAG #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_ERROR #} p)\n poke p x = do\n {#set MPI_Status.MPI_SOURCE #} p (fromRank $ status_source x)\n {#set MPI_Status.MPI_TAG #} p (fromTag $ status_tag x)\n {#set MPI_Status.MPI_ERROR #} p (cIntConv $ status_error x)\n\n-- NOTE: Int here is picked arbitrary\nallocaCast f =\n alloca $ \\(ptr :: Ptr Int) -> f (castPtr ptr :: Ptr ())\npeekCast = peek . castPtr\n\n\n{-| Haskell datatype that represents values which could be used as\ntags for point-to-point transfers.\n-}\nnewtype Tag = MkTag { tagVal :: CInt -- ^ Extract numeric value of the Tag\n }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Tag where\n (MkTag x) + (MkTag y) = MkTag (x+y)\n (MkTag x) * (MkTag y) = MkTag (x*y)\n abs (MkTag x) = MkTag (abs x)\n signum (MkTag x) = MkTag (signum x)\n fromInteger x\n | fromIntegral x > tagUpperBound = error \"Tag value is over the MPI_TAG_UB\"\n | x < 0 = error \"Negative Tag value\"\n | otherwise = MkTag (fromIntegral x)\n\ninstance Show Tag where\n show = show . tagVal\n\n-- | Map arbitrary 'Enum' value to 'Tag'\ntoTag :: Enum a => a -> Tag\ntoTag x = MkTag { tagVal = cIntConv (fromEnum x) }\n\n-- | Map 'Tag' to arbitrary 'Enum'\nfromTag :: Enum a => Tag -> a\nfromTag = toEnum . cIntConv . tagVal\n\nforeign import ccall unsafe \"&mpi_any_tag\" anyTag_ :: Ptr CInt\n\n-- | Predefined tag value that allows reception of the messages with\n-- arbitrary tag values. Corresponds to @MPI_ANY_TAG@.\nanyTag :: Tag\nanyTag = toTag $ unsafePerformIO $ peek anyTag_\n\n-- | A tag with unit value. Intended to be used as a convenient default.\nunitTag :: Tag\nunitTag = toTag ()\n\n{- | Constants used to describe the required level of multithreading\n support in call to 'initThread'. They also describe provided level\n of multithreading support as returned by 'queryThread' and\n 'initThread'.\n\n[@Single@] Only one thread will execute.\n\n[@Funneled@] The process may be multi-threaded, but the application must\nensure that only the main thread makes MPI calls (see 'isThreadMain').\n\n[@Serialized@] The process may be multi-threaded, and multiple threads may\nmake MPI calls, but only one at a time: MPI calls are not made concurrently from\ntwo distinct threads\n\n[@Multiple@] Multiple threads may call MPI, with no restrictions.\n\nXXX Make sure we have the correct ordering as defined by MPI. Also we should\ndescribe the ordering here (other parts of the docs need it to be explained - see initThread).\n\n-}\n{# enum ThreadSupport {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- | Value thrown as exception when MPI runtime is instructed to pass\n-- errors to user code (via 'commSetErrhandler' and 'errorsReturn').\n-- Since raw MPI errors codes are not standartized and not portable,\n-- they are not exposed.\ndata MPIError\n = MPIError\n { mpiErrorClass :: ErrorClass -- ^ Broad class of errors this one belongs to\n , mpiErrorString :: String -- ^ Human-readable error description\n }\n deriving (Eq, Show, Typeable)\n\ninstance Exception MPIError\n\ncheckError :: CInt -> IO ()\ncheckError code = do\n -- We ignore the error code from the call to Internal.errorClass\n -- because we call errorClass from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n (_, errClassRaw) <- errorClass code\n let errClass = cToEnum errClassRaw\n unless (errClass == Success) $ do\n errStr <- errorString code\n throwIO $ MPIError errClass errStr\n\n-- | Convert MPI error code human-readable error description. Corresponds to @MPI_Error_string@.\nerrorString :: CInt -> IO String\nerrorString code =\n allocaBytes (fromIntegral maxErrorString) $ \\ptr ->\n alloca $ \\lenPtr -> do\n -- We ignore the error code from the call to Internal.errorString\n -- because we call errorString from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n _ <- errorString' code ptr lenPtr\n len <- peek lenPtr\n peekCStringLen (ptr, cIntConv len)\n where\n errorString' = {# call unsafe Error_string as errorString_ #}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n#include \n#include \"init_wrapper.h\"\n#include \"comparison_result.h\"\n#include \"error_classes.h\"\n#include \"thread_support.h\"\n-----------------------------------------------------------------------------\n{- |\nModule : Control.Parallel.MPI.Internal\nCopyright : (c) 2010 Bernie Pope, Dmitry Astapov\nLicense : BSD-style\nMaintainer : florbitous@gmail.com\nStability : experimental\nPortability : ghc\n\nThis module contains low-level Haskell bindings to core MPI functions.\nAll Haskell functions correspond to MPI functions or values with the similar\nname (i.e. @commRank@ is the binding for @MPI_Comm_rank@ etc)\n\nNote that most of this module is re-exported by\n\"Control.Parallel.MPI\", so if you are not interested in writing\nlow-level code, you should probably import \"Control.Parallel.MPI\" and\neither \"Control.Parallel.MPI.Storable\" or \"Control.Parallel.MPI.Serializable\".\n-}\n-----------------------------------------------------------------------------\nmodule Control.Parallel.MPI.Internal\n (\n\n -- * MPI runtime management.\n -- ** Initialization, finalization, termination.\n init, finalize, initialized, finalized, abort,\n -- ** Multi-threaded environment support.\n ThreadSupport (..), initThread, queryThread, isThreadMain,\n\n -- ** Runtime attributes.\n getProcessorName, Version (..), getVersion, Implementation(..), getImplementation, universeSize,\n\n -- ** Info objects\n Info, infoNull, infoCreate, infoSet, infoDelete, infoGet,\n\n -- * Requests and statuses.\n Request, Status (..), getCount, test, testPtr, cancel, cancelPtr, wait, waitPtr, waitall, requestNull, \n\n -- * Process management.\n -- ** Communicators.\n Comm, commWorld, commSelf, commNull, commTestInter,\n commSize, commRemoteSize, \n commRank, \n commCompare, commFree, commGroup, commGetAttr,\n\n -- ** Process groups.\n Group, groupEmpty, groupRank, groupSize, groupUnion,\n groupIntersection, groupDifference, groupCompare, groupExcl,\n groupIncl, groupTranslateRanks,\n -- ** Comparisons.\n ComparisonResult (..),\n\n -- ** Dynamic process management\n commGetParent, commSpawn, commSpawnSimple, argvNull, errcodesIgnore,\n openPort, closePort, commAccept, commConnect, commDisconnect,\n\n -- * Error handling.\n Errhandler, errorsAreFatal, errorsReturn, errorsThrowExceptions, commSetErrhandler, commGetErrhandler,\n ErrorClass (..), MPIError(..), mpiUndefined,\n\n -- * Ranks.\n Rank, rankId, toRank, fromRank, anySource, theRoot, procNull,\n\n -- * Data types.\n Datatype, char, wchar, short, int, long, longLong, unsignedChar, unsignedShort, unsigned, unsignedLong, unsignedLongLong, float, double, longDouble, byte, packed, typeSize,\n\n -- * Point-to-point operations.\n -- ** Tags.\n Tag, toTag, fromTag, anyTag, unitTag, tagUpperBound,\n\n -- ** Blocking operations.\n BufferPtr, Count, -- XXX: what will break if we don't export those?\n send, ssend, rsend, recv,\n -- ** Non-blocking operations.\n isend, issend, irecv,\n isendPtr, issendPtr, irecvPtr,\n\n\n -- * Collective operations.\n -- ** One-to-all.\n bcast, scatter, scatterv,\n -- ** All-to-one.\n gather, gatherv, reduce,\n -- ** All-to-all.\n allgather, allgatherv,\n alltoall, alltoallv,\n allreduce, \n reduceScatterBlock,\n reduceScatter,\n barrier,\n\n -- ** Reduction operations.\n Operation, maxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp,\n opCreate, opFree,\n\n -- * Timing.\n wtime, wtick, wtimeIsGlobal, wtimeIsGlobalKey\n\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Data.Maybe (fromMaybe)\nimport Control.Monad (liftM, unless)\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception\n\n{# context prefix = \"MPI\" #}\n\n-- | Pointer to memory buffer that either holds data to be sent or is\n-- used to receive some data. You would\n-- probably have to use 'castPtr' to pass some actual pointers to\n-- API functions.\ntype BufferPtr = Ptr ()\n\n-- | Count of elements in the send\/receive buffer\ntype Count = CInt\n\n{- |\nHaskell enum that contains MPI constants\n@MPI_IDENT@, @MPI_CONGRUENT@, @MPI_SIMILAR@ and @MPI_UNEQUAL@.\n\nThose are used to compare communicators ('commCompare') and\nprocess groups ('groupCompare'). Refer to those\nfunctions for description of comparison rules.\n-}\n{# enum ComparisonResult {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- Which Haskell type will be used as Comm depends on the MPI\n-- implementation that was selected during compilation. It could be\n-- CInt, Ptr (), Ptr CInt or something else.\ntype MPIComm = {# type MPI_Comm #}\n\n{- | Abstract type representing MPI communicator handle. Different MPI\n implementations use different C types to implement this, so\n concrete Haskell type behind @Comm@ is hidden from user.\n\n In any MPI program you have predefined communicator 'commWorld'\n which includes all running processes. You could create new\n communicators with TODO\n-}\nnewtype Comm = MkComm { fromComm :: MPIComm } deriving Eq\npeekComm ptr = MkComm <$> peek ptr\nwithComm comm f = alloca $ \\ptr -> do poke ptr (fromComm comm)\n f (castPtr ptr)\n\nforeign import ccall \"&mpi_comm_world\" commWorld_ :: Ptr MPIComm\nforeign import ccall \"&mpi_comm_self\" commSelf_ :: Ptr MPIComm\n\n-- | Predefined handle for communicator that includes all running\n-- processes. Similar to @MPI_Comm_world@\ncommWorld :: Comm\ncommWorld = MkComm <$> unsafePerformIO $ peek commWorld_\n\n-- | Predefined handle for communicator that includes only current\n-- process. Similar to @MPI_Comm_self@\ncommSelf :: Comm\ncommSelf = MkComm <$> unsafePerformIO $ peek commSelf_\n\nforeign import ccall \"&mpi_max_processor_name\" max_processor_name_ :: Ptr CInt\nforeign import ccall \"&mpi_max_port_name\" max_port_name_ :: Ptr CInt\nforeign import ccall \"&mpi_max_error_string\" max_error_string_ :: Ptr CInt\n\n-- | Max length of \"processor name\" as returned by 'getProcessorName'\nmaxProcessorName :: CInt\nmaxProcessorName = unsafePerformIO $ peek max_processor_name_\n\n-- | Max length of \"port name\" as returned by 'openPort'\nmaxPortName :: CInt\nmaxPortName = unsafePerformIO $ peek max_port_name_\n\n-- | Max length of error description as returned by 'errorString'\nmaxErrorString :: CInt\nmaxErrorString = unsafePerformIO $ peek max_error_string_\n\n-- | Initialize the MPI environment. The MPI environment must be intialized by each\n-- MPI process before any other MPI function is called. Note that\n-- the environment may also be initialized by the functions 'initThread', 'mpi',\n-- and 'mpiWorld'. It is an error to attempt to initialize the environment more\n-- than once for a given MPI program execution. The only MPI functions that may\n-- be called before the MPI environment is initialized are 'getVersion',\n-- 'initialized' and 'finalized'. This function corresponds to @MPI_Init@.\n{# fun unsafe init_wrapper as init {} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been initialized. Returns @True@ if the\n-- environment has been initialized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Initialized@.\n{# fun unsafe Initialized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been finalized. Returns @True@ if the\n-- environment has been finalized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Finalized@.\n{# fun unsafe Finalized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Initialize the MPI environment with a \/required\/ level of thread support.\n-- See the documentation for 'init' for more information about MPI initialization.\n-- The \/provided\/ level of thread support is returned in the result.\n-- There is no guarantee that provided will be greater than or equal to required.\n-- The level of provided thread support depends on the underlying MPI implementation,\n-- and may also depend on information provided when the program is executed\n-- (for example, by supplying appropriate arguments to @mpiexec@).\n-- If the required level of support cannot be provided then it will try to\n-- return the least supported level greater than what was required.\n-- If that cannot be satisfied then it will return the highest supported level\n-- provided by the MPI implementation. See the documentation for 'ThreadSupport'\n-- for information about what levels are available and their relative ordering.\n-- This function corresponds to @MPI_Init_thread@.\n{# fun unsafe init_wrapper_thread as initThread\n {cFromEnum `ThreadSupport', alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\n-- | Returns the current provided level of thread support. This will be the value\n-- returned as \\\"provided level of support\\\" by 'initThread' as well. This function\n-- corresponds to @MPI_Query_thread@.\n{# fun unsafe Query_thread as ^ {alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\n-- | This function can be called by a thread to find out whether it is the main thread (the\n-- thread that called 'init' or 'initThread'.\n{# fun unsafe Is_thread_main as ^\n {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Terminate the MPI execution environment.\n-- Once 'finalize' is called no other MPI functions may be called except\n-- 'getVersion', 'initialized' and 'finalized', however non-MPI computations\n-- may continue. Each process must complete\n-- any pending communication that it initiated before calling 'finalize'.\n-- Note: the error code returned\n-- by 'finalize' is not checked. This function corresponds to @MPI_Finalize@.\n{# fun unsafe Finalize as ^ {} -> `()' discard*- #}\ndiscard _ = return ()\n-- XXX can't call checkError on finalize, because\n-- checkError calls Internal.errorClass and Internal.errorString.\n-- These cannot be called after finalize (at least on OpenMPI).\n\n-- | Return the name of the current processing host. From this value it\n-- must be possible to identify a specific piece of hardware on which\n-- the code is running.\ngetProcessorName :: IO String\ngetProcessorName = do\n allocaBytes (fromIntegral maxProcessorName) $ \\ptr -> do\n len <- getProcessorName' ptr\n peekCStringLen (ptr, cIntConv len)\n where\n getProcessorName' = {# fun unsafe Get_processor_name as getProcessorName_\n {id `Ptr CChar', alloca- `CInt' peekIntConv*} -> `()' checkError*- #}\n\n-- | MPI implementation version\ndata Version =\n Version { version :: Int, subversion :: Int }\n deriving (Eq, Ord)\n\ninstance Show Version where\n show v = show (version v) ++ \".\" ++ show (subversion v)\n\n-- | Which MPI version the code is running on.\ngetVersion :: IO Version\ngetVersion = do\n (version, subversion) <- getVersion'\n return $ Version version subversion\n where\n getVersion' = {# fun unsafe Get_version as getVersion_\n {alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Supported MPI implementations\ndata Implementation = MPICH2 | OpenMPI deriving (Eq,Show)\n\n-- | Which MPI implementation was used during linking\ngetImplementation :: Implementation\ngetImplementation =\n#ifdef MPICH2\n MPICH2\n#else\n OpenMPI\n#endif\n\n-- | Return the number of processes involved in a communicator. For 'commWorld'\n-- it returns the total number of processes available. If the communicator is\n-- and intra-communicator it returns the number of processes in the local group.\n-- This function corresponds to @MPI_Comm_size@.\n{# fun unsafe Comm_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n-- | For intercommunicators, returns size of the remote process group.\n-- Corresponds to @MPI_Comm_remote_size@.\n{# fun unsafe Comm_remote_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n{- | Check whether the given communicator is intercommunicator - that\n is, communicator connecting two different groups of processes.\n\nRefer to MPI Report v2.2, Section 5.2 \"Communicator Argument\" for\nmore details.\n-}\n{# fun unsafe Comm_test_inter as ^\n {fromComm `Comm', alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Look up MPI communicator argument by the given numeric key.\n-- Lookup of some standard MPI arguments is provided by convenience\n-- functions 'tagUpperBound' and 'wtimeIsGlobal'.\ncommGetAttr :: Storable e => Comm -> Int -> IO (Maybe e)\ncommGetAttr comm key = do\n isInitialized <- initialized\n if isInitialized then do\n alloca $ \\ptr -> do\n found <- commGetAttr' comm key (castPtr ptr)\n if found then do ptr2 <- peek ptr\n Just <$> peek ptr2\n else return Nothing\n else return Nothing\n where\n commGetAttr' = {# fun unsafe Comm_get_attr as commGetAttr_\n {fromComm `Comm', cIntConv `Int', id `Ptr ()', alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Maximum tag value supported by the current MPI implementation. Corresponds to the value of standard MPI\n-- attribute @MPI_TAG_UB@.\n--\n-- When called before 'init' or 'initThread' would return 0.\ntagUpperBound :: Int\ntagUpperBound =\n let key = unsafePerformIO (peek tagUB_)\n in fromMaybe 0 $ unsafePerformIO (commGetAttr commWorld key)\n\nforeign import ccall unsafe \"&mpi_tag_ub\" tagUB_ :: Ptr Int\n\n{- | True if clocks at all processes in\n'commWorld' are synchronized, False otherwise. The expectation is that\nthe variation in time, as measured by calls to 'wtime', will be less then one half the\nround-trip time for an MPI message of length zero. \n\nCommunicators other than 'commWorld' could have different clocks.\nYou could find it out by querying attribute 'wtimeIsGlobalKey' with 'commGetAttr'.\n\nWhen wtimeIsGlobal is called before 'init' or 'initThread' it would return False.\n-}\nwtimeIsGlobal :: Bool\nwtimeIsGlobal =\n fromMaybe False $ unsafePerformIO (commGetAttr commWorld wtimeIsGlobalKey)\n\nforeign import ccall unsafe \"&mpi_wtime_is_global\" wtimeIsGlobal_ :: Ptr Int\n\n-- | Numeric key for standard MPI communicator attribute @MPI_WTIME_IS_GLOBAL@.\n-- To be used with 'commGetAttr'.\nwtimeIsGlobalKey :: Int\nwtimeIsGlobalKey = unsafePerformIO (peek wtimeIsGlobal_)\n\n{- | \nMany ``dynamic'' MPI applications are expected to exist in a static runtime environment, in which resources have been allocated before the application is run. When a user (or possibly a batch system) runs one of these quasi-static applications, she will usually specify a number of processes to start and a total number of processes that are expected. An application simply needs to know how many slots there are, i.e., how many processes it should spawn.\n\nThis attribute indicates the total number of processes that are expected.\n\nWhen universeSize is called before 'init' or 'initThread' it would return False.\n-}\nuniverseSize :: Comm -> IO (Maybe Int)\nuniverseSize c =\n commGetAttr c universeSizeKey\n\nforeign import ccall unsafe \"&mpi_universe_size\" universeSize_ :: Ptr Int\n\n-- | Numeric key for recommended MPI communicator attribute @MPI_UNIVERSE_SIZE@.\n-- To be used with 'commGetAttr'.\nuniverseSizeKey :: Int\nuniverseSizeKey = unsafePerformIO (peek universeSize_)\n\n-- | Return the rank of the calling process for the given\n-- communicator. If it is an intercommunicator, returns rank of the\n-- process in the local group.\n{# fun unsafe Comm_rank as ^\n {fromComm `Comm', alloca- `Rank' peekIntConv* } -> `()' checkError*- #}\n\n{- | Compares two communicators.\n\n* If they are handles for the same MPI communicator object, result is 'Identical';\n\n* If both communicators are identical in constituents and rank\n order, result is `Congruent';\n\n* If they have the same members, but with different ranks, then\n result is 'Similar';\n\n* Otherwise, result is 'Unequal'.\n\n-}\n{# fun unsafe Comm_compare as ^\n {fromComm `Comm', fromComm `Comm', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- | Test for an incomming message, without actually receiving it.\n-- If a message has been sent from @Rank@ to the current process with @Tag@ on the\n-- communicator @Comm@ then 'probe' will return the 'Status' of the message. Otherwise\n-- it will block the current process until such a matching message is sent.\n-- This allows the current process to check for an incoming message and decide\n-- how to receive it, based on the information in the 'Status'.\n-- This function corresponds to @MPI_Probe@.\n-- The most common usecase is to call @probe@ first and then use 'getCount' to find out size of incoming message.\n-- However since different implementations provide additional fields in @Status@, we cannot deserialize Status into Haskell land\n-- and serialize it back without losing information. Hence the use of Ptr Status.\n{# fun Probe as ^\n {fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Status'} -> `()' checkError*- #}\n{- probe :: Rank -- ^ Rank of the sender.\n -> Tag -- ^ Tag of the sent message.\n -> Comm -- ^ Communicator.\n -> IO Status -- ^ Information about the incoming message (but not the content of the message). -}\n\n{-| Returns the number of entries received. (we count entries, each of\ntype @Datatype@, not bytes.) The datatype argument should match the\nargument provided by the receive call that set the status variable. -}\ngetCount :: Comm -> Rank -> Tag -> Datatype -> IO Int\ngetCount comm rank tag datatype =\n alloca $ \\statusPtr -> do\n probe rank tag comm statusPtr\n cnt <- getCount' statusPtr datatype\n return $ fromIntegral cnt\n where\n getCount' = {# fun unsafe Get_count as getCount_\n {castPtr `Ptr Status', fromDatatype `Datatype', alloca- `CInt' peekIntConv*} -> `()' checkError*- #}\n\n\n{-| Send the values (as specified by @BufferPtr@, @Count@, @Datatype@) to\n the process specified by (@Comm@, @Rank@, @Tag@). Caller will\n block until data is copied from the send buffer by the MPI\n-}\n{# fun unsafe Send as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{-| Variant of 'send' that would terminate only when receiving side\nactually starts receiving data. \n-}\n{# fun unsafe Ssend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{-| Variant of 'send' that expects the relevant 'recv' to be already\nstarted, otherwise this call could terminate with MPI error.\n-}\n{# fun unsafe Rsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n-- | Receives data from the process\n-- specified by (@Comm@, @Rank@, @Tag@) and stores it into buffer specified\n-- by (@BufferPtr@, @Count@, @Datatype@).\n{# fun unsafe Recv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast* } -> `()' checkError*- #}\n-- | Send the values (as specified by @BufferPtr@, @Count@, @Datatype@) to\n-- the process specified by (@Comm@, @Rank@, @Tag@) in non-blocking mode.\n-- \n-- Use 'probe' or 'test' to check the status of the operation,\n-- 'cancel' to terminate it or 'wait' to block until it completes.\n-- Operation would be considered complete as soon as MPI finishes\n-- copying the data from the send buffer. \n{# fun unsafe Isend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n-- | Variant of the 'isend' that would be considered complete only when\n-- receiving side actually starts receiving data. \n{# fun unsafe Issend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n-- | Non-blocking variant of 'recv'. Receives data from the process\n-- specified by (@Comm@, @Rank@, @Tag@) and stores it into buffer specified\n-- by (@BufferPtr@, @Count@, @Datatype@).\n{# fun Irecv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n\n-- | Like 'isend', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun unsafe Isend as isendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'issend', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun unsafe Issend as issendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'irecv', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun Irecv as irecvPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Broadcast data from one member to all members of the communicator.\n{# fun unsafe Bcast as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocks until all processes on the communicator call this function.\n-- This function corresponds to @MPI_Barrier@.\n{# fun unsafe Barrier as ^ {fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocking test for the completion of a send of receive.\n-- See 'test' for a non-blocking variant.\n-- This function corresponds to @MPI_Wait@. Request pointer could\n-- be changed to point to @requestNull@. See @wait@ for variant that does not mutate request value.\n{# fun unsafe Wait as waitPtr\n {castPtr `Ptr Request', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Same as @waitPtr@, but does not change Haskell @Request@ value to point to @procNull@.\n-- Usually, this is harmless - your request just would be considered inactive.\nwait request = withRequest request waitPtr\n\n-- | Takes pointer to the array of Requests of given size, 'wait's on all of them,\n-- populates array of Statuses of the same size. This function corresponds to @MPI_Waitall@\n{# fun unsafe Waitall as ^\n { id `Count', castPtr `Ptr Request', castPtr `Ptr Status'} -> `()' checkError*- #}\n-- TODO: Make this Storable Array instead of Ptr ?\n\n-- | Non-blocking test for the completion of a send or receive.\n-- Returns @Nothing@ if the request is not complete, otherwise\n-- it returns @Just status@.\n--\n-- Note that while MPI would modify\n-- request to be @requestNull@ if the operation is complete,\n-- Haskell value would not be changed. So, if you got (Just status)\n-- as a result, consider your request to be @requestNull@. Or use @testPtr@.\n--\n-- See 'wait' for a blocking variant.\n-- This function corresponds to @MPI_Test@.\ntest :: Request -> IO (Maybe Status)\ntest request = withRequest request testPtr\n\n-- | Analogous to 'test' but uses pointer to @Request@. If request is completed, pointer would be \n-- set to point to @requestNull@.\ntestPtr :: Ptr Request -> IO (Maybe Status)\ntestPtr reqPtr = do\n (flag, status) <- testPtr' reqPtr\n request' <- peek reqPtr\n if flag\n then do if request' == requestNull\n then return $ Just status\n else error \"testPtr: request modified, but not set to MPI_REQUEST_NULL!\"\n else return Nothing\n where testPtr' = {# fun unsafe Test as testPtr_\n {castPtr `Ptr Request', alloca- `Bool' peekBool*, allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Cancel a pending communication request.\n-- This function corresponds to @MPI_Cancel@. Sets pointer to point to @requestNull@.\n{# fun unsafe Cancel as cancelPtr\n {castPtr `Ptr Request'} -> `()' checkError*- #}\n\n\n-- | Same as @cancelPtr@, but does not change Haskell @Request@ value to point to @procNull@.\n-- Usually, this is harmless - your request just would be considered inactive.\ncancel request = withRequest request cancelPtr\n\nwithRequest req f = do alloca $ \\ptr -> do poke ptr req\n f (castPtr ptr)\n\n-- | Scatter data from one member to all members of\n-- a group.\n{# fun unsafe Scatter as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Gather data from all members of a group to one\n-- member.\n{# fun unsafe Gather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- Note: We pass counts\/displs as Ptr CInt so that caller could supply nullPtr here\n-- which would be impossible if we marshal arrays ourselves here.\n\n-- | A variation of 'scatter' which allows to use data segments of\n-- different length.\n{# fun unsafe Scatterv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'gather' which allows to use data segments of\n-- different length.\n{# fun unsafe Gatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'gather' where all members of\n-- a group receive the result.\n{# fun unsafe Allgather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'allgather' that allows to use data segments of\n-- different length.\n{# fun unsafe Allgatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Scatter\/Gather data from all\n-- members to all members of a group (also called complete exchange)\n{# fun unsafe Alltoall as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variant of 'alltoall' allows to use data segments of different length.\n{# fun unsafe Alltoallv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\n\n-- | Applies predefined or user-defined reduction operations to data,\n-- and delivers result to the single process.\n{# fun Reduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Applies predefined or user-defined reduction operations to data,\n-- and delivers result to all members of the group.\n{# fun Allreduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A combined reduction and scatter operation - result is split and\n-- parts are distributed among the participating processes.\n--\n-- See 'reduceScatter' for variant that allows to specify personal\n-- block size for each process.\n--\n-- Note that this call is not supported with some MPI implementations,\n-- like OpenMPI <= 1.5 and would cause a run-time 'error' in that case.\n#if 0\n{# fun Reduce_scatter_block as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n#else\nreduceScatterBlock :: BufferPtr -> BufferPtr -> Count -> Datatype -> Operation -> Comm -> IO ()\nreduceScatterBlock = error \"reduceScatterBlock is not supported by OpenMPI\"\n#endif\n\n-- | A combined reduction and scatter operation - result is split and\n-- parts are distributed among the participating processes.\n{# fun Reduce_scatter as ^\n { id `BufferPtr', id `BufferPtr', id `Ptr CInt', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n\n-- TODO: In the following haddock block, mention SCAN and EXSCAN once\n-- they are implemented \n\n{- | Binds a user-dened reduction operation to an 'Operation' handle that can\nsubsequently be used in 'reduce', 'allreduce', and 'reduceScatter'.\nThe user-defined operation is assumed to be associative. \n\nIf second argument to @opCreate@ is @True@, then the operation should be both commutative and associative. If\nit is not commutative, then the order of operands is fixed and is defined to be in ascending,\nprocess rank order, beginning with process zero. The order of evaluation can be changed,\ntaking advantage of the associativity of the operation. If operation\nis commutative then the order\nof evaluation can be changed, taking advantage of commutativity and\nassociativity.\n\nUser-defined operation accepts four arguments, @invec@, @inoutvec@,\n@len@ and @datatype@:\n\n[@invec@] first input vector\n\n[@inoutvec@] second input vector, which is also the output vector\n\n[@len@] length of both vectors\n\n[@datatype@] type of the elements in both vectors.\n\nFunction is expected to apply reduction operation to the elements\nof @invec@ and @inoutvec@ in pariwise manner:\n\n@\ninoutvec[i] = op invec[i] inoutvec[i]\n@\n\nFull example with user-defined function that mimics standard operation\n'sumOp':\n\n@\nimport \"Control.Parallel.MPI.Fast\"\n\nforeign import ccall \\\"wrapper\\\" \n wrap :: (Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()) \n -> IO (FunPtr (Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()))\nreduceUserOpTest myRank = do\n numProcs <- commSize commWorld\n userSumPtr <- wrap userSum\n mySumOp <- opCreate True userSumPtr\n (src :: StorableArray Int Double) <- newListArray (0,99) [0..99]\n if myRank \/= root\n then reduceSend commWorld root sumOp src\n else do\n (result :: StorableArray Int Double) <- intoNewArray_ (0,99) $ reduceRecv commWorld root mySumOp src\n recvMsg <- getElems result\n freeHaskellFunPtr userSumPtr\n where\n userSum :: Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()\n userSum inPtr inoutPtr lenPtr _ = do\n len <- peek lenPtr\n let offs = sizeOf ( undefined :: CDouble )\n let loop 0 _ _ = return ()\n loop n inPtr inoutPtr = do\n a <- peek inPtr\n b <- peek inoutPtr\n poke inoutPtr (a+b)\n loop (n-1) (plusPtr inPtr offs) (plusPtr inoutPtr offs)\n loop len inPtr inoutPtr\n@\n-}\n{# fun unsafe Op_create as ^\n {castFunPtr `FunPtr (Ptr t -> Ptr t -> Ptr CInt -> Ptr Datatype -> IO ())', cFromEnum `Bool', alloca- `Operation' peekOperation*} -> `()' checkError*- #}\n\n{- | Free the handle for user-defined reduction operation created by 'opCreate'\n-}\n{# fun Op_free as ^ {withOperation* `Operation'} -> `()' checkError*- #}\n\n{- | Returns a \nfloating-point number of seconds, representing elapsed wallclock\ntime since some time in the past.\n\nThe \\\"time in the past\\\" is guaranteed not to change during the life of the process.\nThe user is responsible for converting large numbers of seconds to other units if they are\npreferred. The time is local to the node that calls @wtime@, but see 'wtimeIsGlobal'.\n-}\n{# fun unsafe Wtime as ^ {} -> `Double' realToFrac #}\n\n{- | Returns the resolution of 'wtime' in seconds. That is, it returns,\nas a double precision value, the number of seconds between successive clock ticks. For\nexample, if the clock is implemented by the hardware as a counter that is incremented\nevery millisecond, the value returned by @wtick@ should be 10^(-3).\n-}\n{# fun unsafe Wtick as ^ {} -> `Double' realToFrac #}\n\n-- | Return the process group from a communicator. With\n-- intercommunicator, returns the local group.\n{# fun unsafe Comm_group as ^\n {fromComm `Comm', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Returns the rank of the calling process in the given group. This function corresponds to @MPI_Group_rank@.\ngroupRank :: Group -> Rank\ngroupRank = unsafePerformIO <$> groupRank'\n where groupRank' = {# fun unsafe Group_rank as groupRank_\n {fromGroup `Group', alloca- `Rank' peekIntConv*} -> `()' checkError*- #}\n\n-- | Returns the size of a group. This function corresponds to @MPI_Group_size@.\ngroupSize :: Group -> Int\ngroupSize = unsafePerformIO <$> groupSize'\n where groupSize' = {# fun unsafe Group_size as groupSize_\n {fromGroup `Group', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Constructs the union of two groups: all the members of the first group, followed by all the members of the \n-- second group that do not appear in the first group. This function corresponds to @MPI_Group_union@.\ngroupUnion :: Group -> Group -> Group\ngroupUnion g1 g2 = unsafePerformIO $ groupUnion' g1 g2\n where groupUnion' = {# fun unsafe Group_union as groupUnion_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Constructs a new group which is the intersection of two groups. This function corresponds to @MPI_Group_intersection@.\ngroupIntersection :: Group -> Group -> Group\ngroupIntersection g1 g2 = unsafePerformIO $ groupIntersection' g1 g2\n where groupIntersection' = {# fun unsafe Group_intersection as groupIntersection_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Constructs a new group which contains all the elements of the first group which are not in the second group. \n-- This function corresponds to @MPI_Group_difference@.\ngroupDifference :: Group -> Group -> Group\ngroupDifference g1 g2 = unsafePerformIO $ groupDifference' g1 g2\n where groupDifference' = {# fun unsafe Group_difference as groupDifference_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Compares two groups. Returns 'MPI_IDENT' if the order and members of the two groups are the same,\n-- 'MPI_SIMILAR' if only the members are the same, and 'MPI_UNEQUAL' otherwise.\ngroupCompare :: Group -> Group -> ComparisonResult\ngroupCompare g1 g2 = unsafePerformIO $ groupCompare' g1 g2\n where\n groupCompare' = {# fun unsafe Group_compare as groupCompare_\n {fromGroup `Group', fromGroup `Group', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- Technically it might make better sense to make the second argument a Set rather than a list\n-- but the order is significant in the groupIncl function (the other function, not this one).\n-- For the sake of keeping their types in sync, a list is used instead.\n{- | Create a new @Group@ from the given one. Exclude processes\nwith given @Rank@s from the new @Group@. Processes in new @Group@ will\nhave ranks @[0...]@.\n-}\n{# fun unsafe Group_excl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n{- | Create a new @Group@ from the given one. Include only processes\nwith given @Rank@s in the new @Group@. Processes in new @Group@ will\nhave ranks @[0...]@.\n-}\n{# fun unsafe Group_incl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n{- | Given two @Group@s and list of @Rank@s of some processes in the\nfirst @Group@, return @Rank@s of those processes in the second\n@Group@. If there are no corresponding @Rank@ in the second @Group@,\n'mpiUndefined' is returned.\n\nThis function is important for determining the relative numbering of the same processes\nin two different groups. For instance, if one knows the ranks of certain processes in the group\nof 'commWorld', one might want to know their ranks in a subset of that group.\nNote that 'procNull' is a valid rank for input to @groupTranslateRanks@, which\nreturns 'procNull' as the translated rank.\n-}\ngroupTranslateRanks :: Group -> [Rank] -> Group -> [Rank]\ngroupTranslateRanks group1 ranks group2 =\n unsafePerformIO $ do\n let (rankIntList :: [Int]) = map fromEnum ranks\n withArrayLen rankIntList $ \\size ranksPtr ->\n allocaArray size $ \\resultPtr -> do\n groupTranslateRanks' group1 (cFromEnum size) (castPtr ranksPtr) group2 resultPtr\n map toRank <$> peekArray size resultPtr\n where\n groupTranslateRanks' = {# fun unsafe Group_translate_ranks as groupTranslateRanks_\n {fromGroup `Group', id `CInt', id `Ptr CInt', fromGroup `Group', id `Ptr CInt'} -> `()' checkError*- #}\n\nwithRanksAsInts ranks f = withArrayLen (map fromEnum ranks) $ \\size ptr -> f (cIntConv size, castPtr ptr)\n\n{- | If a process was started with 'commSpawn', @commGetParent@\nreturns the parent intercommunicator of the current process. This\nparent intercommunicator is created implicitly inside of 'init' and\nis the same intercommunicator returned by 'commSpawn' in the\nparents. If the process was not spawned, @commGetParent@ returns\n'commNull'. After the parent communicator is freed or disconnected,\n@commGetParent@ returns 'commNull'. -} \n\n{# fun unsafe Comm_get_parent as ^\n {alloca- `Comm' peekComm*} -> `()' checkError*- #}\n\nwithT = with\n{# fun unsafe Comm_spawn as ^\n { `String' \n , withT* `Ptr CChar'\n , id `Count'\n , fromInfo `Info'\n , fromRank `Rank'\n , fromComm `Comm'\n , alloca- `Comm' peekComm*\n , id `Ptr CInt'} -> `()' checkError*- #}\n\nforeign import ccall unsafe \"&mpi_argv_null\" mpiArgvNull_ :: Ptr (Ptr CChar)\nforeign import ccall unsafe \"&mpi_errcodes_ignore\" mpiErrcodesIgnore_ :: Ptr (Ptr CInt)\nargvNull = unsafePerformIO $ peek mpiArgvNull_\nerrcodesIgnore = unsafePerformIO $ peek mpiErrcodesIgnore_\n\n{-| Simplified version of `commSpawn' that does not support argument passing and spawn error code checking. -}\ncommSpawnSimple rank program maxprocs =\n commSpawn program argvNull maxprocs infoNull rank commSelf errcodesIgnore\n\n{-| Opens up a port (network address) on the server where clients\n can establish connections using @commConnect@.\n\nRefer to MPI Report v2.2, Section 10.4 \"Establishing communication\"\nfor more details on client\/server programming with MPI. -}\nopenPort :: Info -> IO String\nopenPort info = do\n allocaBytes (fromIntegral maxPortName) $ \\ptr -> do\n openPort' info ptr\n peekCStringLen (ptr, fromIntegral maxPortName)\n where\n openPort' = {# fun unsafe Open_port as openPort_\n {fromInfo `Info', id `Ptr CChar'} -> `()' checkError*- #}\n\n-- | Closes the specified port on the server.\n{# fun unsafe Close_port as ^\n {`String'} -> `()' checkError*- #}\n\n{-| @commAccept@ allows a connection from a client. The intercommunicator\n object returned can be used to communicate with the client. -}\n{# fun unsafe Comm_accept as ^\n { `String'\n , fromInfo `Info'\n , fromRank `Rank'\n , fromComm `Comm'\n , alloca- `Comm' peekComm*} -> `()' checkError*- #}\n\n{-| @commConnect@ creates a connection to the server. The intercommunicator \n object returned can be used to communicate with the server. -}\n{# fun unsafe Comm_connect as ^\n { `String'\n , fromInfo `Info'\n , fromRank `Rank'\n , fromComm `Comm'\n , alloca- `Comm' peekComm*} -> `()' checkError*- #}\n\n-- | Free a communicator object.\n{# fun Comm_free as ^ {withComm* `Comm'} -> `()' checkError*- #}\n\n-- | Stop pending communication and deallocate a communicator object.\n{# fun Comm_disconnect as ^ {withComm* `Comm'} -> `()' checkError*- #}\n\nforeign import ccall \"&mpi_undefined\" mpiUndefined_ :: Ptr Int\n\n-- | Predefined constant that might be returned as @Rank@ by calls\n-- like 'groupTranslateRanks'. Corresponds to @MPI_UNDEFINED@. Please\n-- refer to \\\"MPI Report Constant And Predefined Handle Index\\\" for a\n-- list of situations where @mpiUndefined@ could appear.\nmpiUndefined :: Int\nmpiUndefined = unsafePerformIO $ peek mpiUndefined_\n\n-- | Return the number of bytes used to store an MPI @Datatype@.\ntypeSize :: Datatype -> Int\ntypeSize = unsafePerformIO . typeSize'\n where\n typeSize' =\n {# fun unsafe Type_size as typeSize_\n {fromDatatype `Datatype', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n{# fun unsafe Error_class as ^\n { id `CInt', alloca- `CInt' peek*} -> `CInt' id #}\n\n-- | Set the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_set_errhandler@.\n{# fun unsafe Comm_set_errhandler as ^\n {fromComm `Comm', fromErrhandler `Errhandler'} -> `()' checkError*- #}\n\n-- | Get the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_get_errhandler@.\n{# fun unsafe Comm_get_errhandler as ^\n {fromComm `Comm', alloca- `Errhandler' peekErrhandler*} -> `()' checkError*- #}\n\n-- | Tries to terminate all MPI processes in its communicator argument.\n-- The second argument is an error code which \/may\/ be used as the return status\n-- of the MPI process, but this is not guaranteed. On systems where 'Int' has a larger\n-- range than 'CInt', the error code will be clipped to fit into the range of 'CInt'.\n-- This function corresponds to @MPI_Abort@.\nabort :: Comm -> Int -> IO ()\nabort comm code =\n abort' comm (toErrorCode code)\n where\n toErrorCode :: Int -> CInt\n toErrorCode i\n -- Assumes Int always has range at least as big as CInt.\n | i < (fromIntegral (minBound :: CInt)) = minBound\n | i > (fromIntegral (maxBound :: CInt)) = maxBound\n | otherwise = cIntConv i\n\n abort' = {# fun unsafe Abort as abort_ {fromComm `Comm', id `CInt'} -> `()' checkError*- #}\n\n\ntype MPIDatatype = {# type MPI_Datatype #}\n\n-- | Haskell datatype used to represent @MPI_Datatype@. \n-- Please refer to Chapter 4 of MPI Report v. 2.2 for a description\n-- of various datatypes.\nnewtype Datatype = MkDatatype { fromDatatype :: MPIDatatype }\n\nforeign import ccall unsafe \"&mpi_char\" char_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_wchar\" wchar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_short\" short_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_int\" int_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long\" long_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_long\" longLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_char\" unsignedChar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_short\" unsignedShort_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned\" unsigned_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long\" unsignedLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long_long\" unsignedLongLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_float\" float_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_double\" double_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_double\" longDouble_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_byte\" byte_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_packed\" packed_ :: Ptr MPIDatatype\n\nchar, wchar, short, int, long, longLong, unsignedChar, unsignedShort :: Datatype\nunsigned, unsignedLong, unsignedLongLong, float, double, longDouble :: Datatype\nbyte, packed :: Datatype\n\nchar = MkDatatype <$> unsafePerformIO $ peek char_\nwchar = MkDatatype <$> unsafePerformIO $ peek wchar_\nshort = MkDatatype <$> unsafePerformIO $ peek short_\nint = MkDatatype <$> unsafePerformIO $ peek int_\nlong = MkDatatype <$> unsafePerformIO $ peek long_\nlongLong = MkDatatype <$> unsafePerformIO $ peek longLong_\nunsignedChar = MkDatatype <$> unsafePerformIO $ peek unsignedChar_\nunsignedShort = MkDatatype <$> unsafePerformIO $ peek unsignedShort_\nunsigned = MkDatatype <$> unsafePerformIO $ peek unsigned_\nunsignedLong = MkDatatype <$> unsafePerformIO $ peek unsignedLong_\nunsignedLongLong = MkDatatype <$> unsafePerformIO $ peek unsignedLongLong_\nfloat = MkDatatype <$> unsafePerformIO $ peek float_\ndouble = MkDatatype <$> unsafePerformIO $ peek double_\nlongDouble = MkDatatype <$> unsafePerformIO $ peek longDouble_\nbyte = MkDatatype <$> unsafePerformIO $ peek byte_\npacked = MkDatatype <$> unsafePerformIO $ peek packed_\n\ntype MPIErrhandler = {# type MPI_Errhandler #}\n\n-- | Haskell datatype that represents values usable as @MPI_Errhandler@\nnewtype Errhandler = MkErrhandler { fromErrhandler :: MPIErrhandler } deriving Storable\npeekErrhandler ptr = MkErrhandler <$> peek ptr\n\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr MPIErrhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr MPIErrhandler\n\n-- | Predefined @Errhandler@ that will terminate the process on any\n-- MPI error\nerrorsAreFatal :: Errhandler\nerrorsAreFatal = MkErrhandler <$> unsafePerformIO $ peek errorsAreFatal_\n\n-- | Predefined @Errhandler@ that will convert errors into Haskell\n-- exceptions. Mimics the semantics of @MPI_Errors_return@\nerrorsReturn :: Errhandler\nerrorsReturn = MkErrhandler <$> unsafePerformIO $ peek errorsReturn_\n\n-- | Same as 'errorsReturn', but with a more meaningful name.\nerrorsThrowExceptions :: Errhandler\nerrorsThrowExceptions = errorsReturn\n\n{# enum ErrorClass {underscoreToCase} deriving (Eq,Ord,Show,Typeable) #}\n\n-- XXX Should this be a ForeinPtr?\n-- there is a MPI_Group_free function, which we should probably\n-- call when the group is no longer referenced.\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIGroup = {# type MPI_Group #}\n\n-- | Haskell datatype representing MPI process groups.\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\npeekGroup ptr = MkGroup <$> peek ptr\n\nforeign import ccall \"&mpi_group_empty\" groupEmpty_ :: Ptr MPIGroup\n-- | A predefined group without any members. Corresponds to @MPI_GROUP_EMPTY@.\ngroupEmpty :: Group\ngroupEmpty = MkGroup <$> unsafePerformIO $ peek groupEmpty_\n\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIOperation = {# type MPI_Op #}\n\n{- | Abstract type representing handle for MPI reduction operation\n(that can be used with 'reduce', 'allreduce', and 'reduceScatter').\n-}\nnewtype Operation = MkOperation { fromOperation :: MPIOperation } deriving Storable\npeekOperation ptr = MkOperation <$> peek ptr\nwithOperation op f = alloca $ \\ptr -> do poke ptr (fromOperation op)\n f (castPtr ptr)\n\nforeign import ccall unsafe \"&mpi_max\" maxOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_min\" minOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_sum\" sumOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_prod\" prodOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_land\" landOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_band\" bandOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lor\" lorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bor\" borOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lxor\" lxorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bxor\" bxorOp_ :: Ptr MPIOperation\n-- foreign import ccall \"mpi_maxloc\" maxlocOp :: MPIOperation\n-- foreign import ccall \"mpi_minloc\" minlocOp :: MPIOperation\n-- foreign import ccall \"mpi_replace\" replaceOp :: MPIOperation\n-- TODO: support for those requires better support for pair datatypes\n\n-- | Predefined reduction operation: maximum\nmaxOp :: Operation\nmaxOp = MkOperation <$> unsafePerformIO $ peek maxOp_\n\n-- | Predefined reduction operation: minimum\nminOp :: Operation\nminOp = MkOperation <$> unsafePerformIO $ peek minOp_\n\n-- | Predefined reduction operation: (+)\nsumOp :: Operation\nsumOp = MkOperation <$> unsafePerformIO $ peek sumOp_\n\n-- | Predefined reduction operation: (*)\nprodOp :: Operation\nprodOp = MkOperation <$> unsafePerformIO $ peek prodOp_\n\n-- | Predefined reduction operation: logical \\\"and\\\"\nlandOp :: Operation\nlandOp = MkOperation <$> unsafePerformIO $ peek landOp_\n\n-- | Predefined reduction operation: bit-wise \\\"and\\\"\nbandOp :: Operation\nbandOp = MkOperation <$> unsafePerformIO $ peek bandOp_\n\n-- | Predefined reduction operation: logical \\\"or\\\"\nlorOp :: Operation\nlorOp = MkOperation <$> unsafePerformIO $ peek lorOp_\n\n-- | Predefined reduction operation: bit-wise \\\"or\\\"\nborOp :: Operation\nborOp = MkOperation <$> unsafePerformIO $ peek borOp_\n\n-- | Predefined reduction operation: logical \\\"xor\\\"\nlxorOp :: Operation\nlxorOp = MkOperation <$> unsafePerformIO $ peek lxorOp_\n\n-- | Predefined reduction operation: bit-wise \\\"xor\\\"\nbxorOp :: Operation\nbxorOp = MkOperation <$> unsafePerformIO $ peek bxorOp_\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIInfo = {# type MPI_Info #}\n\n{- | Abstract type representing handle for MPI Info object\n-}\nnewtype Info = MkInfo { fromInfo :: MPIInfo } deriving Storable\npeekInfo ptr = MkInfo <$> peek ptr\n\nforeign import ccall \"&mpi_info_null\" infoNull_ :: Ptr MPIInfo\n\n-- | Predefined info object that has no info\ninfoNull :: Info\ninfoNull = unsafePerformIO $ peekInfo infoNull_\n\n{-| Creates new empty info object -}\n{# fun unsafe Info_create as ^\n {alloca- `Info' peekInfo*} -> `()' checkError*- #}\n\n{-| Adds specified (key, value) pair to info object -}\n{# fun unsafe Info_set as ^\n {fromInfo `Info', `String', `String'} -> `()' checkError*- #}\n\n{-| Deletes the specified key from info object -}\n{# fun unsafe Info_delete as ^\n {fromInfo `Info', `String'} -> `()' checkError*- #}\n\n{-| Gets the specified key -}\ninfoGet :: Info -> String -> IO (Maybe String)\ninfoGet info key = do\n (len, found) <- infoGetValuelen' info key \n -- len+1 is required to allow for the terminating \\NULL\n if found\/=0 then allocaBytes (fromIntegral len + 1)\n (\\bufferPtr -> do\n found <- infoGet' info key (len+1) bufferPtr\n if found\/=0 then Just <$> peekCStringLen (bufferPtr, fromIntegral len)\n else return Nothing)\n else return Nothing\n\ninfoGetValuelen' = {# fun unsafe Info_get_valuelen as infoGetValuelen_\n {fromInfo `Info', `String', alloca- `CInt' peek*, alloca- `CInt' peek* } -> `()' checkError*- #}\n\ninfoGet' = {# fun unsafe Info_get as infoGet_\n {fromInfo `Info', `String', id `CInt', castPtr `Ptr CChar', alloca- `CInt' peek*} -> `()' checkError*- #}\n\n\n{- | Haskell datatype that represents values which\n could be used as MPI rank designations. Low-level MPI calls require\n that you use 32-bit non-negative integer values as ranks, so any\n non-numeric Haskell Ranks should provide a sensible instances of\n 'Enum'.\n\nAttempt to supply a value that does not fit into 32 bits will cause a\nrun-time 'error'.\n-}\nnewtype Rank = MkRank { rankId :: CInt -- ^ Extract numeric value of the 'Rank'\n }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Rank where\n (MkRank x) + (MkRank y) = MkRank (x+y)\n (MkRank x) * (MkRank y) = MkRank (x*y)\n abs (MkRank x) = MkRank (abs x)\n signum (MkRank x) = MkRank (signum x)\n fromInteger x\n | x > ( fromIntegral (maxBound :: CInt)) = error \"Rank value does not fit into 32 bits\"\n | x < 0 = error \"Negative Rank value\"\n | otherwise = MkRank (fromIntegral x)\n\nforeign import ccall \"&mpi_any_source\" anySource_ :: Ptr CInt\nforeign import ccall \"&mpi_root\" theRoot_ :: Ptr CInt\nforeign import ccall \"&mpi_proc_null\" procNull_ :: Ptr CInt\nforeign import ccall \"&mpi_request_null\" requestNull_ :: Ptr MPIRequest\nforeign import ccall \"&mpi_comm_null\" commNull_ :: Ptr MPIComm\n\n-- | Predefined rank number that allows reception of point-to-point messages\n-- regardless of their source. Corresponds to @MPI_ANY_SOURCE@\nanySource :: Rank\nanySource = toRank $ unsafePerformIO $ peek anySource_\n\n-- | Predefined rank number that specifies root process during\n-- operations involving intercommunicators. Corresponds to @MPI_ROOT@\ntheRoot :: Rank\ntheRoot = toRank $ unsafePerformIO $ peek theRoot_\n\n-- | Predefined rank number that specifies non-root processes during\n-- operations involving intercommunicators. Corresponds to @MPI_PROC_NULL@\nprocNull :: Rank\nprocNull = toRank $ unsafePerformIO $ peek procNull_\n\n-- | Predefined request handle value that specifies non-existing or finished request.\n-- Corresponds to @MPI_REQUEST_NULL@\nrequestNull :: Request\nrequestNull = unsafePerformIO $ peekRequest requestNull_\n\n-- | Predefined communicator handle value that specifies non-existing or destroyed (inter-)communicator.\n-- Corresponds to @MPI_COMM_NULL@\ncommNull :: Comm\ncommNull = unsafePerformIO $ peekComm commNull_\n\ninstance Show Rank where\n show = show . rankId\n\n-- | Map arbitrary 'Enum' value to 'Rank'\ntoRank :: Enum a => a -> Rank\ntoRank x = MkRank { rankId = cIntConv (fromEnum x) }\n\n-- | Map 'Rank' to arbitrary 'Enum'\nfromRank :: Enum a => Rank -> a\nfromRank = toEnum . cIntConv . rankId\n\ntype MPIRequest = {# type MPI_Request #}\n{-| Haskell representation of the @MPI_Request@ type. Returned by\nnon-blocking communication operations, could be further processed with\n'probe', 'test', 'cancel' or 'wait'. -}\nnewtype Request = MkRequest MPIRequest deriving (Storable,Eq)\npeekRequest ptr = MkRequest <$> peek ptr\n\n{-\nThis module provides Haskell representation of the @MPI_Status@ type\n(request status).\n\nField `status_error' should be used with care:\n\\\"The error field in status is not needed for calls that return only\none status, such as @MPI_WAIT@, since that would only duplicate the\ninformation returned by the function itself. The current design avoids\nthe additional overhead of setting it, in such cases. The field is\nneeded for calls that return multiple statuses, since each request may\nhave had a different failure.\\\"\n(this is a quote from )\n\nThis means that, for example, during the call to @MPI_Wait@\nimplementation is free to leave this field filled with whatever\ngarbage got there during memory allocation. Haskell FFI is not\nblanking out freshly allocated memory, so beware!\n-}\n\n-- | Haskell structure that holds fields of @MPI_Status@.\ndata Status =\n Status\n { status_source :: Rank -- ^ rank of the source process\n , status_tag :: Tag -- ^ tag assigned at source\n , status_error :: CInt -- ^ error code, if any\n }\n deriving (Eq, Ord, Show)\n\ninstance Storable Status where\n sizeOf _ = {#sizeof MPI_Status #}\n alignment _ = 4\n peek p = Status\n <$> liftM (MkRank . cIntConv) ({#get MPI_Status->MPI_SOURCE #} p)\n <*> liftM (MkTag . cIntConv) ({#get MPI_Status->MPI_TAG #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_ERROR #} p)\n poke p x = do\n {#set MPI_Status.MPI_SOURCE #} p (fromRank $ status_source x)\n {#set MPI_Status.MPI_TAG #} p (fromTag $ status_tag x)\n {#set MPI_Status.MPI_ERROR #} p (cIntConv $ status_error x)\n\n-- NOTE: Int here is picked arbitrary\nallocaCast f =\n alloca $ \\(ptr :: Ptr Int) -> f (castPtr ptr :: Ptr ())\npeekCast = peek . castPtr\n\n\n{-| Haskell datatype that represents values which could be used as\ntags for point-to-point transfers.\n-}\nnewtype Tag = MkTag { tagVal :: CInt -- ^ Extract numeric value of the Tag\n }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Tag where\n (MkTag x) + (MkTag y) = MkTag (x+y)\n (MkTag x) * (MkTag y) = MkTag (x*y)\n abs (MkTag x) = MkTag (abs x)\n signum (MkTag x) = MkTag (signum x)\n fromInteger x\n | fromIntegral x > tagUpperBound = error \"Tag value is over the MPI_TAG_UB\"\n | x < 0 = error \"Negative Tag value\"\n | otherwise = MkTag (fromIntegral x)\n\ninstance Show Tag where\n show = show . tagVal\n\n-- | Map arbitrary 'Enum' value to 'Tag'\ntoTag :: Enum a => a -> Tag\ntoTag x = MkTag { tagVal = cIntConv (fromEnum x) }\n\n-- | Map 'Tag' to arbitrary 'Enum'\nfromTag :: Enum a => Tag -> a\nfromTag = toEnum . cIntConv . tagVal\n\nforeign import ccall unsafe \"&mpi_any_tag\" anyTag_ :: Ptr CInt\n\n-- | Predefined tag value that allows reception of the messages with\n-- arbitrary tag values. Corresponds to @MPI_ANY_TAG@.\nanyTag :: Tag\nanyTag = toTag $ unsafePerformIO $ peek anyTag_\n\n-- | A tag with unit value. Intended to be used as a convenient default.\nunitTag :: Tag\nunitTag = toTag ()\n\n{- | Constants used to describe the required level of multithreading\n support in call to 'initThread'. They also describe provided level\n of multithreading support as returned by 'queryThread' and\n 'initThread'.\n\n[@Single@] Only one thread will execute.\n\n[@Funneled@] The process may be multi-threaded, but the application must\nensure that only the main thread makes MPI calls (see 'isThreadMain').\n\n[@Serialized@] The process may be multi-threaded, and multiple threads may\nmake MPI calls, but only one at a time: MPI calls are not made concurrently from\ntwo distinct threads\n\n[@Multiple@] Multiple threads may call MPI, with no restrictions.\n\nXXX Make sure we have the correct ordering as defined by MPI. Also we should\ndescribe the ordering here (other parts of the docs need it to be explained - see initThread).\n\n-}\n{# enum ThreadSupport {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- | Value thrown as exception when MPI runtime is instructed to pass\n-- errors to user code (via 'commSetErrhandler' and 'errorsReturn').\n-- Since raw MPI errors codes are not standartized and not portable,\n-- they are not exposed.\ndata MPIError\n = MPIError\n { mpiErrorClass :: ErrorClass -- ^ Broad class of errors this one belongs to\n , mpiErrorString :: String -- ^ Human-readable error description\n }\n deriving (Eq, Show, Typeable)\n\ninstance Exception MPIError\n\ncheckError :: CInt -> IO ()\ncheckError code = do\n -- We ignore the error code from the call to Internal.errorClass\n -- because we call errorClass from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n (_, errClassRaw) <- errorClass code\n let errClass = cToEnum errClassRaw\n unless (errClass == Success) $ do\n errStr <- errorString code\n throwIO $ MPIError errClass errStr\n\n-- | Convert MPI error code human-readable error description. Corresponds to @MPI_Error_string@.\nerrorString :: CInt -> IO String\nerrorString code =\n allocaBytes (fromIntegral maxErrorString) $ \\ptr ->\n alloca $ \\lenPtr -> do\n -- We ignore the error code from the call to Internal.errorString\n -- because we call errorString from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n _ <- errorString' code ptr lenPtr\n len <- peek lenPtr\n peekCStringLen (ptr, cIntConv len)\n where\n errorString' = {# call unsafe Error_string as errorString_ #}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"1f5287e0b8b83343df9a79c46237a0869045ec24","subject":"Fix stats\/socket callback types","message":"Fix stats\/socket callback types\n","repos":"haskell-works\/kafka-client","old_file":"src\/Kafka\/Internal\/RdKafka.chs","new_file":"src\/Kafka\/Internal\/RdKafka.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE EmptyDataDecls #-}\n\nmodule Kafka.Internal.RdKafka where\n\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as BS\nimport Data.Text (Text)\nimport qualified Data.Text as Text\nimport Control.Monad (liftM)\nimport Data.Int (Int32, Int64)\nimport Data.Word (Word8)\nimport Foreign.Concurrent (newForeignPtr)\nimport Foreign.Marshal.Alloc (alloca, allocaBytes)\nimport Foreign.Marshal.Array (peekArray, allocaArray)\nimport Foreign.Storable (Storable(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr)\nimport Foreign.ForeignPtr (FinalizerPtr, addForeignPtrFinalizer, newForeignPtr_, withForeignPtr)\nimport Foreign.C.Error (Errno(..), getErrno)\nimport Foreign.C.String (CString, newCString, withCAString, peekCAString, peekCString)\nimport Foreign.C.Types (CFile, CInt(..), CSize, CChar)\nimport System.IO (Handle, stdin, stdout, stderr)\nimport System.Posix.IO (handleToFd)\nimport System.Posix.Types (Fd(..))\n\n#include \n\ntype CInt64T = {#type int64_t #}\ntype CInt32T = {#type int32_t #}\n\n{#pointer *FILE as CFilePtr -> CFile #}\n{#pointer *size_t as CSizePtr -> CSize #}\n\ntype Word8Ptr = Ptr Word8\ntype CCharBufPointer = Ptr CChar\n\n{#enum rd_kafka_type_t as ^ {underscoreToCase} deriving (Show, Eq) #}\n{#enum rd_kafka_conf_res_t as ^ {underscoreToCase} deriving (Show, Eq) #}\n{#enum rd_kafka_resp_err_t as ^ {underscoreToCase} deriving (Show, Eq, Bounded) #}\n{#enum rd_kafka_timestamp_type_t as ^ {underscoreToCase} deriving (Show, Eq) #}\n\ntype RdKafkaMsgFlag = Int\nrdKafkaMsgFlagFree :: RdKafkaMsgFlag\nrdKafkaMsgFlagFree = 0x1\nrdKafkaMsgFlagCopy :: RdKafkaMsgFlag\nrdKafkaMsgFlagCopy = 0x2\n\n-- Number of bytes allocated for an error buffer\nnErrorBytes :: Int\nnErrorBytes = 1024 * 8\n\n-- Helper functions\n{#fun pure rd_kafka_version as ^\n {} -> `Int' #}\n\n{#fun pure rd_kafka_version_str as ^\n {} -> `String' #}\n\n{#fun pure rd_kafka_err2str as ^\n {enumToCInt `RdKafkaRespErrT'} -> `String' #}\n\n{#fun pure rd_kafka_err2name as ^\n {enumToCInt `RdKafkaRespErrT'} -> `String' #}\n\n{#fun pure rd_kafka_errno2err as ^\n {`Int'} -> `RdKafkaRespErrT' cIntToEnum #}\n\npeekCAText :: CString -> IO Text\npeekCAText cp = Text.pack <$> peekCAString cp\n\npeekCText :: CString -> IO Text\npeekCText cp = Text.pack <$> peekCString cp\n\nkafkaErrnoString :: IO String\nkafkaErrnoString = do\n (Errno num) <- getErrno\n return $ rdKafkaErr2str $ rdKafkaErrno2err (fromIntegral num)\n\n-- Kafka Pointer Types\ndata RdKafkaConfT\n{#pointer *rd_kafka_conf_t as RdKafkaConfTPtr foreign -> RdKafkaConfT #}\n\ndata RdKafkaTopicConfT\n{#pointer *rd_kafka_topic_conf_t as RdKafkaTopicConfTPtr foreign -> RdKafkaTopicConfT #}\n\ndata RdKafkaT\n{#pointer *rd_kafka_t as RdKafkaTPtr foreign -> RdKafkaT #}\n\ndata RdKafkaTopicPartitionT = RdKafkaTopicPartitionT\n { topic'RdKafkaTopicPartitionT :: CString\n , partition'RdKafkaTopicPartitionT :: Int\n , offset'RdKafkaTopicPartitionT :: Int64\n , metadata'RdKafkaTopicPartitionT :: Word8Ptr\n , metadataSize'RdKafkaTopicPartitionT :: Int\n , opaque'RdKafkaTopicPartitionT :: Word8Ptr\n , err'RdKafkaTopicPartitionT :: RdKafkaRespErrT\n } deriving (Show, Eq)\n\ninstance Storable RdKafkaTopicPartitionT where\n alignment _ = {#alignof rd_kafka_topic_partition_t#}\n sizeOf _ = {#sizeof rd_kafka_topic_partition_t#}\n peek p = RdKafkaTopicPartitionT\n <$> liftM id ({#get rd_kafka_topic_partition_t->topic #} p)\n <*> liftM fromIntegral ({#get rd_kafka_topic_partition_t->partition #} p)\n <*> liftM fromIntegral ({#get rd_kafka_topic_partition_t->offset #} p)\n <*> liftM castPtr ({#get rd_kafka_topic_partition_t->metadata #} p)\n <*> liftM fromIntegral ({#get rd_kafka_topic_partition_t->metadata_size #} p)\n <*> liftM castPtr ({#get rd_kafka_topic_partition_t->opaque #} p)\n <*> liftM cIntToEnum ({#get rd_kafka_topic_partition_t->err #} p)\n poke p x = do\n {#set rd_kafka_topic_partition_t.topic#} p (id $ topic'RdKafkaTopicPartitionT x)\n {#set rd_kafka_topic_partition_t.partition#} p (fromIntegral $ partition'RdKafkaTopicPartitionT x)\n {#set rd_kafka_topic_partition_t.offset#} p (fromIntegral $ offset'RdKafkaTopicPartitionT x)\n {#set rd_kafka_topic_partition_t.metadata#} p (castPtr $ metadata'RdKafkaTopicPartitionT x)\n {#set rd_kafka_topic_partition_t.metadata_size#} p (fromIntegral $ metadataSize'RdKafkaTopicPartitionT x)\n {#set rd_kafka_topic_partition_t.opaque#} p (castPtr $ opaque'RdKafkaTopicPartitionT x)\n {#set rd_kafka_topic_partition_t.err#} p (enumToCInt $ err'RdKafkaTopicPartitionT x)\n\n{#pointer *rd_kafka_topic_partition_t as RdKafkaTopicPartitionTPtr foreign -> RdKafkaTopicPartitionT #}\n\ndata RdKafkaTopicPartitionListT = RdKafkaTopicPartitionListT\n { cnt'RdKafkaTopicPartitionListT :: Int\n , size'RdKafkaTopicPartitionListT :: Int\n , elems'RdKafkaTopicPartitionListT :: Ptr RdKafkaTopicPartitionT\n } deriving (Show, Eq)\n\n{#pointer *rd_kafka_topic_partition_list_t as RdKafkaTopicPartitionListTPtr foreign -> RdKafkaTopicPartitionListT #}\n\ninstance Storable RdKafkaTopicPartitionListT where\n alignment _ = {#alignof rd_kafka_topic_partition_list_t#}\n sizeOf _ = {#sizeof rd_kafka_topic_partition_list_t #}\n peek p = RdKafkaTopicPartitionListT\n <$> liftM fromIntegral ({#get rd_kafka_topic_partition_list_t->cnt #} p)\n <*> liftM fromIntegral ({#get rd_kafka_topic_partition_list_t->size #} p)\n <*> liftM castPtr ({#get rd_kafka_topic_partition_list_t->elems #} p)\n poke p x = do\n {#set rd_kafka_topic_partition_list_t.cnt#} p (fromIntegral $ cnt'RdKafkaTopicPartitionListT x)\n {#set rd_kafka_topic_partition_list_t.size#} p (fromIntegral $ size'RdKafkaTopicPartitionListT x)\n {#set rd_kafka_topic_partition_list_t.elems#} p (castPtr $ elems'RdKafkaTopicPartitionListT x)\n\ndata RdKafkaTopicT\n{#pointer *rd_kafka_topic_t as RdKafkaTopicTPtr foreign -> RdKafkaTopicT #}\n\ndata RdKafkaMessageT = RdKafkaMessageT\n { err'RdKafkaMessageT :: RdKafkaRespErrT\n , topic'RdKafkaMessageT :: Ptr RdKafkaTopicT\n , partition'RdKafkaMessageT :: Int\n , len'RdKafkaMessageT :: Int\n , keyLen'RdKafkaMessageT :: Int\n , offset'RdKafkaMessageT :: Int64\n , payload'RdKafkaMessageT :: Word8Ptr\n , key'RdKafkaMessageT :: Word8Ptr\n , opaque'RdKafkaMessageT :: Ptr ()\n }\n deriving (Show, Eq)\n\ninstance Storable RdKafkaMessageT where\n alignment _ = {#alignof rd_kafka_message_t#}\n sizeOf _ = {#sizeof rd_kafka_message_t#}\n peek p = RdKafkaMessageT\n <$> liftM cIntToEnum ({#get rd_kafka_message_t->err #} p)\n <*> liftM castPtr ({#get rd_kafka_message_t->rkt #} p)\n <*> liftM fromIntegral ({#get rd_kafka_message_t->partition #} p)\n <*> liftM fromIntegral ({#get rd_kafka_message_t->len #} p)\n <*> liftM fromIntegral ({#get rd_kafka_message_t->key_len #} p)\n <*> liftM fromIntegral ({#get rd_kafka_message_t->offset #} p)\n <*> liftM castPtr ({#get rd_kafka_message_t->payload #} p)\n <*> liftM castPtr ({#get rd_kafka_message_t->key #} p)\n <*> liftM castPtr ({#get rd_kafka_message_t->_private #} p)\n poke p x = do\n {#set rd_kafka_message_t.err#} p (enumToCInt $ err'RdKafkaMessageT x)\n {#set rd_kafka_message_t.rkt#} p (castPtr $ topic'RdKafkaMessageT x)\n {#set rd_kafka_message_t.partition#} p (fromIntegral $ partition'RdKafkaMessageT x)\n {#set rd_kafka_message_t.len#} p (fromIntegral $ len'RdKafkaMessageT x)\n {#set rd_kafka_message_t.key_len#} p (fromIntegral $ keyLen'RdKafkaMessageT x)\n {#set rd_kafka_message_t.offset#} p (fromIntegral $ offset'RdKafkaMessageT x)\n {#set rd_kafka_message_t.payload#} p (castPtr $ payload'RdKafkaMessageT x)\n {#set rd_kafka_message_t.key#} p (castPtr $ key'RdKafkaMessageT x)\n {#set rd_kafka_message_t._private#} p (castPtr $ opaque'RdKafkaMessageT x)\n\n{#pointer *rd_kafka_message_t as RdKafkaMessageTPtr foreign -> RdKafkaMessageT #}\n\ndata RdKafkaMetadataBrokerT = RdKafkaMetadataBrokerT\n { id'RdKafkaMetadataBrokerT :: Int\n , host'RdKafkaMetadataBrokerT :: CString\n , port'RdKafkaMetadataBrokerT :: Int\n } deriving (Show, Eq)\n\n{#pointer *rd_kafka_metadata_broker_t as RdKafkaMetadataBrokerTPtr -> RdKafkaMetadataBrokerT #}\n\n\ninstance Storable RdKafkaMetadataBrokerT where\n alignment _ = {#alignof rd_kafka_metadata_broker_t#}\n sizeOf _ = {#sizeof rd_kafka_metadata_broker_t#}\n peek p = RdKafkaMetadataBrokerT\n <$> liftM fromIntegral ({#get rd_kafka_metadata_broker_t->id #} p)\n <*> liftM id ({#get rd_kafka_metadata_broker_t->host #} p)\n <*> liftM fromIntegral ({#get rd_kafka_metadata_broker_t->port #} p)\n poke = undefined\n\ndata RdKafkaMetadataPartitionT = RdKafkaMetadataPartitionT\n { id'RdKafkaMetadataPartitionT :: Int\n , err'RdKafkaMetadataPartitionT :: RdKafkaRespErrT\n , leader'RdKafkaMetadataPartitionT :: Int\n , replicaCnt'RdKafkaMetadataPartitionT :: Int\n , replicas'RdKafkaMetadataPartitionT :: Ptr CInt32T\n , isrCnt'RdKafkaMetadataPartitionT :: Int\n , isrs'RdKafkaMetadataPartitionT :: Ptr CInt32T\n } deriving (Show, Eq)\n\ninstance Storable RdKafkaMetadataPartitionT where\n alignment _ = {#alignof rd_kafka_metadata_partition_t#}\n sizeOf _ = {#sizeof rd_kafka_metadata_partition_t#}\n peek p = RdKafkaMetadataPartitionT\n <$> liftM fromIntegral ({#get rd_kafka_metadata_partition_t->id#} p)\n <*> liftM cIntToEnum ({#get rd_kafka_metadata_partition_t->err#} p)\n <*> liftM fromIntegral ({#get rd_kafka_metadata_partition_t->leader#} p)\n <*> liftM fromIntegral ({#get rd_kafka_metadata_partition_t->replica_cnt#} p)\n <*> liftM castPtr ({#get rd_kafka_metadata_partition_t->replicas#} p)\n <*> liftM fromIntegral ({#get rd_kafka_metadata_partition_t->isr_cnt#} p)\n <*> liftM castPtr ({#get rd_kafka_metadata_partition_t->isrs#} p)\n\n poke = undefined\n\n{#pointer *rd_kafka_metadata_partition_t as RdKafkaMetadataPartitionTPtr -> RdKafkaMetadataPartitionT #}\n\ndata RdKafkaMetadataTopicT = RdKafkaMetadataTopicT\n { topic'RdKafkaMetadataTopicT :: CString\n , partitionCnt'RdKafkaMetadataTopicT :: Int\n , partitions'RdKafkaMetadataTopicT :: Ptr RdKafkaMetadataPartitionT\n , err'RdKafkaMetadataTopicT :: RdKafkaRespErrT\n } deriving (Show, Eq)\n\ninstance Storable RdKafkaMetadataTopicT where\n alignment _ = {#alignof rd_kafka_metadata_topic_t#}\n sizeOf _ = {#sizeof rd_kafka_metadata_topic_t #}\n peek p = RdKafkaMetadataTopicT\n <$> liftM id ({#get rd_kafka_metadata_topic_t->topic #} p)\n <*> liftM fromIntegral ({#get rd_kafka_metadata_topic_t->partition_cnt #} p)\n <*> liftM castPtr ({#get rd_kafka_metadata_topic_t->partitions #} p)\n <*> liftM cIntToEnum ({#get rd_kafka_metadata_topic_t->err #} p)\n poke _ _ = undefined\n\n{#pointer *rd_kafka_metadata_topic_t as RdKafkaMetadataTopicTPtr -> RdKafkaMetadataTopicT #}\n\ndata RdKafkaMetadataT = RdKafkaMetadataT\n { brokerCnt'RdKafkaMetadataT :: Int\n , brokers'RdKafkaMetadataT :: RdKafkaMetadataBrokerTPtr\n , topicCnt'RdKafkaMetadataT :: Int\n , topics'RdKafkaMetadataT :: RdKafkaMetadataTopicTPtr\n , origBrokerId'RdKafkaMetadataT :: CInt32T\n } deriving (Show, Eq)\n\ninstance Storable RdKafkaMetadataT where\n alignment _ = {#alignof rd_kafka_metadata_t#}\n sizeOf _ = {#sizeof rd_kafka_metadata_t#}\n peek p = RdKafkaMetadataT\n <$> liftM fromIntegral ({#get rd_kafka_metadata_t->broker_cnt #} p)\n <*> liftM castPtr ({#get rd_kafka_metadata_t->brokers #} p)\n <*> liftM fromIntegral ({#get rd_kafka_metadata_t->topic_cnt #} p)\n <*> liftM castPtr ({#get rd_kafka_metadata_t->topics #} p)\n <*> liftM fromIntegral ({#get rd_kafka_metadata_t->orig_broker_id #} p)\n poke _ _ = undefined\n\n{#pointer *rd_kafka_metadata_t as RdKafkaMetadataTPtr foreign -> RdKafkaMetadataT #}\n\n-------------------------------------------------------------------------------------------------\n---- Partitions\n{#fun rd_kafka_topic_partition_list_new as ^\n {`Int'} -> `RdKafkaTopicPartitionListTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_topic_partition_list_destroy\"\n rdKafkaTopicPartitionListDestroyF :: FinalizerPtr RdKafkaTopicPartitionListT\nforeign import ccall unsafe \"rdkafka.h rd_kafka_topic_partition_list_destroy\"\n rdKafkaTopicPartitionListDestroy :: Ptr RdKafkaTopicPartitionListT -> IO ()\n\nnewRdKafkaTopicPartitionListT :: Int -> IO RdKafkaTopicPartitionListTPtr\nnewRdKafkaTopicPartitionListT size = do\n ret <- rdKafkaTopicPartitionListNew size\n addForeignPtrFinalizer rdKafkaTopicPartitionListDestroyF ret\n return ret\n\n{# fun rd_kafka_topic_partition_list_add as ^\n {`RdKafkaTopicPartitionListTPtr', `String', `Int'} -> `RdKafkaTopicPartitionTPtr' #}\n\n{# fun rd_kafka_topic_partition_list_add_range as ^\n {`RdKafkaTopicPartitionListTPtr', `String', `Int', `Int'} -> `()' #}\n\n{# fun rd_kafka_topic_partition_list_copy as ^\n {`RdKafkaTopicPartitionListTPtr'} -> `RdKafkaTopicPartitionListTPtr' #}\n\ncopyRdKafkaTopicPartitionList :: RdKafkaTopicPartitionListTPtr -> IO RdKafkaTopicPartitionListTPtr\ncopyRdKafkaTopicPartitionList pl = do\n cp <- rdKafkaTopicPartitionListCopy pl\n addForeignPtrFinalizer rdKafkaTopicPartitionListDestroyF cp\n return cp\n\n{# fun rd_kafka_topic_partition_list_set_offset as ^\n {`RdKafkaTopicPartitionListTPtr', `String', `Int', `Int64'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n---- Rebalance Callback\ntype RdRebalanceCallback' = Ptr RdKafkaT -> CInt -> Ptr RdKafkaTopicPartitionListT -> Ptr Word8 -> IO ()\ntype RdRebalanceCallback = Ptr RdKafkaT -> RdKafkaRespErrT -> Ptr RdKafkaTopicPartitionListT -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkRebalanceCallback :: RdRebalanceCallback' -> IO (FunPtr RdRebalanceCallback')\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_rebalance_cb\"\n rdKafkaConfSetRebalanceCb' ::\n Ptr RdKafkaConfT\n -> FunPtr RdRebalanceCallback'\n -> IO ()\n\nrdKafkaConfSetRebalanceCb :: RdKafkaConfTPtr -> RdRebalanceCallback -> IO ()\nrdKafkaConfSetRebalanceCb conf cb = do\n cb' <- mkRebalanceCallback (\\k e p _ -> cb k (cIntToEnum e) p)\n withForeignPtr conf $ \\c -> rdKafkaConfSetRebalanceCb' c cb'\n return ()\n\n---- Delivery Callback\ntype DeliveryCallback' = Ptr RdKafkaT -> Ptr RdKafkaMessageT -> Word8Ptr -> IO ()\ntype DeliveryCallback = Ptr RdKafkaT -> Ptr RdKafkaMessageT -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkDeliveryCallback :: DeliveryCallback' -> IO (FunPtr DeliveryCallback')\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_dr_msg_cb\"\n rdKafkaConfSetDrMsgCb' :: Ptr RdKafkaConfT -> FunPtr DeliveryCallback' -> IO ()\n\nrdKafkaConfSetDrMsgCb :: RdKafkaConfTPtr -> DeliveryCallback -> IO ()\nrdKafkaConfSetDrMsgCb conf cb = do\n cb' <- mkDeliveryCallback (\\k m _ -> cb k m)\n withForeignPtr conf $ \\c -> rdKafkaConfSetDrMsgCb' c cb'\n return ()\n\n---- Consume Callback\ntype ConsumeCallback = Ptr RdKafkaMessageT -> Word8Ptr -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkConsumeCallback :: ConsumeCallback -> IO (FunPtr ConsumeCallback)\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_consume_cb\"\n rdKafkaConfSetConsumeCb' :: Ptr RdKafkaConfT -> FunPtr ConsumeCallback -> IO ()\n\nrdKafkaConfSetConsumeCb :: RdKafkaConfTPtr -> ConsumeCallback -> IO ()\nrdKafkaConfSetConsumeCb conf cb = do\n cb' <- mkConsumeCallback cb\n withForeignPtr conf $ \\c -> rdKafkaConfSetConsumeCb' c cb'\n return ()\n\n---- Offset Commit Callback\ntype OffsetCommitCallback' = Ptr RdKafkaT -> CInt -> Ptr RdKafkaTopicPartitionListT -> Word8Ptr -> IO ()\ntype OffsetCommitCallback = Ptr RdKafkaT -> RdKafkaRespErrT -> Ptr RdKafkaTopicPartitionListT -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkOffsetCommitCallback :: OffsetCommitCallback' -> IO (FunPtr OffsetCommitCallback')\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_offset_commit_cb\"\n rdKafkaConfSetOffsetCommitCb' :: Ptr RdKafkaConfT -> FunPtr OffsetCommitCallback' -> IO ()\n\nrdKafkaConfSetOffsetCommitCb :: RdKafkaConfTPtr -> OffsetCommitCallback -> IO ()\nrdKafkaConfSetOffsetCommitCb conf cb = do\n cb' <- mkOffsetCommitCallback (\\k e p _ -> cb k (cIntToEnum e) p)\n withForeignPtr conf $ \\c -> rdKafkaConfSetOffsetCommitCb' c cb'\n return ()\n\n\n----- Error Callback\ntype ErrorCallback' = Ptr RdKafkaT -> CInt -> CString -> Word8Ptr -> IO ()\ntype ErrorCallback = Ptr RdKafkaT -> RdKafkaRespErrT -> String -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkErrorCallback :: ErrorCallback' -> IO (FunPtr ErrorCallback')\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_error_cb\"\n rdKafkaConfSetErrorCb' :: Ptr RdKafkaConfT -> FunPtr ErrorCallback' -> IO ()\n\nrdKafkaConfSetErrorCb :: RdKafkaConfTPtr -> ErrorCallback -> IO ()\nrdKafkaConfSetErrorCb conf cb = do\n cb' <- mkErrorCallback (\\k e r _ -> peekCAString r >>= cb k (cIntToEnum e))\n withForeignPtr conf $ \\c -> rdKafkaConfSetErrorCb' c cb'\n\n---- Throttle Callback\ntype ThrottleCallback = Ptr RdKafkaT -> CString -> Int -> Int -> Word8Ptr -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkThrottleCallback :: ThrottleCallback -> IO (FunPtr ThrottleCallback)\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_throttle_cb\"\n rdKafkaConfSetThrottleCb' :: Ptr RdKafkaConfT -> FunPtr ThrottleCallback -> IO ()\n\nrdKafkaConfSetThrottleCb :: RdKafkaConfTPtr -> ThrottleCallback -> IO ()\nrdKafkaConfSetThrottleCb conf cb = do\n cb' <- mkThrottleCallback cb\n withForeignPtr conf $ \\c -> rdKafkaConfSetThrottleCb' c cb'\n return ()\n\n---- Log Callback\ntype LogCallback' = Ptr RdKafkaT -> CInt -> CString -> CString -> IO ()\ntype LogCallback = Ptr RdKafkaT -> Int -> String -> String -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkLogCallback :: LogCallback' -> IO (FunPtr LogCallback')\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_log_cb\"\n rdKafkaConfSetLogCb' :: Ptr RdKafkaConfT -> FunPtr LogCallback' -> IO ()\n\nrdKafkaConfSetLogCb :: RdKafkaConfTPtr -> LogCallback -> IO ()\nrdKafkaConfSetLogCb conf cb = do\n cb' <- mkLogCallback $ \\k l f b -> do\n f' <- peekCAString f\n b' <- peekCAString b\n cb k (cIntConv l) f' b'\n withForeignPtr conf $ \\c -> rdKafkaConfSetLogCb' c cb'\n\n---- Stats Callback\ntype StatsCallback' = Ptr RdKafkaT -> CString -> CSize -> Word8Ptr -> IO CInt\ntype StatsCallback = Ptr RdKafkaT -> ByteString -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkStatsCallback :: StatsCallback' -> IO (FunPtr StatsCallback')\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_stats_cb\"\n rdKafkaConfSetStatsCb' :: Ptr RdKafkaConfT -> FunPtr StatsCallback' -> IO ()\n\nrdKafkaConfSetStatsCb :: RdKafkaConfTPtr -> StatsCallback -> IO ()\nrdKafkaConfSetStatsCb conf cb = do\n cb' <- mkStatsCallback $ \\k j jl _ -> BS.packCStringLen (j, cIntConv jl) >>= cb k >> pure 0\n withForeignPtr conf $ \\c -> rdKafkaConfSetStatsCb' c cb'\n return ()\n\n---- Socket Callback\ntype SocketCallback = Int -> Int -> Int -> Word8Ptr -> IO CInt\n\nforeign import ccall safe \"wrapper\"\n mkSocketCallback :: SocketCallback -> IO (FunPtr SocketCallback)\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_socket_cb\"\n rdKafkaConfSetSocketCb' :: Ptr RdKafkaConfT -> FunPtr SocketCallback -> IO ()\n\nrdKafkaConfSetSocketCb :: RdKafkaConfTPtr -> SocketCallback -> IO ()\nrdKafkaConfSetSocketCb conf cb = do\n cb' <- mkSocketCallback cb\n withForeignPtr conf $ \\c -> rdKafkaConfSetSocketCb' c cb' >> pure 0\n return ()\n\n{#fun rd_kafka_conf_set_opaque as ^\n {`RdKafkaConfTPtr', castPtr `Word8Ptr'} -> `()' #}\n\n{#fun rd_kafka_opaque as ^\n {`RdKafkaTPtr'} -> `Word8Ptr' castPtr #}\n\n{#fun rd_kafka_conf_set_default_topic_conf as ^\n {`RdKafkaConfTPtr', `RdKafkaTopicConfTPtr'} -> `()' #}\n\n---- Partitioner Callback\ntype PartitionerCallback =\n Ptr RdKafkaTopicTPtr\n -> Word8Ptr -- keydata\n -> Int -- keylen\n -> Int -- partition_cnt\n -> Word8Ptr -- topic_opaque\n -> Word8Ptr -- msg_opaque\n -> IO Int\n\nforeign import ccall safe \"wrapper\"\n mkPartitionerCallback :: PartitionerCallback -> IO (FunPtr PartitionerCallback)\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_topic_conf_set_partitioner_cb\"\n rdKafkaTopicConfSetPartitionerCb' :: Ptr RdKafkaTopicConfT -> FunPtr PartitionerCallback -> IO ()\n\nrdKafkaTopicConfSetPartitionerCb :: RdKafkaTopicConfTPtr -> PartitionerCallback -> IO ()\nrdKafkaTopicConfSetPartitionerCb conf cb = do\n cb' <- mkPartitionerCallback cb\n withForeignPtr conf $ \\c -> rdKafkaTopicConfSetPartitionerCb' c cb'\n return ()\n\n---- Partition\n\n{#fun rd_kafka_topic_partition_available as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T'} -> `Int' #}\n\n{#fun rd_kafka_msg_partitioner_random as ^\n { `RdKafkaTopicTPtr'\n , castPtr `Word8Ptr'\n , cIntConv `CSize'\n , cIntConv `CInt32T'\n , castPtr `Word8Ptr'\n , castPtr `Word8Ptr'}\n -> `CInt32T' cIntConv #}\n\n{#fun rd_kafka_msg_partitioner_consistent as ^\n { `RdKafkaTopicTPtr'\n , castPtr `Word8Ptr'\n , cIntConv `CSize'\n , cIntConv `CInt32T'\n , castPtr `Word8Ptr'\n , castPtr `Word8Ptr'}\n -> `CInt32T' cIntConv #}\n\n{#fun rd_kafka_msg_partitioner_consistent_random as ^\n { `RdKafkaTopicTPtr'\n , castPtr `Word8Ptr'\n , cIntConv `CSize'\n , cIntConv `CInt32T'\n , castPtr `Word8Ptr'\n , castPtr `Word8Ptr'}\n -> `CInt32T' cIntConv #}\n\n---- Poll \/ Yield\n\n{#fun rd_kafka_yield as ^\n {`RdKafkaTPtr'} -> `()' #}\n\n---- Pause \/ Resume\n{#fun rd_kafka_pause_partitions as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'} -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_resume_partitions as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'} -> `RdKafkaRespErrT' cIntToEnum #}\n\n---- QUEUE\ndata RdKafkaQueueT\n{#pointer *rd_kafka_queue_t as RdKafkaQueueTPtr foreign -> RdKafkaQueueT #}\n\n{#fun rd_kafka_queue_new as ^\n {`RdKafkaTPtr'} -> `RdKafkaQueueTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_queue_destroy\"\n rdKafkaQueueDestroyF :: FinalizerPtr RdKafkaQueueT\n\n{#fun rd_kafka_queue_destroy as ^\n {`RdKafkaQueueTPtr'} -> `()'#}\n\nnewRdKafkaQueue :: RdKafkaTPtr -> IO RdKafkaQueueTPtr\nnewRdKafkaQueue k = do\n q <- rdKafkaQueueNew k\n addForeignPtrFinalizer rdKafkaQueueDestroyF q\n return q\n\n{#fun rd_kafka_consume_queue as ^\n {`RdKafkaQueueTPtr', `Int'} -> `RdKafkaMessageTPtr' #}\n\n{#fun rd_kafka_queue_forward as ^\n {`RdKafkaQueueTPtr', `RdKafkaQueueTPtr'} -> `()' #}\n\n{#fun rd_kafka_queue_get_partition as rdKafkaQueueGetPartition'\n {`RdKafkaTPtr', `String', `Int'} -> `RdKafkaQueueTPtr' #}\n\nrdKafkaQueueGetPartition :: RdKafkaTPtr -> String -> Int -> IO (Maybe RdKafkaQueueTPtr)\nrdKafkaQueueGetPartition k t p = do\n ret <- rdKafkaQueueGetPartition' k t p\n withForeignPtr ret $ \\realPtr ->\n if realPtr == nullPtr then return Nothing\n else do\n addForeignPtrFinalizer rdKafkaQueueDestroyF ret\n return $ Just ret\n\n{#fun rd_kafka_consume_batch_queue as rdKafkaConsumeBatchQueue'\n {`RdKafkaQueueTPtr', `Int', castPtr `Ptr (Ptr RdKafkaMessageT)', cIntConv `CSize'}\n -> `CSize' cIntConv #}\n\nrdKafkaConsumeBatchQueue :: RdKafkaQueueTPtr -> Int -> Int -> IO [RdKafkaMessageTPtr]\nrdKafkaConsumeBatchQueue qptr timeout batchSize = do\n allocaArray batchSize $ \\pArr -> do\n rSize <- rdKafkaConsumeBatchQueue' qptr timeout pArr (fromIntegral batchSize)\n peekArray (fromIntegral rSize) pArr >>= traverse (flip newForeignPtr (return ()))\n\n-------------------------------------------------------------------------------------------------\n---- High-level KafkaConsumer\n\n{#fun rd_kafka_subscribe as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_unsubscribe as ^\n {`RdKafkaTPtr'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_subscription as rdKafkaSubscription'\n {`RdKafkaTPtr', alloca- `Ptr RdKafkaTopicPartitionListT' peekPtr*}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\nrdKafkaSubscription :: RdKafkaTPtr -> IO (Either RdKafkaRespErrT RdKafkaTopicPartitionListTPtr)\nrdKafkaSubscription k = do\n (err, sub) <- rdKafkaSubscription' k\n case err of\n RdKafkaRespErrNoError ->\n Right <$> newForeignPtr sub (rdKafkaTopicPartitionListDestroy sub)\n e -> return (Left e)\n\n{#fun rd_kafka_consumer_poll as ^\n {`RdKafkaTPtr', `Int'} -> `RdKafkaMessageTPtr' #}\n\npollRdKafkaConsumer :: RdKafkaTPtr -> Int -> IO RdKafkaMessageTPtr\npollRdKafkaConsumer k t = do\n m <- rdKafkaConsumerPoll k t\n addForeignPtrFinalizer rdKafkaMessageDestroyF m\n return m\n\n{#fun rd_kafka_consumer_close as ^\n {`RdKafkaTPtr'} -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_poll_set_consumer as ^\n {`RdKafkaTPtr'} -> `RdKafkaRespErrT' cIntToEnum #}\n\n-- rd_kafka_assign\n{#fun rd_kafka_assign as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_assignment as rdKafkaAssignment'\n {`RdKafkaTPtr', alloca- `Ptr RdKafkaTopicPartitionListT' peekPtr* }\n -> `RdKafkaRespErrT' cIntToEnum #}\n\nrdKafkaAssignment :: RdKafkaTPtr -> IO (Either RdKafkaRespErrT RdKafkaTopicPartitionListTPtr)\nrdKafkaAssignment k = do\n (err, ass) <- rdKafkaAssignment' k\n case err of\n RdKafkaRespErrNoError ->\n Right <$> newForeignPtr ass (rdKafkaTopicPartitionListDestroy ass)\n e -> return (Left e)\n\n{#fun rd_kafka_commit as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr', boolToCInt `Bool'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_commit_message as ^\n {`RdKafkaTPtr', `RdKafkaMessageTPtr', boolToCInt `Bool'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_committed as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr', `Int'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_position as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n-------------------------------------------------------------------------------------------------\n---- Groups\ndata RdKafkaGroupMemberInfoT = RdKafkaGroupMemberInfoT\n { memberId'RdKafkaGroupMemberInfoT :: CString\n , clientId'RdKafkaGroupMemberInfoT :: CString\n , clientHost'RdKafkaGroupMemberInfoT :: CString\n , memberMetadata'RdKafkaGroupMemberInfoT :: Word8Ptr\n , memberMetadataSize'RdKafkaGroupMemberInfoT :: Int\n , memberAssignment'RdKafkaGroupMemberInfoT :: Word8Ptr\n , memberAssignmentSize'RdKafkaGroupMemberInfoT :: Int }\n\ninstance Storable RdKafkaGroupMemberInfoT where\n alignment _ = {#alignof rd_kafka_group_member_info#}\n sizeOf _ = {#sizeof rd_kafka_group_member_info#}\n peek p = RdKafkaGroupMemberInfoT\n <$> liftM id ({#get rd_kafka_group_member_info->member_id #} p)\n <*> liftM id ({#get rd_kafka_group_member_info->client_id #} p)\n <*> liftM id ({#get rd_kafka_group_member_info->client_host #} p)\n <*> liftM castPtr ({#get rd_kafka_group_member_info->member_metadata #} p)\n <*> liftM fromIntegral ({#get rd_kafka_group_member_info->member_metadata_size #} p)\n <*> liftM castPtr ({#get rd_kafka_group_member_info->member_assignment #} p)\n <*> liftM fromIntegral ({#get rd_kafka_group_member_info->member_assignment_size #} p)\n poke p x = do\n {#set rd_kafka_group_member_info.member_id#} p (id $ memberId'RdKafkaGroupMemberInfoT x)\n {#set rd_kafka_group_member_info.client_id#} p (id $ clientId'RdKafkaGroupMemberInfoT x)\n {#set rd_kafka_group_member_info.client_host#} p (id $ clientHost'RdKafkaGroupMemberInfoT x)\n {#set rd_kafka_group_member_info.member_metadata#} p (castPtr $ memberMetadata'RdKafkaGroupMemberInfoT x)\n {#set rd_kafka_group_member_info.member_metadata_size#} p (fromIntegral $ memberMetadataSize'RdKafkaGroupMemberInfoT x)\n {#set rd_kafka_group_member_info.member_assignment#} p (castPtr $ memberAssignment'RdKafkaGroupMemberInfoT x)\n {#set rd_kafka_group_member_info.member_assignment_size#} p (fromIntegral $ memberAssignmentSize'RdKafkaGroupMemberInfoT x)\n\n{#pointer *rd_kafka_group_member_info as RdKafkaGroupMemberInfoTPtr -> RdKafkaGroupMemberInfoT #}\n\ndata RdKafkaGroupInfoT = RdKafkaGroupInfoT\n { broker'RdKafkaGroupInfoT :: RdKafkaMetadataBrokerTPtr\n , group'RdKafkaGroupInfoT :: CString\n , err'RdKafkaGroupInfoT :: RdKafkaRespErrT\n , state'RdKafkaGroupInfoT :: CString\n , protocolType'RdKafkaGroupInfoT :: CString\n , protocol'RdKafkaGroupInfoT :: CString\n , members'RdKafkaGroupInfoT :: RdKafkaGroupMemberInfoTPtr\n , memberCnt'RdKafkaGroupInfoT :: Int }\n\ninstance Storable RdKafkaGroupInfoT where\n alignment _ = {#alignof rd_kafka_group_info #}\n sizeOf _ = {#sizeof rd_kafka_group_info #}\n peek p = RdKafkaGroupInfoT\n <$> liftM castPtr ({#get rd_kafka_group_info->broker #} p)\n <*> liftM id ({#get rd_kafka_group_info->group #} p)\n <*> liftM cIntToEnum ({#get rd_kafka_group_info->err #} p)\n <*> liftM id ({#get rd_kafka_group_info->state #} p)\n <*> liftM id ({#get rd_kafka_group_info->protocol_type #} p)\n <*> liftM id ({#get rd_kafka_group_info->protocol #} p)\n <*> liftM castPtr ({#get rd_kafka_group_info->members #} p)\n <*> liftM fromIntegral ({#get rd_kafka_group_info->member_cnt #} p)\n poke p x = do\n {#set rd_kafka_group_info.broker#} p (castPtr $ broker'RdKafkaGroupInfoT x)\n {#set rd_kafka_group_info.group#} p (id $ group'RdKafkaGroupInfoT x)\n {#set rd_kafka_group_info.err#} p (enumToCInt $ err'RdKafkaGroupInfoT x)\n {#set rd_kafka_group_info.state#} p (id $ state'RdKafkaGroupInfoT x)\n {#set rd_kafka_group_info.protocol_type#} p (id $ protocolType'RdKafkaGroupInfoT x)\n {#set rd_kafka_group_info.protocol#} p (id $ protocol'RdKafkaGroupInfoT x)\n {#set rd_kafka_group_info.members#} p (castPtr $ members'RdKafkaGroupInfoT x)\n {#set rd_kafka_group_info.member_cnt#} p (fromIntegral $ memberCnt'RdKafkaGroupInfoT x)\n\n{#pointer *rd_kafka_group_info as RdKafkaGroupInfoTPtr foreign -> RdKafkaGroupInfoT #}\n\ndata RdKafkaGroupListT = RdKafkaGroupListT\n { groups'RdKafkaGroupListT :: Ptr RdKafkaGroupInfoT\n , groupCnt'RdKafkaGroupListT :: Int }\n\ninstance Storable RdKafkaGroupListT where\n alignment _ = {#alignof rd_kafka_group_list #}\n sizeOf _ = {#sizeof rd_kafka_group_list #}\n peek p = RdKafkaGroupListT\n <$> liftM castPtr ({#get rd_kafka_group_list->groups #} p)\n <*> liftM fromIntegral ({#get rd_kafka_group_list->group_cnt #} p)\n poke p x = do\n {#set rd_kafka_group_list.groups#} p (castPtr $ groups'RdKafkaGroupListT x)\n {#set rd_kafka_group_list.group_cnt#} p (fromIntegral $ groupCnt'RdKafkaGroupListT x)\n\n{#pointer *rd_kafka_group_list as RdKafkaGroupListTPtr foreign -> RdKafkaGroupListT #}\n\n{#fun rd_kafka_list_groups as rdKafkaListGroups'\n {`RdKafkaTPtr', `CString', alloca- `Ptr RdKafkaGroupListT' peek*, `Int'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\nforeign import ccall \"rdkafka.h &rd_kafka_group_list_destroy\"\n rdKafkaGroupListDestroyF :: FinalizerPtr RdKafkaGroupListT\n\nforeign import ccall \"rdkafka.h rd_kafka_group_list_destroy\"\n rdKafkaGroupListDestroy :: Ptr RdKafkaGroupListT -> IO ()\n\nrdKafkaListGroups :: RdKafkaTPtr -> Maybe String -> Int -> IO (Either RdKafkaRespErrT RdKafkaGroupListTPtr)\nrdKafkaListGroups k g t = case g of\n Nothing -> listGroups nullPtr\n Just strGrp -> withCAString strGrp listGroups\n where\n listGroups grp = do\n (err, res) <- rdKafkaListGroups' k grp t\n case err of\n RdKafkaRespErrNoError -> Right <$> newForeignPtr res (rdKafkaGroupListDestroy res)\n e -> return $ Left e\n-------------------------------------------------------------------------------------------------\n\n-- rd_kafka_message\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_message_destroy\"\n rdKafkaMessageDestroyF :: FinalizerPtr RdKafkaMessageT\n\nforeign import ccall unsafe \"rdkafka.h rd_kafka_message_destroy\"\n rdKafkaMessageDestroy :: Ptr RdKafkaMessageT -> IO ()\n\n{#fun rd_kafka_query_watermark_offsets as rdKafkaQueryWatermarkOffsets'\n {`RdKafkaTPtr', `String', cIntConv `CInt32T',\n alloca- `Int64' peekInt64Conv*, alloca- `Int64' peekInt64Conv*,\n cIntConv `Int'\n } -> `RdKafkaRespErrT' cIntToEnum #}\n\n\nrdKafkaQueryWatermarkOffsets :: RdKafkaTPtr -> String -> Int -> Int -> IO (Either RdKafkaRespErrT (Int64, Int64))\nrdKafkaQueryWatermarkOffsets kafka topic partition timeout = do\n (err, l, h) <- rdKafkaQueryWatermarkOffsets' kafka topic (cIntConv partition) timeout\n return $ case err of\n RdKafkaRespErrNoError -> Right (cIntConv l, cIntConv h)\n e -> Left e\n\n{#pointer *rd_kafka_timestamp_type_t as RdKafkaTimestampTypeTPtr foreign -> RdKafkaTimestampTypeT #}\n\ninstance Storable RdKafkaTimestampTypeT where\n sizeOf _ = {#sizeof rd_kafka_timestamp_type_t#}\n alignment _ = {#alignof rd_kafka_timestamp_type_t#}\n peek p = cIntToEnum <$> peek (castPtr p)\n poke p x = poke (castPtr p) (enumToCInt x)\n\n{#fun rd_kafka_message_timestamp as rdKafkaReadTimestamp'\n {castPtr `Ptr RdKafkaMessageT', `RdKafkaTimestampTypeTPtr'} -> `CInt64T' cIntConv #}\n\n{#fun rd_kafka_message_timestamp as ^\n {`RdKafkaMessageTPtr', `RdKafkaTimestampTypeTPtr'} -> `CInt64T' cIntConv #}\n\n{#fun rd_kafka_offsets_for_times as rdKafkaOffsetsForTimes\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr', `Int'} -> `RdKafkaRespErrT' cIntToEnum #}\n\n-- rd_kafka_conf\n{#fun rd_kafka_conf_new as ^\n {} -> `RdKafkaConfTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_conf_destroy\"\n rdKafkaConfDestroy :: FinalizerPtr RdKafkaConfT\n\n{#fun rd_kafka_conf_dup as ^\n {`RdKafkaConfTPtr'} -> `RdKafkaConfTPtr' #}\n\n{#fun rd_kafka_conf_set as ^\n {`RdKafkaConfTPtr', `String', `String', id `CCharBufPointer', cIntConv `CSize'}\n -> `RdKafkaConfResT' cIntToEnum #}\n\nnewRdKafkaConfT :: IO RdKafkaConfTPtr\nnewRdKafkaConfT = do\n ret <- rdKafkaConfNew\n addForeignPtrFinalizer rdKafkaConfDestroy ret\n return ret\n\n{#fun rd_kafka_conf_dump as ^\n {`RdKafkaConfTPtr', castPtr `CSizePtr'} -> `Ptr CString' id #}\n\n{#fun rd_kafka_conf_dump_free as ^\n {id `Ptr CString', cIntConv `CSize'} -> `()' #}\n\n{#fun rd_kafka_conf_properties_show as ^\n {`CFilePtr'} -> `()' #}\n\n-- rd_kafka_topic_conf\n{#fun rd_kafka_topic_conf_new as ^\n {} -> `RdKafkaTopicConfTPtr' #}\n\n{#fun rd_kafka_topic_conf_dup as ^\n {`RdKafkaTopicConfTPtr'} -> `RdKafkaTopicConfTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_topic_conf_destroy\"\n rdKafkaTopicConfDestroy :: FinalizerPtr RdKafkaTopicConfT\n\n{#fun rd_kafka_topic_conf_set as ^\n {`RdKafkaTopicConfTPtr', `String', `String', id `CCharBufPointer', cIntConv `CSize'}\n -> `RdKafkaConfResT' cIntToEnum #}\n\nnewRdKafkaTopicConfT :: IO RdKafkaTopicConfTPtr\nnewRdKafkaTopicConfT = do\n ret <- rdKafkaTopicConfNew\n addForeignPtrFinalizer rdKafkaTopicConfDestroy ret\n return ret\n\n{#fun rd_kafka_topic_conf_dump as ^\n {`RdKafkaTopicConfTPtr', castPtr `CSizePtr'} -> `Ptr CString' id #}\n\n-- rd_kafka\n{#fun rd_kafka_new as ^\n {enumToCInt `RdKafkaTypeT', `RdKafkaConfTPtr', id `CCharBufPointer', cIntConv `CSize'}\n -> `RdKafkaTPtr' #}\n\nforeign import ccall safe \"rdkafka.h &rd_kafka_destroy\"\n rdKafkaDestroy :: FunPtr (Ptr RdKafkaT -> IO ())\n\nnewRdKafkaT :: RdKafkaTypeT -> RdKafkaConfTPtr -> IO (Either Text RdKafkaTPtr)\nnewRdKafkaT kafkaType confPtr =\n allocaBytes nErrorBytes $ \\charPtr -> do\n duper <- rdKafkaConfDup confPtr\n ret <- rdKafkaNew kafkaType duper charPtr (fromIntegral nErrorBytes)\n withForeignPtr ret $ \\realPtr -> do\n if realPtr == nullPtr then peekCText charPtr >>= return . Left\n else do\n -- do not call 'rd_kafka_close_consumer' on destroying all Kafka.\n -- when needed, applications should do it explicitly.\n -- {# call rd_kafka_destroy_flags #} realPtr 0x8\n addForeignPtrFinalizer rdKafkaDestroy ret\n return $ Right ret\n\n{#fun rd_kafka_brokers_add as ^\n {`RdKafkaTPtr', `String'} -> `Int' #}\n\n{#fun rd_kafka_set_log_level as ^\n {`RdKafkaTPtr', `Int'} -> `()' #}\n\n-- rd_kafka consume\n\n{#fun rd_kafka_consume_start as rdKafkaConsumeStartInternal\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', cIntConv `CInt64T'} -> `Int' #}\n\nrdKafkaConsumeStart :: RdKafkaTopicTPtr -> Int -> Int64 -> IO (Maybe String)\nrdKafkaConsumeStart topicPtr partition offset = do\n i <- rdKafkaConsumeStartInternal topicPtr (fromIntegral partition) (fromIntegral offset)\n case i of\n -1 -> kafkaErrnoString >>= return . Just\n _ -> return Nothing\n{#fun rd_kafka_consume_stop as rdKafkaConsumeStopInternal\n {`RdKafkaTopicTPtr', cIntConv `CInt32T'} -> `Int' #}\n\n{#fun rd_kafka_seek as rdKafkaSeek\n {`RdKafkaTopicTPtr', `Int32', `Int64', `Int'} -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_consume as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', `Int'} -> `RdKafkaMessageTPtr' #}\n\n{#fun rd_kafka_consume_batch as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', `Int', castPtr `Ptr (Ptr RdKafkaMessageT)', cIntConv `CSize'}\n -> `CSize' cIntConv #}\n\nrdKafkaConsumeStop :: RdKafkaTopicTPtr -> Int -> IO (Maybe String)\nrdKafkaConsumeStop topicPtr partition = do\n i <- rdKafkaConsumeStopInternal topicPtr (fromIntegral partition)\n case i of\n -1 -> kafkaErrnoString >>= return . Just\n _ -> return Nothing\n\n{#fun rd_kafka_offset_store as rdKafkaOffsetStore\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', cIntConv `CInt64T'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_offsets_store as rdKafkaOffsetsStore\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n-- rd_kafka produce\n\n{#fun rd_kafka_produce as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', `Int', castPtr `Word8Ptr',\n cIntConv `CSize', castPtr `Word8Ptr', cIntConv `CSize', castPtr `Ptr ()'}\n -> `Int' #}\n\n{#fun rd_kafka_produce_batch as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', `Int', `RdKafkaMessageTPtr', `Int'} -> `Int' #}\n\n\n-- rd_kafka_metadata\n\n{#fun rd_kafka_metadata as rdKafkaMetadata'\n {`RdKafkaTPtr', boolToCInt `Bool', `RdKafkaTopicTPtr',\n alloca- `Ptr RdKafkaMetadataT' peekPtr*, `Int'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\nforeign import ccall unsafe \"rdkafka.h rd_kafka_metadata_destroy\"\n rdKafkaMetadataDestroy :: Ptr RdKafkaMetadataT -> IO ()\n\nrdKafkaMetadata :: RdKafkaTPtr -> Bool -> Maybe RdKafkaTopicTPtr -> Int -> IO (Either RdKafkaRespErrT RdKafkaMetadataTPtr)\nrdKafkaMetadata k allTopics mt timeout = do\n tptr <- maybe (newForeignPtr_ nullPtr) pure mt\n (err, res) <- rdKafkaMetadata' k allTopics tptr timeout\n case err of\n RdKafkaRespErrNoError -> Right <$> newForeignPtr res (rdKafkaMetadataDestroy res)\n e -> return (Left e)\n\n{#fun rd_kafka_poll as ^\n {`RdKafkaTPtr', `Int'} -> `Int' #}\n\n{#fun rd_kafka_outq_len as ^\n {`RdKafkaTPtr'} -> `Int' #}\n\n{#fun rd_kafka_dump as ^\n {`CFilePtr', `RdKafkaTPtr'} -> `()' #}\n\n-- rd_kafka_topic\n{#fun rd_kafka_topic_name as ^\n {`RdKafkaTopicTPtr'} -> `String' #}\n\n{#fun rd_kafka_topic_new as ^\n {`RdKafkaTPtr', `String', `RdKafkaTopicConfTPtr'} -> `RdKafkaTopicTPtr' #}\n\n{# fun rd_kafka_topic_destroy as ^\n {castPtr `Ptr RdKafkaTopicT'} -> `()' #}\n\ndestroyUnmanagedRdKafkaTopic :: RdKafkaTopicTPtr -> IO ()\ndestroyUnmanagedRdKafkaTopic ptr =\n withForeignPtr ptr rdKafkaTopicDestroy\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_topic_destroy\"\n rdKafkaTopicDestroy' :: FinalizerPtr RdKafkaTopicT\n\nnewUnmanagedRdKafkaTopicT :: RdKafkaTPtr -> String -> Maybe RdKafkaTopicConfTPtr -> IO (Either String RdKafkaTopicTPtr)\nnewUnmanagedRdKafkaTopicT kafkaPtr topic topicConfPtr = do\n duper <- maybe (newForeignPtr_ nullPtr) rdKafkaTopicConfDup topicConfPtr\n ret <- rdKafkaTopicNew kafkaPtr topic duper\n withForeignPtr ret $ \\realPtr ->\n if realPtr == nullPtr then kafkaErrnoString >>= return . Left\n else return $ Right ret\n\nnewRdKafkaTopicT :: RdKafkaTPtr -> String -> Maybe RdKafkaTopicConfTPtr -> IO (Either String RdKafkaTopicTPtr)\nnewRdKafkaTopicT kafkaPtr topic topicConfPtr = do\n res <- newUnmanagedRdKafkaTopicT kafkaPtr topic topicConfPtr\n _ <- traverse (addForeignPtrFinalizer rdKafkaTopicDestroy') res\n return res\n\n-- Marshall \/ Unmarshall\nenumToCInt :: Enum a => a -> CInt\nenumToCInt = fromIntegral . fromEnum\n{-# INLINE enumToCInt #-}\n\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\n{-# INLINE cIntToEnum #-}\n\ncIntConv :: (Integral a, Num b) => a -> b\ncIntConv = fromIntegral\n{-# INLINE cIntConv #-}\n\nboolToCInt :: Bool -> CInt\nboolToCInt True = CInt 1\nboolToCInt False = CInt 0\n{-# INLINE boolToCInt #-}\n\npeekInt64Conv :: (Storable a, Integral a) => Ptr a -> IO Int64\npeekInt64Conv = liftM cIntConv . peek\n{-# INLINE peekInt64Conv #-}\n\npeekPtr :: Ptr a -> IO (Ptr b)\npeekPtr = peek . castPtr\n{-# INLINE peekPtr #-}\n\n-- Handle -> File descriptor\n\nforeign import ccall \"\" fdopen :: Fd -> CString -> IO (Ptr CFile)\n\nhandleToCFile :: Handle -> String -> IO (CFilePtr)\nhandleToCFile h m =\n do iomode <- newCString m\n fd <- handleToFd h\n fdopen fd iomode\n\nc_stdin :: IO CFilePtr\nc_stdin = handleToCFile stdin \"r\"\nc_stdout :: IO CFilePtr\nc_stdout = handleToCFile stdout \"w\"\nc_stderr :: IO CFilePtr\nc_stderr = handleToCFile stderr \"w\"\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE EmptyDataDecls #-}\n\nmodule Kafka.Internal.RdKafka where\n\nimport Data.ByteString (ByteString)\nimport qualified Data.ByteString as BS\nimport Data.Text (Text)\nimport qualified Data.Text as Text\nimport Control.Monad (liftM)\nimport Data.Int (Int32, Int64)\nimport Data.Word (Word8)\nimport Foreign.Concurrent (newForeignPtr)\nimport Foreign.Marshal.Alloc (alloca, allocaBytes)\nimport Foreign.Marshal.Array (peekArray, allocaArray)\nimport Foreign.Storable (Storable(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr)\nimport Foreign.ForeignPtr (FinalizerPtr, addForeignPtrFinalizer, newForeignPtr_, withForeignPtr)\nimport Foreign.C.Error (Errno(..), getErrno)\nimport Foreign.C.String (CString, newCString, withCAString, peekCAString, peekCString)\nimport Foreign.C.Types (CFile, CInt(..), CSize, CChar)\nimport System.IO (Handle, stdin, stdout, stderr)\nimport System.Posix.IO (handleToFd)\nimport System.Posix.Types (Fd(..))\n\n#include \n\ntype CInt64T = {#type int64_t #}\ntype CInt32T = {#type int32_t #}\n\n{#pointer *FILE as CFilePtr -> CFile #}\n{#pointer *size_t as CSizePtr -> CSize #}\n\ntype Word8Ptr = Ptr Word8\ntype CCharBufPointer = Ptr CChar\n\n{#enum rd_kafka_type_t as ^ {underscoreToCase} deriving (Show, Eq) #}\n{#enum rd_kafka_conf_res_t as ^ {underscoreToCase} deriving (Show, Eq) #}\n{#enum rd_kafka_resp_err_t as ^ {underscoreToCase} deriving (Show, Eq, Bounded) #}\n{#enum rd_kafka_timestamp_type_t as ^ {underscoreToCase} deriving (Show, Eq) #}\n\ntype RdKafkaMsgFlag = Int\nrdKafkaMsgFlagFree :: RdKafkaMsgFlag\nrdKafkaMsgFlagFree = 0x1\nrdKafkaMsgFlagCopy :: RdKafkaMsgFlag\nrdKafkaMsgFlagCopy = 0x2\n\n-- Number of bytes allocated for an error buffer\nnErrorBytes :: Int\nnErrorBytes = 1024 * 8\n\n-- Helper functions\n{#fun pure rd_kafka_version as ^\n {} -> `Int' #}\n\n{#fun pure rd_kafka_version_str as ^\n {} -> `String' #}\n\n{#fun pure rd_kafka_err2str as ^\n {enumToCInt `RdKafkaRespErrT'} -> `String' #}\n\n{#fun pure rd_kafka_err2name as ^\n {enumToCInt `RdKafkaRespErrT'} -> `String' #}\n\n{#fun pure rd_kafka_errno2err as ^\n {`Int'} -> `RdKafkaRespErrT' cIntToEnum #}\n\npeekCAText :: CString -> IO Text\npeekCAText cp = Text.pack <$> peekCAString cp\n\npeekCText :: CString -> IO Text\npeekCText cp = Text.pack <$> peekCString cp\n\nkafkaErrnoString :: IO String\nkafkaErrnoString = do\n (Errno num) <- getErrno\n return $ rdKafkaErr2str $ rdKafkaErrno2err (fromIntegral num)\n\n-- Kafka Pointer Types\ndata RdKafkaConfT\n{#pointer *rd_kafka_conf_t as RdKafkaConfTPtr foreign -> RdKafkaConfT #}\n\ndata RdKafkaTopicConfT\n{#pointer *rd_kafka_topic_conf_t as RdKafkaTopicConfTPtr foreign -> RdKafkaTopicConfT #}\n\ndata RdKafkaT\n{#pointer *rd_kafka_t as RdKafkaTPtr foreign -> RdKafkaT #}\n\ndata RdKafkaTopicPartitionT = RdKafkaTopicPartitionT\n { topic'RdKafkaTopicPartitionT :: CString\n , partition'RdKafkaTopicPartitionT :: Int\n , offset'RdKafkaTopicPartitionT :: Int64\n , metadata'RdKafkaTopicPartitionT :: Word8Ptr\n , metadataSize'RdKafkaTopicPartitionT :: Int\n , opaque'RdKafkaTopicPartitionT :: Word8Ptr\n , err'RdKafkaTopicPartitionT :: RdKafkaRespErrT\n } deriving (Show, Eq)\n\ninstance Storable RdKafkaTopicPartitionT where\n alignment _ = {#alignof rd_kafka_topic_partition_t#}\n sizeOf _ = {#sizeof rd_kafka_topic_partition_t#}\n peek p = RdKafkaTopicPartitionT\n <$> liftM id ({#get rd_kafka_topic_partition_t->topic #} p)\n <*> liftM fromIntegral ({#get rd_kafka_topic_partition_t->partition #} p)\n <*> liftM fromIntegral ({#get rd_kafka_topic_partition_t->offset #} p)\n <*> liftM castPtr ({#get rd_kafka_topic_partition_t->metadata #} p)\n <*> liftM fromIntegral ({#get rd_kafka_topic_partition_t->metadata_size #} p)\n <*> liftM castPtr ({#get rd_kafka_topic_partition_t->opaque #} p)\n <*> liftM cIntToEnum ({#get rd_kafka_topic_partition_t->err #} p)\n poke p x = do\n {#set rd_kafka_topic_partition_t.topic#} p (id $ topic'RdKafkaTopicPartitionT x)\n {#set rd_kafka_topic_partition_t.partition#} p (fromIntegral $ partition'RdKafkaTopicPartitionT x)\n {#set rd_kafka_topic_partition_t.offset#} p (fromIntegral $ offset'RdKafkaTopicPartitionT x)\n {#set rd_kafka_topic_partition_t.metadata#} p (castPtr $ metadata'RdKafkaTopicPartitionT x)\n {#set rd_kafka_topic_partition_t.metadata_size#} p (fromIntegral $ metadataSize'RdKafkaTopicPartitionT x)\n {#set rd_kafka_topic_partition_t.opaque#} p (castPtr $ opaque'RdKafkaTopicPartitionT x)\n {#set rd_kafka_topic_partition_t.err#} p (enumToCInt $ err'RdKafkaTopicPartitionT x)\n\n{#pointer *rd_kafka_topic_partition_t as RdKafkaTopicPartitionTPtr foreign -> RdKafkaTopicPartitionT #}\n\ndata RdKafkaTopicPartitionListT = RdKafkaTopicPartitionListT\n { cnt'RdKafkaTopicPartitionListT :: Int\n , size'RdKafkaTopicPartitionListT :: Int\n , elems'RdKafkaTopicPartitionListT :: Ptr RdKafkaTopicPartitionT\n } deriving (Show, Eq)\n\n{#pointer *rd_kafka_topic_partition_list_t as RdKafkaTopicPartitionListTPtr foreign -> RdKafkaTopicPartitionListT #}\n\ninstance Storable RdKafkaTopicPartitionListT where\n alignment _ = {#alignof rd_kafka_topic_partition_list_t#}\n sizeOf _ = {#sizeof rd_kafka_topic_partition_list_t #}\n peek p = RdKafkaTopicPartitionListT\n <$> liftM fromIntegral ({#get rd_kafka_topic_partition_list_t->cnt #} p)\n <*> liftM fromIntegral ({#get rd_kafka_topic_partition_list_t->size #} p)\n <*> liftM castPtr ({#get rd_kafka_topic_partition_list_t->elems #} p)\n poke p x = do\n {#set rd_kafka_topic_partition_list_t.cnt#} p (fromIntegral $ cnt'RdKafkaTopicPartitionListT x)\n {#set rd_kafka_topic_partition_list_t.size#} p (fromIntegral $ size'RdKafkaTopicPartitionListT x)\n {#set rd_kafka_topic_partition_list_t.elems#} p (castPtr $ elems'RdKafkaTopicPartitionListT x)\n\ndata RdKafkaTopicT\n{#pointer *rd_kafka_topic_t as RdKafkaTopicTPtr foreign -> RdKafkaTopicT #}\n\ndata RdKafkaMessageT = RdKafkaMessageT\n { err'RdKafkaMessageT :: RdKafkaRespErrT\n , topic'RdKafkaMessageT :: Ptr RdKafkaTopicT\n , partition'RdKafkaMessageT :: Int\n , len'RdKafkaMessageT :: Int\n , keyLen'RdKafkaMessageT :: Int\n , offset'RdKafkaMessageT :: Int64\n , payload'RdKafkaMessageT :: Word8Ptr\n , key'RdKafkaMessageT :: Word8Ptr\n , opaque'RdKafkaMessageT :: Ptr ()\n }\n deriving (Show, Eq)\n\ninstance Storable RdKafkaMessageT where\n alignment _ = {#alignof rd_kafka_message_t#}\n sizeOf _ = {#sizeof rd_kafka_message_t#}\n peek p = RdKafkaMessageT\n <$> liftM cIntToEnum ({#get rd_kafka_message_t->err #} p)\n <*> liftM castPtr ({#get rd_kafka_message_t->rkt #} p)\n <*> liftM fromIntegral ({#get rd_kafka_message_t->partition #} p)\n <*> liftM fromIntegral ({#get rd_kafka_message_t->len #} p)\n <*> liftM fromIntegral ({#get rd_kafka_message_t->key_len #} p)\n <*> liftM fromIntegral ({#get rd_kafka_message_t->offset #} p)\n <*> liftM castPtr ({#get rd_kafka_message_t->payload #} p)\n <*> liftM castPtr ({#get rd_kafka_message_t->key #} p)\n <*> liftM castPtr ({#get rd_kafka_message_t->_private #} p)\n poke p x = do\n {#set rd_kafka_message_t.err#} p (enumToCInt $ err'RdKafkaMessageT x)\n {#set rd_kafka_message_t.rkt#} p (castPtr $ topic'RdKafkaMessageT x)\n {#set rd_kafka_message_t.partition#} p (fromIntegral $ partition'RdKafkaMessageT x)\n {#set rd_kafka_message_t.len#} p (fromIntegral $ len'RdKafkaMessageT x)\n {#set rd_kafka_message_t.key_len#} p (fromIntegral $ keyLen'RdKafkaMessageT x)\n {#set rd_kafka_message_t.offset#} p (fromIntegral $ offset'RdKafkaMessageT x)\n {#set rd_kafka_message_t.payload#} p (castPtr $ payload'RdKafkaMessageT x)\n {#set rd_kafka_message_t.key#} p (castPtr $ key'RdKafkaMessageT x)\n {#set rd_kafka_message_t._private#} p (castPtr $ opaque'RdKafkaMessageT x)\n\n{#pointer *rd_kafka_message_t as RdKafkaMessageTPtr foreign -> RdKafkaMessageT #}\n\ndata RdKafkaMetadataBrokerT = RdKafkaMetadataBrokerT\n { id'RdKafkaMetadataBrokerT :: Int\n , host'RdKafkaMetadataBrokerT :: CString\n , port'RdKafkaMetadataBrokerT :: Int\n } deriving (Show, Eq)\n\n{#pointer *rd_kafka_metadata_broker_t as RdKafkaMetadataBrokerTPtr -> RdKafkaMetadataBrokerT #}\n\n\ninstance Storable RdKafkaMetadataBrokerT where\n alignment _ = {#alignof rd_kafka_metadata_broker_t#}\n sizeOf _ = {#sizeof rd_kafka_metadata_broker_t#}\n peek p = RdKafkaMetadataBrokerT\n <$> liftM fromIntegral ({#get rd_kafka_metadata_broker_t->id #} p)\n <*> liftM id ({#get rd_kafka_metadata_broker_t->host #} p)\n <*> liftM fromIntegral ({#get rd_kafka_metadata_broker_t->port #} p)\n poke = undefined\n\ndata RdKafkaMetadataPartitionT = RdKafkaMetadataPartitionT\n { id'RdKafkaMetadataPartitionT :: Int\n , err'RdKafkaMetadataPartitionT :: RdKafkaRespErrT\n , leader'RdKafkaMetadataPartitionT :: Int\n , replicaCnt'RdKafkaMetadataPartitionT :: Int\n , replicas'RdKafkaMetadataPartitionT :: Ptr CInt32T\n , isrCnt'RdKafkaMetadataPartitionT :: Int\n , isrs'RdKafkaMetadataPartitionT :: Ptr CInt32T\n } deriving (Show, Eq)\n\ninstance Storable RdKafkaMetadataPartitionT where\n alignment _ = {#alignof rd_kafka_metadata_partition_t#}\n sizeOf _ = {#sizeof rd_kafka_metadata_partition_t#}\n peek p = RdKafkaMetadataPartitionT\n <$> liftM fromIntegral ({#get rd_kafka_metadata_partition_t->id#} p)\n <*> liftM cIntToEnum ({#get rd_kafka_metadata_partition_t->err#} p)\n <*> liftM fromIntegral ({#get rd_kafka_metadata_partition_t->leader#} p)\n <*> liftM fromIntegral ({#get rd_kafka_metadata_partition_t->replica_cnt#} p)\n <*> liftM castPtr ({#get rd_kafka_metadata_partition_t->replicas#} p)\n <*> liftM fromIntegral ({#get rd_kafka_metadata_partition_t->isr_cnt#} p)\n <*> liftM castPtr ({#get rd_kafka_metadata_partition_t->isrs#} p)\n\n poke = undefined\n\n{#pointer *rd_kafka_metadata_partition_t as RdKafkaMetadataPartitionTPtr -> RdKafkaMetadataPartitionT #}\n\ndata RdKafkaMetadataTopicT = RdKafkaMetadataTopicT\n { topic'RdKafkaMetadataTopicT :: CString\n , partitionCnt'RdKafkaMetadataTopicT :: Int\n , partitions'RdKafkaMetadataTopicT :: Ptr RdKafkaMetadataPartitionT\n , err'RdKafkaMetadataTopicT :: RdKafkaRespErrT\n } deriving (Show, Eq)\n\ninstance Storable RdKafkaMetadataTopicT where\n alignment _ = {#alignof rd_kafka_metadata_topic_t#}\n sizeOf _ = {#sizeof rd_kafka_metadata_topic_t #}\n peek p = RdKafkaMetadataTopicT\n <$> liftM id ({#get rd_kafka_metadata_topic_t->topic #} p)\n <*> liftM fromIntegral ({#get rd_kafka_metadata_topic_t->partition_cnt #} p)\n <*> liftM castPtr ({#get rd_kafka_metadata_topic_t->partitions #} p)\n <*> liftM cIntToEnum ({#get rd_kafka_metadata_topic_t->err #} p)\n poke _ _ = undefined\n\n{#pointer *rd_kafka_metadata_topic_t as RdKafkaMetadataTopicTPtr -> RdKafkaMetadataTopicT #}\n\ndata RdKafkaMetadataT = RdKafkaMetadataT\n { brokerCnt'RdKafkaMetadataT :: Int\n , brokers'RdKafkaMetadataT :: RdKafkaMetadataBrokerTPtr\n , topicCnt'RdKafkaMetadataT :: Int\n , topics'RdKafkaMetadataT :: RdKafkaMetadataTopicTPtr\n , origBrokerId'RdKafkaMetadataT :: CInt32T\n } deriving (Show, Eq)\n\ninstance Storable RdKafkaMetadataT where\n alignment _ = {#alignof rd_kafka_metadata_t#}\n sizeOf _ = {#sizeof rd_kafka_metadata_t#}\n peek p = RdKafkaMetadataT\n <$> liftM fromIntegral ({#get rd_kafka_metadata_t->broker_cnt #} p)\n <*> liftM castPtr ({#get rd_kafka_metadata_t->brokers #} p)\n <*> liftM fromIntegral ({#get rd_kafka_metadata_t->topic_cnt #} p)\n <*> liftM castPtr ({#get rd_kafka_metadata_t->topics #} p)\n <*> liftM fromIntegral ({#get rd_kafka_metadata_t->orig_broker_id #} p)\n poke _ _ = undefined\n\n{#pointer *rd_kafka_metadata_t as RdKafkaMetadataTPtr foreign -> RdKafkaMetadataT #}\n\n-------------------------------------------------------------------------------------------------\n---- Partitions\n{#fun rd_kafka_topic_partition_list_new as ^\n {`Int'} -> `RdKafkaTopicPartitionListTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_topic_partition_list_destroy\"\n rdKafkaTopicPartitionListDestroyF :: FinalizerPtr RdKafkaTopicPartitionListT\nforeign import ccall unsafe \"rdkafka.h rd_kafka_topic_partition_list_destroy\"\n rdKafkaTopicPartitionListDestroy :: Ptr RdKafkaTopicPartitionListT -> IO ()\n\nnewRdKafkaTopicPartitionListT :: Int -> IO RdKafkaTopicPartitionListTPtr\nnewRdKafkaTopicPartitionListT size = do\n ret <- rdKafkaTopicPartitionListNew size\n addForeignPtrFinalizer rdKafkaTopicPartitionListDestroyF ret\n return ret\n\n{# fun rd_kafka_topic_partition_list_add as ^\n {`RdKafkaTopicPartitionListTPtr', `String', `Int'} -> `RdKafkaTopicPartitionTPtr' #}\n\n{# fun rd_kafka_topic_partition_list_add_range as ^\n {`RdKafkaTopicPartitionListTPtr', `String', `Int', `Int'} -> `()' #}\n\n{# fun rd_kafka_topic_partition_list_copy as ^\n {`RdKafkaTopicPartitionListTPtr'} -> `RdKafkaTopicPartitionListTPtr' #}\n\ncopyRdKafkaTopicPartitionList :: RdKafkaTopicPartitionListTPtr -> IO RdKafkaTopicPartitionListTPtr\ncopyRdKafkaTopicPartitionList pl = do\n cp <- rdKafkaTopicPartitionListCopy pl\n addForeignPtrFinalizer rdKafkaTopicPartitionListDestroyF cp\n return cp\n\n{# fun rd_kafka_topic_partition_list_set_offset as ^\n {`RdKafkaTopicPartitionListTPtr', `String', `Int', `Int64'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n---- Rebalance Callback\ntype RdRebalanceCallback' = Ptr RdKafkaT -> CInt -> Ptr RdKafkaTopicPartitionListT -> Ptr Word8 -> IO ()\ntype RdRebalanceCallback = Ptr RdKafkaT -> RdKafkaRespErrT -> Ptr RdKafkaTopicPartitionListT -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkRebalanceCallback :: RdRebalanceCallback' -> IO (FunPtr RdRebalanceCallback')\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_rebalance_cb\"\n rdKafkaConfSetRebalanceCb' ::\n Ptr RdKafkaConfT\n -> FunPtr RdRebalanceCallback'\n -> IO ()\n\nrdKafkaConfSetRebalanceCb :: RdKafkaConfTPtr -> RdRebalanceCallback -> IO ()\nrdKafkaConfSetRebalanceCb conf cb = do\n cb' <- mkRebalanceCallback (\\k e p _ -> cb k (cIntToEnum e) p)\n withForeignPtr conf $ \\c -> rdKafkaConfSetRebalanceCb' c cb'\n return ()\n\n---- Delivery Callback\ntype DeliveryCallback' = Ptr RdKafkaT -> Ptr RdKafkaMessageT -> Word8Ptr -> IO ()\ntype DeliveryCallback = Ptr RdKafkaT -> Ptr RdKafkaMessageT -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkDeliveryCallback :: DeliveryCallback' -> IO (FunPtr DeliveryCallback')\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_dr_msg_cb\"\n rdKafkaConfSetDrMsgCb' :: Ptr RdKafkaConfT -> FunPtr DeliveryCallback' -> IO ()\n\nrdKafkaConfSetDrMsgCb :: RdKafkaConfTPtr -> DeliveryCallback -> IO ()\nrdKafkaConfSetDrMsgCb conf cb = do\n cb' <- mkDeliveryCallback (\\k m _ -> cb k m)\n withForeignPtr conf $ \\c -> rdKafkaConfSetDrMsgCb' c cb'\n return ()\n\n---- Consume Callback\ntype ConsumeCallback = Ptr RdKafkaMessageT -> Word8Ptr -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkConsumeCallback :: ConsumeCallback -> IO (FunPtr ConsumeCallback)\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_consume_cb\"\n rdKafkaConfSetConsumeCb' :: Ptr RdKafkaConfT -> FunPtr ConsumeCallback -> IO ()\n\nrdKafkaConfSetConsumeCb :: RdKafkaConfTPtr -> ConsumeCallback -> IO ()\nrdKafkaConfSetConsumeCb conf cb = do\n cb' <- mkConsumeCallback cb\n withForeignPtr conf $ \\c -> rdKafkaConfSetConsumeCb' c cb'\n return ()\n\n---- Offset Commit Callback\ntype OffsetCommitCallback' = Ptr RdKafkaT -> CInt -> Ptr RdKafkaTopicPartitionListT -> Word8Ptr -> IO ()\ntype OffsetCommitCallback = Ptr RdKafkaT -> RdKafkaRespErrT -> Ptr RdKafkaTopicPartitionListT -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkOffsetCommitCallback :: OffsetCommitCallback' -> IO (FunPtr OffsetCommitCallback')\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_offset_commit_cb\"\n rdKafkaConfSetOffsetCommitCb' :: Ptr RdKafkaConfT -> FunPtr OffsetCommitCallback' -> IO ()\n\nrdKafkaConfSetOffsetCommitCb :: RdKafkaConfTPtr -> OffsetCommitCallback -> IO ()\nrdKafkaConfSetOffsetCommitCb conf cb = do\n cb' <- mkOffsetCommitCallback (\\k e p _ -> cb k (cIntToEnum e) p)\n withForeignPtr conf $ \\c -> rdKafkaConfSetOffsetCommitCb' c cb'\n return ()\n\n\n----- Error Callback\ntype ErrorCallback' = Ptr RdKafkaT -> CInt -> CString -> Word8Ptr -> IO ()\ntype ErrorCallback = Ptr RdKafkaT -> RdKafkaRespErrT -> String -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkErrorCallback :: ErrorCallback' -> IO (FunPtr ErrorCallback')\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_error_cb\"\n rdKafkaConfSetErrorCb' :: Ptr RdKafkaConfT -> FunPtr ErrorCallback' -> IO ()\n\nrdKafkaConfSetErrorCb :: RdKafkaConfTPtr -> ErrorCallback -> IO ()\nrdKafkaConfSetErrorCb conf cb = do\n cb' <- mkErrorCallback (\\k e r _ -> peekCAString r >>= cb k (cIntToEnum e))\n withForeignPtr conf $ \\c -> rdKafkaConfSetErrorCb' c cb'\n\n---- Throttle Callback\ntype ThrottleCallback = Ptr RdKafkaT -> CString -> Int -> Int -> Word8Ptr -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkThrottleCallback :: ThrottleCallback -> IO (FunPtr ThrottleCallback)\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_throttle_cb\"\n rdKafkaConfSetThrottleCb' :: Ptr RdKafkaConfT -> FunPtr ThrottleCallback -> IO ()\n\nrdKafkaConfSetThrottleCb :: RdKafkaConfTPtr -> ThrottleCallback -> IO ()\nrdKafkaConfSetThrottleCb conf cb = do\n cb' <- mkThrottleCallback cb\n withForeignPtr conf $ \\c -> rdKafkaConfSetThrottleCb' c cb'\n return ()\n\n---- Log Callback\ntype LogCallback' = Ptr RdKafkaT -> CInt -> CString -> CString -> IO ()\ntype LogCallback = Ptr RdKafkaT -> Int -> String -> String -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkLogCallback :: LogCallback' -> IO (FunPtr LogCallback')\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_log_cb\"\n rdKafkaConfSetLogCb' :: Ptr RdKafkaConfT -> FunPtr LogCallback' -> IO ()\n\nrdKafkaConfSetLogCb :: RdKafkaConfTPtr -> LogCallback -> IO ()\nrdKafkaConfSetLogCb conf cb = do\n cb' <- mkLogCallback $ \\k l f b -> do\n f' <- peekCAString f\n b' <- peekCAString b\n cb k (cIntConv l) f' b'\n withForeignPtr conf $ \\c -> rdKafkaConfSetLogCb' c cb'\n\n---- Stats Callback\ntype StatsCallback' = Ptr RdKafkaT -> CString -> CSize -> Word8Ptr -> IO ()\ntype StatsCallback = Ptr RdKafkaT -> ByteString -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkStatsCallback :: StatsCallback' -> IO (FunPtr StatsCallback')\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_stats_cb\"\n rdKafkaConfSetStatsCb' :: Ptr RdKafkaConfT -> FunPtr StatsCallback' -> IO ()\n\nrdKafkaConfSetStatsCb :: RdKafkaConfTPtr -> StatsCallback -> IO ()\nrdKafkaConfSetStatsCb conf cb = do\n cb' <- mkStatsCallback $ \\k j jl _ -> BS.packCStringLen (j, cIntConv jl) >>= cb k\n withForeignPtr conf $ \\c -> rdKafkaConfSetStatsCb' c cb'\n return ()\n\n---- Socket Callback\ntype SocketCallback = Int -> Int -> Int -> Word8Ptr -> IO ()\n\nforeign import ccall safe \"wrapper\"\n mkSocketCallback :: SocketCallback -> IO (FunPtr SocketCallback)\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_conf_set_socket_cb\"\n rdKafkaConfSetSocketCb' :: Ptr RdKafkaConfT -> FunPtr SocketCallback -> IO ()\n\nrdKafkaConfSetSocketCb :: RdKafkaConfTPtr -> SocketCallback -> IO ()\nrdKafkaConfSetSocketCb conf cb = do\n cb' <- mkSocketCallback cb\n withForeignPtr conf $ \\c -> rdKafkaConfSetSocketCb' c cb'\n return ()\n\n{#fun rd_kafka_conf_set_opaque as ^\n {`RdKafkaConfTPtr', castPtr `Word8Ptr'} -> `()' #}\n\n{#fun rd_kafka_opaque as ^\n {`RdKafkaTPtr'} -> `Word8Ptr' castPtr #}\n\n{#fun rd_kafka_conf_set_default_topic_conf as ^\n {`RdKafkaConfTPtr', `RdKafkaTopicConfTPtr'} -> `()' #}\n\n---- Partitioner Callback\ntype PartitionerCallback =\n Ptr RdKafkaTopicTPtr\n -> Word8Ptr -- keydata\n -> Int -- keylen\n -> Int -- partition_cnt\n -> Word8Ptr -- topic_opaque\n -> Word8Ptr -- msg_opaque\n -> IO Int\n\nforeign import ccall safe \"wrapper\"\n mkPartitionerCallback :: PartitionerCallback -> IO (FunPtr PartitionerCallback)\n\nforeign import ccall safe \"rd_kafka.h rd_kafka_topic_conf_set_partitioner_cb\"\n rdKafkaTopicConfSetPartitionerCb' :: Ptr RdKafkaTopicConfT -> FunPtr PartitionerCallback -> IO ()\n\nrdKafkaTopicConfSetPartitionerCb :: RdKafkaTopicConfTPtr -> PartitionerCallback -> IO ()\nrdKafkaTopicConfSetPartitionerCb conf cb = do\n cb' <- mkPartitionerCallback cb\n withForeignPtr conf $ \\c -> rdKafkaTopicConfSetPartitionerCb' c cb'\n return ()\n\n---- Partition\n\n{#fun rd_kafka_topic_partition_available as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T'} -> `Int' #}\n\n{#fun rd_kafka_msg_partitioner_random as ^\n { `RdKafkaTopicTPtr'\n , castPtr `Word8Ptr'\n , cIntConv `CSize'\n , cIntConv `CInt32T'\n , castPtr `Word8Ptr'\n , castPtr `Word8Ptr'}\n -> `CInt32T' cIntConv #}\n\n{#fun rd_kafka_msg_partitioner_consistent as ^\n { `RdKafkaTopicTPtr'\n , castPtr `Word8Ptr'\n , cIntConv `CSize'\n , cIntConv `CInt32T'\n , castPtr `Word8Ptr'\n , castPtr `Word8Ptr'}\n -> `CInt32T' cIntConv #}\n\n{#fun rd_kafka_msg_partitioner_consistent_random as ^\n { `RdKafkaTopicTPtr'\n , castPtr `Word8Ptr'\n , cIntConv `CSize'\n , cIntConv `CInt32T'\n , castPtr `Word8Ptr'\n , castPtr `Word8Ptr'}\n -> `CInt32T' cIntConv #}\n\n---- Poll \/ Yield\n\n{#fun rd_kafka_yield as ^\n {`RdKafkaTPtr'} -> `()' #}\n\n---- Pause \/ Resume\n{#fun rd_kafka_pause_partitions as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'} -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_resume_partitions as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'} -> `RdKafkaRespErrT' cIntToEnum #}\n\n---- QUEUE\ndata RdKafkaQueueT\n{#pointer *rd_kafka_queue_t as RdKafkaQueueTPtr foreign -> RdKafkaQueueT #}\n\n{#fun rd_kafka_queue_new as ^\n {`RdKafkaTPtr'} -> `RdKafkaQueueTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_queue_destroy\"\n rdKafkaQueueDestroyF :: FinalizerPtr RdKafkaQueueT\n\n{#fun rd_kafka_queue_destroy as ^\n {`RdKafkaQueueTPtr'} -> `()'#}\n\nnewRdKafkaQueue :: RdKafkaTPtr -> IO RdKafkaQueueTPtr\nnewRdKafkaQueue k = do\n q <- rdKafkaQueueNew k\n addForeignPtrFinalizer rdKafkaQueueDestroyF q\n return q\n\n{#fun rd_kafka_consume_queue as ^\n {`RdKafkaQueueTPtr', `Int'} -> `RdKafkaMessageTPtr' #}\n\n{#fun rd_kafka_queue_forward as ^\n {`RdKafkaQueueTPtr', `RdKafkaQueueTPtr'} -> `()' #}\n\n{#fun rd_kafka_queue_get_partition as rdKafkaQueueGetPartition'\n {`RdKafkaTPtr', `String', `Int'} -> `RdKafkaQueueTPtr' #}\n\nrdKafkaQueueGetPartition :: RdKafkaTPtr -> String -> Int -> IO (Maybe RdKafkaQueueTPtr)\nrdKafkaQueueGetPartition k t p = do\n ret <- rdKafkaQueueGetPartition' k t p\n withForeignPtr ret $ \\realPtr ->\n if realPtr == nullPtr then return Nothing\n else do\n addForeignPtrFinalizer rdKafkaQueueDestroyF ret\n return $ Just ret\n\n{#fun rd_kafka_consume_batch_queue as rdKafkaConsumeBatchQueue'\n {`RdKafkaQueueTPtr', `Int', castPtr `Ptr (Ptr RdKafkaMessageT)', cIntConv `CSize'}\n -> `CSize' cIntConv #}\n\nrdKafkaConsumeBatchQueue :: RdKafkaQueueTPtr -> Int -> Int -> IO [RdKafkaMessageTPtr]\nrdKafkaConsumeBatchQueue qptr timeout batchSize = do\n allocaArray batchSize $ \\pArr -> do\n rSize <- rdKafkaConsumeBatchQueue' qptr timeout pArr (fromIntegral batchSize)\n peekArray (fromIntegral rSize) pArr >>= traverse (flip newForeignPtr (return ()))\n\n-------------------------------------------------------------------------------------------------\n---- High-level KafkaConsumer\n\n{#fun rd_kafka_subscribe as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_unsubscribe as ^\n {`RdKafkaTPtr'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_subscription as rdKafkaSubscription'\n {`RdKafkaTPtr', alloca- `Ptr RdKafkaTopicPartitionListT' peekPtr*}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\nrdKafkaSubscription :: RdKafkaTPtr -> IO (Either RdKafkaRespErrT RdKafkaTopicPartitionListTPtr)\nrdKafkaSubscription k = do\n (err, sub) <- rdKafkaSubscription' k\n case err of\n RdKafkaRespErrNoError ->\n Right <$> newForeignPtr sub (rdKafkaTopicPartitionListDestroy sub)\n e -> return (Left e)\n\n{#fun rd_kafka_consumer_poll as ^\n {`RdKafkaTPtr', `Int'} -> `RdKafkaMessageTPtr' #}\n\npollRdKafkaConsumer :: RdKafkaTPtr -> Int -> IO RdKafkaMessageTPtr\npollRdKafkaConsumer k t = do\n m <- rdKafkaConsumerPoll k t\n addForeignPtrFinalizer rdKafkaMessageDestroyF m\n return m\n\n{#fun rd_kafka_consumer_close as ^\n {`RdKafkaTPtr'} -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_poll_set_consumer as ^\n {`RdKafkaTPtr'} -> `RdKafkaRespErrT' cIntToEnum #}\n\n-- rd_kafka_assign\n{#fun rd_kafka_assign as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_assignment as rdKafkaAssignment'\n {`RdKafkaTPtr', alloca- `Ptr RdKafkaTopicPartitionListT' peekPtr* }\n -> `RdKafkaRespErrT' cIntToEnum #}\n\nrdKafkaAssignment :: RdKafkaTPtr -> IO (Either RdKafkaRespErrT RdKafkaTopicPartitionListTPtr)\nrdKafkaAssignment k = do\n (err, ass) <- rdKafkaAssignment' k\n case err of\n RdKafkaRespErrNoError ->\n Right <$> newForeignPtr ass (rdKafkaTopicPartitionListDestroy ass)\n e -> return (Left e)\n\n{#fun rd_kafka_commit as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr', boolToCInt `Bool'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_commit_message as ^\n {`RdKafkaTPtr', `RdKafkaMessageTPtr', boolToCInt `Bool'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_committed as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr', `Int'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_position as ^\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n-------------------------------------------------------------------------------------------------\n---- Groups\ndata RdKafkaGroupMemberInfoT = RdKafkaGroupMemberInfoT\n { memberId'RdKafkaGroupMemberInfoT :: CString\n , clientId'RdKafkaGroupMemberInfoT :: CString\n , clientHost'RdKafkaGroupMemberInfoT :: CString\n , memberMetadata'RdKafkaGroupMemberInfoT :: Word8Ptr\n , memberMetadataSize'RdKafkaGroupMemberInfoT :: Int\n , memberAssignment'RdKafkaGroupMemberInfoT :: Word8Ptr\n , memberAssignmentSize'RdKafkaGroupMemberInfoT :: Int }\n\ninstance Storable RdKafkaGroupMemberInfoT where\n alignment _ = {#alignof rd_kafka_group_member_info#}\n sizeOf _ = {#sizeof rd_kafka_group_member_info#}\n peek p = RdKafkaGroupMemberInfoT\n <$> liftM id ({#get rd_kafka_group_member_info->member_id #} p)\n <*> liftM id ({#get rd_kafka_group_member_info->client_id #} p)\n <*> liftM id ({#get rd_kafka_group_member_info->client_host #} p)\n <*> liftM castPtr ({#get rd_kafka_group_member_info->member_metadata #} p)\n <*> liftM fromIntegral ({#get rd_kafka_group_member_info->member_metadata_size #} p)\n <*> liftM castPtr ({#get rd_kafka_group_member_info->member_assignment #} p)\n <*> liftM fromIntegral ({#get rd_kafka_group_member_info->member_assignment_size #} p)\n poke p x = do\n {#set rd_kafka_group_member_info.member_id#} p (id $ memberId'RdKafkaGroupMemberInfoT x)\n {#set rd_kafka_group_member_info.client_id#} p (id $ clientId'RdKafkaGroupMemberInfoT x)\n {#set rd_kafka_group_member_info.client_host#} p (id $ clientHost'RdKafkaGroupMemberInfoT x)\n {#set rd_kafka_group_member_info.member_metadata#} p (castPtr $ memberMetadata'RdKafkaGroupMemberInfoT x)\n {#set rd_kafka_group_member_info.member_metadata_size#} p (fromIntegral $ memberMetadataSize'RdKafkaGroupMemberInfoT x)\n {#set rd_kafka_group_member_info.member_assignment#} p (castPtr $ memberAssignment'RdKafkaGroupMemberInfoT x)\n {#set rd_kafka_group_member_info.member_assignment_size#} p (fromIntegral $ memberAssignmentSize'RdKafkaGroupMemberInfoT x)\n\n{#pointer *rd_kafka_group_member_info as RdKafkaGroupMemberInfoTPtr -> RdKafkaGroupMemberInfoT #}\n\ndata RdKafkaGroupInfoT = RdKafkaGroupInfoT\n { broker'RdKafkaGroupInfoT :: RdKafkaMetadataBrokerTPtr\n , group'RdKafkaGroupInfoT :: CString\n , err'RdKafkaGroupInfoT :: RdKafkaRespErrT\n , state'RdKafkaGroupInfoT :: CString\n , protocolType'RdKafkaGroupInfoT :: CString\n , protocol'RdKafkaGroupInfoT :: CString\n , members'RdKafkaGroupInfoT :: RdKafkaGroupMemberInfoTPtr\n , memberCnt'RdKafkaGroupInfoT :: Int }\n\ninstance Storable RdKafkaGroupInfoT where\n alignment _ = {#alignof rd_kafka_group_info #}\n sizeOf _ = {#sizeof rd_kafka_group_info #}\n peek p = RdKafkaGroupInfoT\n <$> liftM castPtr ({#get rd_kafka_group_info->broker #} p)\n <*> liftM id ({#get rd_kafka_group_info->group #} p)\n <*> liftM cIntToEnum ({#get rd_kafka_group_info->err #} p)\n <*> liftM id ({#get rd_kafka_group_info->state #} p)\n <*> liftM id ({#get rd_kafka_group_info->protocol_type #} p)\n <*> liftM id ({#get rd_kafka_group_info->protocol #} p)\n <*> liftM castPtr ({#get rd_kafka_group_info->members #} p)\n <*> liftM fromIntegral ({#get rd_kafka_group_info->member_cnt #} p)\n poke p x = do\n {#set rd_kafka_group_info.broker#} p (castPtr $ broker'RdKafkaGroupInfoT x)\n {#set rd_kafka_group_info.group#} p (id $ group'RdKafkaGroupInfoT x)\n {#set rd_kafka_group_info.err#} p (enumToCInt $ err'RdKafkaGroupInfoT x)\n {#set rd_kafka_group_info.state#} p (id $ state'RdKafkaGroupInfoT x)\n {#set rd_kafka_group_info.protocol_type#} p (id $ protocolType'RdKafkaGroupInfoT x)\n {#set rd_kafka_group_info.protocol#} p (id $ protocol'RdKafkaGroupInfoT x)\n {#set rd_kafka_group_info.members#} p (castPtr $ members'RdKafkaGroupInfoT x)\n {#set rd_kafka_group_info.member_cnt#} p (fromIntegral $ memberCnt'RdKafkaGroupInfoT x)\n\n{#pointer *rd_kafka_group_info as RdKafkaGroupInfoTPtr foreign -> RdKafkaGroupInfoT #}\n\ndata RdKafkaGroupListT = RdKafkaGroupListT\n { groups'RdKafkaGroupListT :: Ptr RdKafkaGroupInfoT\n , groupCnt'RdKafkaGroupListT :: Int }\n\ninstance Storable RdKafkaGroupListT where\n alignment _ = {#alignof rd_kafka_group_list #}\n sizeOf _ = {#sizeof rd_kafka_group_list #}\n peek p = RdKafkaGroupListT\n <$> liftM castPtr ({#get rd_kafka_group_list->groups #} p)\n <*> liftM fromIntegral ({#get rd_kafka_group_list->group_cnt #} p)\n poke p x = do\n {#set rd_kafka_group_list.groups#} p (castPtr $ groups'RdKafkaGroupListT x)\n {#set rd_kafka_group_list.group_cnt#} p (fromIntegral $ groupCnt'RdKafkaGroupListT x)\n\n{#pointer *rd_kafka_group_list as RdKafkaGroupListTPtr foreign -> RdKafkaGroupListT #}\n\n{#fun rd_kafka_list_groups as rdKafkaListGroups'\n {`RdKafkaTPtr', `CString', alloca- `Ptr RdKafkaGroupListT' peek*, `Int'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\nforeign import ccall \"rdkafka.h &rd_kafka_group_list_destroy\"\n rdKafkaGroupListDestroyF :: FinalizerPtr RdKafkaGroupListT\n\nforeign import ccall \"rdkafka.h rd_kafka_group_list_destroy\"\n rdKafkaGroupListDestroy :: Ptr RdKafkaGroupListT -> IO ()\n\nrdKafkaListGroups :: RdKafkaTPtr -> Maybe String -> Int -> IO (Either RdKafkaRespErrT RdKafkaGroupListTPtr)\nrdKafkaListGroups k g t = case g of\n Nothing -> listGroups nullPtr\n Just strGrp -> withCAString strGrp listGroups\n where\n listGroups grp = do\n (err, res) <- rdKafkaListGroups' k grp t\n case err of\n RdKafkaRespErrNoError -> Right <$> newForeignPtr res (rdKafkaGroupListDestroy res)\n e -> return $ Left e\n-------------------------------------------------------------------------------------------------\n\n-- rd_kafka_message\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_message_destroy\"\n rdKafkaMessageDestroyF :: FinalizerPtr RdKafkaMessageT\n\nforeign import ccall unsafe \"rdkafka.h rd_kafka_message_destroy\"\n rdKafkaMessageDestroy :: Ptr RdKafkaMessageT -> IO ()\n\n{#fun rd_kafka_query_watermark_offsets as rdKafkaQueryWatermarkOffsets'\n {`RdKafkaTPtr', `String', cIntConv `CInt32T',\n alloca- `Int64' peekInt64Conv*, alloca- `Int64' peekInt64Conv*,\n cIntConv `Int'\n } -> `RdKafkaRespErrT' cIntToEnum #}\n\n\nrdKafkaQueryWatermarkOffsets :: RdKafkaTPtr -> String -> Int -> Int -> IO (Either RdKafkaRespErrT (Int64, Int64))\nrdKafkaQueryWatermarkOffsets kafka topic partition timeout = do\n (err, l, h) <- rdKafkaQueryWatermarkOffsets' kafka topic (cIntConv partition) timeout\n return $ case err of\n RdKafkaRespErrNoError -> Right (cIntConv l, cIntConv h)\n e -> Left e\n\n{#pointer *rd_kafka_timestamp_type_t as RdKafkaTimestampTypeTPtr foreign -> RdKafkaTimestampTypeT #}\n\ninstance Storable RdKafkaTimestampTypeT where\n sizeOf _ = {#sizeof rd_kafka_timestamp_type_t#}\n alignment _ = {#alignof rd_kafka_timestamp_type_t#}\n peek p = cIntToEnum <$> peek (castPtr p)\n poke p x = poke (castPtr p) (enumToCInt x)\n\n{#fun rd_kafka_message_timestamp as rdKafkaReadTimestamp'\n {castPtr `Ptr RdKafkaMessageT', `RdKafkaTimestampTypeTPtr'} -> `CInt64T' cIntConv #}\n\n{#fun rd_kafka_message_timestamp as ^\n {`RdKafkaMessageTPtr', `RdKafkaTimestampTypeTPtr'} -> `CInt64T' cIntConv #}\n\n{#fun rd_kafka_offsets_for_times as rdKafkaOffsetsForTimes\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr', `Int'} -> `RdKafkaRespErrT' cIntToEnum #}\n\n-- rd_kafka_conf\n{#fun rd_kafka_conf_new as ^\n {} -> `RdKafkaConfTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_conf_destroy\"\n rdKafkaConfDestroy :: FinalizerPtr RdKafkaConfT\n\n{#fun rd_kafka_conf_dup as ^\n {`RdKafkaConfTPtr'} -> `RdKafkaConfTPtr' #}\n\n{#fun rd_kafka_conf_set as ^\n {`RdKafkaConfTPtr', `String', `String', id `CCharBufPointer', cIntConv `CSize'}\n -> `RdKafkaConfResT' cIntToEnum #}\n\nnewRdKafkaConfT :: IO RdKafkaConfTPtr\nnewRdKafkaConfT = do\n ret <- rdKafkaConfNew\n addForeignPtrFinalizer rdKafkaConfDestroy ret\n return ret\n\n{#fun rd_kafka_conf_dump as ^\n {`RdKafkaConfTPtr', castPtr `CSizePtr'} -> `Ptr CString' id #}\n\n{#fun rd_kafka_conf_dump_free as ^\n {id `Ptr CString', cIntConv `CSize'} -> `()' #}\n\n{#fun rd_kafka_conf_properties_show as ^\n {`CFilePtr'} -> `()' #}\n\n-- rd_kafka_topic_conf\n{#fun rd_kafka_topic_conf_new as ^\n {} -> `RdKafkaTopicConfTPtr' #}\n\n{#fun rd_kafka_topic_conf_dup as ^\n {`RdKafkaTopicConfTPtr'} -> `RdKafkaTopicConfTPtr' #}\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_topic_conf_destroy\"\n rdKafkaTopicConfDestroy :: FinalizerPtr RdKafkaTopicConfT\n\n{#fun rd_kafka_topic_conf_set as ^\n {`RdKafkaTopicConfTPtr', `String', `String', id `CCharBufPointer', cIntConv `CSize'}\n -> `RdKafkaConfResT' cIntToEnum #}\n\nnewRdKafkaTopicConfT :: IO RdKafkaTopicConfTPtr\nnewRdKafkaTopicConfT = do\n ret <- rdKafkaTopicConfNew\n addForeignPtrFinalizer rdKafkaTopicConfDestroy ret\n return ret\n\n{#fun rd_kafka_topic_conf_dump as ^\n {`RdKafkaTopicConfTPtr', castPtr `CSizePtr'} -> `Ptr CString' id #}\n\n-- rd_kafka\n{#fun rd_kafka_new as ^\n {enumToCInt `RdKafkaTypeT', `RdKafkaConfTPtr', id `CCharBufPointer', cIntConv `CSize'}\n -> `RdKafkaTPtr' #}\n\nforeign import ccall safe \"rdkafka.h &rd_kafka_destroy\"\n rdKafkaDestroy :: FunPtr (Ptr RdKafkaT -> IO ())\n\nnewRdKafkaT :: RdKafkaTypeT -> RdKafkaConfTPtr -> IO (Either Text RdKafkaTPtr)\nnewRdKafkaT kafkaType confPtr =\n allocaBytes nErrorBytes $ \\charPtr -> do\n duper <- rdKafkaConfDup confPtr\n ret <- rdKafkaNew kafkaType duper charPtr (fromIntegral nErrorBytes)\n withForeignPtr ret $ \\realPtr -> do\n if realPtr == nullPtr then peekCText charPtr >>= return . Left\n else do\n -- do not call 'rd_kafka_close_consumer' on destroying all Kafka.\n -- when needed, applications should do it explicitly.\n -- {# call rd_kafka_destroy_flags #} realPtr 0x8\n addForeignPtrFinalizer rdKafkaDestroy ret\n return $ Right ret\n\n{#fun rd_kafka_brokers_add as ^\n {`RdKafkaTPtr', `String'} -> `Int' #}\n\n{#fun rd_kafka_set_log_level as ^\n {`RdKafkaTPtr', `Int'} -> `()' #}\n\n-- rd_kafka consume\n\n{#fun rd_kafka_consume_start as rdKafkaConsumeStartInternal\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', cIntConv `CInt64T'} -> `Int' #}\n\nrdKafkaConsumeStart :: RdKafkaTopicTPtr -> Int -> Int64 -> IO (Maybe String)\nrdKafkaConsumeStart topicPtr partition offset = do\n i <- rdKafkaConsumeStartInternal topicPtr (fromIntegral partition) (fromIntegral offset)\n case i of\n -1 -> kafkaErrnoString >>= return . Just\n _ -> return Nothing\n{#fun rd_kafka_consume_stop as rdKafkaConsumeStopInternal\n {`RdKafkaTopicTPtr', cIntConv `CInt32T'} -> `Int' #}\n\n{#fun rd_kafka_seek as rdKafkaSeek\n {`RdKafkaTopicTPtr', `Int32', `Int64', `Int'} -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_consume as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', `Int'} -> `RdKafkaMessageTPtr' #}\n\n{#fun rd_kafka_consume_batch as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', `Int', castPtr `Ptr (Ptr RdKafkaMessageT)', cIntConv `CSize'}\n -> `CSize' cIntConv #}\n\nrdKafkaConsumeStop :: RdKafkaTopicTPtr -> Int -> IO (Maybe String)\nrdKafkaConsumeStop topicPtr partition = do\n i <- rdKafkaConsumeStopInternal topicPtr (fromIntegral partition)\n case i of\n -1 -> kafkaErrnoString >>= return . Just\n _ -> return Nothing\n\n{#fun rd_kafka_offset_store as rdKafkaOffsetStore\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', cIntConv `CInt64T'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n{#fun rd_kafka_offsets_store as rdKafkaOffsetsStore\n {`RdKafkaTPtr', `RdKafkaTopicPartitionListTPtr'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\n-- rd_kafka produce\n\n{#fun rd_kafka_produce as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', `Int', castPtr `Word8Ptr',\n cIntConv `CSize', castPtr `Word8Ptr', cIntConv `CSize', castPtr `Ptr ()'}\n -> `Int' #}\n\n{#fun rd_kafka_produce_batch as ^\n {`RdKafkaTopicTPtr', cIntConv `CInt32T', `Int', `RdKafkaMessageTPtr', `Int'} -> `Int' #}\n\n\n-- rd_kafka_metadata\n\n{#fun rd_kafka_metadata as rdKafkaMetadata'\n {`RdKafkaTPtr', boolToCInt `Bool', `RdKafkaTopicTPtr',\n alloca- `Ptr RdKafkaMetadataT' peekPtr*, `Int'}\n -> `RdKafkaRespErrT' cIntToEnum #}\n\nforeign import ccall unsafe \"rdkafka.h rd_kafka_metadata_destroy\"\n rdKafkaMetadataDestroy :: Ptr RdKafkaMetadataT -> IO ()\n\nrdKafkaMetadata :: RdKafkaTPtr -> Bool -> Maybe RdKafkaTopicTPtr -> Int -> IO (Either RdKafkaRespErrT RdKafkaMetadataTPtr)\nrdKafkaMetadata k allTopics mt timeout = do\n tptr <- maybe (newForeignPtr_ nullPtr) pure mt\n (err, res) <- rdKafkaMetadata' k allTopics tptr timeout\n case err of\n RdKafkaRespErrNoError -> Right <$> newForeignPtr res (rdKafkaMetadataDestroy res)\n e -> return (Left e)\n\n{#fun rd_kafka_poll as ^\n {`RdKafkaTPtr', `Int'} -> `Int' #}\n\n{#fun rd_kafka_outq_len as ^\n {`RdKafkaTPtr'} -> `Int' #}\n\n{#fun rd_kafka_dump as ^\n {`CFilePtr', `RdKafkaTPtr'} -> `()' #}\n\n-- rd_kafka_topic\n{#fun rd_kafka_topic_name as ^\n {`RdKafkaTopicTPtr'} -> `String' #}\n\n{#fun rd_kafka_topic_new as ^\n {`RdKafkaTPtr', `String', `RdKafkaTopicConfTPtr'} -> `RdKafkaTopicTPtr' #}\n\n{# fun rd_kafka_topic_destroy as ^\n {castPtr `Ptr RdKafkaTopicT'} -> `()' #}\n\ndestroyUnmanagedRdKafkaTopic :: RdKafkaTopicTPtr -> IO ()\ndestroyUnmanagedRdKafkaTopic ptr =\n withForeignPtr ptr rdKafkaTopicDestroy\n\nforeign import ccall unsafe \"rdkafka.h &rd_kafka_topic_destroy\"\n rdKafkaTopicDestroy' :: FinalizerPtr RdKafkaTopicT\n\nnewUnmanagedRdKafkaTopicT :: RdKafkaTPtr -> String -> Maybe RdKafkaTopicConfTPtr -> IO (Either String RdKafkaTopicTPtr)\nnewUnmanagedRdKafkaTopicT kafkaPtr topic topicConfPtr = do\n duper <- maybe (newForeignPtr_ nullPtr) rdKafkaTopicConfDup topicConfPtr\n ret <- rdKafkaTopicNew kafkaPtr topic duper\n withForeignPtr ret $ \\realPtr ->\n if realPtr == nullPtr then kafkaErrnoString >>= return . Left\n else return $ Right ret\n\nnewRdKafkaTopicT :: RdKafkaTPtr -> String -> Maybe RdKafkaTopicConfTPtr -> IO (Either String RdKafkaTopicTPtr)\nnewRdKafkaTopicT kafkaPtr topic topicConfPtr = do\n res <- newUnmanagedRdKafkaTopicT kafkaPtr topic topicConfPtr\n _ <- traverse (addForeignPtrFinalizer rdKafkaTopicDestroy') res\n return res\n\n-- Marshall \/ Unmarshall\nenumToCInt :: Enum a => a -> CInt\nenumToCInt = fromIntegral . fromEnum\n{-# INLINE enumToCInt #-}\n\ncIntToEnum :: Enum a => CInt -> a\ncIntToEnum = toEnum . fromIntegral\n{-# INLINE cIntToEnum #-}\n\ncIntConv :: (Integral a, Num b) => a -> b\ncIntConv = fromIntegral\n{-# INLINE cIntConv #-}\n\nboolToCInt :: Bool -> CInt\nboolToCInt True = CInt 1\nboolToCInt False = CInt 0\n{-# INLINE boolToCInt #-}\n\npeekInt64Conv :: (Storable a, Integral a) => Ptr a -> IO Int64\npeekInt64Conv = liftM cIntConv . peek\n{-# INLINE peekInt64Conv #-}\n\npeekPtr :: Ptr a -> IO (Ptr b)\npeekPtr = peek . castPtr\n{-# INLINE peekPtr #-}\n\n-- Handle -> File descriptor\n\nforeign import ccall \"\" fdopen :: Fd -> CString -> IO (Ptr CFile)\n\nhandleToCFile :: Handle -> String -> IO (CFilePtr)\nhandleToCFile h m =\n do iomode <- newCString m\n fd <- handleToFd h\n fdopen fd iomode\n\nc_stdin :: IO CFilePtr\nc_stdin = handleToCFile stdin \"r\"\nc_stdout :: IO CFilePtr\nc_stdout = handleToCFile stdout \"w\"\nc_stderr :: IO CFilePtr\nc_stderr = handleToCFile stderr \"w\"\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"}
{"commit":"d3ded7b689648729230f412ffa0c009a84bae29e","subject":"[project @ 2004-05-20 16:53:58 by duncan_coutts] haddock fix","message":"[project @ 2004-05-20 16:53:58 by duncan_coutts]\nhaddock fix\n\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"gtk\/gdk\/Pixbuf.chs","new_file":"gtk\/gdk\/Pixbuf.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Pixbuf@\n--\n-- Author : Vincenzo Ciancia, Axel Simon\n-- Created: 26 March 2002\n--\n-- Version $Revision: 1.6 $ from $Date: 2004\/05\/20 16:53:58 $\n--\n-- Copyright (c) 2002 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Library General Public\n-- License as published by the Free Software Foundation; either\n-- version 2 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Library General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- @ref data Pixbuf@s are bitmap images in memory.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * A Pixbuf is used to represent images. It contains information\n-- about the image's pixel data, its color space, bits per sample, width\n-- and height, and the rowstride or number of bytes between rows.\n--\n-- * This module contains functions to scale and crop\n-- @ref data Pixbuf@s and to scale and crop a @ref data Pixbuf@ and \n-- compose the result with an existing image.\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * if there is a portable way of modifying external arrays in Haskell do:\n--\tgdk_pixbuf_get_pixels, gdk_pixbuf_new_from_data, everything in\n--\tInline data, \n--\n-- * if anybody writes an image manipulation program, do the checker board\n-- functions: gdk_pixbuf_composite_color_simple and\n-- gdk_pixbuf_composite_color. Moreover, do: pixbuf_saturate_and_pixelate\n--\n-- * the animation functions\n--\n-- * pixbuf loader\n--\n-- * module interface\n--\n-- * rendering function for Bitmaps and Pixmaps when the latter are added\n--\nmodule Pixbuf(\n Pixbuf,\n PixbufClass,\n PixbufError(..),\n Colorspace(..),\n pixbufGetColorSpace,\n pixbufGetNChannels,\n pixbufGetHasAlpha,\n pixbufGetBitsPerSample,\n pixbufGetWidth,\n pixbufGetHeight,\n pixbufGetRowstride,\n pixbufGetOption,\n pixbufNewFromFile,\n ImageType,\n pixbufGetFormats,\n pixbufSave,\n pixbufNew,\n pixbufNewFromXPMData,\n InlineImage,\n pixbufNewFromInline,\n pixbufNewSubpixbuf,\n pixbufCopy,\n InterpType(..),\n pixbufScaleSimple,\n pixbufScale,\n pixbufComposite,\n pixbufAddAlpha,\n pixbufCopyArea,\n pixbufFill,\n pixbufGetFromDrawable\n ) where\n\nimport FFI\n{#import Hierarchy#}\nimport GObject\nimport Monad\n\nimport Structs\t\t(GError(..), GQuark, Rectangle(..))\nimport LocalData\t(unsafePerformIO)\nimport Exception\t(bracket)\nimport LocalData\t((.|.), shiftL)\n\n{#context prefix=\"gdk\" #}\n\n-- @data PixbufError@ Error codes for loading image files.\n--\n{#enum PixbufError {underscoreToCase} #}\n\n\n-- @data Colorspace@ Enumerate all supported color spaces.\n--\n-- * Only RGB is supported right now.\n--\n{#enum Colorspace {underscoreToCase} #}\n\n-- @method pixbufGetColorSpace@ Queries the color space of a pixbuf.\n--\npixbufGetColorSpace :: Pixbuf -> IO Colorspace\npixbufGetColorSpace pb = liftM (toEnum . fromIntegral) $\n {#call unsafe pixbuf_get_colorspace#} pb\n\n-- @method pixbufGetNChannels@ Queries the number of colors for each pixel.\n--\npixbufGetNChannels :: Pixbuf -> IO Int\npixbufGetNChannels pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_n_channels#} pb\n\n-- @method pixbufGetHasAlpha@ Query if the image has an alpha channel.\n--\n-- * The alpha channel determines the opaqueness of the pixel.\n--\npixbufGetHasAlpha :: Pixbuf -> IO Bool\npixbufGetHasAlpha pb =\n liftM toBool $ {#call unsafe pixbuf_get_has_alpha#} pb\n\n-- @method pixbufGetBitsPerSample@ Queries the number of bits for each color.\n--\n-- * Each pixel is has a number of cannels for each pixel, each channel\n-- has this many bits.\n--\npixbufGetBitsPerSample :: Pixbuf -> IO Int\npixbufGetBitsPerSample pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_bits_per_sample#} pb\n\n-- @method pixbufGetWidth@ Queries the width of this image.\n--\npixbufGetWidth :: Pixbuf -> IO Int\npixbufGetWidth pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_width#} pb\n\n-- @method pixbufGetHeight@ Queries the height of this image.\n--\npixbufGetHeight :: Pixbuf -> IO Int\npixbufGetHeight pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_height#} pb\n\n-- @method pixbufGetRowstride@ Queries the rowstride of this image.\n--\n-- * Queries the rowstride of a pixbuf, which is the number of bytes between\n-- rows. Use this value to caculate the offset to a certain row.\n--\npixbufGetRowstride :: Pixbuf -> IO Int\npixbufGetRowstride pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_rowstride#} pb\n\n-- @method pixbufGetOption@ Returns an attribut of an image.\n--\n-- * Looks up if some information was stored under the @ref arg key@ when\n-- this image was saved.\n--\npixbufGetOption :: Pixbuf -> String -> IO (Maybe String)\npixbufGetOption pb key = withUTFString key $ \\strPtr -> do\n resPtr <- {#call unsafe pixbuf_get_option#} pb strPtr\n if (resPtr==nullPtr) then return Nothing else\n liftM Just $ peekUTFString resPtr\n\n-- pixbufErrorDomain -- helper function\npixbufErrorDomain :: GQuark\npixbufErrorDomain = unsafePerformIO {#call unsafe pixbuf_error_quark#}\n\n-- @constructor pixbufNewFromFile@ Load an image synchonously.\n--\n-- * Use this function to load only small images as this call will block.\n--\n-- * The function will return @literal Left (err,msg)@ where @ref arg err@\n-- is the error code and @ref arg msg@ is a human readable description\n-- of the error. If an error occurs which is not captured by any of\n-- those in @ref data PixbufError@, an exception is thrown.\n--\npixbufNewFromFile :: FilePath -> IO (Either (PixbufError,String) Pixbuf)\npixbufNewFromFile fname = withUTFString fname $ \\strPtr ->\n alloca $ \\errPtrPtr -> do\n pbPtr <- {#call unsafe pixbuf_new_from_file#} strPtr (castPtr errPtrPtr)\n if pbPtr\/=nullPtr then liftM Right $ makeNewGObject mkPixbuf (return pbPtr)\n else do\n errPtr <- peek errPtrPtr\n (GError dom code msg) <- peek errPtr\n if dom==pixbufErrorDomain then\n return (Left (toEnum (fromIntegral code), msg))\n else\n\terror msg\n\n-- @type ImageType@ A string representing an image file format.\n--\ntype ImageType = String\n\n-- @constant pixbufGetFormats@ A list of valid image file formats.\n--\npixbufGetFormats :: [ImageType]\n\npixbufGetFormats = [\"png\",\"bmp\",\"wbmp\", \"gif\",\"ico\",\"ani\",\"jpeg\",\"pnm\",\n\t\t \"ras\",\"tiff\",\"xpm\",\"xbm\",\"tga\"]\n\n-- @method pixbufSave@ Save an image to disk.\n--\n-- * The function takes a list of key - value pairs to specify\n-- either how an image is saved or to actually save this additional\n-- data with the image. JPEG images can be saved with a \"quality\"\n-- parameter; its value should be in the range [0,100]. Text chunks\n-- can be attached to PNG images by specifying parameters of the form\n-- \"tEXt::key\", where key is an ASCII string of length 1-79.\n-- The values are Unicode strings.\n--\n-- * The function returns @literal Nothing@ if writing was successful.\n-- Otherwise the error code and a description is returned or,\n-- if the error is not captured by one of the error codes in\n-- @ref data PixbufError@, an exception is thrown.\n--\npixbufSave :: Pixbuf -> FilePath -> ImageType -> [(String, String)] ->\n\t IO (Maybe (PixbufError, String))\npixbufSave pb fname iType options =\n let (keys, values) = unzip options in\n let optLen = length keys in\n withUTFString fname $ \\fnPtr ->\n withUTFString iType $ \\tyPtr ->\n allocaArray0 optLen $ \\keysPtr ->\n allocaArray optLen $ \\valuesPtr ->\n alloca $ \\errPtrPtr -> do\n keyPtrs <- mapM newUTFString keys\n valuePtrs <- mapM newUTFString values\n pokeArray keysPtr keyPtrs\n pokeArray valuesPtr valuePtrs\n res <- {#call unsafe pixbuf_savev#} pb fnPtr tyPtr keysPtr valuesPtr\n\t\t\t\t\t(castPtr errPtrPtr)\n mapM_ free keyPtrs\n mapM_ free valuePtrs\n if not (toBool res) then return Nothing else do\n errPtr <- peek errPtrPtr\n (GError dom code msg) <- peek errPtr\n if dom==pixbufErrorDomain then\n return (Just (toEnum (fromIntegral code), msg))\n else\n\terror msg\n\n-- @constructor pixbufNew@ Create a new image in memory.\n--\n-- * Creates a new pixbuf structure and allocates a buffer for\n-- it. Note that the buffer is not cleared initially.\n--\npixbufNew :: Colorspace -> Bool -> Int -> Int -> Int -> IO Pixbuf\npixbufNew colorspace hasAlpha bitsPerSample width height =\n makeNewGObject mkPixbuf $ \n {#call pixbuf_new#} ((fromIntegral . fromEnum) colorspace)\n (fromBool hasAlpha) (fromIntegral bitsPerSample) (fromIntegral width)\n (fromIntegral height)\n\n-- @constructor pixbufNewFromXPMData@ Create a new image from a String.\n--\n-- * Creates a new pixbuf from a string description.\n--\npixbufNewFromXPMData :: [String] -> IO Pixbuf\npixbufNewFromXPMData s =\n bracket (mapM newUTFString s) (mapM free) $ \\strPtrs ->\n withArray0 nullPtr strPtrs $ \\strsPtr ->\n makeNewGObject mkPixbuf $ {#call pixbuf_new_from_xpm_data#} strsPtr\n\n-- @data InlineImage@ A dymmy type for inline picture data.\n--\n-- * This dummy type is used to declare pointers to image data\n-- that is embedded in the executable. See\n-- @ref constructor pixbufNewFromInline@ for an example.\n--\ndata InlineImage = InlineImage\n\n-- @constructor pixbufNewFromInline@ Create a new image from a static pointer.\n--\n-- * Like @ref constructor pixbufNewFromXPMData@, this function allows to\n-- include images in the final binary program. The method used by this\n-- function uses a binary representation and therefore needs less space\n-- in the final executable. Save the image you want to include as\n-- @literal png@ and run @prog\n-- echo #include \"my_image.h\" > my_image.c\n-- gdk-pixbuf-csource --raw --extern --name=my_image myimage.png >> my_image.c\n-- @ on it. Write a header file @literal my_image.h@ containing @prog\n-- #include \n-- extern guint8 my_image\\[\\];\n-- @ and save it in the current directory.\n-- The created file can be compiled with @prog\n-- cc -c my_image.c `pkg-config --cflags gdk-2.0`\n-- @ into an object file which must be linked into your Haskell program by\n-- specifying @literal my_image.o@ and @literal \"-#include my_image.h\"@ on\n-- the command line of GHC.\n-- Within you application you delcare a pointer to this image: @prog\n-- foreign label \"my_image\" myImage :: Ptr InlineImage\n-- @ Calling @ref constructor pixbufNewFromInline@ with this pointer will\n-- return the image in the object file. Creating the C file with\n-- the @literal --raw@ flag will result in a non-compressed image in the\n-- object file. The advantage is that the picture will not be\n-- copied when this function is called.\n--\n--\npixbufNewFromInline :: Ptr InlineImage -> IO Pixbuf\npixbufNewFromInline iPtr = alloca $ \\errPtrPtr -> do\n pbPtr <- {#call unsafe pixbuf_new_from_inline#} (-1) (castPtr iPtr)\n (fromBool False) (castPtr errPtrPtr)\n if pbPtr\/=nullPtr then makeNewGObject mkPixbuf (return pbPtr)\n else do\n errPtr <- peek errPtrPtr\n (GError dom code msg) <- peek errPtr\n error msg\n\n-- @method pixbufNewSubpixbuf@ Create a restricted view of an image.\n--\n-- * This function returns a @ref data Pixbuf@ object which shares\n-- the image of the original one but only shows a part of it.\n-- Modifying either buffer will affect the other.\n--\n-- * This function throw an exception if the requested bounds are invalid.\n--\npixbufNewSubpixbuf :: Pixbuf -> Int -> Int -> Int -> Int -> IO Pixbuf\npixbufNewSubpixbuf pb srcX srcY height width =\n makeNewGObject mkPixbuf $ do\n pbPtr <- {#call unsafe pixbuf_new_subpixbuf#} pb\n (fromIntegral srcX) (fromIntegral srcY)\n (fromIntegral height) (fromIntegral width)\n if pbPtr==nullPtr then error \"pixbufNewSubpixbuf: invalid bounds\"\n else return pbPtr\n\n-- @constructor pixbufCopy@ Create a deep copy of an image.\n--\npixbufCopy :: Pixbuf -> IO Pixbuf\npixbufCopy pb = makeNewGObject mkPixbuf $ {#call unsafe pixbuf_copy#} pb\n\n\n-- @data InterpType@ How an image is scaled.\n--\n--\n-- * @variant InterpNearest@ Nearest neighbor sampling; this is the\n-- fastest and lowest quality mode. Quality is normally unacceptable when\n-- scaling down, but may be OK when scaling up.\n--\n-- * @variant InterpTiles@ This is an accurate simulation of the\n-- PostScript image operator without any interpolation enabled. Each\n-- pixel is rendered as a tiny parallelogram of solid color, the edges of\n-- which are implemented with antialiasing. It resembles nearest neighbor\n-- for enlargement, and bilinear for reduction.\n--\n-- * @variant InterpBilinear@ Best quality\/speed balance; use this\n-- mode by default. Bilinear interpolation. For enlargement, it is\n-- equivalent to point-sampling the ideal bilinear-interpolated\n-- image. For reduction, it is equivalent to laying down small tiles and\n-- integrating over the coverage area.\n--\n-- * @variant InterpHyper@ This is the slowest and highest quality\n-- reconstruction function. It is derived from the hyperbolic filters in\n-- Wolberg's \"Digital Image Warping\", and is formally defined as the\n-- hyperbolic-filter sampling the ideal hyperbolic-filter interpolated\n-- image (the filter is designed to be idempotent for 1:1 pixel mapping).\n--\n{#enum InterpType {underscoreToCase} #}\n\n-- @method pixbufScaleSimple@ Scale an image.\n--\n-- * Creates a new @ref data GdkPixbuf@ containing a copy of \n-- @ref arg src@ scaled to the given measures. Leaves @ref arg src@\n-- unaffected. \n--\n-- * @ref arg interp@ affects the quality and speed of the scaling function.\n-- @variant InterpNearest@ is the fastest option but yields very poor\n-- quality when scaling down. @variant InterpBilinear@ is a good\n-- trade-off between speed and quality and should thus be used as a\n-- default.\n--\npixbufScaleSimple :: Pixbuf -> Int -> Int -> InterpType -> IO Pixbuf\npixbufScaleSimple pb width height interp =\n makeNewGObject mkPixbuf $ liftM castPtr $ \n\t{#call pixbuf_scale_simple#} (toPixbuf pb) \n\t(fromIntegral width) (fromIntegral height)\n\t(fromIntegral $ fromEnum interp)\n\n-- @method pixbufScale@ Copy a scaled image part to another image.\n--\n-- * This function is the generic version of @ref method pixbufScaleSimple@.\n-- It scales @ref arg src@ by @ref arg scaleX@ and @ref arg scaleY@ and\n-- translate the image by @ref arg offsetX@ and @ref arg offsetY@. Whatever\n-- is in the intersection with the rectangle @ref arg destX@,\n-- @ref arg destY@, @ref arg destWidth@, @ref arg destHeight@ will be\n-- rendered into @ref arg dest@.\n--\n-- * The rectangle in the destination is simply overwritten. Use\n-- @ref method pixbufComposite@ if you need to blend the source\n-- image onto the destination.\n--\npixbufScale :: Pixbuf -> Pixbuf -> Int -> Int -> Int -> Int ->\n\t Double -> Double -> Double -> Double -> InterpType -> IO ()\npixbufScale src dest destX destY destWidth destHeight offsetX offsetY\n scaleX scaleY interp = {#call unsafe pixbuf_scale#} src dest\n (fromIntegral destX) (fromIntegral destY) (fromIntegral destHeight)\n (fromIntegral destWidth) (realToFrac offsetX) (realToFrac offsetY)\n (realToFrac scaleX) (realToFrac scaleY)\n ((fromIntegral . fromEnum) interp)\n\n-- @method pixbufComposite@ Blend a scaled image part onto another image.\n--\n-- * This function is similar to @ref method pixbufScale@ but allows the\n-- original image to \"shine through\". The @ref arg alpha@ value determines\n-- how opaque the source image is. Passing @literal 0@ is\n-- equivalent to not calling this function at all, passing\n-- @literal 255@ has the\n-- same effect as calling @ref method pixbufScale@.\n--\npixbufComposite :: Pixbuf -> Pixbuf -> Int -> Int -> Int -> Int ->\n\t\t Double -> Double -> Double -> Double -> InterpType ->\n\t \t Word8 -> IO ()\npixbufComposite src dest destX destY destWidth destHeight\n offsetX offsetY scaleX scaleY interp alpha =\n {#call unsafe pixbuf_composite#} src dest\n (fromIntegral destX) (fromIntegral destY) (fromIntegral destHeight)\n (fromIntegral destWidth) (realToFrac offsetX) (realToFrac offsetY)\n (realToFrac scaleX) (realToFrac scaleY)\n ((fromIntegral . fromEnum) interp) (fromIntegral alpha)\n\n-- @method pixbufAddAlpha@ Add an opacity layer to the @ref data Pixbuf@.\n--\n-- * This function returns a copy of the given @ref arg src@\n-- @ref data Pixbuf@, leaving @ref arg src@ unmodified.\n-- The new @ref data Pixbuf@ has an alpha (opacity)\n-- channel which defaults to @literal 255@ (fully opaque pixels)\n-- unless @ref arg src@ already had an alpha channel in which case\n-- the original values are kept.\n-- Passing in a color triple @literal (r,g,b)@ makes all\n-- pixels that have this color fully transparent\n-- (opacity of @literal 0@). The pixel color itself remains unchanged\n-- during this substitution.\n--\npixbufAddAlpha :: Pixbuf -> Maybe (Word8, Word8, Word8) -> IO Pixbuf\npixbufAddAlpha pb Nothing = makeNewGObject mkPixbuf $\n {#call unsafe pixbuf_add_alpha#} pb (fromBool False) 0 0 0\npixbufAddAlpha pb (Just (r,g,b)) = makeNewGObject mkPixbuf $\n {#call unsafe pixbuf_add_alpha#} pb (fromBool True)\n (fromIntegral r) (fromIntegral g) (fromIntegral b)\n\n-- @method pixbufCopyArea@ Copy a rectangular portion into another\n-- @ref data Pixbuf@.\n--\n-- * The source @ref data Pixbuf@ remains unchanged. Converion between\n-- different formats is done automatically.\n--\npixbufCopyArea :: Pixbuf -> Int -> Int -> Int -> Int ->\n\t\t Pixbuf -> Int -> Int -> IO ()\npixbufCopyArea src srcX srcY srcWidth srcHeight dest destX destY =\n {#call unsafe pixbuf_copy_area#} src (fromIntegral srcX)\n (fromIntegral srcY) (fromIntegral srcHeight) (fromIntegral srcWidth)\n dest (fromIntegral destX) (fromIntegral destY)\n\n-- @method pixbufFill@ Fills a @ref data Pixbuf@ with a color.\n--\n-- * The passed-in color is a quadruple consisting of the red, green, blue\n-- and alpha component of the pixel. If the @ref data Pixbuf@ does not\n-- have an alpha channel, the alpha value is ignored.\n--\npixbufFill :: Pixbuf -> Word8 -> Word8 -> Word8 -> Word8 -> IO ()\npixbufFill pb red green blue alpha = {#call unsafe pixbuf_fill#} pb\n ((fromIntegral red) `shiftL` 24 .|.\n (fromIntegral green) `shiftL` 16 .|.\n (fromIntegral blue) `shiftL` 8 .|.\n (fromIntegral alpha))\n\n-- @method pixbufGetFromDrawable@ Take a screenshot of a @ref data Drawable@.\n--\n-- * This function creates a @ref data Pixbuf@ and fills it with the image\n-- currently in the @ref data Drawable@ (which might be invalid if the\n-- window is obscured or minimized). Note that this transfers data from\n-- the server to the client on X Windows.\n--\n-- * This function will return a @ref data Pixbuf@ with no alpha channel\n-- containing the part of the @ref data Drawable@ specified by the\n-- rectangle. The function will return @literal Nothing@ if the window\n-- is not currently visible.\n--\npixbufGetFromDrawable :: DrawableClass d => d -> Rectangle -> IO (Maybe Pixbuf)\npixbufGetFromDrawable d (Rectangle x y width height) = do\n pbPtr <- {#call unsafe pixbuf_get_from_drawable#} \n (mkPixbuf nullForeignPtr) (toDrawable d) (mkColormap nullForeignPtr)\n (fromIntegral x) (fromIntegral y) 0 0\n (fromIntegral width) (fromIntegral height)\n if pbPtr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkPixbuf (return pbPtr)\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Pixbuf@\n--\n-- Author : Vincenzo Ciancia, Axel Simon\n-- Created: 26 March 2002\n--\n-- Version $Revision: 1.5 $ from $Date: 2003\/07\/09 22:42:44 $\n--\n-- Copyright (c) 2002 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Library General Public\n-- License as published by the Free Software Foundation; either\n-- version 2 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Library General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- @ref data Pixbuf@s are bitmap images in memory.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * A Pixbuf is used to represent images. It contains information\n-- about the image's pixel data, its color space, bits per sample, width\n-- and height, and the rowstride or number of bytes between rows.\n--\n-- * This module contains functions to scale and crop\n-- @ref data Pixbuf@s and to scale and crop a @ref data Pixbuf@ and \n-- compose the result with an existing image.\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * if there is a portable way of modifying external arrays in Haskell do:\n--\tgdk_pixbuf_get_pixels, gdk_pixbuf_new_from_data, everything in\n--\tInline data, \n--\n-- * if anybody writes an image manipulation program, do the checker board\n-- functions: gdk_pixbuf_composite_color_simple and\n-- gdk_pixbuf_composite_color. Moreover, do: pixbuf_saturate_and_pixelate\n--\n-- * the animation functions\n--\n-- * pixbuf loader\n--\n-- * module interface\n--\n-- * rendering function for Bitmaps and Pixmaps when the latter are added\n--\nmodule Pixbuf(\n Pixbuf,\n PixbufClass,\n PixbufError(..),\n Colorspace(..),\n pixbufGetColorSpace,\n pixbufGetNChannels,\n pixbufGetHasAlpha,\n pixbufGetBitsPerSample,\n pixbufGetWidth,\n pixbufGetHeight,\n pixbufGetRowstride,\n pixbufGetOption,\n pixbufNewFromFile,\n ImageType,\n pixbufGetFormats,\n pixbufSave,\n pixbufNew,\n pixbufNewFromXPMData,\n InlineImage,\n pixbufNewFromInline,\n pixbufNewSubpixbuf,\n pixbufCopy,\n InterpType(..),\n pixbufScaleSimple,\n pixbufScale,\n pixbufComposite,\n pixbufAddAlpha,\n pixbufCopyArea,\n pixbufFill,\n pixbufGetFromDrawable\n ) where\n\nimport FFI\n{#import Hierarchy#}\nimport GObject\nimport Monad\n\nimport Structs\t\t(GError(..), GQuark, Rectangle(..))\nimport LocalData\t(unsafePerformIO)\nimport Exception\t(bracket)\nimport LocalData\t((.|.), shiftL)\n\n{#context prefix=\"gdk\" #}\n\n-- @data PixbufError@ Error codes for loading image files.\n--\n{#enum PixbufError {underscoreToCase} #}\n\n\n-- @data Colorspace@ Enumerate all supported color spaces.\n--\n-- * Only RGB is supported right now.\n--\n{#enum Colorspace {underscoreToCase} #}\n\n-- @method pixbufGetColorSpace@ Queries the color space of a pixbuf.\n--\npixbufGetColorSpace :: Pixbuf -> IO Colorspace\npixbufGetColorSpace pb = liftM (toEnum . fromIntegral) $\n {#call unsafe pixbuf_get_colorspace#} pb\n\n-- @method pixbufGetNChannels@ Queries the number of colors for each pixel.\n--\npixbufGetNChannels :: Pixbuf -> IO Int\npixbufGetNChannels pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_n_channels#} pb\n\n-- @method pixbufGetHasAlpha@ Query if the image has an alpha channel.\n--\n-- * The alpha channel determines the opaqueness of the pixel.\n--\npixbufGetHasAlpha :: Pixbuf -> IO Bool\npixbufGetHasAlpha pb =\n liftM toBool $ {#call unsafe pixbuf_get_has_alpha#} pb\n\n-- @method pixbufGetBitsPerSample@ Queries the number of bits for each color.\n--\n-- * Each pixel is has a number of cannels for each pixel, each channel\n-- has this many bits.\n--\npixbufGetBitsPerSample :: Pixbuf -> IO Int\npixbufGetBitsPerSample pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_bits_per_sample#} pb\n\n-- @method pixbufGetWidth@ Queries the width of this image.\n--\npixbufGetWidth :: Pixbuf -> IO Int\npixbufGetWidth pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_width#} pb\n\n-- @method pixbufGetHeight@ Queries the height of this image.\n--\npixbufGetHeight :: Pixbuf -> IO Int\npixbufGetHeight pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_height#} pb\n\n-- @method pixbufGetRowstride@ Queries the rowstride of this image.\n--\n-- * Queries the rowstride of a pixbuf, which is the number of bytes between\n-- rows. Use this value to caculate the offset to a certain row.\n--\npixbufGetRowstride :: Pixbuf -> IO Int\npixbufGetRowstride pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_rowstride#} pb\n\n-- @method pixbufGetOption@ Returns an attribut of an image.\n--\n-- * Looks up if some information was stored under the @ref arg key@ when\n-- this image was saved.\n--\npixbufGetOption :: Pixbuf -> String -> IO (Maybe String)\npixbufGetOption pb key = withUTFString key $ \\strPtr -> do\n resPtr <- {#call unsafe pixbuf_get_option#} pb strPtr\n if (resPtr==nullPtr) then return Nothing else\n liftM Just $ peekUTFString resPtr\n\n-- pixbufErrorDomain -- helper function\npixbufErrorDomain :: GQuark\npixbufErrorDomain = unsafePerformIO {#call unsafe pixbuf_error_quark#}\n\n-- @constructor pixbufNewFromFile@ Load an image synchonously.\n--\n-- * Use this function to load only small images as this call will block.\n--\n-- * The function will return @literal Left (err,msg)@ where @ref arg err@\n-- is the error code and @ref arg msg@ is a human readable description\n-- of the error. If an error occurs which is not captured by any of\n-- those in @ref data PixbufError@, an exception is thrown.\n--\npixbufNewFromFile :: FilePath -> IO (Either (PixbufError,String) Pixbuf)\npixbufNewFromFile fname = withUTFString fname $ \\strPtr ->\n alloca $ \\errPtrPtr -> do\n pbPtr <- {#call unsafe pixbuf_new_from_file#} strPtr (castPtr errPtrPtr)\n if pbPtr\/=nullPtr then liftM Right $ makeNewGObject mkPixbuf (return pbPtr)\n else do\n errPtr <- peek errPtrPtr\n (GError dom code msg) <- peek errPtr\n if dom==pixbufErrorDomain then\n return (Left (toEnum (fromIntegral code), msg))\n else\n\terror msg\n\n-- @type ImageType@ A string representing an image file format.\n--\ntype ImageType = String\n\n-- @constant pixbufGetFormats@ A list of valid image file formats.\n--\npixbufGetFormats :: [ImageType]\n\npixbufGetFormats = [\"png\",\"bmp\",\"wbmp\", \"gif\",\"ico\",\"ani\",\"jpeg\",\"pnm\",\n\t\t \"ras\",\"tiff\",\"xpm\",\"xbm\",\"tga\"]\n\n-- @method pixbufSave@ Save an image to disk.\n--\n-- * The function takes a list of key - value pairs to specify\n-- either how an image is saved or to actually save this additional\n-- data with the image. JPEG images can be saved with a \"quality\"\n-- parameter; its value should be in the range [0,100]. Text chunks\n-- can be attached to PNG images by specifying parameters of the form\n-- \"tEXt::key\", where key is an ASCII string of length 1-79.\n-- The values are Unicode strings.\n--\n-- * The function returns @literal Nothing@ if writing was successful.\n-- Otherwise the error code and a description is returned or,\n-- if the error is not captured by one of the error codes in\n-- @ref data PixbufError@, an exception is thrown.\n--\npixbufSave :: Pixbuf -> FilePath -> ImageType -> [(String, String)] ->\n\t IO (Maybe (PixbufError, String))\npixbufSave pb fname iType options =\n let (keys, values) = unzip options in\n let optLen = length keys in\n withUTFString fname $ \\fnPtr ->\n withUTFString iType $ \\tyPtr ->\n allocaArray0 optLen $ \\keysPtr ->\n allocaArray optLen $ \\valuesPtr ->\n alloca $ \\errPtrPtr -> do\n keyPtrs <- mapM newUTFString keys\n valuePtrs <- mapM newUTFString values\n pokeArray keysPtr keyPtrs\n pokeArray valuesPtr valuePtrs\n res <- {#call unsafe pixbuf_savev#} pb fnPtr tyPtr keysPtr valuesPtr\n\t\t\t\t\t(castPtr errPtrPtr)\n mapM_ free keyPtrs\n mapM_ free valuePtrs\n if not (toBool res) then return Nothing else do\n errPtr <- peek errPtrPtr\n (GError dom code msg) <- peek errPtr\n if dom==pixbufErrorDomain then\n return (Just (toEnum (fromIntegral code), msg))\n else\n\terror msg\n\n-- @constructor pixbufNew@ Create a new image in memory.\n--\n-- * Creates a new pixbuf structure and allocates a buffer for\n-- it. Note that the buffer is not cleared initially.\n--\npixbufNew :: Colorspace -> Bool -> Int -> Int -> Int -> IO Pixbuf\npixbufNew colorspace hasAlpha bitsPerSample width height =\n makeNewGObject mkPixbuf $ \n {#call pixbuf_new#} ((fromIntegral . fromEnum) colorspace)\n (fromBool hasAlpha) (fromIntegral bitsPerSample) (fromIntegral width)\n (fromIntegral height)\n\n-- @constructor pixbufNewFromXPMData@ Create a new image from a String.\n--\n-- * Creates a new pixbuf from a string description.\n--\npixbufNewFromXPMData :: [String] -> IO Pixbuf\npixbufNewFromXPMData s =\n bracket (mapM newUTFString s) (mapM free) $ \\strPtrs ->\n withArray0 nullPtr strPtrs $ \\strsPtr ->\n makeNewGObject mkPixbuf $ {#call pixbuf_new_from_xpm_data#} strsPtr\n\n-- @data InlineImage@ A dymmy type for inline picture data.\n--\n-- * This dummy type is used to declare pointers to image data\n-- that is embedded in the executable. See\n-- @ref constructor pixbufNewFromInline@ for an example.\n--\ndata InlineImage = InlineImage\n\n-- @constructor pixbufNewFromInline@ Create a new image from a static pointer.\n--\n-- * Like @ref constructor pixbufNewFromXPMData@, this function allows to\n-- include images in the final binary program. The method used by this\n-- function uses a binary representation and therefore needs less space\n-- in the final executable. Save the image you want to include as\n-- @literal png@ and run @prog\n-- echo #include \"my_image.h\" > my_image.c\n-- gdk-pixbuf-csource --raw --extern --name=my_image myimage.png >> my_image.c\n-- @ on it. Write a header file @literal my_image.h@ containing @prog\n-- #include \n-- extern guint8 my_image[];\n-- @ and save it in the current directory.\n-- The created file can be compiled with @prog\n-- cc -c my_image.c `pkg-config --cflags gdk-2.0`\n-- @ into an object file which must be linked into your Haskell program by\n-- specifying @literal my_image.o@ and @literal \"-#include my_image.h\"@ on\n-- the command line of GHC.\n-- Within you application you delcare a pointer to this image: @prog\n-- foreign label \"my_image\" myImage :: Ptr InlineImage\n-- @ Calling @ref constructor pixbufNewFromInline@ with this pointer will\n-- return the image in the object file. Creating the C file with\n-- the @literal --raw@ flag will result in a non-compressed image in the\n-- object file. The advantage is that the picture will not be\n-- copied when this function is called.\n--\n--\npixbufNewFromInline :: Ptr InlineImage -> IO Pixbuf\npixbufNewFromInline iPtr = alloca $ \\errPtrPtr -> do\n pbPtr <- {#call unsafe pixbuf_new_from_inline#} (-1) (castPtr iPtr)\n (fromBool False) (castPtr errPtrPtr)\n if pbPtr\/=nullPtr then makeNewGObject mkPixbuf (return pbPtr)\n else do\n errPtr <- peek errPtrPtr\n (GError dom code msg) <- peek errPtr\n error msg\n\n-- @method pixbufNewSubpixbuf@ Create a restricted view of an image.\n--\n-- * This function returns a @ref data Pixbuf@ object which shares\n-- the image of the original one but only shows a part of it.\n-- Modifying either buffer will affect the other.\n--\n-- * This function throw an exception if the requested bounds are invalid.\n--\npixbufNewSubpixbuf :: Pixbuf -> Int -> Int -> Int -> Int -> IO Pixbuf\npixbufNewSubpixbuf pb srcX srcY height width =\n makeNewGObject mkPixbuf $ do\n pbPtr <- {#call unsafe pixbuf_new_subpixbuf#} pb\n (fromIntegral srcX) (fromIntegral srcY)\n (fromIntegral height) (fromIntegral width)\n if pbPtr==nullPtr then error \"pixbufNewSubpixbuf: invalid bounds\"\n else return pbPtr\n\n-- @constructor pixbufCopy@ Create a deep copy of an image.\n--\npixbufCopy :: Pixbuf -> IO Pixbuf\npixbufCopy pb = makeNewGObject mkPixbuf $ {#call unsafe pixbuf_copy#} pb\n\n\n-- @data InterpType@ How an image is scaled.\n--\n--\n-- * @variant InterpNearest@ Nearest neighbor sampling; this is the\n-- fastest and lowest quality mode. Quality is normally unacceptable when\n-- scaling down, but may be OK when scaling up.\n--\n-- * @variant InterpTiles@ This is an accurate simulation of the\n-- PostScript image operator without any interpolation enabled. Each\n-- pixel is rendered as a tiny parallelogram of solid color, the edges of\n-- which are implemented with antialiasing. It resembles nearest neighbor\n-- for enlargement, and bilinear for reduction.\n--\n-- * @variant InterpBilinear@ Best quality\/speed balance; use this\n-- mode by default. Bilinear interpolation. For enlargement, it is\n-- equivalent to point-sampling the ideal bilinear-interpolated\n-- image. For reduction, it is equivalent to laying down small tiles and\n-- integrating over the coverage area.\n--\n-- * @variant InterpHyper@ This is the slowest and highest quality\n-- reconstruction function. It is derived from the hyperbolic filters in\n-- Wolberg's \"Digital Image Warping\", and is formally defined as the\n-- hyperbolic-filter sampling the ideal hyperbolic-filter interpolated\n-- image (the filter is designed to be idempotent for 1:1 pixel mapping).\n--\n{#enum InterpType {underscoreToCase} #}\n\n-- @method pixbufScaleSimple@ Scale an image.\n--\n-- * Creates a new @ref data GdkPixbuf@ containing a copy of \n-- @ref arg src@ scaled to the given measures. Leaves @ref arg src@\n-- unaffected. \n--\n-- * @ref arg interp@ affects the quality and speed of the scaling function.\n-- @variant InterpNearest@ is the fastest option but yields very poor\n-- quality when scaling down. @variant InterpBilinear@ is a good\n-- trade-off between speed and quality and should thus be used as a\n-- default.\n--\npixbufScaleSimple :: Pixbuf -> Int -> Int -> InterpType -> IO Pixbuf\npixbufScaleSimple pb width height interp =\n makeNewGObject mkPixbuf $ liftM castPtr $ \n\t{#call pixbuf_scale_simple#} (toPixbuf pb) \n\t(fromIntegral width) (fromIntegral height)\n\t(fromIntegral $ fromEnum interp)\n\n-- @method pixbufScale@ Copy a scaled image part to another image.\n--\n-- * This function is the generic version of @ref method pixbufScaleSimple@.\n-- It scales @ref arg src@ by @ref arg scaleX@ and @ref arg scaleY@ and\n-- translate the image by @ref arg offsetX@ and @ref arg offsetY@. Whatever\n-- is in the intersection with the rectangle @ref arg destX@,\n-- @ref arg destY@, @ref arg destWidth@, @ref arg destHeight@ will be\n-- rendered into @ref arg dest@.\n--\n-- * The rectangle in the destination is simply overwritten. Use\n-- @ref method pixbufComposite@ if you need to blend the source\n-- image onto the destination.\n--\npixbufScale :: Pixbuf -> Pixbuf -> Int -> Int -> Int -> Int ->\n\t Double -> Double -> Double -> Double -> InterpType -> IO ()\npixbufScale src dest destX destY destWidth destHeight offsetX offsetY\n scaleX scaleY interp = {#call unsafe pixbuf_scale#} src dest\n (fromIntegral destX) (fromIntegral destY) (fromIntegral destHeight)\n (fromIntegral destWidth) (realToFrac offsetX) (realToFrac offsetY)\n (realToFrac scaleX) (realToFrac scaleY)\n ((fromIntegral . fromEnum) interp)\n\n-- @method pixbufComposite@ Blend a scaled image part onto another image.\n--\n-- * This function is similar to @ref method pixbufScale@ but allows the\n-- original image to \"shine through\". The @ref arg alpha@ value determines\n-- how opaque the source image is. Passing @literal 0@ is\n-- equivalent to not calling this function at all, passing\n-- @literal 255@ has the\n-- same effect as calling @ref method pixbufScale@.\n--\npixbufComposite :: Pixbuf -> Pixbuf -> Int -> Int -> Int -> Int ->\n\t\t Double -> Double -> Double -> Double -> InterpType ->\n\t \t Word8 -> IO ()\npixbufComposite src dest destX destY destWidth destHeight\n offsetX offsetY scaleX scaleY interp alpha =\n {#call unsafe pixbuf_composite#} src dest\n (fromIntegral destX) (fromIntegral destY) (fromIntegral destHeight)\n (fromIntegral destWidth) (realToFrac offsetX) (realToFrac offsetY)\n (realToFrac scaleX) (realToFrac scaleY)\n ((fromIntegral . fromEnum) interp) (fromIntegral alpha)\n\n-- @method pixbufAddAlpha@ Add an opacity layer to the @ref data Pixbuf@.\n--\n-- * This function returns a copy of the given @ref arg src@\n-- @ref data Pixbuf@, leaving @ref arg src@ unmodified.\n-- The new @ref data Pixbuf@ has an alpha (opacity)\n-- channel which defaults to @literal 255@ (fully opaque pixels)\n-- unless @ref arg src@ already had an alpha channel in which case\n-- the original values are kept.\n-- Passing in a color triple @literal (r,g,b)@ makes all\n-- pixels that have this color fully transparent\n-- (opacity of @literal 0@). The pixel color itself remains unchanged\n-- during this substitution.\n--\npixbufAddAlpha :: Pixbuf -> Maybe (Word8, Word8, Word8) -> IO Pixbuf\npixbufAddAlpha pb Nothing = makeNewGObject mkPixbuf $\n {#call unsafe pixbuf_add_alpha#} pb (fromBool False) 0 0 0\npixbufAddAlpha pb (Just (r,g,b)) = makeNewGObject mkPixbuf $\n {#call unsafe pixbuf_add_alpha#} pb (fromBool True)\n (fromIntegral r) (fromIntegral g) (fromIntegral b)\n\n-- @method pixbufCopyArea@ Copy a rectangular portion into another\n-- @ref data Pixbuf@.\n--\n-- * The source @ref data Pixbuf@ remains unchanged. Converion between\n-- different formats is done automatically.\n--\npixbufCopyArea :: Pixbuf -> Int -> Int -> Int -> Int ->\n\t\t Pixbuf -> Int -> Int -> IO ()\npixbufCopyArea src srcX srcY srcWidth srcHeight dest destX destY =\n {#call unsafe pixbuf_copy_area#} src (fromIntegral srcX)\n (fromIntegral srcY) (fromIntegral srcHeight) (fromIntegral srcWidth)\n dest (fromIntegral destX) (fromIntegral destY)\n\n-- @method pixbufFill@ Fills a @ref data Pixbuf@ with a color.\n--\n-- * The passed-in color is a quadruple consisting of the red, green, blue\n-- and alpha component of the pixel. If the @ref data Pixbuf@ does not\n-- have an alpha channel, the alpha value is ignored.\n--\npixbufFill :: Pixbuf -> Word8 -> Word8 -> Word8 -> Word8 -> IO ()\npixbufFill pb red green blue alpha = {#call unsafe pixbuf_fill#} pb\n ((fromIntegral red) `shiftL` 24 .|.\n (fromIntegral green) `shiftL` 16 .|.\n (fromIntegral blue) `shiftL` 8 .|.\n (fromIntegral alpha))\n\n-- @method pixbufGetFromDrawable@ Take a screenshot of a @ref data Drawable@.\n--\n-- * This function creates a @ref data Pixbuf@ and fills it with the image\n-- currently in the @ref data Drawable@ (which might be invalid if the\n-- window is obscured or minimized). Note that this transfers data from\n-- the server to the client on X Windows.\n--\n-- * This function will return a @ref data Pixbuf@ with no alpha channel\n-- containing the part of the @ref data Drawable@ specified by the\n-- rectangle. The function will return @literal Nothing@ if the window\n-- is not currently visible.\n--\npixbufGetFromDrawable :: DrawableClass d => d -> Rectangle -> IO (Maybe Pixbuf)\npixbufGetFromDrawable d (Rectangle x y width height) = do\n pbPtr <- {#call unsafe pixbuf_get_from_drawable#} \n (mkPixbuf nullForeignPtr) (toDrawable d) (mkColormap nullForeignPtr)\n (fromIntegral x) (fromIntegral y) 0 0\n (fromIntegral width) (fromIntegral height)\n if pbPtr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkPixbuf (return pbPtr)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"56f5d3450cde977471050770e062c7c8ad7b8cb2","subject":"warning police","message":"warning police\n","repos":"mwu-tow\/cuda","old_file":"Foreign\/CUDA\/Driver\/Marshal.chs","new_file":"Foreign\/CUDA\/Driver\/Marshal.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# OPTIONS_HADDOCK prune #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Marshal\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Memory management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Marshal (\n\n -- * Host Allocation\n AllocFlag(..),\n mallocHostArray, freeHost, registerArray, unregisterArray,\n\n -- * Device Allocation\n mallocArray, allocaArray, free,\n\n -- * Unified Memory Allocation\n AttachFlag(..),\n mallocManagedArray,\n\n -- * Marshalling\n peekArray, peekArrayAsync, peekArray2D, peekArray2DAsync, peekListArray,\n pokeArray, pokeArrayAsync, pokeArray2D, pokeArray2DAsync, pokeListArray,\n copyArray, copyArrayAsync, copyArray2D, copyArray2DAsync,\n copyArrayPeer, copyArrayPeerAsync,\n\n -- * Combined Allocation and Marshalling\n newListArray, newListArrayLen,\n withListArray, withListArrayLen,\n\n -- * Utility\n memset, memsetAsync,\n getDevicePtr, getBasePtr, getMemInfo,\n\n -- Internal\n useDeviceHandle, peekDeviceHandle\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Ptr\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Stream ( Stream(..), defaultStream )\nimport Foreign.CUDA.Driver.Context ( Context(..) )\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Data.Int\nimport Data.Maybe\nimport Unsafe.Coerce\nimport Control.Applicative\nimport Control.Exception\nimport Prelude\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.Storable\nimport qualified Foreign.Marshal as F\n\n#c\ntypedef enum CUmemhostalloc_option_enum {\n CU_MEMHOSTALLOC_OPTION_PORTABLE = CU_MEMHOSTALLOC_PORTABLE,\n CU_MEMHOSTALLOC_OPTION_DEVICE_MAPPED = CU_MEMHOSTALLOC_DEVICEMAP,\n CU_MEMHOSTALLOC_OPTION_WRITE_COMBINED = CU_MEMHOSTALLOC_WRITECOMBINED\n} CUmemhostalloc_option;\n#endc\n\n\n--------------------------------------------------------------------------------\n-- Host Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Options for host allocation\n--\n{# enum CUmemhostalloc_option as AllocFlag\n { underscoreToCase }\n with prefix=\"CU_MEMHOSTALLOC_OPTION\" deriving (Eq, Show) #}\n\n-- |\n-- Allocate a section of linear memory on the host which is page-locked and\n-- directly accessible from the device. The storage is sufficient to hold the\n-- given number of elements of a storable type.\n--\n-- Note that since the amount of pageable memory is thusly reduced, overall\n-- system performance may suffer. This is best used sparingly to allocate\n-- staging areas for data exchange.\n--\n{-# INLINEABLE mallocHostArray #-}\nmallocHostArray :: Storable a => [AllocFlag] -> Int -> IO (HostPtr a)\nmallocHostArray !flags = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (HostPtr a')\n doMalloc x !n = resultIfOk =<< cuMemHostAlloc (n * sizeOf x) flags\n\n{-# INLINE cuMemHostAlloc #-}\n{# fun unsafe cuMemHostAlloc\n { alloca'- `HostPtr a' peekHP*\n , `Int'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n peekHP !p = HostPtr . castPtr <$> peek p\n\n\n-- |\n-- Free a section of page-locked host memory\n--\n{-# INLINEABLE freeHost #-}\nfreeHost :: HostPtr a -> IO ()\nfreeHost !p = nothingIfOk =<< cuMemFreeHost p\n\n{-# INLINE cuMemFreeHost #-}\n{# fun unsafe cuMemFreeHost\n { useHP `HostPtr a' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Page-locks the specified array (on the host) and maps it for the device(s) as\n-- specified by the given allocation flags. Subsequently, the memory is accessed\n-- directly by the device so can be read and written with much higher bandwidth\n-- than pageable memory that has not been registered. The memory range is added\n-- to the same tracking mechanism as 'mallocHostArray' to automatically\n-- accelerate calls to functions such as 'pokeArray'.\n--\n-- Note that page-locking excessive amounts of memory may degrade system\n-- performance, since it reduces the amount of pageable memory available. This\n-- is best used sparingly to allocate staging areas for data exchange.\n--\n-- This function is not yet implemented on Mac OS X. Requires cuda-4.0.\n--\n{-# INLINEABLE registerArray #-}\nregisterArray :: Storable a => [AllocFlag] -> Int -> Ptr a -> IO (HostPtr a)\n#if CUDA_VERSION < 4000\nregisterArray _ _ _ = requireSDK 4.0 \"registerArray\"\n#else\nregisterArray !flags !n = go undefined\n where\n go :: Storable b => b -> Ptr b -> IO (HostPtr b)\n go x !p = do\n status <- cuMemHostRegister p (n * sizeOf x) flags\n resultIfOk (status,HostPtr p)\n\n{-# INLINE cuMemHostRegister #-}\n{# fun unsafe cuMemHostRegister\n { castPtr `Ptr a'\n , `Int'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Unmaps the memory from the given pointer, and makes it pageable again.\n--\n-- This function is not yet implemented on Mac OS X. Requires cuda-4.0.\n--\n{-# INLINEABLE unregisterArray #-}\nunregisterArray :: HostPtr a -> IO (Ptr a)\n#if CUDA_VERSION < 4000\nunregisterArray _ = requireSDK 4.0 \"unregisterArray\"\n#else\nunregisterArray (HostPtr !p) = do\n status <- cuMemHostUnregister p\n resultIfOk (status,p)\n\n{-# INLINE cuMemHostUnregister #-}\n{# fun unsafe cuMemHostUnregister\n { castPtr `Ptr a' } -> `Status' cToEnum #}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Device Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a section of linear memory on the device, and return a reference to\n-- it. The memory is sufficient to hold the given number of elements of storable\n-- type. It is suitably aligned for any type, and is not cleared.\n--\n{-# INLINEABLE mallocArray #-}\nmallocArray :: Storable a => Int -> IO (DevicePtr a)\nmallocArray = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')\n doMalloc x !n = resultIfOk =<< cuMemAlloc (n * sizeOf x)\n\n{-# INLINE cuMemAlloc #-}\n{# fun unsafe cuMemAlloc\n { alloca'- `DevicePtr a' peekDeviceHandle*\n , `Int' } -> `Status' cToEnum #}\n where\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n\n\n-- |\n-- Execute a computation on the device, passing a pointer to a temporarily\n-- allocated block of memory sufficient to hold the given number of elements of\n-- storable type. The memory is freed when the computation terminates (normally\n-- or via an exception), so the pointer must not be used after this.\n--\n-- Note that kernel launches can be asynchronous, so you may want to add a\n-- synchronisation point using 'sync' as part of the computation.\n--\n{-# INLINEABLE allocaArray #-}\nallocaArray :: Storable a => Int -> (DevicePtr a -> IO b) -> IO b\nallocaArray !n = bracket (mallocArray n) free\n\n\n-- |\n-- Release a section of device memory\n--\n{-# INLINEABLE free #-}\nfree :: DevicePtr a -> IO ()\nfree !dp = nothingIfOk =<< cuMemFree dp\n\n{-# INLINE cuMemFree #-}\n{# fun unsafe cuMemFree\n { useDeviceHandle `DevicePtr a' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Unified memory allocations\n--------------------------------------------------------------------------------\n\n-- |\n-- Options for unified memory allocations\n--\n#if CUDA_VERSION < 6000\ndata AttachFlag\n#else\n{# enum CUmemAttach_flags as AttachFlag\n { underscoreToCase }\n with prefix=\"CU_MEM_ATTACH_OPTION\" deriving (Eq, Show) #}\n#endif\n\n-- |\n-- Allocates memory that will be automatically managed by the Unified Memory\n-- system\n--\n{-# INLINEABLE mallocManagedArray #-}\nmallocManagedArray :: Storable a => [AttachFlag] -> Int -> IO (DevicePtr a)\n#if CUDA_VERSION < 6000\nmallocManagedArray _ _ = requireSDK 6.0 \"mallocManagedArray\"\n#else\nmallocManagedArray !flags = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')\n doMalloc x !n = resultIfOk =<< cuMemAllocManaged (n * sizeOf x) flags\n\n{-# INLINE cuMemAllocManaged #-}\n{# fun unsafe cuMemAllocManaged\n { alloca'- `DevicePtr a' peekDeviceHandle*\n , `Int'\n , combineBitMasks `[AttachFlag]' } -> `Status' cToEnum #}\n where\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- Device -> Host\n-- --------------\n\n-- |\n-- Copy a number of elements from the device to host memory. This is a\n-- synchronous operation\n--\n{-# INLINEABLE peekArray #-}\npeekArray :: Storable a => Int -> DevicePtr a -> Ptr a -> IO ()\npeekArray !n !dptr !hptr = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ = nothingIfOk =<< cuMemcpyDtoH hptr dptr (n * sizeOf x)\n\n{-# INLINE cuMemcpyDtoH #-}\n{# fun cuMemcpyDtoH\n { castPtr `Ptr a'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy memory from the device asynchronously, possibly associated with a\n-- particular stream. The destination host memory must be page-locked.\n--\n{-# INLINEABLE peekArrayAsync #-}\npeekArrayAsync :: Storable a => Int -> DevicePtr a -> HostPtr a -> Maybe Stream -> IO ()\npeekArrayAsync !n !dptr !hptr !mst = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ = nothingIfOk =<< cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) (fromMaybe defaultStream mst)\n\n{-# INLINE cuMemcpyDtoHAsync #-}\n{# fun cuMemcpyDtoHAsync\n { useHP `HostPtr a'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Copy a 2D array from the device to the host.\n--\n{-# INLINEABLE peekArray2D #-}\npeekArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> Ptr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> IO ()\npeekArray2D !w !h !dptr !dw !dx !dy !hptr !hw !hx !hy = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n in\n nothingIfOk =<< cuMemcpy2DDtoH hptr hw' hx' hy dptr dw' dx' dy w' h\n\n{-# INLINE cuMemcpy2DDtoH #-}\n{# fun cuMemcpy2DDtoH\n { castPtr `Ptr a'\n , `Int'\n , `Int'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n }\n -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D array from the device to the host asynchronously, possibly\n-- associated with a particular execution stream. The destination host memory\n-- must be page-locked.\n--\n{-# INLINEABLE peekArray2DAsync #-}\npeekArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> HostPtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> Maybe Stream -- ^ stream to associate to\n -> IO ()\npeekArray2DAsync !w !h !dptr !dw !dx !dy !hptr !hw !hx !hy !mst = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n st = fromMaybe defaultStream mst\n in\n nothingIfOk =<< cuMemcpy2DDtoHAsync hptr hw' hx' hy dptr dw' dx' dy w' h st\n\n{-# INLINE cuMemcpy2DDtoHAsync #-}\n{# fun cuMemcpy2DDtoHAsync\n { useHP `HostPtr a'\n , `Int'\n , `Int'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , useStream `Stream'\n }\n -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Copy a number of elements from the device into a new Haskell list. Note that\n-- this requires two memory copies: firstly from the device into a heap\n-- allocated array, and from there marshalled into a list.\n--\n{-# INLINEABLE peekListArray #-}\npeekListArray :: Storable a => Int -> DevicePtr a -> IO [a]\npeekListArray !n !dptr =\n F.allocaArray n $ \\p -> do\n peekArray n dptr p\n F.peekArray n p\n\n\n-- Host -> Device\n-- --------------\n\n-- |\n-- Copy a number of elements onto the device. This is a synchronous operation\n--\n{-# INLINEABLE pokeArray #-}\npokeArray :: Storable a => Int -> Ptr a -> DevicePtr a -> IO ()\npokeArray !n !hptr !dptr = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPoke x _ = nothingIfOk =<< cuMemcpyHtoD dptr hptr (n * sizeOf x)\n\n{-# INLINE cuMemcpyHtoD #-}\n{# fun cuMemcpyHtoD\n { useDeviceHandle `DevicePtr a'\n , castPtr `Ptr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy memory onto the device asynchronously, possibly associated with a\n-- particular stream. The source host memory must be page-locked.\n--\n{-# INLINEABLE pokeArrayAsync #-}\npokeArrayAsync :: Storable a => Int -> HostPtr a -> DevicePtr a -> Maybe Stream -> IO ()\npokeArrayAsync !n !hptr !dptr !mst = dopoke undefined dptr\n where\n dopoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n dopoke x _ = nothingIfOk =<< cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) (fromMaybe defaultStream mst)\n\n{-# INLINE cuMemcpyHtoDAsync #-}\n{# fun cuMemcpyHtoDAsync\n { useDeviceHandle `DevicePtr a'\n , useHP `HostPtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Copy a 2D array from the host to the device.\n--\n{-# INLINEABLE pokeArray2D #-}\npokeArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> Ptr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> IO ()\npokeArray2D !w !h !hptr !hw !hx !hy !dptr !dw !dx !dy = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPoke x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n in\n nothingIfOk =<< cuMemcpy2DHtoD dptr dw' dx' dy hptr hw' hx' hy w' h\n\n{-# INLINE cuMemcpy2DHtoD #-}\n{# fun cuMemcpy2DHtoD\n { useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , castPtr `Ptr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n }\n -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D array from the host to the device asynchronously, possibly\n-- associated with a particular execution stream. The source host memory must be\n-- page-locked.\n--\n{-# INLINEABLE pokeArray2DAsync #-}\npokeArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> HostPtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> Maybe Stream -- ^ stream to associate to\n -> IO ()\npokeArray2DAsync !w !h !hptr !hw !hx !hy !dptr !dw !dx !dy !mst = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPoke x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n st = fromMaybe defaultStream mst\n in\n nothingIfOk =<< cuMemcpy2DHtoDAsync dptr dw' dx' dy hptr hw' hx' hy w' h st\n\n{-# INLINE cuMemcpy2DHtoDAsync #-}\n{# fun cuMemcpy2DHtoDAsync\n { useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , useHP `HostPtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , useStream `Stream'\n }\n -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Write a list of storable elements into a device array. The device array must\n-- be sufficiently large to hold the entire list. This requires two marshalling\n-- operations.\n--\n{-# INLINEABLE pokeListArray #-}\npokeListArray :: Storable a => [a] -> DevicePtr a -> IO ()\npokeListArray !xs !dptr = F.withArrayLen xs $ \\ !len !p -> pokeArray len p dptr\n\n\n-- Device -> Device\n-- ----------------\n\n-- |\n-- Copy the given number of elements from the first device array (source) to the\n-- second device (destination). The copied areas may not overlap. This operation\n-- is asynchronous with respect to the host, but will never overlap with kernel\n-- execution.\n--\n{-# INLINEABLE copyArray #-}\ncopyArray :: Storable a => Int -> DevicePtr a -> DevicePtr a -> IO ()\ncopyArray !n = docopy undefined\n where\n docopy :: Storable a' => a' -> DevicePtr a' -> DevicePtr a' -> IO ()\n docopy x src dst = nothingIfOk =<< cuMemcpyDtoD dst src (n * sizeOf x)\n\n{-# INLINE cuMemcpyDtoD #-}\n{# fun unsafe cuMemcpyDtoD\n { useDeviceHandle `DevicePtr a'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy the given number of elements from the first device array (source) to the\n-- second device array (destination). The copied areas may not overlap. The\n-- operation is asynchronous with respect to the host, and can be asynchronous\n-- to other device operations by associating it with a particular stream.\n--\n{-# INLINEABLE copyArrayAsync #-}\ncopyArrayAsync :: Storable a => Int -> DevicePtr a -> DevicePtr a -> Maybe Stream -> IO ()\ncopyArrayAsync !n !src !dst !mst = docopy undefined src\n where\n docopy :: Storable a' => a' -> DevicePtr a' -> IO ()\n docopy x _ = nothingIfOk =<< cuMemcpyDtoDAsync dst src (n * sizeOf x) (fromMaybe defaultStream mst)\n\n{-# INLINE cuMemcpyDtoDAsync #-}\n{# fun unsafe cuMemcpyDtoDAsync\n { useDeviceHandle `DevicePtr a'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D array from the first device array (source) to the second device\n-- array (destination). The copied areas must not overlap. This operation is\n-- asynchronous with respect to the host, but will never overlap with kernel\n-- execution.\n--\n{-# INLINEABLE copyArray2D #-}\ncopyArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> IO ()\ncopyArray2D !w !h !src !hw !hx !hy !dst !dw !dx !dy = doCopy undefined dst\n where\n doCopy :: Storable a' => a' -> DevicePtr a' -> IO ()\n doCopy x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n in\n nothingIfOk =<< cuMemcpy2DDtoD dst dw' dx' dy src hw' hx' hy w' h\n\n{-# INLINE cuMemcpy2DDtoD #-}\n{# fun unsafe cuMemcpy2DDtoD\n { useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n }\n -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D array from the first device array (source) to the second device\n-- array (destination). The copied areas may not overlap. The operation is\n-- asynchronous with respect to the host, and can be asynchronous to other\n-- device operations by associating it with a particular execution stream.\n--\n{-# INLINEABLE copyArray2DAsync #-}\ncopyArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> Maybe Stream -- ^ stream to associate to\n -> IO ()\ncopyArray2DAsync !w !h !src !hw !hx !hy !dst !dw !dx !dy !mst = doCopy undefined dst\n where\n doCopy :: Storable a' => a' -> DevicePtr a' -> IO ()\n doCopy x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n st = fromMaybe defaultStream mst\n in\n nothingIfOk =<< cuMemcpy2DDtoDAsync dst dw' dx' dy src hw' hx' hy w' h st\n\n{-# INLINE cuMemcpy2DDtoDAsync #-}\n{# fun unsafe cuMemcpy2DDtoDAsync\n { useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , useStream `Stream'\n }\n -> `Status' cToEnum #}\n\n\n\n-- Context -> Context\n-- ------------------\n\n-- |\n-- Copies an array from device memory in one context to device memory in another\n-- context. Note that this function is asynchronous with respect to the host,\n-- but serialised with respect to all pending and future asynchronous work in\n-- the source and destination contexts. To avoid this synchronisation, use\n-- 'copyArrayPeerAsync' instead.\n--\n{-# INLINEABLE copyArrayPeer #-}\ncopyArrayPeer :: Storable a\n => Int -- ^ number of array elements\n -> DevicePtr a -> Context -- ^ source array and context\n -> DevicePtr a -> Context -- ^ destination array and context\n -> IO ()\n#if CUDA_VERSION < 4000\ncopyArrayPeer _ _ _ _ _ = requireSDK 4.0 \"copyArrayPeer\"\n#else\ncopyArrayPeer !n !src !srcCtx !dst !dstCtx = go undefined src dst\n where\n go :: Storable b => b -> DevicePtr b -> DevicePtr b -> IO ()\n go x _ _ = nothingIfOk =<< cuMemcpyPeer dst dstCtx src srcCtx (n * sizeOf x)\n\n{-# INLINE cuMemcpyPeer #-}\n{# fun unsafe cuMemcpyPeer\n { useDeviceHandle `DevicePtr a'\n , useContext `Context'\n , useDeviceHandle `DevicePtr a'\n , useContext `Context'\n , `Int' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Copies from device memory in one context to device memory in another context.\n-- Note that this function is asynchronous with respect to the host and all work\n-- in other streams and devices.\n--\n{-# INLINEABLE copyArrayPeerAsync #-}\ncopyArrayPeerAsync :: Storable a\n => Int -- ^ number of array elements\n -> DevicePtr a -> Context -- ^ source array and context\n -> DevicePtr a -> Context -- ^ destination array and device context\n -> Maybe Stream -- ^ stream to associate with\n -> IO ()\n#if CUDA_VERSION < 4000\ncopyArrayPeerAsync _ _ _ _ _ _ = requireSDK 4.0 \"copyArrayPeerAsync\"\n#else\ncopyArrayPeerAsync !n !src !srcCtx !dst !dstCtx !st = go undefined src dst\n where\n go :: Storable b => b -> DevicePtr b -> DevicePtr b -> IO ()\n go x _ _ = nothingIfOk =<< cuMemcpyPeerAsync dst dstCtx src srcCtx (n * sizeOf x) stream\n stream = fromMaybe defaultStream st\n\n{-# INLINE cuMemcpyPeerAsync #-}\n{# fun unsafe cuMemcpyPeerAsync\n { useDeviceHandle `DevicePtr a'\n , useContext `Context'\n , useDeviceHandle `DevicePtr a'\n , useContext `Context'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Combined Allocation and Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Write a list of storable elements into a newly allocated device array,\n-- returning the device pointer together with the number of elements that were\n-- written. Note that this requires two memory copies: firstly from a Haskell\n-- list to a heap allocated array, and from there onto the graphics device. The\n-- memory should be 'free'd when no longer required.\n--\n{-# INLINEABLE newListArrayLen #-}\nnewListArrayLen :: Storable a => [a] -> IO (DevicePtr a, Int)\nnewListArrayLen xs =\n F.withArrayLen xs $ \\len p ->\n bracketOnError (mallocArray len) free $ \\d_xs -> do\n pokeArray len p d_xs\n return (d_xs, len)\n\n\n-- |\n-- Write a list of storable elements into a newly allocated device array. This\n-- is 'newListArrayLen' composed with 'fst'.\n--\n{-# INLINEABLE newListArray #-}\nnewListArray :: Storable a => [a] -> IO (DevicePtr a)\nnewListArray xs = fst `fmap` newListArrayLen xs\n\n\n-- |\n-- Temporarily store a list of elements into a newly allocated device array. An\n-- IO action is applied to to the array, the result of which is returned.\n-- Similar to 'newListArray', this requires copying the data twice.\n--\n-- As with 'allocaArray', the memory is freed once the action completes, so you\n-- should not return the pointer from the action, and be wary of asynchronous\n-- kernel execution.\n--\n{-# INLINEABLE withListArray #-}\nwithListArray :: Storable a => [a] -> (DevicePtr a -> IO b) -> IO b\nwithListArray xs = withListArrayLen xs . const\n\n\n-- |\n-- A variant of 'withListArray' which also supplies the number of elements in\n-- the array to the applied function\n--\n{-# INLINEABLE withListArrayLen #-}\nwithListArrayLen :: Storable a => [a] -> (Int -> DevicePtr a -> IO b) -> IO b\nwithListArrayLen xs f =\n bracket (newListArrayLen xs) (free . fst) (uncurry . flip $ f)\n--\n-- XXX: Will this attempt to double-free the device array on error (together\n-- with newListArrayLen)?\n--\n\n\n--------------------------------------------------------------------------------\n-- Utility\n--------------------------------------------------------------------------------\n\n-- |\n-- Set a number of data elements to the specified value, which may be either 8-,\n-- 16-, or 32-bits wide.\n--\n{-# INLINEABLE memset #-}\nmemset :: Storable a => DevicePtr a -> Int -> a -> IO ()\nmemset !dptr !n !val = case sizeOf val of\n 1 -> nothingIfOk =<< cuMemsetD8 dptr val n\n 2 -> nothingIfOk =<< cuMemsetD16 dptr val n\n 4 -> nothingIfOk =<< cuMemsetD32 dptr val n\n _ -> cudaError \"can only memset 8-, 16-, and 32-bit values\"\n\n--\n-- We use unsafe coerce below to reinterpret the bits of the value to memset as,\n-- into the integer type required by the setting functions.\n--\n{-# INLINE cuMemsetD8 #-}\n{# fun unsafe cuMemsetD8\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{-# INLINE cuMemsetD16 #-}\n{# fun unsafe cuMemsetD16\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{-# INLINE cuMemsetD32 #-}\n{# fun unsafe cuMemsetD32\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set the number of data elements to the specified value, which may be either\n-- 8-, 16-, or 32-bits wide. The operation is asynchronous and may optionally be\n-- associated with a stream. Requires cuda-3.2.\n--\n{-# INLINEABLE memsetAsync #-}\nmemsetAsync :: Storable a => DevicePtr a -> Int -> a -> Maybe Stream -> IO ()\n#if CUDA_VERSION < 3020\nmemsetAsync _ _ _ _ = requireSDK 3.2 \"memsetAsync\"\n#else\nmemsetAsync !dptr !n !val !mst = case sizeOf val of\n 1 -> nothingIfOk =<< cuMemsetD8Async dptr val n stream\n 2 -> nothingIfOk =<< cuMemsetD16Async dptr val n stream\n 4 -> nothingIfOk =<< cuMemsetD32Async dptr val n stream\n _ -> cudaError \"can only memset 8-, 16-, and 32-bit values\"\n where\n stream = fromMaybe defaultStream mst\n\n{-# INLINE cuMemsetD8Async #-}\n{# fun unsafe cuMemsetD8Async\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n{-# INLINE cuMemsetD16Async #-}\n{# fun unsafe cuMemsetD16Async\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n{-# INLINE cuMemsetD32Async #-}\n{# fun unsafe cuMemsetD32Async\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Return the device pointer associated with a mapped, pinned host buffer, which\n-- was allocated with the 'DeviceMapped' option by 'mallocHostArray'.\n--\n-- Currently, no options are supported and this must be empty.\n--\n{-# INLINEABLE getDevicePtr #-}\ngetDevicePtr :: [AllocFlag] -> HostPtr a -> IO (DevicePtr a)\ngetDevicePtr !flags !hp = resultIfOk =<< cuMemHostGetDevicePointer hp flags\n\n{-# INLINE cuMemHostGetDevicePointer #-}\n{# fun unsafe cuMemHostGetDevicePointer\n { alloca'- `DevicePtr a' peekDeviceHandle*\n , useHP `HostPtr a'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n useHP = castPtr . useHostPtr\n\n-- |\n-- Return the base address and allocation size of the given device pointer\n--\n{-# INLINEABLE getBasePtr #-}\ngetBasePtr :: DevicePtr a -> IO (DevicePtr a, Int64)\ngetBasePtr !dptr = do\n (status,base,size) <- cuMemGetAddressRange dptr\n resultIfOk (status, (base,size))\n\n{-# INLINE cuMemGetAddressRange #-}\n{# fun unsafe cuMemGetAddressRange\n { alloca'- `DevicePtr a' peekDeviceHandle*\n , alloca'- `Int64' peekIntConv*\n , useDeviceHandle `DevicePtr a' } -> `Status' cToEnum #}\n where\n alloca' :: Storable a => (Ptr a -> IO b) -> IO b\n alloca' = F.alloca\n\n-- |\n-- Return the amount of free and total memory respectively available to the\n-- current context (bytes)\n--\n{-# INLINEABLE getMemInfo #-}\ngetMemInfo :: IO (Int64, Int64)\ngetMemInfo = do\n (!status,!f,!t) <- cuMemGetInfo\n resultIfOk (status,(f,t))\n\n{-# INLINE cuMemGetInfo #-}\n{# fun unsafe cuMemGetInfo\n { alloca'- `Int64' peekIntConv*\n , alloca'- `Int64' peekIntConv* } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\ntype DeviceHandle = {# type CUdeviceptr #}\n\n-- Lift an opaque handle to a typed DevicePtr representation. This occasions\n-- arcane distinctions for the different driver versions and Tesla (compute 1.x)\n-- and Fermi (compute 2.x) class architectures on 32- and 64-bit hosts.\n--\n{-# INLINE peekDeviceHandle #-}\npeekDeviceHandle :: Ptr DeviceHandle -> IO (DevicePtr a)\npeekDeviceHandle !p = DevicePtr . intPtrToPtr . fromIntegral <$> peek p\n\n-- Use a device pointer as an opaque handle type\n--\n{-# INLINE useDeviceHandle #-}\nuseDeviceHandle :: DevicePtr a -> DeviceHandle\nuseDeviceHandle = fromIntegral . ptrToIntPtr . useDevicePtr\n\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE CPP #-}\n{-# LANGUAGE EmptyDataDecls #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# OPTIONS_HADDOCK prune #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Marshal\n-- Copyright : [2009..2014] Trevor L. McDonell\n-- License : BSD\n--\n-- Memory management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Marshal (\n\n -- * Host Allocation\n AllocFlag(..),\n mallocHostArray, freeHost, registerArray, unregisterArray,\n\n -- * Device Allocation\n mallocArray, allocaArray, free,\n\n -- * Unified Memory Allocation\n AttachFlag(..),\n mallocManagedArray,\n\n -- * Marshalling\n peekArray, peekArrayAsync, peekArray2D, peekArray2DAsync, peekListArray,\n pokeArray, pokeArrayAsync, pokeArray2D, pokeArray2DAsync, pokeListArray,\n copyArray, copyArrayAsync, copyArray2D, copyArray2DAsync,\n copyArrayPeer, copyArrayPeerAsync,\n\n -- * Combined Allocation and Marshalling\n newListArray, newListArrayLen,\n withListArray, withListArrayLen,\n\n -- * Utility\n memset, memsetAsync,\n getDevicePtr, getBasePtr, getMemInfo,\n\n -- Internal\n useDeviceHandle, peekDeviceHandle\n\n) where\n\n#include \"cbits\/stubs.h\"\n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Ptr\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Stream ( Stream(..), defaultStream )\nimport Foreign.CUDA.Driver.Context ( Context(..) )\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Data.Int\nimport Data.Maybe\nimport Unsafe.Coerce\nimport Control.Applicative\nimport Control.Exception\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.Storable\nimport qualified Foreign.Marshal as F\n\n#c\ntypedef enum CUmemhostalloc_option_enum {\n CU_MEMHOSTALLOC_OPTION_PORTABLE = CU_MEMHOSTALLOC_PORTABLE,\n CU_MEMHOSTALLOC_OPTION_DEVICE_MAPPED = CU_MEMHOSTALLOC_DEVICEMAP,\n CU_MEMHOSTALLOC_OPTION_WRITE_COMBINED = CU_MEMHOSTALLOC_WRITECOMBINED\n} CUmemhostalloc_option;\n#endc\n\n\n--------------------------------------------------------------------------------\n-- Host Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Options for host allocation\n--\n{# enum CUmemhostalloc_option as AllocFlag\n { underscoreToCase }\n with prefix=\"CU_MEMHOSTALLOC_OPTION\" deriving (Eq, Show) #}\n\n-- |\n-- Allocate a section of linear memory on the host which is page-locked and\n-- directly accessible from the device. The storage is sufficient to hold the\n-- given number of elements of a storable type.\n--\n-- Note that since the amount of pageable memory is thusly reduced, overall\n-- system performance may suffer. This is best used sparingly to allocate\n-- staging areas for data exchange.\n--\n{-# INLINEABLE mallocHostArray #-}\nmallocHostArray :: Storable a => [AllocFlag] -> Int -> IO (HostPtr a)\nmallocHostArray !flags = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (HostPtr a')\n doMalloc x !n = resultIfOk =<< cuMemHostAlloc (n * sizeOf x) flags\n\n{-# INLINE cuMemHostAlloc #-}\n{# fun unsafe cuMemHostAlloc\n { alloca'- `HostPtr a' peekHP*\n , `Int'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n peekHP !p = HostPtr . castPtr <$> peek p\n\n\n-- |\n-- Free a section of page-locked host memory\n--\n{-# INLINEABLE freeHost #-}\nfreeHost :: HostPtr a -> IO ()\nfreeHost !p = nothingIfOk =<< cuMemFreeHost p\n\n{-# INLINE cuMemFreeHost #-}\n{# fun unsafe cuMemFreeHost\n { useHP `HostPtr a' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Page-locks the specified array (on the host) and maps it for the device(s) as\n-- specified by the given allocation flags. Subsequently, the memory is accessed\n-- directly by the device so can be read and written with much higher bandwidth\n-- than pageable memory that has not been registered. The memory range is added\n-- to the same tracking mechanism as 'mallocHostArray' to automatically\n-- accelerate calls to functions such as 'pokeArray'.\n--\n-- Note that page-locking excessive amounts of memory may degrade system\n-- performance, since it reduces the amount of pageable memory available. This\n-- is best used sparingly to allocate staging areas for data exchange.\n--\n-- This function is not yet implemented on Mac OS X. Requires cuda-4.0.\n--\n{-# INLINEABLE registerArray #-}\nregisterArray :: Storable a => [AllocFlag] -> Int -> Ptr a -> IO (HostPtr a)\n#if CUDA_VERSION < 4000\nregisterArray _ _ _ = requireSDK 4.0 \"registerArray\"\n#else\nregisterArray !flags !n = go undefined\n where\n go :: Storable b => b -> Ptr b -> IO (HostPtr b)\n go x !p = do\n status <- cuMemHostRegister p (n * sizeOf x) flags\n resultIfOk (status,HostPtr p)\n\n{-# INLINE cuMemHostRegister #-}\n{# fun unsafe cuMemHostRegister\n { castPtr `Ptr a'\n , `Int'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Unmaps the memory from the given pointer, and makes it pageable again.\n--\n-- This function is not yet implemented on Mac OS X. Requires cuda-4.0.\n--\n{-# INLINEABLE unregisterArray #-}\nunregisterArray :: HostPtr a -> IO (Ptr a)\n#if CUDA_VERSION < 4000\nunregisterArray _ = requireSDK 4.0 \"unregisterArray\"\n#else\nunregisterArray (HostPtr !p) = do\n status <- cuMemHostUnregister p\n resultIfOk (status,p)\n\n{-# INLINE cuMemHostUnregister #-}\n{# fun unsafe cuMemHostUnregister\n { castPtr `Ptr a' } -> `Status' cToEnum #}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Device Allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a section of linear memory on the device, and return a reference to\n-- it. The memory is sufficient to hold the given number of elements of storable\n-- type. It is suitably aligned for any type, and is not cleared.\n--\n{-# INLINEABLE mallocArray #-}\nmallocArray :: Storable a => Int -> IO (DevicePtr a)\nmallocArray = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')\n doMalloc x !n = resultIfOk =<< cuMemAlloc (n * sizeOf x)\n\n{-# INLINE cuMemAlloc #-}\n{# fun unsafe cuMemAlloc\n { alloca'- `DevicePtr a' peekDeviceHandle*\n , `Int' } -> `Status' cToEnum #}\n where\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n\n\n-- |\n-- Execute a computation on the device, passing a pointer to a temporarily\n-- allocated block of memory sufficient to hold the given number of elements of\n-- storable type. The memory is freed when the computation terminates (normally\n-- or via an exception), so the pointer must not be used after this.\n--\n-- Note that kernel launches can be asynchronous, so you may want to add a\n-- synchronisation point using 'sync' as part of the computation.\n--\n{-# INLINEABLE allocaArray #-}\nallocaArray :: Storable a => Int -> (DevicePtr a -> IO b) -> IO b\nallocaArray !n = bracket (mallocArray n) free\n\n\n-- |\n-- Release a section of device memory\n--\n{-# INLINEABLE free #-}\nfree :: DevicePtr a -> IO ()\nfree !dp = nothingIfOk =<< cuMemFree dp\n\n{-# INLINE cuMemFree #-}\n{# fun unsafe cuMemFree\n { useDeviceHandle `DevicePtr a' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Unified memory allocations\n--------------------------------------------------------------------------------\n\n-- |\n-- Options for unified memory allocations\n--\n#if CUDA_VERSION < 6000\ndata AttachFlag\n#else\n{# enum CUmemAttach_flags as AttachFlag\n { underscoreToCase }\n with prefix=\"CU_MEM_ATTACH_OPTION\" deriving (Eq, Show) #}\n#endif\n\n-- |\n-- Allocates memory that will be automatically managed by the Unified Memory\n-- system\n--\n{-# INLINEABLE mallocManagedArray #-}\nmallocManagedArray :: Storable a => [AttachFlag] -> Int -> IO (DevicePtr a)\n#if CUDA_VERSION < 6000\nmallocManagedArray _ _ = requireSDK 6.0 \"mallocManagedArray\"\n#else\nmallocManagedArray !flags = doMalloc undefined\n where\n doMalloc :: Storable a' => a' -> Int -> IO (DevicePtr a')\n doMalloc x !n = resultIfOk =<< cuMemAllocManaged (n * sizeOf x) flags\n\n{-# INLINE cuMemAllocManaged #-}\n{# fun unsafe cuMemAllocManaged\n { alloca'- `DevicePtr a' peekDeviceHandle*\n , `Int'\n , combineBitMasks `[AttachFlag]' } -> `Status' cToEnum #}\n where\n alloca' !f = F.alloca $ \\ !p -> poke p nullPtr >> f (castPtr p)\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- Device -> Host\n-- --------------\n\n-- |\n-- Copy a number of elements from the device to host memory. This is a\n-- synchronous operation\n--\n{-# INLINEABLE peekArray #-}\npeekArray :: Storable a => Int -> DevicePtr a -> Ptr a -> IO ()\npeekArray !n !dptr !hptr = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ = nothingIfOk =<< cuMemcpyDtoH hptr dptr (n * sizeOf x)\n\n{-# INLINE cuMemcpyDtoH #-}\n{# fun cuMemcpyDtoH\n { castPtr `Ptr a'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy memory from the device asynchronously, possibly associated with a\n-- particular stream. The destination host memory must be page-locked.\n--\n{-# INLINEABLE peekArrayAsync #-}\npeekArrayAsync :: Storable a => Int -> DevicePtr a -> HostPtr a -> Maybe Stream -> IO ()\npeekArrayAsync !n !dptr !hptr !mst = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ = nothingIfOk =<< cuMemcpyDtoHAsync hptr dptr (n * sizeOf x) (fromMaybe defaultStream mst)\n\n{-# INLINE cuMemcpyDtoHAsync #-}\n{# fun cuMemcpyDtoHAsync\n { useHP `HostPtr a'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Copy a 2D array from the device to the host.\n--\n{-# INLINEABLE peekArray2D #-}\npeekArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> Ptr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> IO ()\npeekArray2D !w !h !dptr !dw !dx !dy !hptr !hw !hx !hy = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n in\n nothingIfOk =<< cuMemcpy2DDtoH hptr hw' hx' hy dptr dw' dx' dy w' h\n\n{-# INLINE cuMemcpy2DDtoH #-}\n{# fun cuMemcpy2DDtoH\n { castPtr `Ptr a'\n , `Int'\n , `Int'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n }\n -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D array from the device to the host asynchronously, possibly\n-- associated with a particular execution stream. The destination host memory\n-- must be page-locked.\n--\n{-# INLINEABLE peekArray2DAsync #-}\npeekArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> HostPtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> Maybe Stream -- ^ stream to associate to\n -> IO ()\npeekArray2DAsync !w !h !dptr !dw !dx !dy !hptr !hw !hx !hy !mst = doPeek undefined dptr\n where\n doPeek :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPeek x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n st = fromMaybe defaultStream mst\n in\n nothingIfOk =<< cuMemcpy2DDtoHAsync hptr hw' hx' hy dptr dw' dx' dy w' h st\n\n{-# INLINE cuMemcpy2DDtoHAsync #-}\n{# fun cuMemcpy2DDtoHAsync\n { useHP `HostPtr a'\n , `Int'\n , `Int'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , useStream `Stream'\n }\n -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Copy a number of elements from the device into a new Haskell list. Note that\n-- this requires two memory copies: firstly from the device into a heap\n-- allocated array, and from there marshalled into a list.\n--\n{-# INLINEABLE peekListArray #-}\npeekListArray :: Storable a => Int -> DevicePtr a -> IO [a]\npeekListArray !n !dptr =\n F.allocaArray n $ \\p -> do\n peekArray n dptr p\n F.peekArray n p\n\n\n-- Host -> Device\n-- --------------\n\n-- |\n-- Copy a number of elements onto the device. This is a synchronous operation\n--\n{-# INLINEABLE pokeArray #-}\npokeArray :: Storable a => Int -> Ptr a -> DevicePtr a -> IO ()\npokeArray !n !hptr !dptr = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPoke x _ = nothingIfOk =<< cuMemcpyHtoD dptr hptr (n * sizeOf x)\n\n{-# INLINE cuMemcpyHtoD #-}\n{# fun cuMemcpyHtoD\n { useDeviceHandle `DevicePtr a'\n , castPtr `Ptr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy memory onto the device asynchronously, possibly associated with a\n-- particular stream. The source host memory must be page-locked.\n--\n{-# INLINEABLE pokeArrayAsync #-}\npokeArrayAsync :: Storable a => Int -> HostPtr a -> DevicePtr a -> Maybe Stream -> IO ()\npokeArrayAsync !n !hptr !dptr !mst = dopoke undefined dptr\n where\n dopoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n dopoke x _ = nothingIfOk =<< cuMemcpyHtoDAsync dptr hptr (n * sizeOf x) (fromMaybe defaultStream mst)\n\n{-# INLINE cuMemcpyHtoDAsync #-}\n{# fun cuMemcpyHtoDAsync\n { useDeviceHandle `DevicePtr a'\n , useHP `HostPtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Copy a 2D array from the host to the device.\n--\n{-# INLINEABLE pokeArray2D #-}\npokeArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> Ptr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> IO ()\npokeArray2D !w !h !hptr !hw !hx !hy !dptr !dw !dx !dy = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPoke x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n in\n nothingIfOk =<< cuMemcpy2DHtoD dptr dw' dx' dy hptr hw' hx' hy w' h\n\n{-# INLINE cuMemcpy2DHtoD #-}\n{# fun cuMemcpy2DHtoD\n { useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , castPtr `Ptr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n }\n -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D array from the host to the device asynchronously, possibly\n-- associated with a particular execution stream. The source host memory must be\n-- page-locked.\n--\n{-# INLINEABLE pokeArray2DAsync #-}\npokeArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> HostPtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> Maybe Stream -- ^ stream to associate to\n -> IO ()\npokeArray2DAsync !w !h !hptr !hw !hx !hy !dptr !dw !dx !dy !mst = doPoke undefined dptr\n where\n doPoke :: Storable a' => a' -> DevicePtr a' -> IO ()\n doPoke x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n st = fromMaybe defaultStream mst\n in\n nothingIfOk =<< cuMemcpy2DHtoDAsync dptr dw' dx' dy hptr hw' hx' hy w' h st\n\n{-# INLINE cuMemcpy2DHtoDAsync #-}\n{# fun cuMemcpy2DHtoDAsync\n { useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , useHP `HostPtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , useStream `Stream'\n }\n -> `Status' cToEnum #}\n where\n useHP = castPtr . useHostPtr\n\n\n-- |\n-- Write a list of storable elements into a device array. The device array must\n-- be sufficiently large to hold the entire list. This requires two marshalling\n-- operations.\n--\n{-# INLINEABLE pokeListArray #-}\npokeListArray :: Storable a => [a] -> DevicePtr a -> IO ()\npokeListArray !xs !dptr = F.withArrayLen xs $ \\ !len !p -> pokeArray len p dptr\n\n\n-- Device -> Device\n-- ----------------\n\n-- |\n-- Copy the given number of elements from the first device array (source) to the\n-- second device (destination). The copied areas may not overlap. This operation\n-- is asynchronous with respect to the host, but will never overlap with kernel\n-- execution.\n--\n{-# INLINEABLE copyArray #-}\ncopyArray :: Storable a => Int -> DevicePtr a -> DevicePtr a -> IO ()\ncopyArray !n = docopy undefined\n where\n docopy :: Storable a' => a' -> DevicePtr a' -> DevicePtr a' -> IO ()\n docopy x src dst = nothingIfOk =<< cuMemcpyDtoD dst src (n * sizeOf x)\n\n{-# INLINE cuMemcpyDtoD #-}\n{# fun unsafe cuMemcpyDtoD\n { useDeviceHandle `DevicePtr a'\n , useDeviceHandle `DevicePtr a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy the given number of elements from the first device array (source) to the\n-- second device array (destination). The copied areas may not overlap. The\n-- operation is asynchronous with respect to the host, and can be asynchronous\n-- to other device operations by associating it with a particular stream.\n--\n{-# INLINEABLE copyArrayAsync #-}\ncopyArrayAsync :: Storable a => Int -> DevicePtr a -> DevicePtr a -> Maybe Stream -> IO ()\ncopyArrayAsync !n !src !dst !mst = docopy undefined src\n where\n docopy :: Storable a' => a' -> DevicePtr a' -> IO ()\n docopy x _ = nothingIfOk =<< cuMemcpyDtoDAsync dst src (n * sizeOf x) (fromMaybe defaultStream mst)\n\n{-# INLINE cuMemcpyDtoDAsync #-}\n{# fun unsafe cuMemcpyDtoDAsync\n { useDeviceHandle `DevicePtr a'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D array from the first device array (source) to the second device\n-- array (destination). The copied areas must not overlap. This operation is\n-- asynchronous with respect to the host, but will never overlap with kernel\n-- execution.\n--\n{-# INLINEABLE copyArray2D #-}\ncopyArray2D\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> IO ()\ncopyArray2D !w !h !src !hw !hx !hy !dst !dw !dx !dy = doCopy undefined dst\n where\n doCopy :: Storable a' => a' -> DevicePtr a' -> IO ()\n doCopy x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n in\n nothingIfOk =<< cuMemcpy2DDtoD dst dw' dx' dy src hw' hx' hy w' h\n\n{-# INLINE cuMemcpy2DDtoD #-}\n{# fun unsafe cuMemcpy2DDtoD\n { useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n }\n -> `Status' cToEnum #}\n\n\n-- |\n-- Copy a 2D array from the first device array (source) to the second device\n-- array (destination). The copied areas may not overlap. The operation is\n-- asynchronous with respect to the host, and can be asynchronous to other\n-- device operations by associating it with a particular execution stream.\n--\n{-# INLINEABLE copyArray2DAsync #-}\ncopyArray2DAsync\n :: Storable a\n => Int -- ^ width to copy (elements)\n -> Int -- ^ height to copy (elements)\n -> DevicePtr a -- ^ source array\n -> Int -- ^ source array width\n -> Int -- ^ source x-coordinate\n -> Int -- ^ source y-coordinate\n -> DevicePtr a -- ^ destination array\n -> Int -- ^ destination array width\n -> Int -- ^ destination x-coordinate\n -> Int -- ^ destination y-coordinate\n -> Maybe Stream -- ^ stream to associate to\n -> IO ()\ncopyArray2DAsync !w !h !src !hw !hx !hy !dst !dw !dx !dy !mst = doCopy undefined dst\n where\n doCopy :: Storable a' => a' -> DevicePtr a' -> IO ()\n doCopy x _ =\n let bytes = sizeOf x\n w' = w * bytes\n hw' = hw * bytes\n hx' = hx * bytes\n dw' = dw * bytes\n dx' = dx * bytes\n st = fromMaybe defaultStream mst\n in\n nothingIfOk =<< cuMemcpy2DDtoDAsync dst dw' dx' dy src hw' hx' hy w' h st\n\n{-# INLINE cuMemcpy2DDtoDAsync #-}\n{# fun unsafe cuMemcpy2DDtoDAsync\n { useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , useDeviceHandle `DevicePtr a'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , `Int'\n , useStream `Stream'\n }\n -> `Status' cToEnum #}\n\n\n\n-- Context -> Context\n-- ------------------\n\n-- |\n-- Copies an array from device memory in one context to device memory in another\n-- context. Note that this function is asynchronous with respect to the host,\n-- but serialised with respect to all pending and future asynchronous work in\n-- the source and destination contexts. To avoid this synchronisation, use\n-- 'copyArrayPeerAsync' instead.\n--\n{-# INLINEABLE copyArrayPeer #-}\ncopyArrayPeer :: Storable a\n => Int -- ^ number of array elements\n -> DevicePtr a -> Context -- ^ source array and context\n -> DevicePtr a -> Context -- ^ destination array and context\n -> IO ()\n#if CUDA_VERSION < 4000\ncopyArrayPeer _ _ _ _ _ = requireSDK 4.0 \"copyArrayPeer\"\n#else\ncopyArrayPeer !n !src !srcCtx !dst !dstCtx = go undefined src dst\n where\n go :: Storable b => b -> DevicePtr b -> DevicePtr b -> IO ()\n go x _ _ = nothingIfOk =<< cuMemcpyPeer dst dstCtx src srcCtx (n * sizeOf x)\n\n{-# INLINE cuMemcpyPeer #-}\n{# fun unsafe cuMemcpyPeer\n { useDeviceHandle `DevicePtr a'\n , useContext `Context'\n , useDeviceHandle `DevicePtr a'\n , useContext `Context'\n , `Int' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Copies from device memory in one context to device memory in another context.\n-- Note that this function is asynchronous with respect to the host and all work\n-- in other streams and devices.\n--\n{-# INLINEABLE copyArrayPeerAsync #-}\ncopyArrayPeerAsync :: Storable a\n => Int -- ^ number of array elements\n -> DevicePtr a -> Context -- ^ source array and context\n -> DevicePtr a -> Context -- ^ destination array and device context\n -> Maybe Stream -- ^ stream to associate with\n -> IO ()\n#if CUDA_VERSION < 4000\ncopyArrayPeerAsync _ _ _ _ _ _ = requireSDK 4.0 \"copyArrayPeerAsync\"\n#else\ncopyArrayPeerAsync !n !src !srcCtx !dst !dstCtx !st = go undefined src dst\n where\n go :: Storable b => b -> DevicePtr b -> DevicePtr b -> IO ()\n go x _ _ = nothingIfOk =<< cuMemcpyPeerAsync dst dstCtx src srcCtx (n * sizeOf x) stream\n stream = fromMaybe defaultStream st\n\n{-# INLINE cuMemcpyPeerAsync #-}\n{# fun unsafe cuMemcpyPeerAsync\n { useDeviceHandle `DevicePtr a'\n , useContext `Context'\n , useDeviceHandle `DevicePtr a'\n , useContext `Context'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Combined Allocation and Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Write a list of storable elements into a newly allocated device array,\n-- returning the device pointer together with the number of elements that were\n-- written. Note that this requires two memory copies: firstly from a Haskell\n-- list to a heap allocated array, and from there onto the graphics device. The\n-- memory should be 'free'd when no longer required.\n--\n{-# INLINEABLE newListArrayLen #-}\nnewListArrayLen :: Storable a => [a] -> IO (DevicePtr a, Int)\nnewListArrayLen xs =\n F.withArrayLen xs $ \\len p ->\n bracketOnError (mallocArray len) free $ \\d_xs -> do\n pokeArray len p d_xs\n return (d_xs, len)\n\n\n-- |\n-- Write a list of storable elements into a newly allocated device array. This\n-- is 'newListArrayLen' composed with 'fst'.\n--\n{-# INLINEABLE newListArray #-}\nnewListArray :: Storable a => [a] -> IO (DevicePtr a)\nnewListArray xs = fst `fmap` newListArrayLen xs\n\n\n-- |\n-- Temporarily store a list of elements into a newly allocated device array. An\n-- IO action is applied to to the array, the result of which is returned.\n-- Similar to 'newListArray', this requires copying the data twice.\n--\n-- As with 'allocaArray', the memory is freed once the action completes, so you\n-- should not return the pointer from the action, and be wary of asynchronous\n-- kernel execution.\n--\n{-# INLINEABLE withListArray #-}\nwithListArray :: Storable a => [a] -> (DevicePtr a -> IO b) -> IO b\nwithListArray xs = withListArrayLen xs . const\n\n\n-- |\n-- A variant of 'withListArray' which also supplies the number of elements in\n-- the array to the applied function\n--\n{-# INLINEABLE withListArrayLen #-}\nwithListArrayLen :: Storable a => [a] -> (Int -> DevicePtr a -> IO b) -> IO b\nwithListArrayLen xs f =\n bracket (newListArrayLen xs) (free . fst) (uncurry . flip $ f)\n--\n-- XXX: Will this attempt to double-free the device array on error (together\n-- with newListArrayLen)?\n--\n\n\n--------------------------------------------------------------------------------\n-- Utility\n--------------------------------------------------------------------------------\n\n-- |\n-- Set a number of data elements to the specified value, which may be either 8-,\n-- 16-, or 32-bits wide.\n--\n{-# INLINEABLE memset #-}\nmemset :: Storable a => DevicePtr a -> Int -> a -> IO ()\nmemset !dptr !n !val = case sizeOf val of\n 1 -> nothingIfOk =<< cuMemsetD8 dptr val n\n 2 -> nothingIfOk =<< cuMemsetD16 dptr val n\n 4 -> nothingIfOk =<< cuMemsetD32 dptr val n\n _ -> cudaError \"can only memset 8-, 16-, and 32-bit values\"\n\n--\n-- We use unsafe coerce below to reinterpret the bits of the value to memset as,\n-- into the integer type required by the setting functions.\n--\n{-# INLINE cuMemsetD8 #-}\n{# fun unsafe cuMemsetD8\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{-# INLINE cuMemsetD16 #-}\n{# fun unsafe cuMemsetD16\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n{-# INLINE cuMemsetD32 #-}\n{# fun unsafe cuMemsetD32\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set the number of data elements to the specified value, which may be either\n-- 8-, 16-, or 32-bits wide. The operation is asynchronous and may optionally be\n-- associated with a stream. Requires cuda-3.2.\n--\n{-# INLINEABLE memsetAsync #-}\nmemsetAsync :: Storable a => DevicePtr a -> Int -> a -> Maybe Stream -> IO ()\n#if CUDA_VERSION < 3020\nmemsetAsync _ _ _ _ = requireSDK 3.2 \"memsetAsync\"\n#else\nmemsetAsync !dptr !n !val !mst = case sizeOf val of\n 1 -> nothingIfOk =<< cuMemsetD8Async dptr val n stream\n 2 -> nothingIfOk =<< cuMemsetD16Async dptr val n stream\n 4 -> nothingIfOk =<< cuMemsetD32Async dptr val n stream\n _ -> cudaError \"can only memset 8-, 16-, and 32-bit values\"\n where\n stream = fromMaybe defaultStream mst\n\n{-# INLINE cuMemsetD8Async #-}\n{# fun unsafe cuMemsetD8Async\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n{-# INLINE cuMemsetD16Async #-}\n{# fun unsafe cuMemsetD16Async\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n{-# INLINE cuMemsetD32Async #-}\n{# fun unsafe cuMemsetD32Async\n { useDeviceHandle `DevicePtr a'\n , unsafeCoerce `a'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n#endif\n\n\n-- |\n-- Return the device pointer associated with a mapped, pinned host buffer, which\n-- was allocated with the 'DeviceMapped' option by 'mallocHostArray'.\n--\n-- Currently, no options are supported and this must be empty.\n--\n{-# INLINEABLE getDevicePtr #-}\ngetDevicePtr :: [AllocFlag] -> HostPtr a -> IO (DevicePtr a)\ngetDevicePtr !flags !hp = resultIfOk =<< cuMemHostGetDevicePointer hp flags\n\n{-# INLINE cuMemHostGetDevicePointer #-}\n{# fun unsafe cuMemHostGetDevicePointer\n { alloca'- `DevicePtr a' peekDeviceHandle*\n , useHP `HostPtr a'\n , combineBitMasks `[AllocFlag]' } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n useHP = castPtr . useHostPtr\n\n-- |\n-- Return the base address and allocation size of the given device pointer\n--\n{-# INLINEABLE getBasePtr #-}\ngetBasePtr :: DevicePtr a -> IO (DevicePtr a, Int64)\ngetBasePtr !dptr = do\n (status,base,size) <- cuMemGetAddressRange dptr\n resultIfOk (status, (base,size))\n\n{-# INLINE cuMemGetAddressRange #-}\n{# fun unsafe cuMemGetAddressRange\n { alloca'- `DevicePtr a' peekDeviceHandle*\n , alloca'- `Int64' peekIntConv*\n , useDeviceHandle `DevicePtr a' } -> `Status' cToEnum #}\n where\n alloca' :: Storable a => (Ptr a -> IO b) -> IO b\n alloca' = F.alloca\n\n-- |\n-- Return the amount of free and total memory respectively available to the\n-- current context (bytes)\n--\n{-# INLINEABLE getMemInfo #-}\ngetMemInfo :: IO (Int64, Int64)\ngetMemInfo = do\n (!status,!f,!t) <- cuMemGetInfo\n resultIfOk (status,(f,t))\n\n{-# INLINE cuMemGetInfo #-}\n{# fun unsafe cuMemGetInfo\n { alloca'- `Int64' peekIntConv*\n , alloca'- `Int64' peekIntConv* } -> `Status' cToEnum #}\n where\n alloca' = F.alloca\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\ntype DeviceHandle = {# type CUdeviceptr #}\n\n-- Lift an opaque handle to a typed DevicePtr representation. This occasions\n-- arcane distinctions for the different driver versions and Tesla (compute 1.x)\n-- and Fermi (compute 2.x) class architectures on 32- and 64-bit hosts.\n--\n{-# INLINE peekDeviceHandle #-}\npeekDeviceHandle :: Ptr DeviceHandle -> IO (DevicePtr a)\npeekDeviceHandle !p = DevicePtr . intPtrToPtr . fromIntegral <$> peek p\n\n-- Use a device pointer as an opaque handle type\n--\n{-# INLINE useDeviceHandle #-}\nuseDeviceHandle :: DevicePtr a -> DeviceHandle\nuseDeviceHandle = fromIntegral . ptrToIntPtr . useDevicePtr\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"55718937b33e186162ddb3ce1f3daceef1b5ad5a","subject":"Add a note about a linkage type removed in LLVM 3.2","message":"Add a note about a linkage type removed in LLVM 3.2\n","repos":"travitch\/llvm-base-types","old_file":"src\/Data\/LLVM\/Types\/Attributes.chs","new_file":"src\/Data\/LLVM\/Types\/Attributes.chs","new_contents":"module Data.LLVM.Types.Attributes (\n -- * Types\n ArithFlags(..),\n defaultArithFlags,\n CmpPredicate(..),\n CallingConvention(..),\n defaultCallingConvention,\n LinkageType(..),\n defaultLinkage,\n VisibilityStyle(..),\n defaultVisibility,\n ParamAttribute(..),\n FunctionAttribute(..),\n TargetTriple(..),\n Assembly(..),\n AtomicOperation(..),\n LandingPadClause(..),\n AtomicOrdering(..),\n defaultAtomicOrdering,\n SynchronizationScope(..),\n defaultSynchronizationScope\n ) where\n\n#include \"c++\/llvm-base-enums.h\"\n\nimport Control.DeepSeq\nimport Data.Text ( Text, unpack )\n\n-- | Types of symbol linkage. Note that LTLinkerPrivateWeakDefAuto is\n-- only available in llvm < 3.2.\n{#enum LinkageType {} deriving (Eq) #}\ninstance Show LinkageType where\n show LTExternal = \"\"\n show LTAvailableExternally = \"available_externally\"\n show LTLinkOnceAny = \"linkonce\"\n show LTLinkOnceODR = \"linkonce_odr\"\n show LTWeakAny = \"weak\"\n show LTWeakODR = \"weak_odr\"\n show LTAppending = \"appending\"\n show LTInternal = \"internal\"\n show LTPrivate = \"private\"\n show LTLinkerPrivate = \"linker_private\"\n show LTLinkerPrivateWeak = \"linker_private_weak\"\n show LTLinkerPrivateWeakDefAuto = \"linker_private_weak_def_auto\"\n show LTDLLImport = \"dllimport\"\n show LTDLLExport = \"dllexport\"\n show LTExternalWeak = \"extern_weak\"\n show LTCommon = \"common\"\n\ninstance NFData LinkageType\ndefaultLinkage :: LinkageType\ndefaultLinkage = LTExternal\n\n{#enum VisibilityStyle {} deriving (Eq) #}\n\ninstance Show VisibilityStyle where\n show VisibilityDefault = \"\"\n show VisibilityHidden = \"hidden\"\n show VisibilityProtected = \"protected\"\n\ninstance NFData VisibilityStyle\ndefaultVisibility :: VisibilityStyle\ndefaultVisibility = VisibilityDefault\n\n{#enum CAtomicOrdering as AtomicOrdering {} deriving (Eq) #}\n\ninstance Show AtomicOrdering where\n show OrderNotAtomic = \"\"\n show OrderUnordered = \"unordered\"\n show OrderMonotonic = \"monotonic\"\n show OrderAcquire = \"acquire\"\n show OrderRelease = \"release\"\n show OrderAcquireRelease = \"acq_rel\"\n show OrderSequentiallyConsistent = \"seq_cst\"\n\ninstance NFData AtomicOrdering\ndefaultAtomicOrdering :: AtomicOrdering\ndefaultAtomicOrdering = OrderNotAtomic\n\n{#enum CSynchronizationScope as SynchronizationScope {} deriving (Eq) #}\n\ninstance Show SynchronizationScope where\n show SSSingleThread = \"singlethread\"\n show SSCrossThread = \"\"\n\ninstance NFData SynchronizationScope\ndefaultSynchronizationScope :: SynchronizationScope\ndefaultSynchronizationScope = SSCrossThread\n\n{#enum AtomicOperation {} deriving (Eq) #}\n\ninstance Show AtomicOperation where\n show AOXchg = \"xchg\"\n show AOAdd = \"add\"\n show AOSub = \"sub\"\n show AOAnd = \"and\"\n show AONand = \"nand\"\n show AOOr = \"or\"\n show AOXor = \"xor\"\n show AOMax = \"max\"\n show AOMin = \"min\"\n show AOUMax = \"umax\"\n show AOUMin = \"umin\"\n\ninstance NFData AtomicOperation\n\n{#enum LandingPadClause {} deriving (Eq) #}\n\ninstance Show LandingPadClause where\n show LPCatch = \"catch\"\n show LPFilter = \"filter\"\n\ninstance NFData LandingPadClause\n\n{#enum ArithFlags {} deriving (Eq) #}\n\ninstance Show ArithFlags where\n show ArithNone = \"\"\n show ArithNUW = \"nuw\"\n show ArithNSW = \"nsw\"\n show ArithBoth = \"nuw nsw\"\n\ninstance NFData ArithFlags\ndefaultArithFlags :: ArithFlags\ndefaultArithFlags = ArithNone\n\n{#enum CmpPredicate {underscoreToCase} deriving (Eq) #}\n\ninstance Show CmpPredicate where\n show FCmpFalse = \"false\"\n show FCmpOeq = \"oeq\"\n show FCmpOgt = \"ogt\"\n show FCmpOge = \"oge\"\n show FCmpOlt = \"olt\"\n show FCmpOle = \"ole\"\n show FCmpOne = \"one\"\n show FCmpOrd = \"ord\"\n show FCmpUno = \"uno\"\n show FCmpUeq = \"ueq\"\n show FCmpUgt = \"ugt\"\n show FCmpUge = \"uge\"\n show FCmpUlt = \"ult\"\n show FCmpUle = \"ule\"\n show FCmpUne = \"une\"\n show FCmpTrue = \"true\"\n show ICmpEq = \"eq\"\n show ICmpNe = \"ne\"\n show ICmpUgt = \"ugt\"\n show ICmpUge = \"uge\"\n show ICmpUlt = \"ult\"\n show ICmpUle = \"ule\"\n show ICmpSgt = \"sgt\"\n show ICmpSge = \"sge\"\n show ICmpSlt = \"slt\"\n show ICmpSle = \"sle\"\n\ninstance NFData CmpPredicate\n\n\n{#enum CallingConvention {} deriving (Eq) #}\ninstance Show CallingConvention where\n show CC_C = \"\"\n show CC_FAST = \"fastcc\"\n show CC_COLD = \"coldcc\"\n show CC_GHC = \"cc 10\"\n show CC_X86_STDCALL = \"cc 64\"\n show CC_X86_FASTCALL = \"cc 65\"\n show CC_ARM_APCS = \"cc 66\"\n show CC_ARM_AAPCS = \"cc 67\"\n show CC_ARM_AAPCS_VFP = \"cc 68\"\n show CC_MSP430_INTR = \"cc 69\"\n show CC_X86_THISCALL = \"cc 70\"\n show CC_PTX_KERNEL = \"cc 71\"\n show CC_PTX_DEVICE = \"cc 72\"\n show CC_MBLAZE_INTR = \"cc 73\"\n show CC_MBLAZE_SVOL = \"cc 74\"\n\ninstance NFData CallingConvention\ndefaultCallingConvention :: CallingConvention\ndefaultCallingConvention = CC_C\n\n -- Representing Assembly\ndata Assembly = Assembly !Text\n deriving (Eq, Ord)\n\ninstance Show Assembly where\n show (Assembly txt) = unpack txt\n\ninstance NFData Assembly where\n rnf a@(Assembly txt) = txt `seq` a `seq` ()\n\n\n-- Param attributes\n\ndata ParamAttribute = PAZeroExt\n | PASignExt\n | PAInReg\n | PAByVal\n | PASRet\n | PANoAlias\n | PANoCapture\n | PANest\n | PAAlign !Int\n deriving (Eq, Ord)\n\ninstance NFData ParamAttribute\n\ninstance Show ParamAttribute where\n show PAZeroExt = \"zeroext\"\n show PASignExt = \"signext\"\n show PAInReg = \"inreg\"\n show PAByVal = \"byval\"\n show PASRet = \"sret\"\n show PANoAlias = \"noalias\"\n show PANoCapture = \"nocapture\"\n show PANest = \"nest\"\n show (PAAlign i) = \"align \" ++ show i\n\n-- Function Attributes\n\ndata FunctionAttribute = FAAlignStack !Int\n | FAAlwaysInline\n | FAHotPatch\n | FAInlineHint\n | FANaked\n | FANoImplicitFloat\n | FANoInline\n | FANoRedZone\n | FANoReturn\n | FANoUnwind\n | FAOptSize\n | FAReadNone\n | FAReadOnly\n | FASSP\n | FASSPReq\n deriving (Eq, Ord)\n\ninstance NFData FunctionAttribute\n\ninstance Show FunctionAttribute where\n show (FAAlignStack n) = \"alignstack(\" ++ show n ++ \")\"\n show FAAlwaysInline = \"alwaysinline\"\n show FAHotPatch = \"hotpatch\"\n show FAInlineHint = \"inlinehint\"\n show FANaked = \"naked\"\n show FANoImplicitFloat = \"noimplicitfloat\"\n show FANoInline = \"noinline\"\n show FANoRedZone = \"noredzone\"\n show FANoReturn = \"noreturn\"\n show FANoUnwind = \"nounwind\"\n show FAOptSize = \"optsize\"\n show FAReadNone = \"readnone\"\n show FAReadOnly = \"readonly\"\n show FASSP = \"ssp\"\n show FASSPReq = \"sspreq\"\n\ndata TargetTriple = TargetTriple Text\n deriving (Eq)\n\ninstance Show TargetTriple where\n show (TargetTriple t) = unpack t\n\ninstance NFData TargetTriple where\n rnf t@(TargetTriple t') = t' `seq` t `seq` ()\n","old_contents":"module Data.LLVM.Types.Attributes (\n -- * Types\n ArithFlags(..),\n defaultArithFlags,\n CmpPredicate(..),\n CallingConvention(..),\n defaultCallingConvention,\n LinkageType(..),\n defaultLinkage,\n VisibilityStyle(..),\n defaultVisibility,\n ParamAttribute(..),\n FunctionAttribute(..),\n TargetTriple(..),\n Assembly(..),\n AtomicOperation(..),\n LandingPadClause(..),\n AtomicOrdering(..),\n defaultAtomicOrdering,\n SynchronizationScope(..),\n defaultSynchronizationScope\n ) where\n\n#include \"c++\/llvm-base-enums.h\"\n\nimport Control.DeepSeq\nimport Data.Text ( Text, unpack )\n\n{#enum LinkageType {} deriving (Eq) #}\ninstance Show LinkageType where\n show LTExternal = \"\"\n show LTAvailableExternally = \"available_externally\"\n show LTLinkOnceAny = \"linkonce\"\n show LTLinkOnceODR = \"linkonce_odr\"\n show LTWeakAny = \"weak\"\n show LTWeakODR = \"weak_odr\"\n show LTAppending = \"appending\"\n show LTInternal = \"internal\"\n show LTPrivate = \"private\"\n show LTLinkerPrivate = \"linker_private\"\n show LTLinkerPrivateWeak = \"linker_private_weak\"\n show LTLinkerPrivateWeakDefAuto = \"linker_private_weak_def_auto\"\n show LTDLLImport = \"dllimport\"\n show LTDLLExport = \"dllexport\"\n show LTExternalWeak = \"extern_weak\"\n show LTCommon = \"common\"\n\ninstance NFData LinkageType\ndefaultLinkage :: LinkageType\ndefaultLinkage = LTExternal\n\n{#enum VisibilityStyle {} deriving (Eq) #}\n\ninstance Show VisibilityStyle where\n show VisibilityDefault = \"\"\n show VisibilityHidden = \"hidden\"\n show VisibilityProtected = \"protected\"\n\ninstance NFData VisibilityStyle\ndefaultVisibility :: VisibilityStyle\ndefaultVisibility = VisibilityDefault\n\n{#enum CAtomicOrdering as AtomicOrdering {} deriving (Eq) #}\n\ninstance Show AtomicOrdering where\n show OrderNotAtomic = \"\"\n show OrderUnordered = \"unordered\"\n show OrderMonotonic = \"monotonic\"\n show OrderAcquire = \"acquire\"\n show OrderRelease = \"release\"\n show OrderAcquireRelease = \"acq_rel\"\n show OrderSequentiallyConsistent = \"seq_cst\"\n\ninstance NFData AtomicOrdering\ndefaultAtomicOrdering :: AtomicOrdering\ndefaultAtomicOrdering = OrderNotAtomic\n\n{#enum CSynchronizationScope as SynchronizationScope {} deriving (Eq) #}\n\ninstance Show SynchronizationScope where\n show SSSingleThread = \"singlethread\"\n show SSCrossThread = \"\"\n\ninstance NFData SynchronizationScope\ndefaultSynchronizationScope :: SynchronizationScope\ndefaultSynchronizationScope = SSCrossThread\n\n{#enum AtomicOperation {} deriving (Eq) #}\n\ninstance Show AtomicOperation where\n show AOXchg = \"xchg\"\n show AOAdd = \"add\"\n show AOSub = \"sub\"\n show AOAnd = \"and\"\n show AONand = \"nand\"\n show AOOr = \"or\"\n show AOXor = \"xor\"\n show AOMax = \"max\"\n show AOMin = \"min\"\n show AOUMax = \"umax\"\n show AOUMin = \"umin\"\n\ninstance NFData AtomicOperation\n\n{#enum LandingPadClause {} deriving (Eq) #}\n\ninstance Show LandingPadClause where\n show LPCatch = \"catch\"\n show LPFilter = \"filter\"\n\ninstance NFData LandingPadClause\n\n{#enum ArithFlags {} deriving (Eq) #}\n\ninstance Show ArithFlags where\n show ArithNone = \"\"\n show ArithNUW = \"nuw\"\n show ArithNSW = \"nsw\"\n show ArithBoth = \"nuw nsw\"\n\ninstance NFData ArithFlags\ndefaultArithFlags :: ArithFlags\ndefaultArithFlags = ArithNone\n\n{#enum CmpPredicate {underscoreToCase} deriving (Eq) #}\n\ninstance Show CmpPredicate where\n show FCmpFalse = \"false\"\n show FCmpOeq = \"oeq\"\n show FCmpOgt = \"ogt\"\n show FCmpOge = \"oge\"\n show FCmpOlt = \"olt\"\n show FCmpOle = \"ole\"\n show FCmpOne = \"one\"\n show FCmpOrd = \"ord\"\n show FCmpUno = \"uno\"\n show FCmpUeq = \"ueq\"\n show FCmpUgt = \"ugt\"\n show FCmpUge = \"uge\"\n show FCmpUlt = \"ult\"\n show FCmpUle = \"ule\"\n show FCmpUne = \"une\"\n show FCmpTrue = \"true\"\n show ICmpEq = \"eq\"\n show ICmpNe = \"ne\"\n show ICmpUgt = \"ugt\"\n show ICmpUge = \"uge\"\n show ICmpUlt = \"ult\"\n show ICmpUle = \"ule\"\n show ICmpSgt = \"sgt\"\n show ICmpSge = \"sge\"\n show ICmpSlt = \"slt\"\n show ICmpSle = \"sle\"\n\ninstance NFData CmpPredicate\n\n\n{#enum CallingConvention {} deriving (Eq) #}\ninstance Show CallingConvention where\n show CC_C = \"\"\n show CC_FAST = \"fastcc\"\n show CC_COLD = \"coldcc\"\n show CC_GHC = \"cc 10\"\n show CC_X86_STDCALL = \"cc 64\"\n show CC_X86_FASTCALL = \"cc 65\"\n show CC_ARM_APCS = \"cc 66\"\n show CC_ARM_AAPCS = \"cc 67\"\n show CC_ARM_AAPCS_VFP = \"cc 68\"\n show CC_MSP430_INTR = \"cc 69\"\n show CC_X86_THISCALL = \"cc 70\"\n show CC_PTX_KERNEL = \"cc 71\"\n show CC_PTX_DEVICE = \"cc 72\"\n show CC_MBLAZE_INTR = \"cc 73\"\n show CC_MBLAZE_SVOL = \"cc 74\"\n\ninstance NFData CallingConvention\ndefaultCallingConvention :: CallingConvention\ndefaultCallingConvention = CC_C\n\n -- Representing Assembly\ndata Assembly = Assembly !Text\n deriving (Eq, Ord)\n\ninstance Show Assembly where\n show (Assembly txt) = unpack txt\n\ninstance NFData Assembly where\n rnf a@(Assembly txt) = txt `seq` a `seq` ()\n\n\n-- Param attributes\n\ndata ParamAttribute = PAZeroExt\n | PASignExt\n | PAInReg\n | PAByVal\n | PASRet\n | PANoAlias\n | PANoCapture\n | PANest\n | PAAlign !Int\n deriving (Eq, Ord)\n\ninstance NFData ParamAttribute\n\ninstance Show ParamAttribute where\n show PAZeroExt = \"zeroext\"\n show PASignExt = \"signext\"\n show PAInReg = \"inreg\"\n show PAByVal = \"byval\"\n show PASRet = \"sret\"\n show PANoAlias = \"noalias\"\n show PANoCapture = \"nocapture\"\n show PANest = \"nest\"\n show (PAAlign i) = \"align \" ++ show i\n\n-- Function Attributes\n\ndata FunctionAttribute = FAAlignStack !Int\n | FAAlwaysInline\n | FAHotPatch\n | FAInlineHint\n | FANaked\n | FANoImplicitFloat\n | FANoInline\n | FANoRedZone\n | FANoReturn\n | FANoUnwind\n | FAOptSize\n | FAReadNone\n | FAReadOnly\n | FASSP\n | FASSPReq\n deriving (Eq, Ord)\n\ninstance NFData FunctionAttribute\n\ninstance Show FunctionAttribute where\n show (FAAlignStack n) = \"alignstack(\" ++ show n ++ \")\"\n show FAAlwaysInline = \"alwaysinline\"\n show FAHotPatch = \"hotpatch\"\n show FAInlineHint = \"inlinehint\"\n show FANaked = \"naked\"\n show FANoImplicitFloat = \"noimplicitfloat\"\n show FANoInline = \"noinline\"\n show FANoRedZone = \"noredzone\"\n show FANoReturn = \"noreturn\"\n show FANoUnwind = \"nounwind\"\n show FAOptSize = \"optsize\"\n show FAReadNone = \"readnone\"\n show FAReadOnly = \"readonly\"\n show FASSP = \"ssp\"\n show FASSPReq = \"sspreq\"\n\ndata TargetTriple = TargetTriple Text\n deriving (Eq)\n\ninstance Show TargetTriple where\n show (TargetTriple t) = unpack t\n\ninstance NFData TargetTriple where\n rnf t@(TargetTriple t') = t' `seq` t `seq` ()\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"d2c56c97fc966637128dc5143cc1b95aff60d8c2","subject":"Add writeAttr for Enums. This is needed for MessageDialog.","message":"Add writeAttr for Enums.\nThis is needed for MessageDialog.\n\n","repos":"gtk2hs\/vte,gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gtksourceview","old_file":"glib\/System\/Glib\/Properties.chs","new_file":"glib\/System\/Glib\/Properties.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GObject Properties\n--\n-- Author : Duncan Coutts\n--\n-- Created: 16 April 2005\n--\n-- Version $Revision: 1.8 $ from $Date: 2005\/08\/29 11:15:58 $\n--\n-- Copyright (C) 2005 Duncan Coutts\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Functions for getting and setting GObject properties\n--\nmodule System.Glib.Properties (\n -- * per-type functions for getting and setting GObject properties\n objectSetPropertyInt,\n objectGetPropertyInt,\n objectSetPropertyUInt,\n objectGetPropertyUInt,\n objectSetPropertyBool,\n objectGetPropertyBool,\n objectSetPropertyEnum,\n objectGetPropertyEnum,\n objectSetPropertyFlags,\n objectGetPropertyFlags,\n objectSetPropertyFloat,\n objectGetPropertyFloat,\n objectSetPropertyDouble,\n objectGetPropertyDouble,\n objectSetPropertyString,\n objectGetPropertyString,\n objectSetPropertyMaybeString,\n objectGetPropertyMaybeString, \n objectSetPropertyBoxedOpaque,\n objectGetPropertyBoxedOpaque,\n objectSetPropertyBoxedStorable,\n objectGetPropertyBoxedStorable,\n objectSetPropertyGObject,\n objectGetPropertyGObject,\n\n -- * constructors for attributes backed by GObject properties\n newAttrFromIntProperty,\n readAttrFromIntProperty,\n newAttrFromUIntProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n newAttrFromFloatProperty,\n newAttrFromDoubleProperty,\n newAttrFromEnumProperty,\n readAttrFromEnumProperty,\n writeAttrFromEnumProperty,\n newAttrFromFlagsProperty,\n newAttrFromStringProperty,\n readAttrFromStringProperty,\n writeAttrFromStringProperty,\n writeAttrFromMaybeStringProperty,\n newAttrFromMaybeStringProperty,\n newAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n ) where\n\nimport Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags, fromFlags, toFlags)\nimport System.Glib.UTFString\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\nimport System.Glib.GObject\t(makeNewGObject)\nimport qualified System.Glib.GTypeConstants as GType\nimport System.Glib.GType\nimport System.Glib.GValueTypes\nimport System.Glib.Attributes\t(Attr, ReadAttr, WriteAttr, ReadWriteAttr,\n\t\t\t\tnewAttr, readAttr, writeAttr)\n\n{# context lib=\"glib\" prefix=\"g\" #}\n\nobjectSetPropertyInternal :: GObjectClass gobj => GType -> (GValue -> a -> IO ()) -> String -> gobj -> a -> IO ()\nobjectSetPropertyInternal gtype valueSet prop obj val =\n withCString prop $ \\propPtr ->\n allocaGValue $ \\gvalue -> do\n valueInit gvalue gtype\n valueSet gvalue val\n {# call g_object_set_property #}\n (toGObject obj)\n propPtr\n gvalue\n\nobjectGetPropertyInternal :: GObjectClass gobj => GType -> (GValue -> IO a) -> String -> gobj -> IO a\nobjectGetPropertyInternal gtype valueGet prop obj =\n withCString prop $ \\propPtr ->\n allocaGValue $ \\gvalue -> do\n valueInit gvalue gtype\n {# call unsafe g_object_get_property #}\n (toGObject obj)\n propPtr\n gvalue\n valueGet gvalue\n\nobjectSetPropertyInt :: GObjectClass gobj => String -> gobj -> Int -> IO ()\nobjectSetPropertyInt = objectSetPropertyInternal GType.int valueSetInt\n\nobjectGetPropertyInt :: GObjectClass gobj => String -> gobj -> IO Int\nobjectGetPropertyInt = objectGetPropertyInternal GType.int valueGetInt\n\nobjectSetPropertyUInt :: GObjectClass gobj => String -> gobj -> Int -> IO ()\nobjectSetPropertyUInt = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral v))\n\nobjectGetPropertyUInt :: GObjectClass gobj => String -> gobj -> IO Int\nobjectGetPropertyUInt = objectGetPropertyInternal GType.uint (\\gv -> liftM fromIntegral $ valueGetUInt gv)\n\nobjectSetPropertyBool :: GObjectClass gobj => String -> gobj -> Bool -> IO ()\nobjectSetPropertyBool = objectSetPropertyInternal GType.bool valueSetBool\n\nobjectGetPropertyBool :: GObjectClass gobj => String -> gobj -> IO Bool\nobjectGetPropertyBool = objectGetPropertyInternal GType.bool valueGetBool\n\nobjectSetPropertyEnum :: (GObjectClass gobj, Enum enum) => GType -> String -> gobj -> enum -> IO ()\nobjectSetPropertyEnum gtype = objectSetPropertyInternal gtype valueSetEnum\n\nobjectGetPropertyEnum :: (GObjectClass gobj, Enum enum) => GType -> String -> gobj -> IO enum\nobjectGetPropertyEnum gtype = objectGetPropertyInternal gtype valueGetEnum\n\nobjectSetPropertyFlags :: (GObjectClass gobj, Flags flag) => String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags = objectSetPropertyInternal GType.flags valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => String -> gobj -> IO [flag]\nobjectGetPropertyFlags = objectGetPropertyInternal GType.flags valueGetFlags\n\nobjectSetPropertyFloat :: GObjectClass gobj => String -> gobj -> Float -> IO ()\nobjectSetPropertyFloat = objectSetPropertyInternal GType.float valueSetFloat\n\nobjectGetPropertyFloat :: GObjectClass gobj => String -> gobj -> IO Float\nobjectGetPropertyFloat = objectGetPropertyInternal GType.float valueGetFloat\n\nobjectSetPropertyDouble :: GObjectClass gobj => String -> gobj -> Double -> IO ()\nobjectSetPropertyDouble = objectSetPropertyInternal GType.double valueSetDouble\n\nobjectGetPropertyDouble :: GObjectClass gobj => String -> gobj -> IO Double\nobjectGetPropertyDouble = objectGetPropertyInternal GType.double valueGetDouble\n\nobjectSetPropertyString :: GObjectClass gobj => String -> gobj -> String -> IO ()\nobjectSetPropertyString = objectSetPropertyInternal GType.string valueSetString\n\nobjectGetPropertyString :: GObjectClass gobj => String -> gobj -> IO String\nobjectGetPropertyString = objectGetPropertyInternal GType.string valueGetString\n\nobjectSetPropertyMaybeString :: GObjectClass gobj => String -> gobj -> Maybe String -> IO ()\nobjectSetPropertyMaybeString = objectSetPropertyInternal GType.string valueSetMaybeString\n\nobjectGetPropertyMaybeString :: GObjectClass gobj => String -> gobj -> IO (Maybe String)\nobjectGetPropertyMaybeString = objectGetPropertyInternal GType.string valueGetMaybeString\n\nobjectSetPropertyBoxedOpaque :: GObjectClass gobj => (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> GType -> String -> gobj -> boxed -> IO ()\nobjectSetPropertyBoxedOpaque with gtype = objectSetPropertyInternal gtype (valueSetBoxed with)\n\nobjectGetPropertyBoxedOpaque :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> GType -> String -> gobj -> IO boxed\nobjectGetPropertyBoxedOpaque peek gtype = objectGetPropertyInternal gtype (valueGetBoxed peek)\n\nobjectSetPropertyBoxedStorable :: (GObjectClass gobj, Storable boxed) => GType -> String -> gobj -> boxed -> IO ()\nobjectSetPropertyBoxedStorable = objectSetPropertyBoxedOpaque with\n\nobjectGetPropertyBoxedStorable :: (GObjectClass gobj, Storable boxed) => GType -> String -> gobj -> IO boxed\nobjectGetPropertyBoxedStorable = objectGetPropertyBoxedOpaque peek\n\nobjectSetPropertyGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> gobj' -> IO ()\nobjectSetPropertyGObject gtype = objectSetPropertyInternal gtype valueSetGObject\n\nobjectGetPropertyGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO gobj'\nobjectGetPropertyGObject gtype = objectGetPropertyInternal gtype valueGetGObject\n\n\n-- Convenience functions to make attribute implementations in the other modules\n-- shorter and more easily extensible.\n--\n\nnewAttrFromIntProperty :: GObjectClass gobj => String -> Attr gobj Int\nnewAttrFromIntProperty propName =\n newAttr (objectGetPropertyInt propName) (objectSetPropertyInt propName)\n\nreadAttrFromIntProperty :: GObjectClass gobj => String -> ReadAttr gobj Int\nreadAttrFromIntProperty propName =\n readAttr (objectGetPropertyInt propName)\n\nnewAttrFromUIntProperty :: GObjectClass gobj => String -> Attr gobj Int\nnewAttrFromUIntProperty propName =\n newAttr (objectGetPropertyUInt propName) (objectSetPropertyUInt propName)\n\nwriteAttrFromUIntProperty :: GObjectClass gobj => String -> WriteAttr gobj Int\nwriteAttrFromUIntProperty propName =\n writeAttr (objectSetPropertyUInt propName)\n\nnewAttrFromBoolProperty :: GObjectClass gobj => String -> Attr gobj Bool\nnewAttrFromBoolProperty propName =\n newAttr (objectGetPropertyBool propName) (objectSetPropertyBool propName)\n\nnewAttrFromFloatProperty :: GObjectClass gobj => String -> Attr gobj Float\nnewAttrFromFloatProperty propName =\n newAttr (objectGetPropertyFloat propName) (objectSetPropertyFloat propName)\n\nnewAttrFromDoubleProperty :: GObjectClass gobj => String -> Attr gobj Double\nnewAttrFromDoubleProperty propName =\n newAttr (objectGetPropertyDouble propName) (objectSetPropertyDouble propName)\n\nnewAttrFromEnumProperty :: (GObjectClass gobj, Enum enum) => String -> GType -> Attr gobj enum\nnewAttrFromEnumProperty propName gtype =\n newAttr (objectGetPropertyEnum gtype propName) (objectSetPropertyEnum gtype propName)\n\nreadAttrFromEnumProperty :: (GObjectClass gobj, Enum enum) => String -> GType -> ReadAttr gobj enum\nreadAttrFromEnumProperty propName gtype =\n readAttr (objectGetPropertyEnum gtype propName)\n\nwriteAttrFromEnumProperty :: (GObjectClass gobj, Enum enum) => String -> GType -> WriteAttr gobj enum\nwriteAttrFromEnumProperty propName gtype =\n writeAttr (objectSetPropertyEnum gtype propName)\n\nnewAttrFromFlagsProperty :: (GObjectClass gobj, Flags flag) => String -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName =\n newAttr (objectGetPropertyFlags propName) (objectSetPropertyFlags propName)\n\nnewAttrFromStringProperty :: GObjectClass gobj => String -> Attr gobj String\nnewAttrFromStringProperty propName =\n newAttr (objectGetPropertyString propName) (objectSetPropertyString propName)\n\nreadAttrFromStringProperty :: GObjectClass gobj => String -> ReadAttr gobj String\nreadAttrFromStringProperty propName =\n readAttr (objectGetPropertyString propName)\n\nwriteAttrFromStringProperty :: GObjectClass gobj => String -> WriteAttr gobj String\nwriteAttrFromStringProperty propName =\n writeAttr (objectSetPropertyString propName)\n\nwriteAttrFromMaybeStringProperty :: GObjectClass gobj => String -> WriteAttr gobj (Maybe String)\nwriteAttrFromMaybeStringProperty propName =\n writeAttr (objectSetPropertyMaybeString propName)\n\nnewAttrFromMaybeStringProperty :: GObjectClass gobj => String -> Attr gobj (Maybe String)\nnewAttrFromMaybeStringProperty propName =\n newAttr (objectGetPropertyMaybeString propName) (objectSetPropertyMaybeString propName)\n\nnewAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> String -> GType -> Attr gobj boxed\nnewAttrFromBoxedOpaqueProperty peek with propName gtype =\n newAttr (objectGetPropertyBoxedOpaque peek gtype propName) (objectSetPropertyBoxedOpaque with gtype propName)\n\nwriteAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> String -> GType -> WriteAttr gobj boxed\nwriteAttrFromBoxedOpaqueProperty with propName gtype =\n writeAttr (objectSetPropertyBoxedOpaque with gtype propName)\n\nnewAttrFromBoxedStorableProperty :: (GObjectClass gobj, Storable boxed) => String -> GType -> Attr gobj boxed\nnewAttrFromBoxedStorableProperty propName gtype =\n newAttr (objectGetPropertyBoxedStorable gtype propName) (objectSetPropertyBoxedStorable gtype propName)\n\nnewAttrFromObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj gobj' gobj''\nnewAttrFromObjectProperty propName gtype =\n newAttr (objectGetPropertyGObject gtype propName) (objectSetPropertyGObject gtype propName)\n\nwriteAttrFromObjectProperty :: (GObjectClass gobj, GObjectClass gobj') => String -> GType -> WriteAttr gobj gobj'\nwriteAttrFromObjectProperty propName gtype =\n writeAttr (objectSetPropertyGObject gtype propName)\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GObject Properties\n--\n-- Author : Duncan Coutts\n--\n-- Created: 16 April 2005\n--\n-- Version $Revision: 1.8 $ from $Date: 2005\/08\/29 11:15:58 $\n--\n-- Copyright (C) 2005 Duncan Coutts\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Functions for getting and setting GObject properties\n--\nmodule System.Glib.Properties (\n -- * per-type functions for getting and setting GObject properties\n objectSetPropertyInt,\n objectGetPropertyInt,\n objectSetPropertyUInt,\n objectGetPropertyUInt,\n objectSetPropertyBool,\n objectGetPropertyBool,\n objectSetPropertyEnum,\n objectGetPropertyEnum,\n objectSetPropertyFlags,\n objectGetPropertyFlags,\n objectSetPropertyFloat,\n objectGetPropertyFloat,\n objectSetPropertyDouble,\n objectGetPropertyDouble,\n objectSetPropertyString,\n objectGetPropertyString,\n objectSetPropertyMaybeString,\n objectGetPropertyMaybeString, \n objectSetPropertyBoxedOpaque,\n objectGetPropertyBoxedOpaque,\n objectSetPropertyBoxedStorable,\n objectGetPropertyBoxedStorable,\n objectSetPropertyGObject,\n objectGetPropertyGObject,\n\n -- * constructors for attributes backed by GObject properties\n newAttrFromIntProperty,\n readAttrFromIntProperty,\n newAttrFromUIntProperty,\n writeAttrFromUIntProperty,\n newAttrFromBoolProperty,\n newAttrFromFloatProperty,\n newAttrFromDoubleProperty,\n newAttrFromEnumProperty,\n readAttrFromEnumProperty,\n newAttrFromFlagsProperty,\n newAttrFromStringProperty,\n readAttrFromStringProperty,\n writeAttrFromStringProperty,\n writeAttrFromMaybeStringProperty,\n newAttrFromMaybeStringProperty,\n newAttrFromBoxedOpaqueProperty,\n writeAttrFromBoxedOpaqueProperty,\n newAttrFromBoxedStorableProperty,\n newAttrFromObjectProperty,\n writeAttrFromObjectProperty,\n ) where\n\nimport Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags\t(Flags, fromFlags, toFlags)\nimport System.Glib.UTFString\n{#import System.Glib.Types#}\n{#import System.Glib.GValue#}\t(GValue(GValue), valueInit, allocaGValue)\nimport System.Glib.GObject\t(makeNewGObject)\nimport qualified System.Glib.GTypeConstants as GType\nimport System.Glib.GType\nimport System.Glib.GValueTypes\nimport System.Glib.Attributes\t(Attr, ReadAttr, WriteAttr, ReadWriteAttr,\n\t\t\t\tnewAttr, readAttr, writeAttr)\n\n{# context lib=\"glib\" prefix=\"g\" #}\n\nobjectSetPropertyInternal :: GObjectClass gobj => GType -> (GValue -> a -> IO ()) -> String -> gobj -> a -> IO ()\nobjectSetPropertyInternal gtype valueSet prop obj val =\n withCString prop $ \\propPtr ->\n allocaGValue $ \\gvalue -> do\n valueInit gvalue gtype\n valueSet gvalue val\n {# call g_object_set_property #}\n (toGObject obj)\n propPtr\n gvalue\n\nobjectGetPropertyInternal :: GObjectClass gobj => GType -> (GValue -> IO a) -> String -> gobj -> IO a\nobjectGetPropertyInternal gtype valueGet prop obj =\n withCString prop $ \\propPtr ->\n allocaGValue $ \\gvalue -> do\n valueInit gvalue gtype\n {# call unsafe g_object_get_property #}\n (toGObject obj)\n propPtr\n gvalue\n valueGet gvalue\n\nobjectSetPropertyInt :: GObjectClass gobj => String -> gobj -> Int -> IO ()\nobjectSetPropertyInt = objectSetPropertyInternal GType.int valueSetInt\n\nobjectGetPropertyInt :: GObjectClass gobj => String -> gobj -> IO Int\nobjectGetPropertyInt = objectGetPropertyInternal GType.int valueGetInt\n\nobjectSetPropertyUInt :: GObjectClass gobj => String -> gobj -> Int -> IO ()\nobjectSetPropertyUInt = objectSetPropertyInternal GType.uint (\\gv v -> valueSetUInt gv (fromIntegral v))\n\nobjectGetPropertyUInt :: GObjectClass gobj => String -> gobj -> IO Int\nobjectGetPropertyUInt = objectGetPropertyInternal GType.uint (\\gv -> liftM fromIntegral $ valueGetUInt gv)\n\nobjectSetPropertyBool :: GObjectClass gobj => String -> gobj -> Bool -> IO ()\nobjectSetPropertyBool = objectSetPropertyInternal GType.bool valueSetBool\n\nobjectGetPropertyBool :: GObjectClass gobj => String -> gobj -> IO Bool\nobjectGetPropertyBool = objectGetPropertyInternal GType.bool valueGetBool\n\nobjectSetPropertyEnum :: (GObjectClass gobj, Enum enum) => GType -> String -> gobj -> enum -> IO ()\nobjectSetPropertyEnum gtype = objectSetPropertyInternal gtype valueSetEnum\n\nobjectGetPropertyEnum :: (GObjectClass gobj, Enum enum) => GType -> String -> gobj -> IO enum\nobjectGetPropertyEnum gtype = objectGetPropertyInternal gtype valueGetEnum\n\nobjectSetPropertyFlags :: (GObjectClass gobj, Flags flag) => String -> gobj -> [flag] -> IO ()\nobjectSetPropertyFlags = objectSetPropertyInternal GType.flags valueSetFlags\n\nobjectGetPropertyFlags :: (GObjectClass gobj, Flags flag) => String -> gobj -> IO [flag]\nobjectGetPropertyFlags = objectGetPropertyInternal GType.flags valueGetFlags\n\nobjectSetPropertyFloat :: GObjectClass gobj => String -> gobj -> Float -> IO ()\nobjectSetPropertyFloat = objectSetPropertyInternal GType.float valueSetFloat\n\nobjectGetPropertyFloat :: GObjectClass gobj => String -> gobj -> IO Float\nobjectGetPropertyFloat = objectGetPropertyInternal GType.float valueGetFloat\n\nobjectSetPropertyDouble :: GObjectClass gobj => String -> gobj -> Double -> IO ()\nobjectSetPropertyDouble = objectSetPropertyInternal GType.double valueSetDouble\n\nobjectGetPropertyDouble :: GObjectClass gobj => String -> gobj -> IO Double\nobjectGetPropertyDouble = objectGetPropertyInternal GType.double valueGetDouble\n\nobjectSetPropertyString :: GObjectClass gobj => String -> gobj -> String -> IO ()\nobjectSetPropertyString = objectSetPropertyInternal GType.string valueSetString\n\nobjectGetPropertyString :: GObjectClass gobj => String -> gobj -> IO String\nobjectGetPropertyString = objectGetPropertyInternal GType.string valueGetString\n\nobjectSetPropertyMaybeString :: GObjectClass gobj => String -> gobj -> Maybe String -> IO ()\nobjectSetPropertyMaybeString = objectSetPropertyInternal GType.string valueSetMaybeString\n\nobjectGetPropertyMaybeString :: GObjectClass gobj => String -> gobj -> IO (Maybe String)\nobjectGetPropertyMaybeString = objectGetPropertyInternal GType.string valueGetMaybeString\n\nobjectSetPropertyBoxedOpaque :: GObjectClass gobj => (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> GType -> String -> gobj -> boxed -> IO ()\nobjectSetPropertyBoxedOpaque with gtype = objectSetPropertyInternal gtype (valueSetBoxed with)\n\nobjectGetPropertyBoxedOpaque :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> GType -> String -> gobj -> IO boxed\nobjectGetPropertyBoxedOpaque peek gtype = objectGetPropertyInternal gtype (valueGetBoxed peek)\n\nobjectSetPropertyBoxedStorable :: (GObjectClass gobj, Storable boxed) => GType -> String -> gobj -> boxed -> IO ()\nobjectSetPropertyBoxedStorable = objectSetPropertyBoxedOpaque with\n\nobjectGetPropertyBoxedStorable :: (GObjectClass gobj, Storable boxed) => GType -> String -> gobj -> IO boxed\nobjectGetPropertyBoxedStorable = objectGetPropertyBoxedOpaque peek\n\nobjectSetPropertyGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> gobj' -> IO ()\nobjectSetPropertyGObject gtype = objectSetPropertyInternal gtype valueSetGObject\n\nobjectGetPropertyGObject :: (GObjectClass gobj, GObjectClass gobj') => GType -> String -> gobj -> IO gobj'\nobjectGetPropertyGObject gtype = objectGetPropertyInternal gtype valueGetGObject\n\n\n-- Convenience functions to make attribute implementations in the other modules\n-- shorter and more easily extensible.\n--\n\nnewAttrFromIntProperty :: GObjectClass gobj => String -> Attr gobj Int\nnewAttrFromIntProperty propName =\n newAttr (objectGetPropertyInt propName) (objectSetPropertyInt propName)\n\nreadAttrFromIntProperty :: GObjectClass gobj => String -> ReadAttr gobj Int\nreadAttrFromIntProperty propName =\n readAttr (objectGetPropertyInt propName)\n\nnewAttrFromUIntProperty :: GObjectClass gobj => String -> Attr gobj Int\nnewAttrFromUIntProperty propName =\n newAttr (objectGetPropertyUInt propName) (objectSetPropertyUInt propName)\n\nwriteAttrFromUIntProperty :: GObjectClass gobj => String -> WriteAttr gobj Int\nwriteAttrFromUIntProperty propName =\n writeAttr (objectSetPropertyUInt propName)\n\nnewAttrFromBoolProperty :: GObjectClass gobj => String -> Attr gobj Bool\nnewAttrFromBoolProperty propName =\n newAttr (objectGetPropertyBool propName) (objectSetPropertyBool propName)\n\nnewAttrFromFloatProperty :: GObjectClass gobj => String -> Attr gobj Float\nnewAttrFromFloatProperty propName =\n newAttr (objectGetPropertyFloat propName) (objectSetPropertyFloat propName)\n\nnewAttrFromDoubleProperty :: GObjectClass gobj => String -> Attr gobj Double\nnewAttrFromDoubleProperty propName =\n newAttr (objectGetPropertyDouble propName) (objectSetPropertyDouble propName)\n\nnewAttrFromEnumProperty :: (GObjectClass gobj, Enum enum) => String -> GType -> Attr gobj enum\nnewAttrFromEnumProperty propName gtype =\n newAttr (objectGetPropertyEnum gtype propName) (objectSetPropertyEnum gtype propName)\n\nreadAttrFromEnumProperty :: (GObjectClass gobj, Enum enum) => String -> GType -> ReadAttr gobj enum\nreadAttrFromEnumProperty propName gtype =\n readAttr (objectGetPropertyEnum gtype propName)\n\nnewAttrFromFlagsProperty :: (GObjectClass gobj, Flags flag) => String -> Attr gobj [flag]\nnewAttrFromFlagsProperty propName =\n newAttr (objectGetPropertyFlags propName) (objectSetPropertyFlags propName)\n\nnewAttrFromStringProperty :: GObjectClass gobj => String -> Attr gobj String\nnewAttrFromStringProperty propName =\n newAttr (objectGetPropertyString propName) (objectSetPropertyString propName)\n\nreadAttrFromStringProperty :: GObjectClass gobj => String -> ReadAttr gobj String\nreadAttrFromStringProperty propName =\n readAttr (objectGetPropertyString propName)\n\nwriteAttrFromStringProperty :: GObjectClass gobj => String -> WriteAttr gobj String\nwriteAttrFromStringProperty propName =\n writeAttr (objectSetPropertyString propName)\n\nwriteAttrFromMaybeStringProperty :: GObjectClass gobj => String -> WriteAttr gobj (Maybe String)\nwriteAttrFromMaybeStringProperty propName =\n writeAttr (objectSetPropertyMaybeString propName)\n\nnewAttrFromMaybeStringProperty :: GObjectClass gobj => String -> Attr gobj (Maybe String)\nnewAttrFromMaybeStringProperty propName =\n newAttr (objectGetPropertyMaybeString propName) (objectSetPropertyMaybeString propName)\n\nnewAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (Ptr boxed -> IO boxed) -> (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> String -> GType -> Attr gobj boxed\nnewAttrFromBoxedOpaqueProperty peek with propName gtype =\n newAttr (objectGetPropertyBoxedOpaque peek gtype propName) (objectSetPropertyBoxedOpaque with gtype propName)\n\nwriteAttrFromBoxedOpaqueProperty :: GObjectClass gobj => (boxed -> (Ptr boxed -> IO ()) -> IO ()) -> String -> GType -> WriteAttr gobj boxed\nwriteAttrFromBoxedOpaqueProperty with propName gtype =\n writeAttr (objectSetPropertyBoxedOpaque with gtype propName)\n\nnewAttrFromBoxedStorableProperty :: (GObjectClass gobj, Storable boxed) => String -> GType -> Attr gobj boxed\nnewAttrFromBoxedStorableProperty propName gtype =\n newAttr (objectGetPropertyBoxedStorable gtype propName) (objectSetPropertyBoxedStorable gtype propName)\n\nnewAttrFromObjectProperty :: (GObjectClass gobj, GObjectClass gobj', GObjectClass gobj'') => String -> GType -> ReadWriteAttr gobj gobj' gobj''\nnewAttrFromObjectProperty propName gtype =\n newAttr (objectGetPropertyGObject gtype propName) (objectSetPropertyGObject gtype propName)\n\nwriteAttrFromObjectProperty :: (GObjectClass gobj, GObjectClass gobj') => String -> GType -> WriteAttr gobj gobj'\nwriteAttrFromObjectProperty propName gtype =\n writeAttr (objectSetPropertyGObject gtype propName)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"50a3232f271131eef7b5c8d28487e9b6eead6820","subject":"removed unnecessary code","message":"removed unnecessary code\n","repos":"ibabushkin\/hapstone","old_file":"src\/Hapstone\/Internal\/Capstone.chs","new_file":"src\/Hapstone\/Internal\/Capstone.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\nmodule Hapstone.Internal.Capstone \n ( Csh\n , CsArch(..)\n , CsSupport(..)\n , CsMode(..)\n , CsOption(..)\n , CsOptionState(..)\n , CsOperand(..)\n , CsGroup(..)\n , CsSkipdataCallback\n , CsSkipdataStruct(..)\n , CsDetail(..)\n , peekDetail\n , CsInsn(..)\n , csInsnOffset\n , CsErr(..)\n , csSupport\n , csOpen\n , csClose\n , csOption\n , csErrno\n , csStrerror\n , csDisasm\n , csDisasmIter\n , csFree\n , csMalloc\n , csRegName\n , csInsnName\n , csGroupName\n , csInsnGroup\n , csRegRead\n , csRegWrite\n , csOpCount\n , csOpIndex\n ) where\n\n{-\nA few notes on API design\n\nThis is just a roughly 1:1 translation of the capstone C headers to Haskell.\nObviously, it isn't a very pleasant experience to use, so a higher-level API\nis needed. The approach there would be like follows:\n* determine the common workflows with capstone (this is easy)\n* write wrappers around those workflows\n\nThe most notorious issues:\n* wrap allocation and deallocation of structs, so that each pure function is\n a no-op to the runtime's state\n* wrap datatype conversion between architecture specific enumerations and\n interger types. This is best done via typeclasses or type families.\n* wrap instruction structures to provide better architecture separation\n\nThose should be less straightforward to handle and require some more work, a\nfew drafts should be easy to write, however.\n\n-}\n\n#include \n\n{#context lib = \"capstone\"#}\n\nimport Control.Monad (join)\n\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String (CString, peekCString, newCString)\nimport Foreign.Marshal.Array (peekArray, pokeArray)\nimport Foreign.Ptr\n\nimport Hapstone.Internal.Util\nimport qualified Hapstone.Internal.Arm64 as Arm64\nimport qualified Hapstone.Internal.Arm as Arm\nimport qualified Hapstone.Internal.Mips as Mips\nimport qualified Hapstone.Internal.Ppc as Ppc\nimport qualified Hapstone.Internal.Sparc as Sparc\nimport qualified Hapstone.Internal.SystemZ as SystemZ\nimport qualified Hapstone.Internal.X86 as X86\nimport qualified Hapstone.Internal.XCore as XCore\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n-- capstone's weird^M^M^M^M^Mopaque handle type\ntype Csh = CSize\n{#typedef csh Csh#}\n\n-- supported architectures\n{#enum cs_arch as CsArch {underscoreToCase} deriving (Show)#}\n\n-- support constants\n{#enum define CsSupport\n { CS_SUPPORT_DIET as CsSupportDiet\n , CS_SUPPORT_X86_REDUCE as CsSupportX86Reduce} deriving (Show)#}\n\n-- work modes\n{#enum cs_mode as CsMode {underscoreToCase} deriving (Show)#}\n\n-- TODO: we will skip user defined dynamic memory routines for now\n\n-- options are, interestingly, represented by different types\n{#enum cs_opt_type as CsOption {underscoreToCase} deriving (Show)#}\n{#enum cs_opt_value as CsOptionState {underscoreToCase} deriving (Show)#}\n\n-- arch-uniting operand type\n{#enum cs_op_type as CsOperand {underscoreToCase} deriving (Show)#}\n\n-- arch-uniting instruction group type\n{#enum cs_group_type as CsGroup {underscoreToCase} deriving (Show)#}\n\n-- callback type for user-defined SKIPDATA work\ntype CsSkipdataCallback =\n FunPtr (Ptr Word8 -> CSize -> CSize -> Ptr () -> IO CSize)\n\n-- user-defined SKIPDATA setup\ndata CsSkipdataStruct = CsSkipdataStruct String CsSkipdataCallback (Ptr ())\n\ninstance Storable CsSkipdataStruct where\n sizeOf _ = {#sizeof cs_opt_skipdata#}\n alignment _ = {#alignof cs_opt_skipdata#}\n peek p = CsSkipdataStruct\n <$> (peekCString =<< {#get cs_opt_skipdata->mnemonic#} p)\n <*> (castFunPtr <$> {#get cs_opt_skipdata->callback#} p)\n <*> {#get cs_opt_skipdata->user_data#} p\n poke p (CsSkipdataStruct s c d) = do\n newCString s >>= {#set cs_opt_skipdata->mnemonic#} p\n {#set cs_opt_skipdata->callback#} p (castFunPtr c)\n {#set cs_opt_skipdata->user_data#} p d\n\n-- safely set SKIPDATA options (reset on Nothing)\ncsSetSkipdata :: Csh -> Maybe CsSkipdataStruct -> IO CsErr\ncsSetSkipdata h Nothing = csOption h CsOptSkipdata CsOptOff\ncsSetSkipdata h (Just s) =\n with s (csOption h CsOptSkipdata . fromIntegral . ptrToWordPtr)\n\n-- architecture specific information\ndata ArchInfo\n = X86 X86.CsX86\n | Arm64 Arm64.CsArm64\n | Arm Arm.CsArm\n | Mips Mips.CsMips\n | Ppc Ppc.CsPpc\n | Sparc Sparc.CsSparc\n | SysZ SystemZ.CsSysZ\n | XCore XCore.CsXCore\n deriving Show\n\n-- instruction information\ndata CsDetail = CsDetail\n { regsRead :: [Word8]\n , regsWrite :: [Word8]\n , groups :: [Word8]\n , archInfo :: Maybe ArchInfo\n } deriving Show\n\n-- the union holding architecture-specific info is not tagged. Thus, we have\n-- no way to determine what kind of data is stored in it without resorting to\n-- some kind of context lookup, as the C code would do. Thus, the\n-- peek-inmplementation does not get architecture information, use peekDetail\n-- for that.\ninstance Storable CsDetail where\n sizeOf _ = {#sizeof cs_detail#}\n alignment _ = {#alignof cs_detail#}\n peek p = CsDetail\n <$> do num <- fromIntegral <$> {#get cs_detail->regs_read_count#} p\n let ptr = plusPtr p {#offsetof cs_detail.regs_read#}\n peekArray num ptr\n <*> do num <- fromIntegral <$> {#get cs_detail->regs_write_count#} p\n let ptr = plusPtr p {#offsetof cs_detail.regs_write#}\n peekArray num ptr\n <*> do num <- fromIntegral <$> {#get cs_detail->groups_count#} p\n let ptr = plusPtr p {#offsetof cs_detail.groups#}\n peekArray num ptr\n <*> pure Nothing\n poke p (CsDetail rR rW g a) = do\n {#set cs_detail->regs_read_count#} p (fromIntegral $ length rR)\n if length rR > 12\n then error \"regs_read overflew 12 bytes\"\n else pokeArray (plusPtr p {#offsetof cs_detail.regs_read#}) rR\n {#set cs_detail->regs_write_count#} p (fromIntegral $ length rW)\n if length rW > 20\n then error \"regs_write overflew 20 bytes\"\n else pokeArray (plusPtr p {#offsetof cs_detail.regs_write#}) rW\n {#set cs_detail->groups_count#} p (fromIntegral $ length g)\n if length g > 8\n then error \"groups overflew 8 bytes\"\n else pokeArray (plusPtr p {#offsetof cs_detail.groups#}) g\n let bP = plusPtr p ({#offsetof cs_detail.groups_count#} + 1)\n case a of\n Just (X86 x) -> poke bP x\n Just (Arm64 x) -> poke bP x\n Just (Arm x) -> poke bP x\n Just (Mips x) -> poke bP x\n Just (Ppc x) -> poke bP x\n Just (Sparc x) -> poke bP x\n Just (SysZ x) -> poke bP x\n Just (XCore x) -> poke bP x\n Nothing -> return ()\n\n-- an arch-sensitive peek for cs_detail\npeekDetail :: CsArch -> Ptr CsDetail -> IO CsDetail\npeekDetail arch p = do\n detail <- peek p\n let bP = plusPtr p 48\n aI <- case arch of\n CsArchX86 -> X86 <$> peek bP\n CsArchArm64 -> Arm64 <$> peek bP\n CsArchArm -> Arm <$> peek bP\n CsArchMips -> Mips <$> peek bP\n CsArchPpc -> Ppc <$> peek bP\n CsArchSparc -> Sparc <$> peek bP\n CsArchSysz -> SysZ <$> peek bP\n CsArchXcore -> XCore <$> peek bP\n return detail { archInfo = Just aI }\n\n-- instructions\ndata CsInsn = CsInsn\n { insnId :: Word32\n , address :: Word64\n , bytes :: [Word8]\n , mnemonic :: String\n , opStr :: String\n , detail :: Maybe CsDetail\n } deriving Show\n\n-- The untagged-union-problem propagates here as well\ninstance Storable CsInsn where\n sizeOf _ = {#sizeof cs_insn#}\n alignment _ = {#alignof cs_insn#}\n peek p = CsInsn\n <$> (fromIntegral <$> {#get cs_insn->id#} p)\n <*> (fromIntegral <$> {#get cs_insn->address#} p)\n <*> do num <- fromIntegral <$> {#get cs_insn->size#} p\n let ptr = plusPtr p {#offsetof cs_insn->bytes#}\n peekArray num ptr\n <*> (peekCString (plusPtr p {#offsetof cs_insn->mnemonic#}))\n <*> (peekCString (plusPtr p {#offsetof cs_insn->op_str#}))\n <*> return Nothing\n --(castPtr <$> {#get cs_insn->detail#} p >>= peekMaybe)\n poke p (CsInsn i a b m o d) = do\n {#set cs_insn->id#} p (fromIntegral i)\n {#set cs_insn->address#} p (fromIntegral a)\n {#set cs_insn->size#} p (fromIntegral $ length b)\n if length b > 16\n then error \"bytes overflew 16 bytes\"\n else pokeArray (plusPtr p {#offsetof cs_insn.bytes#}) b\n if length m >= 32\n then error \"mnemonic overflew 32 bytes\"\n else pokeArray (plusPtr p {#offsetof cs_insn.mnemonic#}) m\n if length o >= 160\n then error \"op_str overflew 160 bytes\"\n else pokeArray (plusPtr p {#offsetof cs_insn.op_str#}) o\n case d of\n Nothing -> {#set cs_insn->detail#} p nullPtr\n Just d' -> do csDetailPtr <- malloc\n poke csDetailPtr d'\n {#set cs_insn->detail#} p (castPtr csDetailPtr)\n\n-- an arch-sensitive peek for cs_insn \npeekWithArch :: CsArch -> Ptr CsInsn -> IO CsInsn\npeekWithArch arch p = do\n insn <- peek p\n bP <- castPtr <$> {#get cs_insn->detail#} p\n if bP \/= nullPtr\n then do\n det <- peekDetail arch bP\n return insn { detail = Just det }\n else return insn\n\n-- our own port of the CS_INSN_OFFSET macro\ncsInsnOffset :: Ptr CsInsn -> Int -> Int\ncsInsnOffset p n = unsafePerformIO $\n (-) <$> getAddr (plusPtr p (n * {#sizeof cs_insn#})) <*> getAddr p\n where getAddr p = fromIntegral <$> {#get cs_insn->address#} p\n\n-- possible error conditions\n{#enum cs_err as CsErr {underscoreToCase} deriving (Show)#}\n\n-- get the library version\n{#fun pure cs_version as ^\n {alloca- `Int' peekNum*, alloca- `Int' peekNum*} -> `Int'#}\n\n-- get information on supported features\nforeign import ccall \"capstone\/capstone.h cs_support\"\n csSupport' :: CInt -> Bool\ncsSupport :: Enum a => a -> Bool\ncsSupport = csSupport' . fromIntegral . fromEnum\n\n-- open a new disassembly handle\n{#fun cs_open as ^\n {`CsArch', combine `[CsMode]', alloca- `Csh' peek*} -> `CsErr'#}\n\n-- close a handle obtained by cs_open\/csOpen\n{#fun cs_close as ^ {id `Ptr Csh'} -> `CsErr'#}\n\n-- set an option on a handle\n{#fun cs_option as ^ `Enum a' =>\n {`Csh', `CsOption', getCULongFromEnum `a'} -> `CsErr'#}\n\n-- get the last error from a handle\n{#fun cs_errno as ^ {`Csh'} -> `CsErr'#}\n\n-- get the description of an error\n{#fun cs_strerror as ^ {`CsErr'} -> `String'#}\n\n-- disassemble a buffer\nforeign import ccall \"capstone\/capstone.h cs_disasm\"\n csDisasm' :: Csh -- handle\n -> Ptr CUChar -> CSize -- buffer to disassemble\n -> CULong -- address to start at\n -> CSize -- number of instructins to disassemble\n -> Ptr (Ptr CsInsn) -- where to put the instructions\n -> IO CSize -- number of succesfully disassembled instructions\n\ncsDisasm :: Csh -> [Word8] -> Word64 -> Int -> IO [CsInsn]\ncsDisasm handle bytes addr num = do\n array <- newArray $ map fromIntegral bytes\n passedPtr <- malloc :: IO (Ptr (Ptr CsInsn))\n resNum <- fromIntegral <$> csDisasm' handle array\n (fromIntegral $ length bytes) (fromIntegral addr)\n (fromIntegral num) passedPtr\n resPtr <- peek passedPtr\n free passedPtr\n res <- peekArray resNum resPtr\n csFree resPtr resNum\n return res\n\n-- free an instruction struct array\n{#fun cs_free as ^ {castPtr `Ptr CsInsn', `Int'} -> `()'#}\n\n-- allocate space for an instruction struct\n{#fun cs_malloc as ^ {`Csh'} -> `Ptr CsInsn' castPtr#}\n\n-- disassemble one instruction at a time\nforeign import ccall \"capstone\/capstone.h cs_disasm_iter\"\n csDisasmIter' :: Csh -- handle\n -> Ptr (Ptr CUChar) -> Ptr CSize -- buffer description\n -> Ptr CULong -- address to start at\n -> Ptr CsInsn -- output buffer\n -> IO Bool -- success\n\ncsDisasmIter :: Csh -> [Word8] -> Word64\n -> IO ([Word8], Word64, Either CsErr CsInsn)\ncsDisasmIter handle bytes addr = do\n array <- newArray (map fromIntegral bytes) :: IO (Ptr CUChar)\n arrayPtr <- malloc :: IO (Ptr (Ptr CUChar))\n poke arrayPtr array\n sizePtr <- malloc :: IO (Ptr CSize)\n poke sizePtr (fromIntegral $ length bytes)\n addrPtr <- malloc :: IO (Ptr CULong)\n poke addrPtr (fromIntegral addr)\n insnPtr <- csMalloc handle\n success <- csDisasmIter' handle arrayPtr sizePtr addrPtr insnPtr\n bytes' <- join $\n peekArray <$> (fromIntegral <$> peek sizePtr) <*> peek arrayPtr\n addr' <- peek addrPtr\n free arrayPtr\n free sizePtr\n free addrPtr\n result <- if success\n then Right <$> peek insnPtr\n else Left <$> csErrno handle\n return (map fromIntegral bytes', fromIntegral addr', result)\n\n-- get a register's name as a String\n{#fun pure cs_reg_name as csRegName' {`Csh', `Int'} -> `CString'#}\ncsRegName :: Enum e => Csh -> e -> Maybe String\ncsRegName h = stringLookup . csRegName' h . fromEnum\n\n-- get a instruction's name as a String\n{#fun pure cs_insn_name as csInsnName' {`Csh', `Int'} -> `CString'#}\ncsInsnName :: Enum e => Csh -> e -> Maybe String\ncsInsnName h = stringLookup . csInsnName' h . fromEnum\n\n-- get a instruction group's name as a String\n{#fun pure cs_group_name as csGroupName' {`Csh', `Int'} -> `CString'#}\ncsGroupName :: Enum e => Csh -> e -> Maybe String\ncsGroupName h = stringLookup . csGroupName' h . fromEnum\n\n-- check whether an instruction is member of a group\nforeign import ccall \"capstone\/capstone.h cs_insn_group\"\n csInsnGroup' :: Csh -> Ptr CsInsn -> IO Bool\ncsInsnGroup :: Csh -> CsInsn -> Bool\ncsInsnGroup h i = unsafePerformIO . withCast i $ csInsnGroup' h\n\n-- check whether an instruction reads from a register\nforeign import ccall \"capstone\/capstone.h cs_reg_read\"\n csRegRead' :: Csh -> Ptr CsInsn -> CUInt -> IO Bool\ncsRegRead :: Csh -> CsInsn -> Int -> Bool\ncsRegRead h i =\n unsafePerformIO . withCast i . flip (csRegRead' h) . fromIntegral\n\n-- check whether an instruction writes to a register\nforeign import ccall \"capstone\/capstone.h cs_reg_write\"\n csRegWrite' :: Csh -> Ptr CsInsn -> CUInt -> IO Bool\ncsRegWrite :: Csh -> CsInsn -> Int -> Bool\ncsRegWrite h i =\n unsafePerformIO . withCast i . flip (csRegWrite' h) . fromIntegral\n\n-- return the number of operands of given type an instruction has\n{#fun pure cs_op_count as ^\n {`Csh', withCast* `CsInsn', `Int'} -> `Int'#}\n\n-- return the position of the first operand of given type an instruction has,\n-- given an inclusive search range\n{#fun pure cs_op_index as ^\n {`Csh', withCast* `CsInsn', `Int', `Int'} -> `Int'#}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\nmodule Hapstone.Internal.Capstone \n ( Csh\n , CsArch(..)\n , CsSupport(..)\n , CsMode(..)\n , CsOption(..)\n , CsOptionState(..)\n , CsOperand(..)\n , CsGroup(..)\n , CsSkipdataCallback\n , CsSkipdataStruct(..)\n , CsDetail(..)\n , peekDetail\n , CsInsn(..)\n , csInsnOffset\n , CsErr(..)\n , csSupport\n , csOpen\n , csClose\n , csOption\n , csErrno\n , csStrerror\n , csDisasm\n , csDisasmIter\n , csFree\n , csMalloc\n , csRegName\n , csInsnName\n , csGroupName\n , csInsnGroup\n , csRegRead\n , csRegWrite\n , csOpCount\n , csOpIndex\n ) where\n\n{-\nA few notes on API design\n\nThis is just a roughly 1:1 translation of the capstone C headers to Haskell.\nObviously, it isn't a very pleasant experience to use, so a higher-level API\nis needed. The approach there would be like follows:\n* determine the common workflows with capstone (this is easy)\n* write wrappers around those workflows\n\nThe most notorious issues:\n* wrap allocation and deallocation of structs, so that each pure function is\n a no-op to the runtime's state\n* wrap datatype conversion between architecture specific enumerations and\n interger types. This is best done via typeclasses or type families.\n* wrap instruction structures to provide better architecture separation\n\nThose should be less straightforward to handle and require some more work, a\nfew drafts should be easy to write, however.\n\n-}\n\n#include \n\n{#context lib = \"capstone\"#}\n\nimport Control.Monad (join)\n\nimport Foreign\nimport Foreign.C.Types\nimport Foreign.C.String (CString, peekCString, newCString)\nimport Foreign.Marshal.Array (peekArray, pokeArray)\nimport Foreign.Ptr\n\nimport Hapstone.Internal.Util\nimport qualified Hapstone.Internal.Arm64 as Arm64\nimport qualified Hapstone.Internal.Arm as Arm\nimport qualified Hapstone.Internal.Mips as Mips\nimport qualified Hapstone.Internal.Ppc as Ppc\nimport qualified Hapstone.Internal.Sparc as Sparc\nimport qualified Hapstone.Internal.SystemZ as SystemZ\nimport qualified Hapstone.Internal.X86 as X86\nimport qualified Hapstone.Internal.XCore as XCore\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n-- capstone's weird^M^M^M^M^Mopaque handle type\ntype Csh = CSize\n{#typedef csh Csh#}\n\n-- supported architectures\n{#enum cs_arch as CsArch {underscoreToCase} deriving (Show)#}\n\n-- support constants\n{#enum define CsSupport\n { CS_SUPPORT_DIET as CsSupportDiet\n , CS_SUPPORT_X86_REDUCE as CsSupportX86Reduce} deriving (Show)#}\n\n-- work modes\n{#enum cs_mode as CsMode {underscoreToCase} deriving (Show)#}\n\n-- TODO: we will skip user defined dynamic memory routines for now\n\n-- options are, interestingly, represented by different types\n{#enum cs_opt_type as CsOption {underscoreToCase} deriving (Show)#}\n{#enum cs_opt_value as CsOptionState {underscoreToCase} deriving (Show)#}\n\n-- arch-uniting operand type\n{#enum cs_op_type as CsOperand {underscoreToCase} deriving (Show)#}\n\n-- arch-uniting instruction group type\n{#enum cs_group_type as CsGroup {underscoreToCase} deriving (Show)#}\n\n-- callback type for user-defined SKIPDATA work\ntype CsSkipdataCallback =\n FunPtr (Ptr Word8 -> CSize -> CSize -> Ptr () -> IO CSize)\n\n-- user-defined SKIPDATA setup\ndata CsSkipdataStruct = CsSkipdataStruct String CsSkipdataCallback (Ptr ())\n\ninstance Storable CsSkipdataStruct where\n sizeOf _ = {#sizeof cs_opt_skipdata#}\n alignment _ = {#alignof cs_opt_skipdata#}\n peek p = CsSkipdataStruct\n <$> (peekCString =<< {#get cs_opt_skipdata->mnemonic#} p)\n <*> (castFunPtr <$> {#get cs_opt_skipdata->callback#} p)\n <*> {#get cs_opt_skipdata->user_data#} p\n poke p (CsSkipdataStruct s c d) = do\n newCString s >>= {#set cs_opt_skipdata->mnemonic#} p\n {#set cs_opt_skipdata->callback#} p (castFunPtr c)\n {#set cs_opt_skipdata->user_data#} p d\n\n-- safely set SKIPDATA options (reset on Nothing)\ncsSetSkipdata :: Csh -> Maybe CsSkipdataStruct -> IO CsErr\ncsSetSkipdata h Nothing = csOption h CsOptSkipdata CsOptOff\ncsSetSkipdata h (Just s) =\n with s (csOption h CsOptSkipdata . fromIntegral . ptrToWordPtr)\n\n-- architecture specific information\ndata ArchInfo\n = X86 X86.CsX86\n | Arm64 Arm64.CsArm64\n | Arm Arm.CsArm\n | Mips Mips.CsMips\n | Ppc Ppc.CsPpc\n | Sparc Sparc.CsSparc\n | SysZ SystemZ.CsSysZ\n | XCore XCore.CsXCore\n deriving Show\n\n-- instruction information\ndata CsDetail = CsDetail\n { regsRead :: [Word8]\n , regsWrite :: [Word8]\n , groups :: [Word8]\n , archInfo :: Maybe ArchInfo\n } deriving Show\n\n-- the union holding architecture-specific info is not tagged. Thus, we have\n-- no way to determine what kind of data is stored in it without resorting to\n-- some kind of context lookup, as the C code would do. Thus, the\n-- peek-inmplementation does not get architecture information, use peekDetail\n-- for that.\ninstance Storable CsDetail where\n sizeOf _ = {#sizeof cs_detail#}\n alignment _ = {#alignof cs_detail#}\n peek p = CsDetail\n <$> do num <- fromIntegral <$> {#get cs_detail->regs_read_count#} p\n let ptr = plusPtr p {#offsetof cs_detail.regs_read#}\n peekArray num ptr\n <*> do num <- fromIntegral <$> {#get cs_detail->regs_write_count#} p\n let ptr = plusPtr p {#offsetof cs_detail.regs_write#}\n peekArray num ptr\n <*> do num <- fromIntegral <$> {#get cs_detail->groups_count#} p\n let ptr = plusPtr p {#offsetof cs_detail.groups#}\n peekArray num ptr\n <*> pure Nothing\n poke p (CsDetail rR rW g a) = do\n {#set cs_detail->regs_read_count#} p (fromIntegral $ length rR)\n if length rR > 12\n then error \"regs_read overflew 12 bytes\"\n else pokeArray (plusPtr p {#offsetof cs_detail.regs_read#}) rR\n {#set cs_detail->regs_write_count#} p (fromIntegral $ length rW)\n if length rW > 20\n then error \"regs_write overflew 20 bytes\"\n else pokeArray (plusPtr p {#offsetof cs_detail.regs_write#}) rW\n {#set cs_detail->groups_count#} p (fromIntegral $ length g)\n if length g > 8\n then error \"groups overflew 8 bytes\"\n else pokeArray (plusPtr p {#offsetof cs_detail.groups#}) g\n let bP = plusPtr p ({#offsetof cs_detail.groups_count#} + 1)\n case a of\n Just (X86 x) -> poke bP x\n Just (Arm64 x) -> poke bP x\n Just (Arm x) -> poke bP x\n Just (Mips x) -> poke bP x\n Just (Ppc x) -> poke bP x\n Just (Sparc x) -> poke bP x\n Just (SysZ x) -> poke bP x\n Just (XCore x) -> poke bP x\n Nothing -> return ()\n\n-- an arch-sensitive peek for cs_detail\npeekDetail :: CsArch -> Ptr CsDetail -> IO CsDetail\npeekDetail arch p = do\n detail <- peek p\n let bP = plusPtr p 48\n aI <- case arch of\n CsArchX86 -> X86 <$> peek (castPtr bP)\n CsArchArm64 -> Arm64 <$> peek (castPtr bP)\n CsArchArm -> Arm <$> peek (castPtr bP)\n CsArchMips -> Mips <$> peek (castPtr bP)\n CsArchPpc -> Ppc <$> peek (castPtr bP)\n CsArchSparc -> Sparc <$> peek (castPtr bP)\n CsArchSysz -> SysZ <$> peek (castPtr bP)\n CsArchXcore -> XCore <$> peek (castPtr bP)\n return detail { archInfo = Just aI }\n\n-- instructions\ndata CsInsn = CsInsn\n { insnId :: Word32\n , address :: Word64\n , bytes :: [Word8]\n , mnemonic :: String\n , opStr :: String\n , detail :: Maybe CsDetail\n } deriving Show\n\n-- The untagged-union-problem propagates here as well\ninstance Storable CsInsn where\n sizeOf _ = {#sizeof cs_insn#}\n alignment _ = {#alignof cs_insn#}\n peek p = CsInsn\n <$> (fromIntegral <$> {#get cs_insn->id#} p)\n <*> (fromIntegral <$> {#get cs_insn->address#} p)\n <*> do num <- fromIntegral <$> {#get cs_insn->size#} p\n let ptr = plusPtr p {#offsetof cs_insn->bytes#}\n peekArray num ptr\n <*> (peekCString (plusPtr p {#offsetof cs_insn->mnemonic#}))\n <*> (peekCString (plusPtr p {#offsetof cs_insn->op_str#}))\n <*> return Nothing\n --(castPtr <$> {#get cs_insn->detail#} p >>= peekMaybe)\n poke p (CsInsn i a b m o d) = do\n {#set cs_insn->id#} p (fromIntegral i)\n {#set cs_insn->address#} p (fromIntegral a)\n {#set cs_insn->size#} p (fromIntegral $ length b)\n if length b > 16\n then error \"bytes overflew 16 bytes\"\n else pokeArray (plusPtr p {#offsetof cs_insn.bytes#}) b\n if length m >= 32\n then error \"mnemonic overflew 32 bytes\"\n else pokeArray (plusPtr p {#offsetof cs_insn.mnemonic#}) m\n if length o >= 160\n then error \"op_str overflew 160 bytes\"\n else pokeArray (plusPtr p {#offsetof cs_insn.op_str#}) o\n case d of\n Nothing -> {#set cs_insn->detail#} p nullPtr\n Just d' -> do csDetailPtr <- malloc\n poke csDetailPtr d'\n {#set cs_insn->detail#} p (castPtr csDetailPtr)\n\n-- an arch-sensitive peek for cs_insn \npeekWithArch :: CsArch -> Ptr CsInsn -> IO CsInsn\npeekWithArch arch p = do\n insn <- peek p\n bP <- castPtr <$> {#get cs_insn->detail#} p\n if bP \/= nullPtr\n then do\n det <- peekDetail arch bP\n return insn { detail = Just det }\n else return insn\n\n-- our own port of the CS_INSN_OFFSET macro\ncsInsnOffset :: Ptr CsInsn -> Int -> Int\ncsInsnOffset p n = unsafePerformIO $\n (-) <$> getAddr (plusPtr p (n * {#sizeof cs_insn#})) <*> getAddr p\n where getAddr p = fromIntegral <$> {#get cs_insn->address#} p\n\n-- possible error conditions\n{#enum cs_err as CsErr {underscoreToCase} deriving (Show)#}\n\n-- get the library version\n{#fun pure cs_version as ^\n {alloca- `Int' peekNum*, alloca- `Int' peekNum*} -> `Int'#}\n\n-- get information on supported features\nforeign import ccall \"capstone\/capstone.h cs_support\"\n csSupport' :: CInt -> Bool\ncsSupport :: Enum a => a -> Bool\ncsSupport = csSupport' . fromIntegral . fromEnum\n\n-- open a new disassembly handle\n{#fun cs_open as ^\n {`CsArch', combine `[CsMode]', alloca- `Csh' peek*} -> `CsErr'#}\n\n-- close a handle obtained by cs_open\/csOpen\n{#fun cs_close as ^ {id `Ptr Csh'} -> `CsErr'#}\n\n-- set an option on a handle\n{#fun cs_option as ^ `Enum a' =>\n {`Csh', `CsOption', getCULongFromEnum `a'} -> `CsErr'#}\n\n-- get the last error from a handle\n{#fun cs_errno as ^ {`Csh'} -> `CsErr'#}\n\n-- get the description of an error\n{#fun cs_strerror as ^ {`CsErr'} -> `String'#}\n\n-- disassemble a buffer\nforeign import ccall \"capstone\/capstone.h cs_disasm\"\n csDisasm' :: Csh -- handle\n -> Ptr CUChar -> CSize -- buffer to disassemble\n -> CULong -- address to start at\n -> CSize -- number of instructins to disassemble\n -> Ptr (Ptr CsInsn) -- where to put the instructions\n -> IO CSize -- number of succesfully disassembled instructions\n\ncsDisasm :: Csh -> [Word8] -> Word64 -> Int -> IO [CsInsn]\ncsDisasm handle bytes addr num = do\n array <- newArray $ map fromIntegral bytes\n passedPtr <- malloc :: IO (Ptr (Ptr CsInsn))\n resNum <- fromIntegral <$> csDisasm' handle array\n (fromIntegral $ length bytes) (fromIntegral addr)\n (fromIntegral num) passedPtr\n resPtr <- peek passedPtr\n free passedPtr\n res <- peekArray resNum resPtr\n csFree resPtr resNum\n return res\n\n-- free an instruction struct array\n{#fun cs_free as ^ {castPtr `Ptr CsInsn', `Int'} -> `()'#}\n\n-- allocate space for an instruction struct\n{#fun cs_malloc as ^ {`Csh'} -> `Ptr CsInsn' castPtr#}\n\n-- disassemble one instruction at a time\nforeign import ccall \"capstone\/capstone.h cs_disasm_iter\"\n csDisasmIter' :: Csh -- handle\n -> Ptr (Ptr CUChar) -> Ptr CSize -- buffer description\n -> Ptr CULong -- address to start at\n -> Ptr CsInsn -- output buffer\n -> IO Bool -- success\n\ncsDisasmIter :: Csh -> [Word8] -> Word64\n -> IO ([Word8], Word64, Either CsErr CsInsn)\ncsDisasmIter handle bytes addr = do\n array <- newArray (map fromIntegral bytes) :: IO (Ptr CUChar)\n arrayPtr <- malloc :: IO (Ptr (Ptr CUChar))\n poke arrayPtr array\n sizePtr <- malloc :: IO (Ptr CSize)\n poke sizePtr (fromIntegral $ length bytes)\n addrPtr <- malloc :: IO (Ptr CULong)\n poke addrPtr (fromIntegral addr)\n insnPtr <- csMalloc handle\n success <- csDisasmIter' handle arrayPtr sizePtr addrPtr insnPtr\n bytes' <- join $\n peekArray <$> (fromIntegral <$> peek sizePtr) <*> peek arrayPtr\n addr' <- peek addrPtr\n free arrayPtr\n free sizePtr\n free addrPtr\n result <- if success\n then Right <$> peek insnPtr\n else Left <$> csErrno handle\n return (map fromIntegral bytes', fromIntegral addr', result)\n\n-- get a register's name as a String\n{#fun pure cs_reg_name as csRegName' {`Csh', `Int'} -> `CString'#}\ncsRegName :: Enum e => Csh -> e -> Maybe String\ncsRegName h = stringLookup . csRegName' h . fromEnum\n\n-- get a instruction's name as a String\n{#fun pure cs_insn_name as csInsnName' {`Csh', `Int'} -> `CString'#}\ncsInsnName :: Enum e => Csh -> e -> Maybe String\ncsInsnName h = stringLookup . csInsnName' h . fromEnum\n\n-- get a instruction group's name as a String\n{#fun pure cs_group_name as csGroupName' {`Csh', `Int'} -> `CString'#}\ncsGroupName :: Enum e => Csh -> e -> Maybe String\ncsGroupName h = stringLookup . csGroupName' h . fromEnum\n\n-- check whether an instruction is member of a group\nforeign import ccall \"capstone\/capstone.h cs_insn_group\"\n csInsnGroup' :: Csh -> Ptr CsInsn -> IO Bool\ncsInsnGroup :: Csh -> CsInsn -> Bool\ncsInsnGroup h i = unsafePerformIO . withCast i $ csInsnGroup' h\n\n-- check whether an instruction reads from a register\nforeign import ccall \"capstone\/capstone.h cs_reg_read\"\n csRegRead' :: Csh -> Ptr CsInsn -> CUInt -> IO Bool\ncsRegRead :: Csh -> CsInsn -> Int -> Bool\ncsRegRead h i =\n unsafePerformIO . withCast i . flip (csRegRead' h) . fromIntegral\n\n-- check whether an instruction writes to a register\nforeign import ccall \"capstone\/capstone.h cs_reg_write\"\n csRegWrite' :: Csh -> Ptr CsInsn -> CUInt -> IO Bool\ncsRegWrite :: Csh -> CsInsn -> Int -> Bool\ncsRegWrite h i =\n unsafePerformIO . withCast i . flip (csRegWrite' h) . fromIntegral\n\n-- return the number of operands of given type an instruction has\n{#fun pure cs_op_count as ^\n {`Csh', withCast* `CsInsn', `Int'} -> `Int'#}\n\n-- return the position of the first operand of given type an instruction has,\n-- given an inclusive search range\n{#fun pure cs_op_index as ^\n {`Csh', withCast* `CsInsn', `Int', `Int'} -> `Int'#}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"c225471b39322f6c9fc94709bee6590e4e731adb","subject":"Use CInt rather than Int pointers.","message":"Use CInt rather than Int pointers.\n\nWith Int, we get incorrect results on 64-bit platforms. A few\noccurrences (anySource, for example) have already been fixed by\nDmitry). This change should fix all remaining occurrences.\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Control\/Parallel\/MPI\/Internal.chs","new_file":"src\/Control\/Parallel\/MPI\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n#include \n#include \"init_wrapper.h\"\n#include \"comparison_result.h\"\n#include \"error_classes.h\"\n#include \"thread_support.h\"\n-----------------------------------------------------------------------------\n{- |\nModule : Control.Parallel.MPI.Internal\nCopyright : (c) 2010 Bernie Pope, Dmitry Astapov\nLicense : BSD-style\nMaintainer : florbitous@gmail.com\nStability : experimental\nPortability : ghc\n\nThis module contains low-level Haskell bindings to core MPI functions.\nAll Haskell functions correspond to MPI functions or values with the similar\nname (i.e. @commRank@ is the binding for @MPI_Comm_rank@ etc)\n\nNote that most of this module is re-exported by\n\"Control.Parallel.MPI\", so if you are not interested in writing\nlow-level code, you should probably import \"Control.Parallel.MPI\" and\neither \"Control.Parallel.MPI.Storable\" or \"Control.Parallel.MPI.Serializable\".\n-}\n-----------------------------------------------------------------------------\nmodule Control.Parallel.MPI.Internal\n (\n\n -- * MPI runtime management.\n -- ** Initialization, finalization, termination.\n init, finalize, initialized, finalized, abort,\n -- ** Multi-threaded environment support.\n ThreadSupport (..), initThread, queryThread, isThreadMain,\n\n -- ** Runtime attributes.\n getProcessorName, Version (..), getVersion, Implementation(..), getImplementation, universeSize,\n\n -- ** Info objects\n Info, infoNull, infoCreate, infoSet, infoDelete, infoGet,\n\n -- * Requests and statuses.\n Request, Status (..), getCount, test, testPtr, cancel, cancelPtr, wait, waitPtr, waitall, requestNull, \n\n -- * Process management.\n -- ** Communicators.\n Comm, commWorld, commSelf, commNull, commTestInter,\n commSize, commRemoteSize, \n commRank, \n commCompare, commGroup, commGetAttr,\n\n -- ** Process groups.\n Group, groupEmpty, groupRank, groupSize, groupUnion,\n groupIntersection, groupDifference, groupCompare, groupExcl,\n groupIncl, groupTranslateRanks,\n -- ** Comparisons.\n ComparisonResult (..),\n\n -- ** Dynamic process management\n commGetParent, commSpawn, commSpawnSimple, argvNull, errcodesIgnore,\n\n -- * Error handling.\n Errhandler, errorsAreFatal, errorsReturn, errorsThrowExceptions, commSetErrhandler, commGetErrhandler,\n ErrorClass (..), MPIError(..), mpiUndefined,\n\n -- * Ranks.\n Rank, rankId, toRank, fromRank, anySource, theRoot, procNull,\n\n -- * Data types.\n Datatype, char, wchar, short, int, long, longLong, unsignedChar, unsignedShort, unsigned, unsignedLong, unsignedLongLong, float, double, longDouble, byte, packed, typeSize,\n\n -- * Point-to-point operations.\n -- ** Tags.\n Tag, toTag, fromTag, anyTag, unitTag, tagUpperBound,\n\n -- ** Blocking operations.\n BufferPtr, Count, -- XXX: what will break if we don't export those?\n send, ssend, rsend, recv,\n -- ** Non-blocking operations.\n isend, issend, irecv,\n isendPtr, issendPtr, irecvPtr,\n\n\n -- * Collective operations.\n -- ** One-to-all.\n bcast, scatter, scatterv,\n -- ** All-to-one.\n gather, gatherv, reduce,\n -- ** All-to-all.\n allgather, allgatherv,\n alltoall, alltoallv,\n allreduce, \n reduceScatterBlock,\n reduceScatter,\n barrier,\n\n -- ** Reduction operations.\n Operation, maxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp,\n opCreate, opFree,\n\n -- * Timing.\n wtime, wtick, wtimeIsGlobal, wtimeIsGlobalKey\n\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Data.Maybe (fromMaybe)\nimport Control.Monad (liftM, unless)\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception\n\n{# context prefix = \"MPI\" #}\n\n-- | Pointer to memory buffer that either holds data to be sent or is\n-- used to receive some data. You would\n-- probably have to use 'castPtr' to pass some actual pointers to\n-- API functions.\ntype BufferPtr = Ptr ()\n\n-- | Count of elements in the send\/receive buffer\ntype Count = CInt\n\n{- |\nHaskell enum that contains MPI constants\n@MPI_IDENT@, @MPI_CONGRUENT@, @MPI_SIMILAR@ and @MPI_UNEQUAL@.\n\nThose are used to compare communicators ('commCompare') and\nprocess groups ('groupCompare'). Refer to those\nfunctions for description of comparison rules.\n-}\n{# enum ComparisonResult {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- Which Haskell type will be used as Comm depends on the MPI\n-- implementation that was selected during compilation. It could be\n-- CInt, Ptr (), Ptr CInt or something else.\ntype MPIComm = {# type MPI_Comm #}\n\n{- | Abstract type representing MPI communicator handle. Different MPI\n implementations use different C types to implement this, so\n concrete Haskell type behind @Comm@ is hidden from user.\n\n In any MPI program you have predefined communicator 'commWorld'\n which includes all running processes. You could create new\n communicators with TODO\n-}\nnewtype Comm = MkComm { fromComm :: MPIComm } deriving Eq\npeekComm ptr = MkComm <$> peek ptr\n\nforeign import ccall \"&mpi_comm_world\" commWorld_ :: Ptr MPIComm\nforeign import ccall \"&mpi_comm_self\" commSelf_ :: Ptr MPIComm\n\n-- | Predefined handle for communicator that includes all running\n-- processes. Similar to @MPI_Comm_world@\ncommWorld :: Comm\ncommWorld = MkComm <$> unsafePerformIO $ peek commWorld_\n\n-- | Predefined handle for communicator that includes only current\n-- process. Similar to @MPI_Comm_self@\ncommSelf :: Comm\ncommSelf = MkComm <$> unsafePerformIO $ peek commSelf_\n\nforeign import ccall \"&mpi_max_processor_name\" max_processor_name_ :: Ptr CInt\nforeign import ccall \"&mpi_max_error_string\" max_error_string_ :: Ptr CInt\n\n-- | Max length of \"processor name\" as returned by 'getProcessorName'\nmaxProcessorName :: CInt\nmaxProcessorName = unsafePerformIO $ peek max_processor_name_\n\n-- | Max length of error description as returned by 'errorString'\nmaxErrorString :: CInt\nmaxErrorString = unsafePerformIO $ peek max_error_string_\n\n-- | Initialize the MPI environment. The MPI environment must be intialized by each\n-- MPI process before any other MPI function is called. Note that\n-- the environment may also be initialized by the functions 'initThread', 'mpi',\n-- and 'mpiWorld'. It is an error to attempt to initialize the environment more\n-- than once for a given MPI program execution. The only MPI functions that may\n-- be called before the MPI environment is initialized are 'getVersion',\n-- 'initialized' and 'finalized'. This function corresponds to @MPI_Init@.\n{# fun unsafe init_wrapper as init {} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been initialized. Returns @True@ if the\n-- environment has been initialized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Initialized@.\n{# fun unsafe Initialized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been finalized. Returns @True@ if the\n-- environment has been finalized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Finalized@.\n{# fun unsafe Finalized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Initialize the MPI environment with a \/required\/ level of thread support.\n-- See the documentation for 'init' for more information about MPI initialization.\n-- The \/provided\/ level of thread support is returned in the result.\n-- There is no guarantee that provided will be greater than or equal to required.\n-- The level of provided thread support depends on the underlying MPI implementation,\n-- and may also depend on information provided when the program is executed\n-- (for example, by supplying appropriate arguments to @mpiexec@).\n-- If the required level of support cannot be provided then it will try to\n-- return the least supported level greater than what was required.\n-- If that cannot be satisfied then it will return the highest supported level\n-- provided by the MPI implementation. See the documentation for 'ThreadSupport'\n-- for information about what levels are available and their relative ordering.\n-- This function corresponds to @MPI_Init_thread@.\n{# fun unsafe init_wrapper_thread as initThread\n {cFromEnum `ThreadSupport', alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\n-- | Returns the current provided level of thread support. This will be the value\n-- returned as \\\"provided level of support\\\" by 'initThread' as well. This function\n-- corresponds to @MPI_Query_thread@.\n{# fun unsafe Query_thread as ^ {alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\n-- | This function can be called by a thread to find out whether it is the main thread (the\n-- thread that called 'init' or 'initThread'.\n{# fun unsafe Is_thread_main as ^\n {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Terminate the MPI execution environment.\n-- Once 'finalize' is called no other MPI functions may be called except\n-- 'getVersion', 'initialized' and 'finalized', however non-MPI computations\n-- may continue. Each process must complete\n-- any pending communication that it initiated before calling 'finalize'.\n-- Note: the error code returned\n-- by 'finalize' is not checked. This function corresponds to @MPI_Finalize@.\n{# fun unsafe Finalize as ^ {} -> `()' discard*- #}\ndiscard _ = return ()\n-- XXX can't call checkError on finalize, because\n-- checkError calls Internal.errorClass and Internal.errorString.\n-- These cannot be called after finalize (at least on OpenMPI).\n\n-- | Return the name of the current processing host. From this value it\n-- must be possible to identify a specific piece of hardware on which\n-- the code is running.\ngetProcessorName :: IO String\ngetProcessorName = do\n allocaBytes (fromIntegral maxProcessorName) $ \\ptr -> do\n len <- getProcessorName' ptr\n peekCStringLen (ptr, cIntConv len)\n where\n getProcessorName' = {# fun unsafe Get_processor_name as getProcessorName_\n {id `Ptr CChar', alloca- `CInt' peekIntConv*} -> `()' checkError*- #}\n\n-- | MPI implementation version\ndata Version =\n Version { version :: Int, subversion :: Int }\n deriving (Eq, Ord)\n\ninstance Show Version where\n show v = show (version v) ++ \".\" ++ show (subversion v)\n\n-- | Which MPI version the code is running on.\ngetVersion :: IO Version\ngetVersion = do\n (version, subversion) <- getVersion'\n return $ Version version subversion\n where\n getVersion' = {# fun unsafe Get_version as getVersion_\n {alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Supported MPI implementations\ndata Implementation = MPICH2 | OpenMPI deriving (Eq,Show)\n\n-- | Which MPI implementation was used during linking\ngetImplementation :: Implementation\ngetImplementation =\n#ifdef MPICH2\n MPICH2\n#else\n OpenMPI\n#endif\n\n-- | Return the number of processes involved in a communicator. For 'commWorld'\n-- it returns the total number of processes available. If the communicator is\n-- and intra-communicator it returns the number of processes in the local group.\n-- This function corresponds to @MPI_Comm_size@.\n{# fun unsafe Comm_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n-- | For intercommunicators, returns size of the remote process group.\n-- Corresponds to @MPI_Comm_remote_size@.\n{# fun unsafe Comm_remote_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n{- | Check whether the given communicator is intercommunicator - that\n is, communicator connecting two different groups of processes.\n\nRefer to MPI Report v2.2, Section 5.2 \"Communicator Argument\" for\nmore details.\n-}\n{# fun unsafe Comm_test_inter as ^\n {fromComm `Comm', alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Look up MPI communicator argument by the given numeric key.\n-- Lookup of some standard MPI arguments is provided by convenience\n-- functions 'tagUpperBound' and 'wtimeIsGlobal'.\ncommGetAttr :: Storable e => Comm -> Int -> IO (Maybe e)\ncommGetAttr comm key = do\n isInitialized <- initialized\n if isInitialized then do\n alloca $ \\ptr -> do\n found <- commGetAttr' comm key (castPtr ptr)\n if found then do ptr2 <- peek ptr\n Just <$> peek ptr2\n else return Nothing\n else return Nothing\n where\n commGetAttr' = {# fun unsafe Comm_get_attr as commGetAttr_\n {fromComm `Comm', cIntConv `Int', id `Ptr ()', alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Maximum tag value supported by the current MPI implementation. Corresponds to the value of standard MPI\n-- attribute @MPI_TAG_UB@.\n--\n-- When called before 'init' or 'initThread' would return 0.\ntagUpperBound :: Int\ntagUpperBound =\n let key = unsafePerformIO (peekIntConv tagUB_)\n in fromMaybe 0 $ unsafePerformIO (commGetAttr commWorld key)\n\nforeign import ccall unsafe \"&mpi_tag_ub\" tagUB_ :: Ptr CInt\n\n{- | True if clocks at all processes in\n'commWorld' are synchronized, False otherwise. The expectation is that\nthe variation in time, as measured by calls to 'wtime', will be less then one half the\nround-trip time for an MPI message of length zero. \n\nCommunicators other than 'commWorld' could have different clocks.\nYou could find it out by querying attribute 'wtimeIsGlobalKey' with 'commGetAttr'.\n\nWhen wtimeIsGlobal is called before 'init' or 'initThread' it would return False.\n-}\nwtimeIsGlobal :: Bool\nwtimeIsGlobal =\n fromMaybe False $ unsafePerformIO (commGetAttr commWorld wtimeIsGlobalKey)\n\nforeign import ccall unsafe \"&mpi_wtime_is_global\" wtimeIsGlobal_ :: Ptr CInt\n\n-- | Numeric key for standard MPI communicator attribute @MPI_WTIME_IS_GLOBAL@.\n-- To be used with 'commGetAttr'.\nwtimeIsGlobalKey :: Int\nwtimeIsGlobalKey = unsafePerformIO (peekIntConv wtimeIsGlobal_)\n\n{- | \nMany ``dynamic'' MPI applications are expected to exist in a static runtime environment, in which resources have been allocated before the application is run. When a user (or possibly a batch system) runs one of these quasi-static applications, she will usually specify a number of processes to start and a total number of processes that are expected. An application simply needs to know how many slots there are, i.e., how many processes it should spawn.\n\nThis attribute indicates the total number of processes that are expected.\n\nWhen universeSize is called before 'init' or 'initThread' it would return False.\n-}\nuniverseSize :: Comm -> IO (Maybe Int)\nuniverseSize c =\n commGetAttr c universeSizeKey\n\nforeign import ccall unsafe \"&mpi_universe_size\" universeSize_ :: Ptr CInt\n\n-- | Numeric key for recommended MPI communicator attribute @MPI_UNIVERSE_SIZE@.\n-- To be used with 'commGetAttr'.\nuniverseSizeKey :: Int\nuniverseSizeKey = unsafePerformIO (peekIntConv universeSize_)\n\n-- | Return the rank of the calling process for the given\n-- communicator. If it is an intercommunicator, returns rank of the\n-- process in the local group.\n{# fun unsafe Comm_rank as ^\n {fromComm `Comm', alloca- `Rank' peekIntConv* } -> `()' checkError*- #}\n\n{- | Compares two communicators.\n\n* If they are handles for the same MPI communicator object, result is 'Identical';\n\n* If both communicators are identical in constituents and rank\n order, result is `Congruent';\n\n* If they have the same members, but with different ranks, then\n result is 'Similar';\n\n* Otherwise, result is 'Unequal'.\n\n-}\n{# fun unsafe Comm_compare as ^\n {fromComm `Comm', fromComm `Comm', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- | Test for an incomming message, without actually receiving it.\n-- If a message has been sent from @Rank@ to the current process with @Tag@ on the\n-- communicator @Comm@ then 'probe' will return the 'Status' of the message. Otherwise\n-- it will block the current process until such a matching message is sent.\n-- This allows the current process to check for an incoming message and decide\n-- how to receive it, based on the information in the 'Status'.\n-- This function corresponds to @MPI_Probe@.\n-- The most common usecase is to call @probe@ first and then use 'getCount' to find out size of incoming message.\n-- However since different implementations provide additional fields in @Status@, we cannot deserialize Status into Haskell land\n-- and serialize it back without losing information. Hence the use of Ptr Status.\n{# fun Probe as ^\n {fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Status'} -> `()' checkError*- #}\n{- probe :: Rank -- ^ Rank of the sender.\n -> Tag -- ^ Tag of the sent message.\n -> Comm -- ^ Communicator.\n -> IO Status -- ^ Information about the incoming message (but not the content of the message). -}\n\n{-| Returns the number of entries received. (we count entries, each of\ntype @Datatype@, not bytes.) The datatype argument should match the\nargument provided by the receive call that set the status variable. -}\ngetCount :: Comm -> Rank -> Tag -> Datatype -> IO Int\ngetCount comm rank tag datatype =\n alloca $ \\statusPtr -> do\n probe rank tag comm statusPtr\n cnt <- getCount' statusPtr datatype\n return $ fromIntegral cnt\n where\n getCount' = {# fun unsafe Get_count as getCount_\n {castPtr `Ptr Status', fromDatatype `Datatype', alloca- `CInt' peekIntConv*} -> `()' checkError*- #}\n\n\n{-| Send the values (as specified by @BufferPtr@, @Count@, @Datatype@) to\n the process specified by (@Comm@, @Rank@, @Tag@). Caller will\n block until data is copied from the send buffer by the MPI\n-}\n{# fun unsafe Send as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{-| Variant of 'send' that would terminate only when receiving side\nactually starts receiving data. \n-}\n{# fun unsafe Ssend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{-| Variant of 'send' that expects the relevant 'recv' to be already\nstarted, otherwise this call could terminate with MPI error.\n-}\n{# fun unsafe Rsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n-- | Receives data from the process\n-- specified by (@Comm@, @Rank@, @Tag@) and stores it into buffer specified\n-- by (@BufferPtr@, @Count@, @Datatype@).\n{# fun unsafe Recv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast* } -> `()' checkError*- #}\n-- | Send the values (as specified by @BufferPtr@, @Count@, @Datatype@) to\n-- the process specified by (@Comm@, @Rank@, @Tag@) in non-blocking mode.\n-- \n-- Use 'probe' or 'test' to check the status of the operation,\n-- 'cancel' to terminate it or 'wait' to block until it completes.\n-- Operation would be considered complete as soon as MPI finishes\n-- copying the data from the send buffer. \n{# fun unsafe Isend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n-- | Variant of the 'isend' that would be considered complete only when\n-- receiving side actually starts receiving data. \n{# fun unsafe Issend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n-- | Non-blocking variant of 'recv'. Receives data from the process\n-- specified by (@Comm@, @Rank@, @Tag@) and stores it into buffer specified\n-- by (@BufferPtr@, @Count@, @Datatype@).\n{# fun Irecv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n\n-- | Like 'isend', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun unsafe Isend as isendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'issend', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun unsafe Issend as issendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'irecv', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun Irecv as irecvPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Broadcast data from one member to all members of the communicator.\n{# fun unsafe Bcast as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocks until all processes on the communicator call this function.\n-- This function corresponds to @MPI_Barrier@.\n{# fun unsafe Barrier as ^ {fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocking test for the completion of a send of receive.\n-- See 'test' for a non-blocking variant.\n-- This function corresponds to @MPI_Wait@. Request pointer could\n-- be changed to point to @requestNull@. See @wait@ for variant that does not mutate request value.\n{# fun unsafe Wait as waitPtr\n {castPtr `Ptr Request', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Same as @waitPtr@, but does not change Haskell @Request@ value to point to @procNull@.\n-- Usually, this is harmless - your request just would be considered inactive.\nwait request = withRequest request waitPtr\n\n-- | Takes pointer to the array of Requests of given size, 'wait's on all of them,\n-- populates array of Statuses of the same size. This function corresponds to @MPI_Waitall@\n{# fun unsafe Waitall as ^\n { id `Count', castPtr `Ptr Request', castPtr `Ptr Status'} -> `()' checkError*- #}\n-- TODO: Make this Storable Array instead of Ptr ?\n\n-- | Non-blocking test for the completion of a send or receive.\n-- Returns @Nothing@ if the request is not complete, otherwise\n-- it returns @Just status@.\n--\n-- Note that while MPI would modify\n-- request to be @requestNull@ if the operation is complete,\n-- Haskell value would not be changed. So, if you got (Just status)\n-- as a result, consider your request to be @requestNull@. Or use @testPtr@.\n--\n-- See 'wait' for a blocking variant.\n-- This function corresponds to @MPI_Test@.\ntest :: Request -> IO (Maybe Status)\ntest request = withRequest request testPtr\n\n-- | Analogous to 'test' but uses pointer to @Request@. If request is completed, pointer would be \n-- set to point to @requestNull@.\ntestPtr :: Ptr Request -> IO (Maybe Status)\ntestPtr reqPtr = do\n (flag, status) <- testPtr' reqPtr\n request' <- peek reqPtr\n if flag\n then do if request' == requestNull\n then return $ Just status\n else error \"testPtr: request modified, but not set to MPI_REQUEST_NULL!\"\n else return Nothing\n where testPtr' = {# fun unsafe Test as testPtr_\n {castPtr `Ptr Request', alloca- `Bool' peekBool*, allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Cancel a pending communication request.\n-- This function corresponds to @MPI_Cancel@. Sets pointer to point to @requestNull@.\n{# fun unsafe Cancel as cancelPtr\n {castPtr `Ptr Request'} -> `()' checkError*- #}\n\n\n-- | Same as @cancelPtr@, but does not change Haskell @Request@ value to point to @procNull@.\n-- Usually, this is harmless - your request just would be considered inactive.\ncancel request = withRequest request cancelPtr\n\nwithRequest req f = do alloca $ \\ptr -> do poke ptr req\n f (castPtr ptr)\n\n-- | Scatter data from one member to all members of\n-- a group.\n{# fun unsafe Scatter as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Gather data from all members of a group to one\n-- member.\n{# fun unsafe Gather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- Note: We pass counts\/displs as Ptr CInt so that caller could supply nullPtr here\n-- which would be impossible if we marshal arrays ourselves here.\n\n-- | A variation of 'scatter' which allows to use data segments of\n-- different length.\n{# fun unsafe Scatterv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'gather' which allows to use data segments of\n-- different length.\n{# fun unsafe Gatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'gather' where all members of\n-- a group receive the result.\n{# fun unsafe Allgather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'allgather' that allows to use data segments of\n-- different length.\n{# fun unsafe Allgatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Scatter\/Gather data from all\n-- members to all members of a group (also called complete exchange)\n{# fun unsafe Alltoall as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variant of 'alltoall' allows to use data segments of different length.\n{# fun unsafe Alltoallv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\n\n-- | Applies predefined or user-defined reduction operations to data,\n-- and delivers result to the single process.\n{# fun Reduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Applies predefined or user-defined reduction operations to data,\n-- and delivers result to all members of the group.\n{# fun Allreduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A combined reduction and scatter operation - result is split and\n-- parts are distributed among the participating processes.\n--\n-- See 'reduceScatter' for variant that allows to specify personal\n-- block size for each process.\n--\n-- Note that this call is not supported with some MPI implementations,\n-- like OpenMPI <= 1.5 and would cause a run-time 'error' in that case.\n#if 0\n{# fun Reduce_scatter_block as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n#else\nreduceScatterBlock :: BufferPtr -> BufferPtr -> Count -> Datatype -> Operation -> Comm -> IO ()\nreduceScatterBlock = error \"reduceScatterBlock is not supported by OpenMPI\"\n#endif\n\n-- | A combined reduction and scatter operation - result is split and\n-- parts are distributed among the participating processes.\n{# fun Reduce_scatter as ^\n { id `BufferPtr', id `BufferPtr', id `Ptr CInt', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n\n-- TODO: In the following haddock block, mention SCAN and EXSCAN once\n-- they are implemented \n\n{- | Binds a user-dened reduction operation to an 'Operation' handle that can\nsubsequently be used in 'reduce', 'allreduce', and 'reduceScatter'.\nThe user-defined operation is assumed to be associative. \n\nIf second argument to @opCreate@ is @True@, then the operation should be both commutative and associative. If\nit is not commutative, then the order of operands is fixed and is defined to be in ascending,\nprocess rank order, beginning with process zero. The order of evaluation can be changed,\ntaking advantage of the associativity of the operation. If operation\nis commutative then the order\nof evaluation can be changed, taking advantage of commutativity and\nassociativity.\n\nUser-defined operation accepts four arguments, @invec@, @inoutvec@,\n@len@ and @datatype@:\n\n[@invec@] first input vector\n\n[@inoutvec@] second input vector, which is also the output vector\n\n[@len@] length of both vectors\n\n[@datatype@] type of the elements in both vectors.\n\nFunction is expected to apply reduction operation to the elements\nof @invec@ and @inoutvec@ in pariwise manner:\n\n@\ninoutvec[i] = op invec[i] inoutvec[i]\n@\n\nFull example with user-defined function that mimics standard operation\n'sumOp':\n\n@\nimport \"Control.Parallel.MPI.Fast\"\n\nforeign import ccall \\\"wrapper\\\" \n wrap :: (Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()) \n -> IO (FunPtr (Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()))\nreduceUserOpTest myRank = do\n numProcs <- commSize commWorld\n userSumPtr <- wrap userSum\n mySumOp <- opCreate True userSumPtr\n (src :: StorableArray Int Double) <- newListArray (0,99) [0..99]\n if myRank \/= root\n then reduceSend commWorld root sumOp src\n else do\n (result :: StorableArray Int Double) <- intoNewArray_ (0,99) $ reduceRecv commWorld root mySumOp src\n recvMsg <- getElems result\n freeHaskellFunPtr userSumPtr\n where\n userSum :: Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()\n userSum inPtr inoutPtr lenPtr _ = do\n len <- peek lenPtr\n let offs = sizeOf ( undefined :: CDouble )\n let loop 0 _ _ = return ()\n loop n inPtr inoutPtr = do\n a <- peek inPtr\n b <- peek inoutPtr\n poke inoutPtr (a+b)\n loop (n-1) (plusPtr inPtr offs) (plusPtr inoutPtr offs)\n loop len inPtr inoutPtr\n@\n-}\n{# fun unsafe Op_create as ^\n {castFunPtr `FunPtr (Ptr t -> Ptr t -> Ptr CInt -> Ptr Datatype -> IO ())', cFromEnum `Bool', alloca- `Operation' peekOperation*} -> `()' checkError*- #}\n\n{- | Free the handle for user-defined reduction operation created by 'opCreate'\n-}\n{# fun Op_free as ^ {withOperation* `Operation'} -> `()' checkError*- #}\n\n{- | Returns a \nfloating-point number of seconds, representing elapsed wallclock\ntime since some time in the past.\n\nThe \\\"time in the past\\\" is guaranteed not to change during the life of the process.\nThe user is responsible for converting large numbers of seconds to other units if they are\npreferred. The time is local to the node that calls @wtime@, but see 'wtimeIsGlobal'.\n-}\n{# fun unsafe Wtime as ^ {} -> `Double' realToFrac #}\n\n{- | Returns the resolution of 'wtime' in seconds. That is, it returns,\nas a double precision value, the number of seconds between successive clock ticks. For\nexample, if the clock is implemented by the hardware as a counter that is incremented\nevery millisecond, the value returned by @wtick@ should be 10^(-3).\n-}\n{# fun unsafe Wtick as ^ {} -> `Double' realToFrac #}\n\n-- | Return the process group from a communicator. With\n-- intercommunicator, returns the local group.\n{# fun unsafe Comm_group as ^\n {fromComm `Comm', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Returns the rank of the calling process in the given group. This function corresponds to @MPI_Group_rank@.\ngroupRank :: Group -> Rank\ngroupRank = unsafePerformIO <$> groupRank'\n where groupRank' = {# fun unsafe Group_rank as groupRank_\n {fromGroup `Group', alloca- `Rank' peekIntConv*} -> `()' checkError*- #}\n\n-- | Returns the size of a group. This function corresponds to @MPI_Group_size@.\ngroupSize :: Group -> Int\ngroupSize = unsafePerformIO <$> groupSize'\n where groupSize' = {# fun unsafe Group_size as groupSize_\n {fromGroup `Group', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Constructs the union of two groups: all the members of the first group, followed by all the members of the \n-- second group that do not appear in the first group. This function corresponds to @MPI_Group_union@.\ngroupUnion :: Group -> Group -> Group\ngroupUnion g1 g2 = unsafePerformIO $ groupUnion' g1 g2\n where groupUnion' = {# fun unsafe Group_union as groupUnion_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Constructs a new group which is the intersection of two groups. This function corresponds to @MPI_Group_intersection@.\ngroupIntersection :: Group -> Group -> Group\ngroupIntersection g1 g2 = unsafePerformIO $ groupIntersection' g1 g2\n where groupIntersection' = {# fun unsafe Group_intersection as groupIntersection_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Constructs a new group which contains all the elements of the first group which are not in the second group. \n-- This function corresponds to @MPI_Group_difference@.\ngroupDifference :: Group -> Group -> Group\ngroupDifference g1 g2 = unsafePerformIO $ groupDifference' g1 g2\n where groupDifference' = {# fun unsafe Group_difference as groupDifference_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Compares two groups. Returns 'MPI_IDENT' if the order and members of the two groups are the same,\n-- 'MPI_SIMILAR' if only the members are the same, and 'MPI_UNEQUAL' otherwise.\ngroupCompare :: Group -> Group -> ComparisonResult\ngroupCompare g1 g2 = unsafePerformIO $ groupCompare' g1 g2\n where\n groupCompare' = {# fun unsafe Group_compare as groupCompare_\n {fromGroup `Group', fromGroup `Group', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- Technically it might make better sense to make the second argument a Set rather than a list\n-- but the order is significant in the groupIncl function (the other function, not this one).\n-- For the sake of keeping their types in sync, a list is used instead.\n{- | Create a new @Group@ from the given one. Exclude processes\nwith given @Rank@s from the new @Group@. Processes in new @Group@ will\nhave ranks @[0...]@.\n-}\n{# fun unsafe Group_excl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n{- | Create a new @Group@ from the given one. Include only processes\nwith given @Rank@s in the new @Group@. Processes in new @Group@ will\nhave ranks @[0...]@.\n-}\n{# fun unsafe Group_incl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n{- | Given two @Group@s and list of @Rank@s of some processes in the\nfirst @Group@, return @Rank@s of those processes in the second\n@Group@. If there are no corresponding @Rank@ in the second @Group@,\n'mpiUndefined' is returned.\n\nThis function is important for determining the relative numbering of the same processes\nin two different groups. For instance, if one knows the ranks of certain processes in the group\nof 'commWorld', one might want to know their ranks in a subset of that group.\nNote that 'procNull' is a valid rank for input to @groupTranslateRanks@, which\nreturns 'procNull' as the translated rank.\n-}\ngroupTranslateRanks :: Group -> [Rank] -> Group -> [Rank]\ngroupTranslateRanks group1 ranks group2 =\n unsafePerformIO $ do\n let (rankIntList :: [Int]) = map fromEnum ranks\n withArrayLen rankIntList $ \\size ranksPtr ->\n allocaArray size $ \\resultPtr -> do\n groupTranslateRanks' group1 (cFromEnum size) (castPtr ranksPtr) group2 resultPtr\n map toRank <$> peekArray size resultPtr\n where\n groupTranslateRanks' = {# fun unsafe Group_translate_ranks as groupTranslateRanks_\n {fromGroup `Group', id `CInt', id `Ptr CInt', fromGroup `Group', id `Ptr CInt'} -> `()' checkError*- #}\n\nwithRanksAsInts ranks f = withArrayLen (map fromEnum ranks) $ \\size ptr -> f (cIntConv size, castPtr ptr)\n\n{- | If a process was started with 'commSpawn', @commGetParent@\nreturns the parent intercommunicator of the current process. This\nparent intercommunicator is created implicitly inside of 'init' and\nis the same intercommunicator returned by 'commSpawn' in the\nparents. If the process was not spawned, @commGetParent@ returns\n'commNull'. After the parent communicator is freed or disconnected,\n@commGetParent@ returns 'commNull'. -} \n\n{# fun unsafe Comm_get_parent as ^\n {alloca- `Comm' peekComm*} -> `()' checkError*- #}\n\nwithT = with\n{# fun unsafe Comm_spawn as ^\n { `String' \n , withT* `Ptr CChar'\n , id `Count'\n , fromInfo `Info'\n , fromRank `Rank'\n , fromComm `Comm'\n , alloca- `Comm' peekComm*\n , id `Ptr CInt'} -> `()' checkError*- #}\n\nforeign import ccall unsafe \"&mpi_argv_null\" mpiArgvNull_ :: Ptr (Ptr CChar)\nforeign import ccall unsafe \"&mpi_errcodes_ignore\" mpiErrcodesIgnore_ :: Ptr (Ptr CInt)\nargvNull = unsafePerformIO $ peek mpiArgvNull_\nerrcodesIgnore = unsafePerformIO $ peek mpiErrcodesIgnore_\n\n{-| Simplified version of `commSpawn' that does not support argument passing and spawn error code checking -}\ncommSpawnSimple rank program maxprocs =\n commSpawn program argvNull maxprocs infoNull rank commSelf errcodesIgnore\n\nforeign import ccall \"&mpi_undefined\" mpiUndefined_ :: Ptr CInt\n\n-- | Predefined constant that might be returned as @Rank@ by calls\n-- like 'groupTranslateRanks'. Corresponds to @MPI_UNDEFINED@. Please\n-- refer to \\\"MPI Report Constant And Predefined Handle Index\\\" for a\n-- list of situations where @mpiUndefined@ could appear.\nmpiUndefined :: Int\nmpiUndefined = unsafePerformIO $ peekIntConv mpiUndefined_\n\n-- | Return the number of bytes used to store an MPI @Datatype@.\ntypeSize :: Datatype -> Int\ntypeSize = unsafePerformIO . typeSize'\n where\n typeSize' =\n {# fun unsafe Type_size as typeSize_\n {fromDatatype `Datatype', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n{# fun unsafe Error_class as ^\n { id `CInt', alloca- `CInt' peek*} -> `CInt' id #}\n\n-- | Set the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_set_errhandler@.\n{# fun unsafe Comm_set_errhandler as ^\n {fromComm `Comm', fromErrhandler `Errhandler'} -> `()' checkError*- #}\n\n-- | Get the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_get_errhandler@.\n{# fun unsafe Comm_get_errhandler as ^\n {fromComm `Comm', alloca- `Errhandler' peekErrhandler*} -> `()' checkError*- #}\n\n-- | Tries to terminate all MPI processes in its communicator argument.\n-- The second argument is an error code which \/may\/ be used as the return status\n-- of the MPI process, but this is not guaranteed. On systems where 'Int' has a larger\n-- range than 'CInt', the error code will be clipped to fit into the range of 'CInt'.\n-- This function corresponds to @MPI_Abort@.\nabort :: Comm -> Int -> IO ()\nabort comm code =\n abort' comm (toErrorCode code)\n where\n toErrorCode :: Int -> CInt\n toErrorCode i\n -- Assumes Int always has range at least as big as CInt.\n | i < (fromIntegral (minBound :: CInt)) = minBound\n | i > (fromIntegral (maxBound :: CInt)) = maxBound\n | otherwise = cIntConv i\n\n abort' = {# fun unsafe Abort as abort_ {fromComm `Comm', id `CInt'} -> `()' checkError*- #}\n\n\ntype MPIDatatype = {# type MPI_Datatype #}\n\n-- | Haskell datatype used to represent @MPI_Datatype@. \n-- Please refer to Chapter 4 of MPI Report v. 2.2 for a description\n-- of various datatypes.\nnewtype Datatype = MkDatatype { fromDatatype :: MPIDatatype }\n\nforeign import ccall unsafe \"&mpi_char\" char_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_wchar\" wchar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_short\" short_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_int\" int_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long\" long_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_long\" longLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_char\" unsignedChar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_short\" unsignedShort_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned\" unsigned_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long\" unsignedLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long_long\" unsignedLongLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_float\" float_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_double\" double_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_double\" longDouble_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_byte\" byte_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_packed\" packed_ :: Ptr MPIDatatype\n\nchar, wchar, short, int, long, longLong, unsignedChar, unsignedShort :: Datatype\nunsigned, unsignedLong, unsignedLongLong, float, double, longDouble :: Datatype\nbyte, packed :: Datatype\n\nchar = MkDatatype <$> unsafePerformIO $ peek char_\nwchar = MkDatatype <$> unsafePerformIO $ peek wchar_\nshort = MkDatatype <$> unsafePerformIO $ peek short_\nint = MkDatatype <$> unsafePerformIO $ peek int_\nlong = MkDatatype <$> unsafePerformIO $ peek long_\nlongLong = MkDatatype <$> unsafePerformIO $ peek longLong_\nunsignedChar = MkDatatype <$> unsafePerformIO $ peek unsignedChar_\nunsignedShort = MkDatatype <$> unsafePerformIO $ peek unsignedShort_\nunsigned = MkDatatype <$> unsafePerformIO $ peek unsigned_\nunsignedLong = MkDatatype <$> unsafePerformIO $ peek unsignedLong_\nunsignedLongLong = MkDatatype <$> unsafePerformIO $ peek unsignedLongLong_\nfloat = MkDatatype <$> unsafePerformIO $ peek float_\ndouble = MkDatatype <$> unsafePerformIO $ peek double_\nlongDouble = MkDatatype <$> unsafePerformIO $ peek longDouble_\nbyte = MkDatatype <$> unsafePerformIO $ peek byte_\npacked = MkDatatype <$> unsafePerformIO $ peek packed_\n\ntype MPIErrhandler = {# type MPI_Errhandler #}\n\n-- | Haskell datatype that represents values usable as @MPI_Errhandler@\nnewtype Errhandler = MkErrhandler { fromErrhandler :: MPIErrhandler } deriving Storable\npeekErrhandler ptr = MkErrhandler <$> peek ptr\n\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr MPIErrhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr MPIErrhandler\n\n-- | Predefined @Errhandler@ that will terminate the process on any\n-- MPI error\nerrorsAreFatal :: Errhandler\nerrorsAreFatal = MkErrhandler <$> unsafePerformIO $ peek errorsAreFatal_\n\n-- | Predefined @Errhandler@ that will convert errors into Haskell\n-- exceptions. Mimics the semantics of @MPI_Errors_return@\nerrorsReturn :: Errhandler\nerrorsReturn = MkErrhandler <$> unsafePerformIO $ peek errorsReturn_\n\n-- | Same as 'errorsReturn', but with a more meaningful name.\nerrorsThrowExceptions :: Errhandler\nerrorsThrowExceptions = errorsReturn\n\n{# enum ErrorClass {underscoreToCase} deriving (Eq,Ord,Show,Typeable) #}\n\n-- XXX Should this be a ForeinPtr?\n-- there is a MPI_Group_free function, which we should probably\n-- call when the group is no longer referenced.\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIGroup = {# type MPI_Group #}\n\n-- | Haskell datatype representing MPI process groups.\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\npeekGroup ptr = MkGroup <$> peek ptr\n\nforeign import ccall \"&mpi_group_empty\" groupEmpty_ :: Ptr MPIGroup\n-- | A predefined group without any members. Corresponds to @MPI_GROUP_EMPTY@.\ngroupEmpty :: Group\ngroupEmpty = MkGroup <$> unsafePerformIO $ peek groupEmpty_\n\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIOperation = {# type MPI_Op #}\n\n{- | Abstract type representing handle for MPI reduction operation\n(that can be used with 'reduce', 'allreduce', and 'reduceScatter').\n-}\nnewtype Operation = MkOperation { fromOperation :: MPIOperation } deriving Storable\npeekOperation ptr = MkOperation <$> peek ptr\nwithOperation op f = alloca $ \\ptr -> do poke ptr (fromOperation op)\n f (castPtr ptr)\n\nforeign import ccall unsafe \"&mpi_max\" maxOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_min\" minOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_sum\" sumOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_prod\" prodOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_land\" landOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_band\" bandOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lor\" lorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bor\" borOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lxor\" lxorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bxor\" bxorOp_ :: Ptr MPIOperation\n-- foreign import ccall \"mpi_maxloc\" maxlocOp :: MPIOperation\n-- foreign import ccall \"mpi_minloc\" minlocOp :: MPIOperation\n-- foreign import ccall \"mpi_replace\" replaceOp :: MPIOperation\n-- TODO: support for those requires better support for pair datatypes\n\n-- | Predefined reduction operation: maximum\nmaxOp :: Operation\nmaxOp = MkOperation <$> unsafePerformIO $ peek maxOp_\n\n-- | Predefined reduction operation: minimum\nminOp :: Operation\nminOp = MkOperation <$> unsafePerformIO $ peek minOp_\n\n-- | Predefined reduction operation: (+)\nsumOp :: Operation\nsumOp = MkOperation <$> unsafePerformIO $ peek sumOp_\n\n-- | Predefined reduction operation: (*)\nprodOp :: Operation\nprodOp = MkOperation <$> unsafePerformIO $ peek prodOp_\n\n-- | Predefined reduction operation: logical \\\"and\\\"\nlandOp :: Operation\nlandOp = MkOperation <$> unsafePerformIO $ peek landOp_\n\n-- | Predefined reduction operation: bit-wise \\\"and\\\"\nbandOp :: Operation\nbandOp = MkOperation <$> unsafePerformIO $ peek bandOp_\n\n-- | Predefined reduction operation: logical \\\"or\\\"\nlorOp :: Operation\nlorOp = MkOperation <$> unsafePerformIO $ peek lorOp_\n\n-- | Predefined reduction operation: bit-wise \\\"or\\\"\nborOp :: Operation\nborOp = MkOperation <$> unsafePerformIO $ peek borOp_\n\n-- | Predefined reduction operation: logical \\\"xor\\\"\nlxorOp :: Operation\nlxorOp = MkOperation <$> unsafePerformIO $ peek lxorOp_\n\n-- | Predefined reduction operation: bit-wise \\\"xor\\\"\nbxorOp :: Operation\nbxorOp = MkOperation <$> unsafePerformIO $ peek bxorOp_\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIInfo = {# type MPI_Info #}\n\n{- | Abstract type representing handle for MPI Info object\n-}\nnewtype Info = MkInfo { fromInfo :: MPIInfo } deriving Storable\npeekInfo ptr = MkInfo <$> peek ptr\n\nforeign import ccall \"&mpi_info_null\" infoNull_ :: Ptr MPIInfo\n\n-- | Predefined info object that has no info\ninfoNull :: Info\ninfoNull = unsafePerformIO $ peekInfo infoNull_\n\n{-| Creates new empty info object -}\n{# fun unsafe Info_create as ^\n {alloca- `Info' peekInfo*} -> `()' checkError*- #}\n\n{-| Adds specified (key, value) pair to info object -}\n{# fun unsafe Info_set as ^\n {fromInfo `Info', `String', `String'} -> `()' checkError*- #}\n\n{-| Deletes the specified key from info object -}\n{# fun unsafe Info_delete as ^\n {fromInfo `Info', `String'} -> `()' checkError*- #}\n\n{-| Gets the specified key -}\ninfoGet :: Info -> String -> IO (Maybe String)\ninfoGet info key = do\n (len, found) <- infoGetValuelen' info key \n -- len+1 is required to allow for the terminating \\NULL\n if found\/=0 then allocaBytes (fromIntegral len + 1)\n (\\bufferPtr -> do\n found <- infoGet' info key (len+1) bufferPtr\n if found\/=0 then Just <$> peekCStringLen (bufferPtr, fromIntegral len)\n else return Nothing)\n else return Nothing\n\ninfoGetValuelen' = {# fun unsafe Info_get_valuelen as infoGetValuelen_\n {fromInfo `Info', `String', alloca- `CInt' peek*, alloca- `CInt' peek* } -> `()' checkError*- #}\n\ninfoGet' = {# fun unsafe Info_get as infoGet_\n {fromInfo `Info', `String', id `CInt', castPtr `Ptr CChar', alloca- `CInt' peek*} -> `()' checkError*- #}\n\n\n{- | Haskell datatype that represents values which\n could be used as MPI rank designations. Low-level MPI calls require\n that you use 32-bit non-negative integer values as ranks, so any\n non-numeric Haskell Ranks should provide a sensible instances of\n 'Enum'.\n\nAttempt to supply a value that does not fit into 32 bits will cause a\nrun-time 'error'.\n-}\nnewtype Rank = MkRank { rankId :: CInt -- ^ Extract numeric value of the 'Rank'\n }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Rank where\n (MkRank x) + (MkRank y) = MkRank (x+y)\n (MkRank x) * (MkRank y) = MkRank (x*y)\n abs (MkRank x) = MkRank (abs x)\n signum (MkRank x) = MkRank (signum x)\n fromInteger x\n | x > ( fromIntegral (maxBound :: CInt)) = error \"Rank value does not fit into 32 bits\"\n | x < 0 = error \"Negative Rank value\"\n | otherwise = MkRank (fromIntegral x)\n\nforeign import ccall \"&mpi_any_source\" anySource_ :: Ptr CInt\nforeign import ccall \"&mpi_root\" theRoot_ :: Ptr CInt\nforeign import ccall \"&mpi_proc_null\" procNull_ :: Ptr CInt\nforeign import ccall \"&mpi_request_null\" requestNull_ :: Ptr MPIRequest\nforeign import ccall \"&mpi_comm_null\" commNull_ :: Ptr MPIComm\n\n-- | Predefined rank number that allows reception of point-to-point messages\n-- regardless of their source. Corresponds to @MPI_ANY_SOURCE@\nanySource :: Rank\nanySource = toRank $ unsafePerformIO $ peek anySource_\n\n-- | Predefined rank number that specifies root process during\n-- operations involving intercommunicators. Corresponds to @MPI_ROOT@\ntheRoot :: Rank\ntheRoot = toRank $ unsafePerformIO $ peek theRoot_\n\n-- | Predefined rank number that specifies non-root processes during\n-- operations involving intercommunicators. Corresponds to @MPI_PROC_NULL@\nprocNull :: Rank\nprocNull = toRank $ unsafePerformIO $ peek procNull_\n\n-- | Predefined request handle value that specifies non-existing or finished request.\n-- Corresponds to @MPI_REQUEST_NULL@\nrequestNull :: Request\nrequestNull = unsafePerformIO $ peekRequest requestNull_\n\n-- | Predefined communicator handle value that specifies non-existing or destroyed (inter-)communicator.\n-- Corresponds to @MPI_COMM_NULL@\ncommNull :: Comm\ncommNull = unsafePerformIO $ peekComm commNull_\n\ninstance Show Rank where\n show = show . rankId\n\n-- | Map arbitrary 'Enum' value to 'Rank'\ntoRank :: Enum a => a -> Rank\ntoRank x = MkRank { rankId = cIntConv (fromEnum x) }\n\n-- | Map 'Rank' to arbitrary 'Enum'\nfromRank :: Enum a => Rank -> a\nfromRank = toEnum . cIntConv . rankId\n\ntype MPIRequest = {# type MPI_Request #}\n{-| Haskell representation of the @MPI_Request@ type. Returned by\nnon-blocking communication operations, could be further processed with\n'probe', 'test', 'cancel' or 'wait'. -}\nnewtype Request = MkRequest MPIRequest deriving (Storable,Eq)\npeekRequest ptr = MkRequest <$> peek ptr\n\n{-\nThis module provides Haskell representation of the @MPI_Status@ type\n(request status).\n\nField `status_error' should be used with care:\n\\\"The error field in status is not needed for calls that return only\none status, such as @MPI_WAIT@, since that would only duplicate the\ninformation returned by the function itself. The current design avoids\nthe additional overhead of setting it, in such cases. The field is\nneeded for calls that return multiple statuses, since each request may\nhave had a different failure.\\\"\n(this is a quote from )\n\nThis means that, for example, during the call to @MPI_Wait@\nimplementation is free to leave this field filled with whatever\ngarbage got there during memory allocation. Haskell FFI is not\nblanking out freshly allocated memory, so beware!\n-}\n\n-- | Haskell structure that holds fields of @MPI_Status@.\ndata Status =\n Status\n { status_source :: Rank -- ^ rank of the source process\n , status_tag :: Tag -- ^ tag assigned at source\n , status_error :: CInt -- ^ error code, if any\n }\n deriving (Eq, Ord, Show)\n\ninstance Storable Status where\n sizeOf _ = {#sizeof MPI_Status #}\n alignment _ = 4\n peek p = Status\n <$> liftM (MkRank . cIntConv) ({#get MPI_Status->MPI_SOURCE #} p)\n <*> liftM (MkTag . cIntConv) ({#get MPI_Status->MPI_TAG #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_ERROR #} p)\n poke p x = do\n {#set MPI_Status.MPI_SOURCE #} p (fromRank $ status_source x)\n {#set MPI_Status.MPI_TAG #} p (fromTag $ status_tag x)\n {#set MPI_Status.MPI_ERROR #} p (cIntConv $ status_error x)\n\n-- NOTE: Int here is picked arbitrary\nallocaCast f =\n alloca $ \\(ptr :: Ptr Int) -> f (castPtr ptr :: Ptr ())\npeekCast = peek . castPtr\n\n\n{-| Haskell datatype that represents values which could be used as\ntags for point-to-point transfers.\n-}\nnewtype Tag = MkTag { tagVal :: CInt -- ^ Extract numeric value of the Tag\n }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Tag where\n (MkTag x) + (MkTag y) = MkTag (x+y)\n (MkTag x) * (MkTag y) = MkTag (x*y)\n abs (MkTag x) = MkTag (abs x)\n signum (MkTag x) = MkTag (signum x)\n fromInteger x\n | fromIntegral x > tagUpperBound = error \"Tag value is over the MPI_TAG_UB\"\n | x < 0 = error \"Negative Tag value\"\n | otherwise = MkTag (fromIntegral x)\n\ninstance Show Tag where\n show = show . tagVal\n\n-- | Map arbitrary 'Enum' value to 'Tag'\ntoTag :: Enum a => a -> Tag\ntoTag x = MkTag { tagVal = cIntConv (fromEnum x) }\n\n-- | Map 'Tag' to arbitrary 'Enum'\nfromTag :: Enum a => Tag -> a\nfromTag = toEnum . cIntConv . tagVal\n\nforeign import ccall unsafe \"&mpi_any_tag\" anyTag_ :: Ptr CInt\n\n-- | Predefined tag value that allows reception of the messages with\n-- arbitrary tag values. Corresponds to @MPI_ANY_TAG@.\nanyTag :: Tag\nanyTag = toTag $ unsafePerformIO $ peek anyTag_\n\n-- | A tag with unit value. Intended to be used as a convenient default.\nunitTag :: Tag\nunitTag = toTag ()\n\n{- | Constants used to describe the required level of multithreading\n support in call to 'initThread'. They also describe provided level\n of multithreading support as returned by 'queryThread' and\n 'initThread'.\n\n[@Single@] Only one thread will execute.\n\n[@Funneled@] The process may be multi-threaded, but the application must\nensure that only the main thread makes MPI calls (see 'isThreadMain').\n\n[@Serialized@] The process may be multi-threaded, and multiple threads may\nmake MPI calls, but only one at a time: MPI calls are not made concurrently from\ntwo distinct threads\n\n[@Multiple@] Multiple threads may call MPI, with no restrictions.\n\nXXX Make sure we have the correct ordering as defined by MPI. Also we should\ndescribe the ordering here (other parts of the docs need it to be explained - see initThread).\n\n-}\n{# enum ThreadSupport {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- | Value thrown as exception when MPI runtime is instructed to pass\n-- errors to user code (via 'commSetErrhandler' and 'errorsReturn').\n-- Since raw MPI errors codes are not standartized and not portable,\n-- they are not exposed.\ndata MPIError\n = MPIError\n { mpiErrorClass :: ErrorClass -- ^ Broad class of errors this one belongs to\n , mpiErrorString :: String -- ^ Human-readable error description\n }\n deriving (Eq, Show, Typeable)\n\ninstance Exception MPIError\n\ncheckError :: CInt -> IO ()\ncheckError code = do\n -- We ignore the error code from the call to Internal.errorClass\n -- because we call errorClass from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n (_, errClassRaw) <- errorClass code\n let errClass = cToEnum errClassRaw\n unless (errClass == Success) $ do\n errStr <- errorString code\n throwIO $ MPIError errClass errStr\n\n-- | Convert MPI error code human-readable error description. Corresponds to @MPI_Error_string@.\nerrorString :: CInt -> IO String\nerrorString code =\n allocaBytes (fromIntegral maxErrorString) $ \\ptr ->\n alloca $ \\lenPtr -> do\n -- We ignore the error code from the call to Internal.errorString\n -- because we call errorString from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n _ <- errorString' code ptr lenPtr\n len <- peek lenPtr\n peekCStringLen (ptr, cIntConv len)\n where\n errorString' = {# call unsafe Error_string as errorString_ #}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n#include \n#include \"init_wrapper.h\"\n#include \"comparison_result.h\"\n#include \"error_classes.h\"\n#include \"thread_support.h\"\n-----------------------------------------------------------------------------\n{- |\nModule : Control.Parallel.MPI.Internal\nCopyright : (c) 2010 Bernie Pope, Dmitry Astapov\nLicense : BSD-style\nMaintainer : florbitous@gmail.com\nStability : experimental\nPortability : ghc\n\nThis module contains low-level Haskell bindings to core MPI functions.\nAll Haskell functions correspond to MPI functions or values with the similar\nname (i.e. @commRank@ is the binding for @MPI_Comm_rank@ etc)\n\nNote that most of this module is re-exported by\n\"Control.Parallel.MPI\", so if you are not interested in writing\nlow-level code, you should probably import \"Control.Parallel.MPI\" and\neither \"Control.Parallel.MPI.Storable\" or \"Control.Parallel.MPI.Serializable\".\n-}\n-----------------------------------------------------------------------------\nmodule Control.Parallel.MPI.Internal\n (\n\n -- * MPI runtime management.\n -- ** Initialization, finalization, termination.\n init, finalize, initialized, finalized, abort,\n -- ** Multi-threaded environment support.\n ThreadSupport (..), initThread, queryThread, isThreadMain,\n\n -- ** Runtime attributes.\n getProcessorName, Version (..), getVersion, Implementation(..), getImplementation, universeSize,\n\n -- ** Info objects\n Info, infoNull, infoCreate, infoSet, infoDelete, infoGet,\n\n -- * Requests and statuses.\n Request, Status (..), getCount, test, testPtr, cancel, cancelPtr, wait, waitPtr, waitall, requestNull, \n\n -- * Process management.\n -- ** Communicators.\n Comm, commWorld, commSelf, commNull, commTestInter,\n commSize, commRemoteSize, \n commRank, \n commCompare, commGroup, commGetAttr,\n\n -- ** Process groups.\n Group, groupEmpty, groupRank, groupSize, groupUnion,\n groupIntersection, groupDifference, groupCompare, groupExcl,\n groupIncl, groupTranslateRanks,\n -- ** Comparisons.\n ComparisonResult (..),\n\n -- ** Dynamic process management\n commGetParent, commSpawn, commSpawnSimple, argvNull, errcodesIgnore,\n\n -- * Error handling.\n Errhandler, errorsAreFatal, errorsReturn, errorsThrowExceptions, commSetErrhandler, commGetErrhandler,\n ErrorClass (..), MPIError(..), mpiUndefined,\n\n -- * Ranks.\n Rank, rankId, toRank, fromRank, anySource, theRoot, procNull,\n\n -- * Data types.\n Datatype, char, wchar, short, int, long, longLong, unsignedChar, unsignedShort, unsigned, unsignedLong, unsignedLongLong, float, double, longDouble, byte, packed, typeSize,\n\n -- * Point-to-point operations.\n -- ** Tags.\n Tag, toTag, fromTag, anyTag, unitTag, tagUpperBound,\n\n -- ** Blocking operations.\n BufferPtr, Count, -- XXX: what will break if we don't export those?\n send, ssend, rsend, recv,\n -- ** Non-blocking operations.\n isend, issend, irecv,\n isendPtr, issendPtr, irecvPtr,\n\n\n -- * Collective operations.\n -- ** One-to-all.\n bcast, scatter, scatterv,\n -- ** All-to-one.\n gather, gatherv, reduce,\n -- ** All-to-all.\n allgather, allgatherv,\n alltoall, alltoallv,\n allreduce, \n reduceScatterBlock,\n reduceScatter,\n barrier,\n\n -- ** Reduction operations.\n Operation, maxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp,\n opCreate, opFree,\n\n -- * Timing.\n wtime, wtick, wtimeIsGlobal, wtimeIsGlobalKey\n\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Data.Maybe (fromMaybe)\nimport Control.Monad (liftM, unless)\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception\n\n{# context prefix = \"MPI\" #}\n\n-- | Pointer to memory buffer that either holds data to be sent or is\n-- used to receive some data. You would\n-- probably have to use 'castPtr' to pass some actual pointers to\n-- API functions.\ntype BufferPtr = Ptr ()\n\n-- | Count of elements in the send\/receive buffer\ntype Count = CInt\n\n{- |\nHaskell enum that contains MPI constants\n@MPI_IDENT@, @MPI_CONGRUENT@, @MPI_SIMILAR@ and @MPI_UNEQUAL@.\n\nThose are used to compare communicators ('commCompare') and\nprocess groups ('groupCompare'). Refer to those\nfunctions for description of comparison rules.\n-}\n{# enum ComparisonResult {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- Which Haskell type will be used as Comm depends on the MPI\n-- implementation that was selected during compilation. It could be\n-- CInt, Ptr (), Ptr CInt or something else.\ntype MPIComm = {# type MPI_Comm #}\n\n{- | Abstract type representing MPI communicator handle. Different MPI\n implementations use different C types to implement this, so\n concrete Haskell type behind @Comm@ is hidden from user.\n\n In any MPI program you have predefined communicator 'commWorld'\n which includes all running processes. You could create new\n communicators with TODO\n-}\nnewtype Comm = MkComm { fromComm :: MPIComm } deriving Eq\npeekComm ptr = MkComm <$> peek ptr\n\nforeign import ccall \"&mpi_comm_world\" commWorld_ :: Ptr MPIComm\nforeign import ccall \"&mpi_comm_self\" commSelf_ :: Ptr MPIComm\n\n-- | Predefined handle for communicator that includes all running\n-- processes. Similar to @MPI_Comm_world@\ncommWorld :: Comm\ncommWorld = MkComm <$> unsafePerformIO $ peek commWorld_\n\n-- | Predefined handle for communicator that includes only current\n-- process. Similar to @MPI_Comm_self@\ncommSelf :: Comm\ncommSelf = MkComm <$> unsafePerformIO $ peek commSelf_\n\nforeign import ccall \"&mpi_max_processor_name\" max_processor_name_ :: Ptr CInt\nforeign import ccall \"&mpi_max_error_string\" max_error_string_ :: Ptr CInt\n\n-- | Max length of \"processor name\" as returned by 'getProcessorName'\nmaxProcessorName :: CInt\nmaxProcessorName = unsafePerformIO $ peek max_processor_name_\n\n-- | Max length of error description as returned by 'errorString'\nmaxErrorString :: CInt\nmaxErrorString = unsafePerformIO $ peek max_error_string_\n\n-- | Initialize the MPI environment. The MPI environment must be intialized by each\n-- MPI process before any other MPI function is called. Note that\n-- the environment may also be initialized by the functions 'initThread', 'mpi',\n-- and 'mpiWorld'. It is an error to attempt to initialize the environment more\n-- than once for a given MPI program execution. The only MPI functions that may\n-- be called before the MPI environment is initialized are 'getVersion',\n-- 'initialized' and 'finalized'. This function corresponds to @MPI_Init@.\n{# fun unsafe init_wrapper as init {} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been initialized. Returns @True@ if the\n-- environment has been initialized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Initialized@.\n{# fun unsafe Initialized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been finalized. Returns @True@ if the\n-- environment has been finalized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Finalized@.\n{# fun unsafe Finalized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Initialize the MPI environment with a \/required\/ level of thread support.\n-- See the documentation for 'init' for more information about MPI initialization.\n-- The \/provided\/ level of thread support is returned in the result.\n-- There is no guarantee that provided will be greater than or equal to required.\n-- The level of provided thread support depends on the underlying MPI implementation,\n-- and may also depend on information provided when the program is executed\n-- (for example, by supplying appropriate arguments to @mpiexec@).\n-- If the required level of support cannot be provided then it will try to\n-- return the least supported level greater than what was required.\n-- If that cannot be satisfied then it will return the highest supported level\n-- provided by the MPI implementation. See the documentation for 'ThreadSupport'\n-- for information about what levels are available and their relative ordering.\n-- This function corresponds to @MPI_Init_thread@.\n{# fun unsafe init_wrapper_thread as initThread\n {cFromEnum `ThreadSupport', alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\n-- | Returns the current provided level of thread support. This will be the value\n-- returned as \\\"provided level of support\\\" by 'initThread' as well. This function\n-- corresponds to @MPI_Query_thread@.\n{# fun unsafe Query_thread as ^ {alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\n-- | This function can be called by a thread to find out whether it is the main thread (the\n-- thread that called 'init' or 'initThread'.\n{# fun unsafe Is_thread_main as ^\n {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Terminate the MPI execution environment.\n-- Once 'finalize' is called no other MPI functions may be called except\n-- 'getVersion', 'initialized' and 'finalized', however non-MPI computations\n-- may continue. Each process must complete\n-- any pending communication that it initiated before calling 'finalize'.\n-- Note: the error code returned\n-- by 'finalize' is not checked. This function corresponds to @MPI_Finalize@.\n{# fun unsafe Finalize as ^ {} -> `()' discard*- #}\ndiscard _ = return ()\n-- XXX can't call checkError on finalize, because\n-- checkError calls Internal.errorClass and Internal.errorString.\n-- These cannot be called after finalize (at least on OpenMPI).\n\n-- | Return the name of the current processing host. From this value it\n-- must be possible to identify a specific piece of hardware on which\n-- the code is running.\ngetProcessorName :: IO String\ngetProcessorName = do\n allocaBytes (fromIntegral maxProcessorName) $ \\ptr -> do\n len <- getProcessorName' ptr\n peekCStringLen (ptr, cIntConv len)\n where\n getProcessorName' = {# fun unsafe Get_processor_name as getProcessorName_\n {id `Ptr CChar', alloca- `CInt' peekIntConv*} -> `()' checkError*- #}\n\n-- | MPI implementation version\ndata Version =\n Version { version :: Int, subversion :: Int }\n deriving (Eq, Ord)\n\ninstance Show Version where\n show v = show (version v) ++ \".\" ++ show (subversion v)\n\n-- | Which MPI version the code is running on.\ngetVersion :: IO Version\ngetVersion = do\n (version, subversion) <- getVersion'\n return $ Version version subversion\n where\n getVersion' = {# fun unsafe Get_version as getVersion_\n {alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Supported MPI implementations\ndata Implementation = MPICH2 | OpenMPI deriving (Eq,Show)\n\n-- | Which MPI implementation was used during linking\ngetImplementation :: Implementation\ngetImplementation =\n#ifdef MPICH2\n MPICH2\n#else\n OpenMPI\n#endif\n\n-- | Return the number of processes involved in a communicator. For 'commWorld'\n-- it returns the total number of processes available. If the communicator is\n-- and intra-communicator it returns the number of processes in the local group.\n-- This function corresponds to @MPI_Comm_size@.\n{# fun unsafe Comm_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n-- | For intercommunicators, returns size of the remote process group.\n-- Corresponds to @MPI_Comm_remote_size@.\n{# fun unsafe Comm_remote_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n{- | Check whether the given communicator is intercommunicator - that\n is, communicator connecting two different groups of processes.\n\nRefer to MPI Report v2.2, Section 5.2 \"Communicator Argument\" for\nmore details.\n-}\n{# fun unsafe Comm_test_inter as ^\n {fromComm `Comm', alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Look up MPI communicator argument by the given numeric key.\n-- Lookup of some standard MPI arguments is provided by convenience\n-- functions 'tagUpperBound' and 'wtimeIsGlobal'.\ncommGetAttr :: Storable e => Comm -> Int -> IO (Maybe e)\ncommGetAttr comm key = do\n isInitialized <- initialized\n if isInitialized then do\n alloca $ \\ptr -> do\n found <- commGetAttr' comm key (castPtr ptr)\n if found then do ptr2 <- peek ptr\n Just <$> peek ptr2\n else return Nothing\n else return Nothing\n where\n commGetAttr' = {# fun unsafe Comm_get_attr as commGetAttr_\n {fromComm `Comm', cIntConv `Int', id `Ptr ()', alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Maximum tag value supported by the current MPI implementation. Corresponds to the value of standard MPI\n-- attribute @MPI_TAG_UB@.\n--\n-- When called before 'init' or 'initThread' would return 0.\ntagUpperBound :: Int\ntagUpperBound =\n let key = unsafePerformIO (peek tagUB_)\n in fromMaybe 0 $ unsafePerformIO (commGetAttr commWorld key)\n\nforeign import ccall unsafe \"&mpi_tag_ub\" tagUB_ :: Ptr Int\n\n{- | True if clocks at all processes in\n'commWorld' are synchronized, False otherwise. The expectation is that\nthe variation in time, as measured by calls to 'wtime', will be less then one half the\nround-trip time for an MPI message of length zero. \n\nCommunicators other than 'commWorld' could have different clocks.\nYou could find it out by querying attribute 'wtimeIsGlobalKey' with 'commGetAttr'.\n\nWhen wtimeIsGlobal is called before 'init' or 'initThread' it would return False.\n-}\nwtimeIsGlobal :: Bool\nwtimeIsGlobal =\n fromMaybe False $ unsafePerformIO (commGetAttr commWorld wtimeIsGlobalKey)\n\nforeign import ccall unsafe \"&mpi_wtime_is_global\" wtimeIsGlobal_ :: Ptr Int\n\n-- | Numeric key for standard MPI communicator attribute @MPI_WTIME_IS_GLOBAL@.\n-- To be used with 'commGetAttr'.\nwtimeIsGlobalKey :: Int\nwtimeIsGlobalKey = unsafePerformIO (peek wtimeIsGlobal_)\n\n{- | \nMany ``dynamic'' MPI applications are expected to exist in a static runtime environment, in which resources have been allocated before the application is run. When a user (or possibly a batch system) runs one of these quasi-static applications, she will usually specify a number of processes to start and a total number of processes that are expected. An application simply needs to know how many slots there are, i.e., how many processes it should spawn.\n\nThis attribute indicates the total number of processes that are expected.\n\nWhen universeSize is called before 'init' or 'initThread' it would return False.\n-}\nuniverseSize :: Comm -> IO (Maybe Int)\nuniverseSize c =\n commGetAttr c universeSizeKey\n\nforeign import ccall unsafe \"&mpi_universe_size\" universeSize_ :: Ptr Int\n\n-- | Numeric key for recommended MPI communicator attribute @MPI_UNIVERSE_SIZE@.\n-- To be used with 'commGetAttr'.\nuniverseSizeKey :: Int\nuniverseSizeKey = unsafePerformIO (peek universeSize_)\n\n-- | Return the rank of the calling process for the given\n-- communicator. If it is an intercommunicator, returns rank of the\n-- process in the local group.\n{# fun unsafe Comm_rank as ^\n {fromComm `Comm', alloca- `Rank' peekIntConv* } -> `()' checkError*- #}\n\n{- | Compares two communicators.\n\n* If they are handles for the same MPI communicator object, result is 'Identical';\n\n* If both communicators are identical in constituents and rank\n order, result is `Congruent';\n\n* If they have the same members, but with different ranks, then\n result is 'Similar';\n\n* Otherwise, result is 'Unequal'.\n\n-}\n{# fun unsafe Comm_compare as ^\n {fromComm `Comm', fromComm `Comm', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- | Test for an incomming message, without actually receiving it.\n-- If a message has been sent from @Rank@ to the current process with @Tag@ on the\n-- communicator @Comm@ then 'probe' will return the 'Status' of the message. Otherwise\n-- it will block the current process until such a matching message is sent.\n-- This allows the current process to check for an incoming message and decide\n-- how to receive it, based on the information in the 'Status'.\n-- This function corresponds to @MPI_Probe@.\n-- The most common usecase is to call @probe@ first and then use 'getCount' to find out size of incoming message.\n-- However since different implementations provide additional fields in @Status@, we cannot deserialize Status into Haskell land\n-- and serialize it back without losing information. Hence the use of Ptr Status.\n{# fun Probe as ^\n {fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Status'} -> `()' checkError*- #}\n{- probe :: Rank -- ^ Rank of the sender.\n -> Tag -- ^ Tag of the sent message.\n -> Comm -- ^ Communicator.\n -> IO Status -- ^ Information about the incoming message (but not the content of the message). -}\n\n{-| Returns the number of entries received. (we count entries, each of\ntype @Datatype@, not bytes.) The datatype argument should match the\nargument provided by the receive call that set the status variable. -}\ngetCount :: Comm -> Rank -> Tag -> Datatype -> IO Int\ngetCount comm rank tag datatype =\n alloca $ \\statusPtr -> do\n probe rank tag comm statusPtr\n cnt <- getCount' statusPtr datatype\n return $ fromIntegral cnt\n where\n getCount' = {# fun unsafe Get_count as getCount_\n {castPtr `Ptr Status', fromDatatype `Datatype', alloca- `CInt' peekIntConv*} -> `()' checkError*- #}\n\n\n{-| Send the values (as specified by @BufferPtr@, @Count@, @Datatype@) to\n the process specified by (@Comm@, @Rank@, @Tag@). Caller will\n block until data is copied from the send buffer by the MPI\n-}\n{# fun unsafe Send as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{-| Variant of 'send' that would terminate only when receiving side\nactually starts receiving data. \n-}\n{# fun unsafe Ssend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{-| Variant of 'send' that expects the relevant 'recv' to be already\nstarted, otherwise this call could terminate with MPI error.\n-}\n{# fun unsafe Rsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n-- | Receives data from the process\n-- specified by (@Comm@, @Rank@, @Tag@) and stores it into buffer specified\n-- by (@BufferPtr@, @Count@, @Datatype@).\n{# fun unsafe Recv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast* } -> `()' checkError*- #}\n-- | Send the values (as specified by @BufferPtr@, @Count@, @Datatype@) to\n-- the process specified by (@Comm@, @Rank@, @Tag@) in non-blocking mode.\n-- \n-- Use 'probe' or 'test' to check the status of the operation,\n-- 'cancel' to terminate it or 'wait' to block until it completes.\n-- Operation would be considered complete as soon as MPI finishes\n-- copying the data from the send buffer. \n{# fun unsafe Isend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n-- | Variant of the 'isend' that would be considered complete only when\n-- receiving side actually starts receiving data. \n{# fun unsafe Issend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n-- | Non-blocking variant of 'recv'. Receives data from the process\n-- specified by (@Comm@, @Rank@, @Tag@) and stores it into buffer specified\n-- by (@BufferPtr@, @Count@, @Datatype@).\n{# fun Irecv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n\n-- | Like 'isend', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun unsafe Isend as isendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'issend', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun unsafe Issend as issendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'irecv', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun Irecv as irecvPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Broadcast data from one member to all members of the communicator.\n{# fun unsafe Bcast as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocks until all processes on the communicator call this function.\n-- This function corresponds to @MPI_Barrier@.\n{# fun unsafe Barrier as ^ {fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocking test for the completion of a send of receive.\n-- See 'test' for a non-blocking variant.\n-- This function corresponds to @MPI_Wait@. Request pointer could\n-- be changed to point to @requestNull@. See @wait@ for variant that does not mutate request value.\n{# fun unsafe Wait as waitPtr\n {castPtr `Ptr Request', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Same as @waitPtr@, but does not change Haskell @Request@ value to point to @procNull@.\n-- Usually, this is harmless - your request just would be considered inactive.\nwait request = withRequest request waitPtr\n\n-- | Takes pointer to the array of Requests of given size, 'wait's on all of them,\n-- populates array of Statuses of the same size. This function corresponds to @MPI_Waitall@\n{# fun unsafe Waitall as ^\n { id `Count', castPtr `Ptr Request', castPtr `Ptr Status'} -> `()' checkError*- #}\n-- TODO: Make this Storable Array instead of Ptr ?\n\n-- | Non-blocking test for the completion of a send or receive.\n-- Returns @Nothing@ if the request is not complete, otherwise\n-- it returns @Just status@.\n--\n-- Note that while MPI would modify\n-- request to be @requestNull@ if the operation is complete,\n-- Haskell value would not be changed. So, if you got (Just status)\n-- as a result, consider your request to be @requestNull@. Or use @testPtr@.\n--\n-- See 'wait' for a blocking variant.\n-- This function corresponds to @MPI_Test@.\ntest :: Request -> IO (Maybe Status)\ntest request = withRequest request testPtr\n\n-- | Analogous to 'test' but uses pointer to @Request@. If request is completed, pointer would be \n-- set to point to @requestNull@.\ntestPtr :: Ptr Request -> IO (Maybe Status)\ntestPtr reqPtr = do\n (flag, status) <- testPtr' reqPtr\n request' <- peek reqPtr\n if flag\n then do if request' == requestNull\n then return $ Just status\n else error \"testPtr: request modified, but not set to MPI_REQUEST_NULL!\"\n else return Nothing\n where testPtr' = {# fun unsafe Test as testPtr_\n {castPtr `Ptr Request', alloca- `Bool' peekBool*, allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Cancel a pending communication request.\n-- This function corresponds to @MPI_Cancel@. Sets pointer to point to @requestNull@.\n{# fun unsafe Cancel as cancelPtr\n {castPtr `Ptr Request'} -> `()' checkError*- #}\n\n\n-- | Same as @cancelPtr@, but does not change Haskell @Request@ value to point to @procNull@.\n-- Usually, this is harmless - your request just would be considered inactive.\ncancel request = withRequest request cancelPtr\n\nwithRequest req f = do alloca $ \\ptr -> do poke ptr req\n f (castPtr ptr)\n\n-- | Scatter data from one member to all members of\n-- a group.\n{# fun unsafe Scatter as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Gather data from all members of a group to one\n-- member.\n{# fun unsafe Gather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- Note: We pass counts\/displs as Ptr CInt so that caller could supply nullPtr here\n-- which would be impossible if we marshal arrays ourselves here.\n\n-- | A variation of 'scatter' which allows to use data segments of\n-- different length.\n{# fun unsafe Scatterv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'gather' which allows to use data segments of\n-- different length.\n{# fun unsafe Gatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'gather' where all members of\n-- a group receive the result.\n{# fun unsafe Allgather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'allgather' that allows to use data segments of\n-- different length.\n{# fun unsafe Allgatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Scatter\/Gather data from all\n-- members to all members of a group (also called complete exchange)\n{# fun unsafe Alltoall as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variant of 'alltoall' allows to use data segments of different length.\n{# fun unsafe Alltoallv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\n\n-- | Applies predefined or user-defined reduction operations to data,\n-- and delivers result to the single process.\n{# fun Reduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Applies predefined or user-defined reduction operations to data,\n-- and delivers result to all members of the group.\n{# fun Allreduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A combined reduction and scatter operation - result is split and\n-- parts are distributed among the participating processes.\n--\n-- See 'reduceScatter' for variant that allows to specify personal\n-- block size for each process.\n--\n-- Note that this call is not supported with some MPI implementations,\n-- like OpenMPI <= 1.5 and would cause a run-time 'error' in that case.\n#if 0\n{# fun Reduce_scatter_block as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n#else\nreduceScatterBlock :: BufferPtr -> BufferPtr -> Count -> Datatype -> Operation -> Comm -> IO ()\nreduceScatterBlock = error \"reduceScatterBlock is not supported by OpenMPI\"\n#endif\n\n-- | A combined reduction and scatter operation - result is split and\n-- parts are distributed among the participating processes.\n{# fun Reduce_scatter as ^\n { id `BufferPtr', id `BufferPtr', id `Ptr CInt', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n\n-- TODO: In the following haddock block, mention SCAN and EXSCAN once\n-- they are implemented \n\n{- | Binds a user-dened reduction operation to an 'Operation' handle that can\nsubsequently be used in 'reduce', 'allreduce', and 'reduceScatter'.\nThe user-defined operation is assumed to be associative. \n\nIf second argument to @opCreate@ is @True@, then the operation should be both commutative and associative. If\nit is not commutative, then the order of operands is fixed and is defined to be in ascending,\nprocess rank order, beginning with process zero. The order of evaluation can be changed,\ntaking advantage of the associativity of the operation. If operation\nis commutative then the order\nof evaluation can be changed, taking advantage of commutativity and\nassociativity.\n\nUser-defined operation accepts four arguments, @invec@, @inoutvec@,\n@len@ and @datatype@:\n\n[@invec@] first input vector\n\n[@inoutvec@] second input vector, which is also the output vector\n\n[@len@] length of both vectors\n\n[@datatype@] type of the elements in both vectors.\n\nFunction is expected to apply reduction operation to the elements\nof @invec@ and @inoutvec@ in pariwise manner:\n\n@\ninoutvec[i] = op invec[i] inoutvec[i]\n@\n\nFull example with user-defined function that mimics standard operation\n'sumOp':\n\n@\nimport \"Control.Parallel.MPI.Fast\"\n\nforeign import ccall \\\"wrapper\\\" \n wrap :: (Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()) \n -> IO (FunPtr (Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()))\nreduceUserOpTest myRank = do\n numProcs <- commSize commWorld\n userSumPtr <- wrap userSum\n mySumOp <- opCreate True userSumPtr\n (src :: StorableArray Int Double) <- newListArray (0,99) [0..99]\n if myRank \/= root\n then reduceSend commWorld root sumOp src\n else do\n (result :: StorableArray Int Double) <- intoNewArray_ (0,99) $ reduceRecv commWorld root mySumOp src\n recvMsg <- getElems result\n freeHaskellFunPtr userSumPtr\n where\n userSum :: Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()\n userSum inPtr inoutPtr lenPtr _ = do\n len <- peek lenPtr\n let offs = sizeOf ( undefined :: CDouble )\n let loop 0 _ _ = return ()\n loop n inPtr inoutPtr = do\n a <- peek inPtr\n b <- peek inoutPtr\n poke inoutPtr (a+b)\n loop (n-1) (plusPtr inPtr offs) (plusPtr inoutPtr offs)\n loop len inPtr inoutPtr\n@\n-}\n{# fun unsafe Op_create as ^\n {castFunPtr `FunPtr (Ptr t -> Ptr t -> Ptr CInt -> Ptr Datatype -> IO ())', cFromEnum `Bool', alloca- `Operation' peekOperation*} -> `()' checkError*- #}\n\n{- | Free the handle for user-defined reduction operation created by 'opCreate'\n-}\n{# fun Op_free as ^ {withOperation* `Operation'} -> `()' checkError*- #}\n\n{- | Returns a \nfloating-point number of seconds, representing elapsed wallclock\ntime since some time in the past.\n\nThe \\\"time in the past\\\" is guaranteed not to change during the life of the process.\nThe user is responsible for converting large numbers of seconds to other units if they are\npreferred. The time is local to the node that calls @wtime@, but see 'wtimeIsGlobal'.\n-}\n{# fun unsafe Wtime as ^ {} -> `Double' realToFrac #}\n\n{- | Returns the resolution of 'wtime' in seconds. That is, it returns,\nas a double precision value, the number of seconds between successive clock ticks. For\nexample, if the clock is implemented by the hardware as a counter that is incremented\nevery millisecond, the value returned by @wtick@ should be 10^(-3).\n-}\n{# fun unsafe Wtick as ^ {} -> `Double' realToFrac #}\n\n-- | Return the process group from a communicator. With\n-- intercommunicator, returns the local group.\n{# fun unsafe Comm_group as ^\n {fromComm `Comm', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Returns the rank of the calling process in the given group. This function corresponds to @MPI_Group_rank@.\ngroupRank :: Group -> Rank\ngroupRank = unsafePerformIO <$> groupRank'\n where groupRank' = {# fun unsafe Group_rank as groupRank_\n {fromGroup `Group', alloca- `Rank' peekIntConv*} -> `()' checkError*- #}\n\n-- | Returns the size of a group. This function corresponds to @MPI_Group_size@.\ngroupSize :: Group -> Int\ngroupSize = unsafePerformIO <$> groupSize'\n where groupSize' = {# fun unsafe Group_size as groupSize_\n {fromGroup `Group', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Constructs the union of two groups: all the members of the first group, followed by all the members of the \n-- second group that do not appear in the first group. This function corresponds to @MPI_Group_union@.\ngroupUnion :: Group -> Group -> Group\ngroupUnion g1 g2 = unsafePerformIO $ groupUnion' g1 g2\n where groupUnion' = {# fun unsafe Group_union as groupUnion_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Constructs a new group which is the intersection of two groups. This function corresponds to @MPI_Group_intersection@.\ngroupIntersection :: Group -> Group -> Group\ngroupIntersection g1 g2 = unsafePerformIO $ groupIntersection' g1 g2\n where groupIntersection' = {# fun unsafe Group_intersection as groupIntersection_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Constructs a new group which contains all the elements of the first group which are not in the second group. \n-- This function corresponds to @MPI_Group_difference@.\ngroupDifference :: Group -> Group -> Group\ngroupDifference g1 g2 = unsafePerformIO $ groupDifference' g1 g2\n where groupDifference' = {# fun unsafe Group_difference as groupDifference_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Compares two groups. Returns 'MPI_IDENT' if the order and members of the two groups are the same,\n-- 'MPI_SIMILAR' if only the members are the same, and 'MPI_UNEQUAL' otherwise.\ngroupCompare :: Group -> Group -> ComparisonResult\ngroupCompare g1 g2 = unsafePerformIO $ groupCompare' g1 g2\n where\n groupCompare' = {# fun unsafe Group_compare as groupCompare_\n {fromGroup `Group', fromGroup `Group', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- Technically it might make better sense to make the second argument a Set rather than a list\n-- but the order is significant in the groupIncl function (the other function, not this one).\n-- For the sake of keeping their types in sync, a list is used instead.\n{- | Create a new @Group@ from the given one. Exclude processes\nwith given @Rank@s from the new @Group@. Processes in new @Group@ will\nhave ranks @[0...]@.\n-}\n{# fun unsafe Group_excl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n{- | Create a new @Group@ from the given one. Include only processes\nwith given @Rank@s in the new @Group@. Processes in new @Group@ will\nhave ranks @[0...]@.\n-}\n{# fun unsafe Group_incl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n{- | Given two @Group@s and list of @Rank@s of some processes in the\nfirst @Group@, return @Rank@s of those processes in the second\n@Group@. If there are no corresponding @Rank@ in the second @Group@,\n'mpiUndefined' is returned.\n\nThis function is important for determining the relative numbering of the same processes\nin two different groups. For instance, if one knows the ranks of certain processes in the group\nof 'commWorld', one might want to know their ranks in a subset of that group.\nNote that 'procNull' is a valid rank for input to @groupTranslateRanks@, which\nreturns 'procNull' as the translated rank.\n-}\ngroupTranslateRanks :: Group -> [Rank] -> Group -> [Rank]\ngroupTranslateRanks group1 ranks group2 =\n unsafePerformIO $ do\n let (rankIntList :: [Int]) = map fromEnum ranks\n withArrayLen rankIntList $ \\size ranksPtr ->\n allocaArray size $ \\resultPtr -> do\n groupTranslateRanks' group1 (cFromEnum size) (castPtr ranksPtr) group2 resultPtr\n map toRank <$> peekArray size resultPtr\n where\n groupTranslateRanks' = {# fun unsafe Group_translate_ranks as groupTranslateRanks_\n {fromGroup `Group', id `CInt', id `Ptr CInt', fromGroup `Group', id `Ptr CInt'} -> `()' checkError*- #}\n\nwithRanksAsInts ranks f = withArrayLen (map fromEnum ranks) $ \\size ptr -> f (cIntConv size, castPtr ptr)\n\n{- | If a process was started with 'commSpawn', @commGetParent@\nreturns the parent intercommunicator of the current process. This\nparent intercommunicator is created implicitly inside of 'init' and\nis the same intercommunicator returned by 'commSpawn' in the\nparents. If the process was not spawned, @commGetParent@ returns\n'commNull'. After the parent communicator is freed or disconnected,\n@commGetParent@ returns 'commNull'. -} \n\n{# fun unsafe Comm_get_parent as ^\n {alloca- `Comm' peekComm*} -> `()' checkError*- #}\n\nwithT = with\n{# fun unsafe Comm_spawn as ^\n { `String' \n , withT* `Ptr CChar'\n , id `Count'\n , fromInfo `Info'\n , fromRank `Rank'\n , fromComm `Comm'\n , alloca- `Comm' peekComm*\n , id `Ptr CInt'} -> `()' checkError*- #}\n\nforeign import ccall unsafe \"&mpi_argv_null\" mpiArgvNull_ :: Ptr (Ptr CChar)\nforeign import ccall unsafe \"&mpi_errcodes_ignore\" mpiErrcodesIgnore_ :: Ptr (Ptr CInt)\nargvNull = unsafePerformIO $ peek mpiArgvNull_\nerrcodesIgnore = unsafePerformIO $ peek mpiErrcodesIgnore_\n\n{-| Simplified version of `commSpawn' that does not support argument passing and spawn error code checking -}\ncommSpawnSimple rank program maxprocs =\n commSpawn program argvNull maxprocs infoNull rank commSelf errcodesIgnore\n\nforeign import ccall \"&mpi_undefined\" mpiUndefined_ :: Ptr Int\n\n-- | Predefined constant that might be returned as @Rank@ by calls\n-- like 'groupTranslateRanks'. Corresponds to @MPI_UNDEFINED@. Please\n-- refer to \\\"MPI Report Constant And Predefined Handle Index\\\" for a\n-- list of situations where @mpiUndefined@ could appear.\nmpiUndefined :: Int\nmpiUndefined = unsafePerformIO $ peek mpiUndefined_\n\n-- | Return the number of bytes used to store an MPI @Datatype@.\ntypeSize :: Datatype -> Int\ntypeSize = unsafePerformIO . typeSize'\n where\n typeSize' =\n {# fun unsafe Type_size as typeSize_\n {fromDatatype `Datatype', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n{# fun unsafe Error_class as ^\n { id `CInt', alloca- `CInt' peek*} -> `CInt' id #}\n\n-- | Set the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_set_errhandler@.\n{# fun unsafe Comm_set_errhandler as ^\n {fromComm `Comm', fromErrhandler `Errhandler'} -> `()' checkError*- #}\n\n-- | Get the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_get_errhandler@.\n{# fun unsafe Comm_get_errhandler as ^\n {fromComm `Comm', alloca- `Errhandler' peekErrhandler*} -> `()' checkError*- #}\n\n-- | Tries to terminate all MPI processes in its communicator argument.\n-- The second argument is an error code which \/may\/ be used as the return status\n-- of the MPI process, but this is not guaranteed. On systems where 'Int' has a larger\n-- range than 'CInt', the error code will be clipped to fit into the range of 'CInt'.\n-- This function corresponds to @MPI_Abort@.\nabort :: Comm -> Int -> IO ()\nabort comm code =\n abort' comm (toErrorCode code)\n where\n toErrorCode :: Int -> CInt\n toErrorCode i\n -- Assumes Int always has range at least as big as CInt.\n | i < (fromIntegral (minBound :: CInt)) = minBound\n | i > (fromIntegral (maxBound :: CInt)) = maxBound\n | otherwise = cIntConv i\n\n abort' = {# fun unsafe Abort as abort_ {fromComm `Comm', id `CInt'} -> `()' checkError*- #}\n\n\ntype MPIDatatype = {# type MPI_Datatype #}\n\n-- | Haskell datatype used to represent @MPI_Datatype@. \n-- Please refer to Chapter 4 of MPI Report v. 2.2 for a description\n-- of various datatypes.\nnewtype Datatype = MkDatatype { fromDatatype :: MPIDatatype }\n\nforeign import ccall unsafe \"&mpi_char\" char_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_wchar\" wchar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_short\" short_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_int\" int_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long\" long_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_long\" longLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_char\" unsignedChar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_short\" unsignedShort_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned\" unsigned_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long\" unsignedLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long_long\" unsignedLongLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_float\" float_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_double\" double_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_double\" longDouble_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_byte\" byte_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_packed\" packed_ :: Ptr MPIDatatype\n\nchar, wchar, short, int, long, longLong, unsignedChar, unsignedShort :: Datatype\nunsigned, unsignedLong, unsignedLongLong, float, double, longDouble :: Datatype\nbyte, packed :: Datatype\n\nchar = MkDatatype <$> unsafePerformIO $ peek char_\nwchar = MkDatatype <$> unsafePerformIO $ peek wchar_\nshort = MkDatatype <$> unsafePerformIO $ peek short_\nint = MkDatatype <$> unsafePerformIO $ peek int_\nlong = MkDatatype <$> unsafePerformIO $ peek long_\nlongLong = MkDatatype <$> unsafePerformIO $ peek longLong_\nunsignedChar = MkDatatype <$> unsafePerformIO $ peek unsignedChar_\nunsignedShort = MkDatatype <$> unsafePerformIO $ peek unsignedShort_\nunsigned = MkDatatype <$> unsafePerformIO $ peek unsigned_\nunsignedLong = MkDatatype <$> unsafePerformIO $ peek unsignedLong_\nunsignedLongLong = MkDatatype <$> unsafePerformIO $ peek unsignedLongLong_\nfloat = MkDatatype <$> unsafePerformIO $ peek float_\ndouble = MkDatatype <$> unsafePerformIO $ peek double_\nlongDouble = MkDatatype <$> unsafePerformIO $ peek longDouble_\nbyte = MkDatatype <$> unsafePerformIO $ peek byte_\npacked = MkDatatype <$> unsafePerformIO $ peek packed_\n\ntype MPIErrhandler = {# type MPI_Errhandler #}\n\n-- | Haskell datatype that represents values usable as @MPI_Errhandler@\nnewtype Errhandler = MkErrhandler { fromErrhandler :: MPIErrhandler } deriving Storable\npeekErrhandler ptr = MkErrhandler <$> peek ptr\n\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr MPIErrhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr MPIErrhandler\n\n-- | Predefined @Errhandler@ that will terminate the process on any\n-- MPI error\nerrorsAreFatal :: Errhandler\nerrorsAreFatal = MkErrhandler <$> unsafePerformIO $ peek errorsAreFatal_\n\n-- | Predefined @Errhandler@ that will convert errors into Haskell\n-- exceptions. Mimics the semantics of @MPI_Errors_return@\nerrorsReturn :: Errhandler\nerrorsReturn = MkErrhandler <$> unsafePerformIO $ peek errorsReturn_\n\n-- | Same as 'errorsReturn', but with a more meaningful name.\nerrorsThrowExceptions :: Errhandler\nerrorsThrowExceptions = errorsReturn\n\n{# enum ErrorClass {underscoreToCase} deriving (Eq,Ord,Show,Typeable) #}\n\n-- XXX Should this be a ForeinPtr?\n-- there is a MPI_Group_free function, which we should probably\n-- call when the group is no longer referenced.\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIGroup = {# type MPI_Group #}\n\n-- | Haskell datatype representing MPI process groups.\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\npeekGroup ptr = MkGroup <$> peek ptr\n\nforeign import ccall \"&mpi_group_empty\" groupEmpty_ :: Ptr MPIGroup\n-- | A predefined group without any members. Corresponds to @MPI_GROUP_EMPTY@.\ngroupEmpty :: Group\ngroupEmpty = MkGroup <$> unsafePerformIO $ peek groupEmpty_\n\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIOperation = {# type MPI_Op #}\n\n{- | Abstract type representing handle for MPI reduction operation\n(that can be used with 'reduce', 'allreduce', and 'reduceScatter').\n-}\nnewtype Operation = MkOperation { fromOperation :: MPIOperation } deriving Storable\npeekOperation ptr = MkOperation <$> peek ptr\nwithOperation op f = alloca $ \\ptr -> do poke ptr (fromOperation op)\n f (castPtr ptr)\n\nforeign import ccall unsafe \"&mpi_max\" maxOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_min\" minOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_sum\" sumOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_prod\" prodOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_land\" landOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_band\" bandOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lor\" lorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bor\" borOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lxor\" lxorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bxor\" bxorOp_ :: Ptr MPIOperation\n-- foreign import ccall \"mpi_maxloc\" maxlocOp :: MPIOperation\n-- foreign import ccall \"mpi_minloc\" minlocOp :: MPIOperation\n-- foreign import ccall \"mpi_replace\" replaceOp :: MPIOperation\n-- TODO: support for those requires better support for pair datatypes\n\n-- | Predefined reduction operation: maximum\nmaxOp :: Operation\nmaxOp = MkOperation <$> unsafePerformIO $ peek maxOp_\n\n-- | Predefined reduction operation: minimum\nminOp :: Operation\nminOp = MkOperation <$> unsafePerformIO $ peek minOp_\n\n-- | Predefined reduction operation: (+)\nsumOp :: Operation\nsumOp = MkOperation <$> unsafePerformIO $ peek sumOp_\n\n-- | Predefined reduction operation: (*)\nprodOp :: Operation\nprodOp = MkOperation <$> unsafePerformIO $ peek prodOp_\n\n-- | Predefined reduction operation: logical \\\"and\\\"\nlandOp :: Operation\nlandOp = MkOperation <$> unsafePerformIO $ peek landOp_\n\n-- | Predefined reduction operation: bit-wise \\\"and\\\"\nbandOp :: Operation\nbandOp = MkOperation <$> unsafePerformIO $ peek bandOp_\n\n-- | Predefined reduction operation: logical \\\"or\\\"\nlorOp :: Operation\nlorOp = MkOperation <$> unsafePerformIO $ peek lorOp_\n\n-- | Predefined reduction operation: bit-wise \\\"or\\\"\nborOp :: Operation\nborOp = MkOperation <$> unsafePerformIO $ peek borOp_\n\n-- | Predefined reduction operation: logical \\\"xor\\\"\nlxorOp :: Operation\nlxorOp = MkOperation <$> unsafePerformIO $ peek lxorOp_\n\n-- | Predefined reduction operation: bit-wise \\\"xor\\\"\nbxorOp :: Operation\nbxorOp = MkOperation <$> unsafePerformIO $ peek bxorOp_\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIInfo = {# type MPI_Info #}\n\n{- | Abstract type representing handle for MPI Info object\n-}\nnewtype Info = MkInfo { fromInfo :: MPIInfo } deriving Storable\npeekInfo ptr = MkInfo <$> peek ptr\n\nforeign import ccall \"&mpi_info_null\" infoNull_ :: Ptr MPIInfo\n\n-- | Predefined info object that has no info\ninfoNull :: Info\ninfoNull = unsafePerformIO $ peekInfo infoNull_\n\n{-| Creates new empty info object -}\n{# fun unsafe Info_create as ^\n {alloca- `Info' peekInfo*} -> `()' checkError*- #}\n\n{-| Adds specified (key, value) pair to info object -}\n{# fun unsafe Info_set as ^\n {fromInfo `Info', `String', `String'} -> `()' checkError*- #}\n\n{-| Deletes the specified key from info object -}\n{# fun unsafe Info_delete as ^\n {fromInfo `Info', `String'} -> `()' checkError*- #}\n\n{-| Gets the specified key -}\ninfoGet :: Info -> String -> IO (Maybe String)\ninfoGet info key = do\n (len, found) <- infoGetValuelen' info key \n -- len+1 is required to allow for the terminating \\NULL\n if found\/=0 then allocaBytes (fromIntegral len + 1)\n (\\bufferPtr -> do\n found <- infoGet' info key (len+1) bufferPtr\n if found\/=0 then Just <$> peekCStringLen (bufferPtr, fromIntegral len)\n else return Nothing)\n else return Nothing\n\ninfoGetValuelen' = {# fun unsafe Info_get_valuelen as infoGetValuelen_\n {fromInfo `Info', `String', alloca- `CInt' peek*, alloca- `CInt' peek* } -> `()' checkError*- #}\n\ninfoGet' = {# fun unsafe Info_get as infoGet_\n {fromInfo `Info', `String', id `CInt', castPtr `Ptr CChar', alloca- `CInt' peek*} -> `()' checkError*- #}\n\n\n{- | Haskell datatype that represents values which\n could be used as MPI rank designations. Low-level MPI calls require\n that you use 32-bit non-negative integer values as ranks, so any\n non-numeric Haskell Ranks should provide a sensible instances of\n 'Enum'.\n\nAttempt to supply a value that does not fit into 32 bits will cause a\nrun-time 'error'.\n-}\nnewtype Rank = MkRank { rankId :: CInt -- ^ Extract numeric value of the 'Rank'\n }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Rank where\n (MkRank x) + (MkRank y) = MkRank (x+y)\n (MkRank x) * (MkRank y) = MkRank (x*y)\n abs (MkRank x) = MkRank (abs x)\n signum (MkRank x) = MkRank (signum x)\n fromInteger x\n | x > ( fromIntegral (maxBound :: CInt)) = error \"Rank value does not fit into 32 bits\"\n | x < 0 = error \"Negative Rank value\"\n | otherwise = MkRank (fromIntegral x)\n\nforeign import ccall \"&mpi_any_source\" anySource_ :: Ptr CInt\nforeign import ccall \"&mpi_root\" theRoot_ :: Ptr CInt\nforeign import ccall \"&mpi_proc_null\" procNull_ :: Ptr CInt\nforeign import ccall \"&mpi_request_null\" requestNull_ :: Ptr MPIRequest\nforeign import ccall \"&mpi_comm_null\" commNull_ :: Ptr MPIComm\n\n-- | Predefined rank number that allows reception of point-to-point messages\n-- regardless of their source. Corresponds to @MPI_ANY_SOURCE@\nanySource :: Rank\nanySource = toRank $ unsafePerformIO $ peek anySource_\n\n-- | Predefined rank number that specifies root process during\n-- operations involving intercommunicators. Corresponds to @MPI_ROOT@\ntheRoot :: Rank\ntheRoot = toRank $ unsafePerformIO $ peek theRoot_\n\n-- | Predefined rank number that specifies non-root processes during\n-- operations involving intercommunicators. Corresponds to @MPI_PROC_NULL@\nprocNull :: Rank\nprocNull = toRank $ unsafePerformIO $ peek procNull_\n\n-- | Predefined request handle value that specifies non-existing or finished request.\n-- Corresponds to @MPI_REQUEST_NULL@\nrequestNull :: Request\nrequestNull = unsafePerformIO $ peekRequest requestNull_\n\n-- | Predefined communicator handle value that specifies non-existing or destroyed (inter-)communicator.\n-- Corresponds to @MPI_COMM_NULL@\ncommNull :: Comm\ncommNull = unsafePerformIO $ peekComm commNull_\n\ninstance Show Rank where\n show = show . rankId\n\n-- | Map arbitrary 'Enum' value to 'Rank'\ntoRank :: Enum a => a -> Rank\ntoRank x = MkRank { rankId = cIntConv (fromEnum x) }\n\n-- | Map 'Rank' to arbitrary 'Enum'\nfromRank :: Enum a => Rank -> a\nfromRank = toEnum . cIntConv . rankId\n\ntype MPIRequest = {# type MPI_Request #}\n{-| Haskell representation of the @MPI_Request@ type. Returned by\nnon-blocking communication operations, could be further processed with\n'probe', 'test', 'cancel' or 'wait'. -}\nnewtype Request = MkRequest MPIRequest deriving (Storable,Eq)\npeekRequest ptr = MkRequest <$> peek ptr\n\n{-\nThis module provides Haskell representation of the @MPI_Status@ type\n(request status).\n\nField `status_error' should be used with care:\n\\\"The error field in status is not needed for calls that return only\none status, such as @MPI_WAIT@, since that would only duplicate the\ninformation returned by the function itself. The current design avoids\nthe additional overhead of setting it, in such cases. The field is\nneeded for calls that return multiple statuses, since each request may\nhave had a different failure.\\\"\n(this is a quote from )\n\nThis means that, for example, during the call to @MPI_Wait@\nimplementation is free to leave this field filled with whatever\ngarbage got there during memory allocation. Haskell FFI is not\nblanking out freshly allocated memory, so beware!\n-}\n\n-- | Haskell structure that holds fields of @MPI_Status@.\ndata Status =\n Status\n { status_source :: Rank -- ^ rank of the source process\n , status_tag :: Tag -- ^ tag assigned at source\n , status_error :: CInt -- ^ error code, if any\n }\n deriving (Eq, Ord, Show)\n\ninstance Storable Status where\n sizeOf _ = {#sizeof MPI_Status #}\n alignment _ = 4\n peek p = Status\n <$> liftM (MkRank . cIntConv) ({#get MPI_Status->MPI_SOURCE #} p)\n <*> liftM (MkTag . cIntConv) ({#get MPI_Status->MPI_TAG #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_ERROR #} p)\n poke p x = do\n {#set MPI_Status.MPI_SOURCE #} p (fromRank $ status_source x)\n {#set MPI_Status.MPI_TAG #} p (fromTag $ status_tag x)\n {#set MPI_Status.MPI_ERROR #} p (cIntConv $ status_error x)\n\n-- NOTE: Int here is picked arbitrary\nallocaCast f =\n alloca $ \\(ptr :: Ptr Int) -> f (castPtr ptr :: Ptr ())\npeekCast = peek . castPtr\n\n\n{-| Haskell datatype that represents values which could be used as\ntags for point-to-point transfers.\n-}\nnewtype Tag = MkTag { tagVal :: CInt -- ^ Extract numeric value of the Tag\n }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Tag where\n (MkTag x) + (MkTag y) = MkTag (x+y)\n (MkTag x) * (MkTag y) = MkTag (x*y)\n abs (MkTag x) = MkTag (abs x)\n signum (MkTag x) = MkTag (signum x)\n fromInteger x\n | fromIntegral x > tagUpperBound = error \"Tag value is over the MPI_TAG_UB\"\n | x < 0 = error \"Negative Tag value\"\n | otherwise = MkTag (fromIntegral x)\n\ninstance Show Tag where\n show = show . tagVal\n\n-- | Map arbitrary 'Enum' value to 'Tag'\ntoTag :: Enum a => a -> Tag\ntoTag x = MkTag { tagVal = cIntConv (fromEnum x) }\n\n-- | Map 'Tag' to arbitrary 'Enum'\nfromTag :: Enum a => Tag -> a\nfromTag = toEnum . cIntConv . tagVal\n\nforeign import ccall unsafe \"&mpi_any_tag\" anyTag_ :: Ptr CInt\n\n-- | Predefined tag value that allows reception of the messages with\n-- arbitrary tag values. Corresponds to @MPI_ANY_TAG@.\nanyTag :: Tag\nanyTag = toTag $ unsafePerformIO $ peek anyTag_\n\n-- | A tag with unit value. Intended to be used as a convenient default.\nunitTag :: Tag\nunitTag = toTag ()\n\n{- | Constants used to describe the required level of multithreading\n support in call to 'initThread'. They also describe provided level\n of multithreading support as returned by 'queryThread' and\n 'initThread'.\n\n[@Single@] Only one thread will execute.\n\n[@Funneled@] The process may be multi-threaded, but the application must\nensure that only the main thread makes MPI calls (see 'isThreadMain').\n\n[@Serialized@] The process may be multi-threaded, and multiple threads may\nmake MPI calls, but only one at a time: MPI calls are not made concurrently from\ntwo distinct threads\n\n[@Multiple@] Multiple threads may call MPI, with no restrictions.\n\nXXX Make sure we have the correct ordering as defined by MPI. Also we should\ndescribe the ordering here (other parts of the docs need it to be explained - see initThread).\n\n-}\n{# enum ThreadSupport {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- | Value thrown as exception when MPI runtime is instructed to pass\n-- errors to user code (via 'commSetErrhandler' and 'errorsReturn').\n-- Since raw MPI errors codes are not standartized and not portable,\n-- they are not exposed.\ndata MPIError\n = MPIError\n { mpiErrorClass :: ErrorClass -- ^ Broad class of errors this one belongs to\n , mpiErrorString :: String -- ^ Human-readable error description\n }\n deriving (Eq, Show, Typeable)\n\ninstance Exception MPIError\n\ncheckError :: CInt -> IO ()\ncheckError code = do\n -- We ignore the error code from the call to Internal.errorClass\n -- because we call errorClass from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n (_, errClassRaw) <- errorClass code\n let errClass = cToEnum errClassRaw\n unless (errClass == Success) $ do\n errStr <- errorString code\n throwIO $ MPIError errClass errStr\n\n-- | Convert MPI error code human-readable error description. Corresponds to @MPI_Error_string@.\nerrorString :: CInt -> IO String\nerrorString code =\n allocaBytes (fromIntegral maxErrorString) $ \\ptr ->\n alloca $ \\lenPtr -> do\n -- We ignore the error code from the call to Internal.errorString\n -- because we call errorString from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n _ <- errorString' code ptr lenPtr\n len <- peek lenPtr\n peekCStringLen (ptr, cIntConv len)\n where\n errorString' = {# call unsafe Error_string as errorString_ #}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"4ab7fc42c02d6a670f0bc59b099728384118f199","subject":"explicit imports","message":"explicit imports\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/Bindings\/GDAL\/Internal.chs","new_file":"src\/Bindings\/GDAL\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE GADTs #-}\n\nmodule Bindings.GDAL.Internal (\n Datatype (..)\n , Access (..)\n , ColorInterpretation (..)\n , PaletteInterpretation (..)\n , Error (..)\n , Geotransform (..)\n , MaybeIOVector\n , ProgressFun\n\n , DriverOptions\n\n , MajorObject\n , Dataset\n , RasterBand\n , Driver\n , ColorTable\n , RasterAttributeTable\n\n , registerAllDrivers\n , driverByName\n , create\n , create'\n , createMem\n , flushCache\n , open\n , openShared\n , createCopy'\n , createCopy\n\n , datatypeSize\n , datatypeByName\n , datatypeUnion\n , datatypeIsComplex\n\n , datasetProjection\n , setDatasetProjection\n , datasetGeotransform\n , setDatasetGeotransform\n\n , withRasterBand\n , bandDatatype\n , blockSize\n , blockLen\n , bandSize\n , readBand\n , readBlock\n , writeBand\n , writeBlock\n , fillBand\n\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Concurrent (newMVar, takeMVar, putMVar, MVar)\nimport Control.Exception (finally, bracket)\nimport Control.Monad (liftM, foldM)\n\nimport Data.Int (Int16, Int32)\nimport Data.Complex (Complex(..), realPart, imagPart)\nimport Data.Typeable (Typeable, cast, typeOf)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector, unsafeFromForeignPtr0, unsafeToForeignPtr0)\nimport Foreign.C.String (withCString, CString, peekCString)\nimport Foreign.C.Types (CDouble(..), CInt(..), CChar(..))\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr, freeHaskellFunPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.ForeignPtr (ForeignPtr, withForeignPtr, newForeignPtr\n ,mallocForeignPtrArray)\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (allocaArray)\nimport Foreign.Marshal.Utils (toBool, fromBool)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n{# enum CPLErr as Error {upcaseFirstLetter} deriving (Eq,Show) #}\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\ninstance Show Datatype where\n show = getDatatypeName\n\n{# fun pure unsafe GDALGetDataTypeSize as datatypeSize\n { fromEnumC `Datatype' } -> `Int' #}\n\n{# fun pure unsafe GDALDataTypeIsComplex as datatypeIsComplex\n { fromEnumC `Datatype' } -> `Bool' #}\n\n{# fun pure unsafe GDALGetDataTypeName as getDatatypeName\n { fromEnumC `Datatype' } -> `String' #}\n\n{# fun pure unsafe GDALGetDataTypeByName as datatypeByName\n { `String' } -> `Datatype' toEnumC #}\n\n{# fun pure unsafe GDALDataTypeUnion as datatypeUnion\n { fromEnumC `Datatype', fromEnumC `Datatype' } -> `Datatype' toEnumC #}\n\n\n{# enum GDALAccess as Access {upcaseFirstLetter} deriving (Eq, Show) #}\n\n{# enum GDALRWFlag as RwFlag {upcaseFirstLetter} deriving (Eq, Show) #}\n\n{# enum GDALColorInterp as ColorInterpretation {upcaseFirstLetter}\n deriving (Eq) #}\n\ninstance Show ColorInterpretation where\n show = getColorInterpretationName\n\n{# fun pure unsafe GDALGetColorInterpretationName as getColorInterpretationName\n { fromEnumC `ColorInterpretation' } -> `String' #}\n\n{# fun pure unsafe GDALGetColorInterpretationByName as getColorInterpretationByName\n { `String' } -> `ColorInterpretation' toEnumC #}\n\n\n{# enum GDALPaletteInterp as PaletteInterpretation {upcaseFirstLetter}\n deriving (Eq) #}\n\ninstance Show PaletteInterpretation where\n show = getPaletteInterpretationName\n\n{# fun pure unsafe GDALGetPaletteInterpretationName as getPaletteInterpretationName\n { fromEnumC `PaletteInterpretation' } -> `String' #}\n\n\n{#pointer GDALMajorObjectH as MajorObject newtype#}\n{#pointer GDALDatasetH as Dataset foreign newtype nocode#}\n\nnewtype Dataset = Dataset (ForeignPtr Dataset, Mutex)\n\nwithDataset, withDataset' :: Dataset -> (Ptr Dataset -> IO b) -> IO b\nwithDataset ds@(Dataset (_, m)) fun = withMutex m $ withDataset' ds fun\n\nwithDataset' (Dataset (fptr,_)) = withForeignPtr fptr\n\n{#pointer GDALRasterBandH as RasterBand newtype#}\n{#pointer GDALDriverH as Driver newtype#}\n{#pointer GDALColorTableH as ColorTable newtype#}\n{#pointer GDALRasterAttributeTableH as RasterAttributeTable newtype#}\n\n{# fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `Driver' id #}\n\ndriverByName :: String -> IO (Maybe Driver)\ndriverByName s = do\n driver@(Driver ptr) <- c_driverByName s\n return $ if ptr==nullPtr then Nothing else Just driver\n\n\ntype DriverOptions = [(String,String)]\n\ncreate :: String -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO (Maybe Dataset)\ncreate drv path nx ny bands dtype options = do\n driver <- driverByName drv\n case driver of\n Nothing -> return Nothing\n Just d -> create' d path nx ny bands dtype options\n\ncreate' :: Driver -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO (Maybe Dataset)\ncreate' drv path nx ny bands dtype options = withCString path $ \\path' -> do\n opts <- toOptionList options\n ptr <- {#call GDALCreate as ^#}\n drv\n path'\n (fromIntegral nx)\n (fromIntegral ny)\n (fromIntegral bands)\n (fromEnumC dtype)\n opts\n newDatasetHandle ptr\n\n{# fun GDALOpen as open\n { `String', fromEnumC `Access'} -> `Maybe Dataset' newDatasetHandle* #}\n\n{# fun GDALOpen as openShared\n { `String', fromEnumC `Access'} -> `Maybe Dataset' newDatasetHandle* #}\n\ncreateCopy' :: Driver -> String -> Dataset -> Bool -> DriverOptions\n -> ProgressFun -> IO (Maybe Dataset)\ncreateCopy' driver path dataset strict options progressFun\n = withCString path $ \\p ->\n withDataset dataset $ \\ds ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = fromBool strict\n o <- toOptionList options\n {#call GDALCreateCopy as ^#} driver p ds s o pFunc (castPtr nullPtr) >>=\n newDatasetHandle\n\nwithProgressFun f = bracket (wrapProgressFun f) freeHaskellFunPtr\n\ncreateCopy :: String -> String -> Dataset -> Bool -> DriverOptions\n -> IO (Maybe Dataset)\ncreateCopy driver path dataset strict options = do\n d <- driverByName driver\n case d of\n Nothing -> return Nothing\n Just d' -> createCopy' d' path dataset strict options (\\_ _ _ -> return 1)\n\ntype ProgressFun = CDouble -> Ptr CChar -> Ptr () -> IO CInt\n\nforeign import ccall \"wrapper\"\n wrapProgressFun :: ProgressFun -> IO (FunPtr ProgressFun)\n\n\nnewDatasetHandle :: Ptr Dataset -> IO (Maybe Dataset)\nnewDatasetHandle p =\n if p==nullPtr then return Nothing\n else do fp <- newForeignPtr closeDataset p\n mutex <- newMutex\n return $ Just $ Dataset (fp, mutex)\n\nforeign import ccall \"gdal.h &GDALClose\"\n closeDataset :: FunPtr (Ptr (Dataset) -> IO ())\n\ncreateMem:: Int -> Int -> Int -> Datatype -> DriverOptions -> IO (Maybe Dataset)\ncreateMem = create \"MEM\" \"\"\n\n{# fun GDALFlushCache as flushCache\n { withDataset* `Dataset'} -> `()' #}\n\n{# fun unsafe GDALGetProjectionRef as datasetProjection\n { withDataset* `Dataset'} -> `String' #}\n\n{# fun unsafe GDALSetProjection as setDatasetProjection\n { withDataset* `Dataset', `String'} -> `Error' toEnumC #}\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset -> IO (Maybe Geotransform)\ndatasetGeotransform ds = withDataset' ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n err <- {#call unsafe GDALGetGeoTransform as ^#} dPtr a\n case toEnumC err of\n CE_None -> liftM Just $ Geotransform\n <$> liftM realToFrac (peekElemOff a 0)\n <*> liftM realToFrac (peekElemOff a 1)\n <*> liftM realToFrac (peekElemOff a 2)\n <*> liftM realToFrac (peekElemOff a 3)\n <*> liftM realToFrac (peekElemOff a 4)\n <*> liftM realToFrac (peekElemOff a 5)\n _ -> return Nothing\n\nsetDatasetGeotransform :: Dataset -> Geotransform -> IO (Error)\nsetDatasetGeotransform ds gt = withDataset ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n let (Geotransform g0 g1 g2 g3 g4 g5) = gt\n pokeElemOff a 0 (realToFrac g0)\n pokeElemOff a 1 (realToFrac g1)\n pokeElemOff a 2 (realToFrac g2)\n pokeElemOff a 3 (realToFrac g3)\n pokeElemOff a 4 (realToFrac g4)\n pokeElemOff a 5 (realToFrac g5)\n liftM toEnumC $ {#call unsafe GDALSetGeoTransform as ^#} dPtr a\n\nwithRasterBand :: Dataset -> Int -> (Maybe RasterBand -> IO a) -> IO a\nwithRasterBand ds band f = withDataset ds $ \\dPtr -> do\n rBand@(RasterBand p) <- {# call unsafe GDALGetRasterBand as ^ #}\n dPtr (fromIntegral band)\n f (if p == nullPtr then Nothing else Just rBand)\n\n{# fun pure unsafe GDALGetRasterDataType as bandDatatype\n { id `RasterBand'} -> `Datatype' toEnumC #}\n\nblockSize :: RasterBand -> (Int,Int)\nblockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr ->\n {#call unsafe GDALGetBlockSize as ^#} band xPtr yPtr >>\n liftA2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nblockLen :: RasterBand -> Int\nblockLen = uncurry (*) . blockSize\n\nbandSize :: RasterBand -> (Int, Int)\nbandSize band\n = ( fromIntegral . {# call pure unsafe GDALGetRasterBandXSize as ^#} $ band\n , fromIntegral . {# call pure unsafe GDALGetRasterBandYSize as ^#} $ band\n )\n\n{# fun GDALFillRaster as fillBand\n { id `RasterBand', `Double', `Double'} -> `Error' toEnumC #}\n\nclass HasDatatype a where\n datatype :: a -> Datatype\n\ninstance HasDatatype (Ptr Word8) where datatype _ = GDT_Byte\ninstance HasDatatype (Ptr Word16) where datatype _ = GDT_UInt16\ninstance HasDatatype (Ptr Word32) where datatype _ = GDT_UInt32\ninstance HasDatatype (Ptr Int16) where datatype _ = GDT_Int16\ninstance HasDatatype (Ptr Int32) where datatype _ = GDT_Int32\ninstance HasDatatype (Ptr Float) where datatype _ = GDT_Float32\ninstance HasDatatype (Ptr Double) where datatype _ = GDT_Float64\n-- GDT_CInt16 or GDT_CInt32 can be written as Complex (Float|Double) but\n-- will be truncated by GDAL. Both can be read as Complex (Float|Double).\n-- This is a limitation imposed by Complex a which constrains a to be a\n-- RealFloat.\ninstance HasDatatype (Ptr (Complex Float)) where datatype _ = GDT_CFloat32\ninstance HasDatatype (Ptr (Complex Double)) where datatype _ = GDT_CFloat64\n\n\ninstance (RealFloat a, Storable a) => Storable (Complex a) where\n sizeOf _ = sizeOf (undefined :: a) * 2\n alignment _ = alignment (undefined :: a)\n \n {-# SPECIALIZE INLINE peek :: Ptr (Complex Float) -> IO (Complex Float) #-}\n {-# SPECIALIZE INLINE peek :: Ptr (Complex Double) -> IO (Complex Double) #-}\n peek p = (:+) <$> peekElemOff (castPtr p) 0 <*> peekElemOff (castPtr p) 1\n\n {-# SPECIALIZE INLINE\n poke :: Ptr (Complex Float) -> Complex Float -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (Complex Double) -> Complex Double -> IO () #-}\n poke p v = pokeElemOff (castPtr p) 0 (realPart v) >>\n pokeElemOff (castPtr p) 1 (imagPart v)\n\n\n\nreadBand :: (Storable a, HasDatatype (Ptr a))\n => RasterBand\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Maybe (Vector a))\nreadBand band xoff yoff sx sy bx by pxs lns = do\n fp <- mallocForeignPtrArray (bx * by)\n err <- withForeignPtr fp $ \\ptr -> do\n _ <- {#call GDALRasterAdviseRead as ^#}\n band\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (datatype ptr))\n (castPtr nullPtr)\n {#call GDALRasterIO as ^#}\n band\n (fromEnumC GF_Read) \n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (datatype ptr))\n (fromIntegral pxs)\n (fromIntegral lns)\n case toEnumC err of\n CE_None -> return $ Just $ unsafeFromForeignPtr0 fp (bx * by)\n _ -> return Nothing\n \nwriteBand :: (Storable a, HasDatatype (Ptr a))\n => RasterBand\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> IO (Error)\nwriteBand band xoff yoff sx sy bx by pxs lns vec = do\n let nElems = bx * by\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then return CE_Failure\n else withForeignPtr fp $ \\ptr -> liftM toEnumC $\n {#call GDALRasterIO as ^#}\n band\n (fromEnumC GF_Write) \n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (datatype ptr))\n (fromIntegral pxs)\n (fromIntegral lns)\n\ndata Block where\n Block :: (Typeable a, Storable a) => Vector a -> Block\n\nreadBlock :: (Storable a, Typeable a)\n => RasterBand -> Int -> Int -> MaybeIOVector a\nreadBlock b x y = do\n block <- readBlock' b x y\n liftM (maybe Nothing (\\(Block a) -> cast a)) $ readBlock' b x y\n\n\nreadBlock' :: RasterBand -> Int -> Int -> IO (Maybe Block)\nreadBlock' b x y = \n case bandDatatype b of\n GDT_Byte ->\n maybeReturn Block (readIt b x y :: MaybeIOVector Word8)\n GDT_Int16 ->\n maybeReturn Block (readIt b x y :: MaybeIOVector Int16)\n GDT_Int32 ->\n maybeReturn Block (readIt b x y :: MaybeIOVector Int32)\n GDT_Float32 ->\n maybeReturn Block (readIt b x y :: MaybeIOVector Float)\n GDT_Float64 ->\n maybeReturn Block (readIt b x y :: MaybeIOVector Double)\n GDT_CInt16 ->\n maybeReturn Block (readIt b x y :: MaybeIOVector (Complex Float))\n GDT_CInt32 ->\n maybeReturn Block (readIt b x y :: MaybeIOVector (Complex Double))\n GDT_CFloat32 ->\n maybeReturn Block (readIt b x y :: MaybeIOVector (Complex Float))\n GDT_CFloat64 ->\n maybeReturn Block (readIt b x y :: MaybeIOVector (Complex Double))\n _ -> return Nothing\n where\n maybeReturn f act = act >>= maybe (return Nothing) (return . Just . f)\n readIt b x y = do\n let l = blockLen b\n rb = {#call GDALReadBlock as ^#} b (fromIntegral x) (fromIntegral y)\n f <- mallocForeignPtrArray l\n e <- withForeignPtr f (rb . castPtr)\n if toEnumC e == CE_None\n then return $ Just $ unsafeFromForeignPtr0 f l\n else return Nothing\n\ntype MaybeIOVector a = IO (Maybe (Vector a))\n\nwriteBlock :: (Storable a, Typeable a)\n => RasterBand\n -> Int -> Int\n -> Vector a\n -> IO (Error)\nwriteBlock b x y vec = do\n let nElems = blockLen b\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len || typeOf vec \/= typeOfBand b\n then return CE_Failure\n else withForeignPtr fp $ \\ptr -> liftM toEnumC $\n {#call GDALWriteBlock as ^#}\n b\n (fromIntegral x)\n (fromIntegral y)\n (castPtr ptr)\n\ntypeOfBand = typeOfdatatype . bandDatatype\n\ntypeOfdatatype dt =\n case dt of\n GDT_Byte -> typeOf (undefined :: Vector Word8)\n GDT_Int16 -> typeOf (undefined :: Vector Int16)\n GDT_Int32 -> typeOf (undefined :: Vector Int32)\n GDT_Float32 -> typeOf (undefined :: Vector Float)\n GDT_Float64 -> typeOf (undefined :: Vector Double)\n GDT_CInt16 -> typeOf (undefined :: Vector (Complex Float))\n GDT_CInt32 -> typeOf (undefined :: Vector (Complex Double))\n GDT_CFloat32 -> typeOf (undefined :: Vector (Complex Float))\n GDT_CFloat64 -> typeOf (undefined :: Vector (Complex Double))\n _ -> typeOf (undefined :: Bool) -- will never match a vector\n\nfromEnumC :: Enum a => a -> CInt\nfromEnumC = fromIntegral . fromEnum\n\ntoEnumC :: Enum a => CInt -> a\ntoEnumC = toEnum . fromIntegral\n\n\ntoOptionList :: [(String,String)] -> IO (Ptr CString)\ntoOptionList opts = foldM folder nullPtr opts\n where folder acc (k,v) = withCString k $ \\k' -> withCString v $ \\v' ->\n {#call unsafe CSLSetNameValue as ^#} acc k' v'\n\ntype Mutex = MVar ()\n\nnewMutex :: IO Mutex\nnewMutex = newMVar ()\n\n\nacquireMutex :: Mutex -> IO ()\nacquireMutex = takeMVar\n\nreleaseMutex :: Mutex -> IO ()\nreleaseMutex m = putMVar m ()\n\nwithMutex m action = finally (acquireMutex m >> action) (releaseMutex m)\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE GADTs #-}\n\nmodule Bindings.GDAL.Internal (\n Datatype (..)\n , Access (..)\n , ColorInterpretation (..)\n , PaletteInterpretation (..)\n , Error (..)\n , Geotransform (..)\n , MaybeIOVector\n , ProgressFun\n\n , DriverOptions\n\n , MajorObject\n , Dataset\n , RasterBand\n , Driver\n , ColorTable\n , RasterAttributeTable\n\n , registerAllDrivers\n , driverByName\n , create\n , create'\n , createMem\n , flushCache\n , open\n , openShared\n , createCopy'\n , createCopy\n\n , datatypeSize\n , datatypeByName\n , datatypeUnion\n , datatypeIsComplex\n\n , datasetProjection\n , setDatasetProjection\n , datasetGeotransform\n , setDatasetGeotransform\n\n , withRasterBand\n , bandDatatype\n , blockSize\n , blockLen\n , bandSize\n , readBand\n , readBlock\n , writeBand\n , writeBlock\n , fillBand\n\n) where\n\nimport Control.Applicative (liftA2, (<$>), (<*>))\nimport Control.Concurrent (newMVar, takeMVar, putMVar, MVar)\nimport Control.Exception (finally, bracket)\nimport Control.Monad (liftM, foldM)\n\nimport Data.Int (Int16, Int32)\nimport Data.Complex (Complex(..), realPart, imagPart)\nimport Data.Typeable (Typeable, cast, typeOf)\nimport Data.Word (Word8, Word16, Word32)\nimport Data.Vector.Storable (Vector, unsafeFromForeignPtr0, unsafeToForeignPtr0)\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Utils\n\nimport System.IO.Unsafe (unsafePerformIO)\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n#include \"cpl_error.h\"\n\n{# enum CPLErr as Error {upcaseFirstLetter} deriving (Eq,Show) #}\n\n{# enum GDALDataType as Datatype {upcaseFirstLetter} deriving (Eq) #}\ninstance Show Datatype where\n show = getDatatypeName\n\n{# fun pure unsafe GDALGetDataTypeSize as datatypeSize\n { fromEnumC `Datatype' } -> `Int' #}\n\n{# fun pure unsafe GDALDataTypeIsComplex as datatypeIsComplex\n { fromEnumC `Datatype' } -> `Bool' #}\n\n{# fun pure unsafe GDALGetDataTypeName as getDatatypeName\n { fromEnumC `Datatype' } -> `String' #}\n\n{# fun pure unsafe GDALGetDataTypeByName as datatypeByName\n { `String' } -> `Datatype' toEnumC #}\n\n{# fun pure unsafe GDALDataTypeUnion as datatypeUnion\n { fromEnumC `Datatype', fromEnumC `Datatype' } -> `Datatype' toEnumC #}\n\n\n{# enum GDALAccess as Access {upcaseFirstLetter} deriving (Eq, Show) #}\n\n{# enum GDALRWFlag as RwFlag {upcaseFirstLetter} deriving (Eq, Show) #}\n\n{# enum GDALColorInterp as ColorInterpretation {upcaseFirstLetter}\n deriving (Eq) #}\n\ninstance Show ColorInterpretation where\n show = getColorInterpretationName\n\n{# fun pure unsafe GDALGetColorInterpretationName as getColorInterpretationName\n { fromEnumC `ColorInterpretation' } -> `String' #}\n\n{# fun pure unsafe GDALGetColorInterpretationByName as getColorInterpretationByName\n { `String' } -> `ColorInterpretation' toEnumC #}\n\n\n{# enum GDALPaletteInterp as PaletteInterpretation {upcaseFirstLetter}\n deriving (Eq) #}\n\ninstance Show PaletteInterpretation where\n show = getPaletteInterpretationName\n\n{# fun pure unsafe GDALGetPaletteInterpretationName as getPaletteInterpretationName\n { fromEnumC `PaletteInterpretation' } -> `String' #}\n\n\n{#pointer GDALMajorObjectH as MajorObject newtype#}\n{#pointer GDALDatasetH as Dataset foreign newtype nocode#}\n\nnewtype Dataset = Dataset (ForeignPtr Dataset, Mutex)\n\nwithDataset, withDataset' :: Dataset -> (Ptr Dataset -> IO b) -> IO b\nwithDataset ds@(Dataset (_, m)) fun = withMutex m $ withDataset' ds fun\n\nwithDataset' (Dataset (fptr,_)) = withForeignPtr fptr\n\n{#pointer GDALRasterBandH as RasterBand newtype#}\n{#pointer GDALDriverH as Driver newtype#}\n{#pointer GDALColorTableH as ColorTable newtype#}\n{#pointer GDALRasterAttributeTableH as RasterAttributeTable newtype#}\n\n{# fun GDALAllRegister as registerAllDrivers {} -> `()' #}\n\n{# fun unsafe GDALGetDriverByName as c_driverByName\n { `String' } -> `Driver' id #}\n\ndriverByName :: String -> IO (Maybe Driver)\ndriverByName s = do\n driver@(Driver ptr) <- c_driverByName s\n return $ if ptr==nullPtr then Nothing else Just driver\n\n\ntype DriverOptions = [(String,String)]\n\ncreate :: String -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO (Maybe Dataset)\ncreate drv path nx ny bands dtype options = do\n driver <- driverByName drv\n case driver of\n Nothing -> return Nothing\n Just d -> create' d path nx ny bands dtype options\n\ncreate' :: Driver -> String -> Int -> Int -> Int -> Datatype -> DriverOptions\n -> IO (Maybe Dataset)\ncreate' drv path nx ny bands dtype options = withCString path $ \\path' -> do\n opts <- toOptionList options\n ptr <- {#call GDALCreate as ^#}\n drv\n path'\n (fromIntegral nx)\n (fromIntegral ny)\n (fromIntegral bands)\n (fromEnumC dtype)\n opts\n newDatasetHandle ptr\n\n{# fun GDALOpen as open\n { `String', fromEnumC `Access'} -> `Maybe Dataset' newDatasetHandle* #}\n\n{# fun GDALOpen as openShared\n { `String', fromEnumC `Access'} -> `Maybe Dataset' newDatasetHandle* #}\n\ncreateCopy' :: Driver -> String -> Dataset -> Bool -> DriverOptions\n -> ProgressFun -> IO (Maybe Dataset)\ncreateCopy' driver path dataset strict options progressFun\n = withCString path $ \\p ->\n withDataset dataset $ \\ds ->\n withProgressFun progressFun $ \\pFunc -> do\n let s = if strict then 1 else 0\n o <- toOptionList options\n {#call GDALCreateCopy as ^#} driver p ds s o pFunc (castPtr nullPtr) >>=\n newDatasetHandle\n\nwithProgressFun f = bracket (wrapProgressFun f) freeHaskellFunPtr\n\ncreateCopy :: String -> String -> Dataset -> Bool -> DriverOptions\n -> IO (Maybe Dataset)\ncreateCopy driver path dataset strict options = do\n d <- driverByName driver\n case d of\n Nothing -> return Nothing\n Just d' -> createCopy' d' path dataset strict options (\\_ _ _ -> return 1)\n\ntype ProgressFun = CDouble -> Ptr CChar -> Ptr () -> IO CInt\n\nforeign import ccall \"wrapper\"\n wrapProgressFun :: ProgressFun -> IO (FunPtr ProgressFun)\n\n\nnewDatasetHandle :: Ptr Dataset -> IO (Maybe Dataset)\nnewDatasetHandle p =\n if p==nullPtr then return Nothing\n else do fp <- newForeignPtr closeDataset p\n mutex <- newMutex\n return $ Just $ Dataset (fp, mutex)\n\nforeign import ccall \"gdal.h &GDALClose\"\n closeDataset :: FunPtr (Ptr (Dataset) -> IO ())\n\ncreateMem:: Int -> Int -> Int -> Datatype -> DriverOptions -> IO (Maybe Dataset)\ncreateMem = create \"MEM\" \"\"\n\n{# fun GDALFlushCache as flushCache\n { withDataset* `Dataset'} -> `()' #}\n\n{# fun unsafe GDALGetProjectionRef as datasetProjection\n { withDataset* `Dataset'} -> `String' #}\n\n{# fun unsafe GDALSetProjection as setDatasetProjection\n { withDataset* `Dataset', `String'} -> `Error' toEnumC #}\n\ndata Geotransform = Geotransform !Double !Double !Double !Double !Double !Double\n deriving (Eq, Show)\n\ndatasetGeotransform :: Dataset -> IO (Maybe Geotransform)\ndatasetGeotransform ds = withDataset' ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n err <- {#call unsafe GDALGetGeoTransform as ^#} dPtr a\n case toEnumC err of\n CE_None -> liftM Just $ Geotransform\n <$> liftM realToFrac (peekElemOff a 0)\n <*> liftM realToFrac (peekElemOff a 1)\n <*> liftM realToFrac (peekElemOff a 2)\n <*> liftM realToFrac (peekElemOff a 3)\n <*> liftM realToFrac (peekElemOff a 4)\n <*> liftM realToFrac (peekElemOff a 5)\n _ -> return Nothing\n\nsetDatasetGeotransform :: Dataset -> Geotransform -> IO (Error)\nsetDatasetGeotransform ds gt = withDataset ds $ \\dPtr -> do\n allocaArray 6 $ \\a -> do\n let (Geotransform g0 g1 g2 g3 g4 g5) = gt\n pokeElemOff a 0 (realToFrac g0)\n pokeElemOff a 1 (realToFrac g1)\n pokeElemOff a 2 (realToFrac g2)\n pokeElemOff a 3 (realToFrac g3)\n pokeElemOff a 4 (realToFrac g4)\n pokeElemOff a 5 (realToFrac g5)\n liftM toEnumC $ {#call unsafe GDALSetGeoTransform as ^#} dPtr a\n\nwithRasterBand :: Dataset -> Int -> (Maybe RasterBand -> IO a) -> IO a\nwithRasterBand ds band f = withDataset ds $ \\dPtr -> do\n rBand@(RasterBand p) <- {# call unsafe GDALGetRasterBand as ^ #}\n dPtr (fromIntegral band)\n f (if p == nullPtr then Nothing else Just rBand)\n\n{# fun pure unsafe GDALGetRasterDataType as bandDatatype\n { id `RasterBand'} -> `Datatype' toEnumC #}\n\nblockSize :: RasterBand -> (Int,Int)\nblockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr ->\n {#call unsafe GDALGetBlockSize as ^#} band xPtr yPtr >>\n liftA2 (,) (liftM fromIntegral $ peek xPtr) (liftM fromIntegral $ peek yPtr)\n\nblockLen :: RasterBand -> Int\nblockLen = uncurry (*) . blockSize\n\nbandSize :: RasterBand -> (Int, Int)\nbandSize band\n = ( fromIntegral . {# call pure unsafe GDALGetRasterBandXSize as ^#} $ band\n , fromIntegral . {# call pure unsafe GDALGetRasterBandYSize as ^#} $ band\n )\n\n{# fun GDALFillRaster as fillBand\n { id `RasterBand', `Double', `Double'} -> `Error' toEnumC #}\n\nclass HasDatatype a where\n datatype :: a -> Datatype\n\ninstance HasDatatype (Ptr Word8) where datatype _ = GDT_Byte\ninstance HasDatatype (Ptr Word16) where datatype _ = GDT_UInt16\ninstance HasDatatype (Ptr Word32) where datatype _ = GDT_UInt32\ninstance HasDatatype (Ptr Int16) where datatype _ = GDT_Int16\ninstance HasDatatype (Ptr Int32) where datatype _ = GDT_Int32\ninstance HasDatatype (Ptr Float) where datatype _ = GDT_Float32\ninstance HasDatatype (Ptr Double) where datatype _ = GDT_Float64\n-- GDT_CInt16 or GDT_CInt32 can be written as Complex (Float|Double) but\n-- will be truncated by GDAL. Both can be read as Complex (Float|Double).\n-- This is a limitation imposed by Complex a which constrains a to be a\n-- RealFloat.\ninstance HasDatatype (Ptr (Complex Float)) where datatype _ = GDT_CFloat32\ninstance HasDatatype (Ptr (Complex Double)) where datatype _ = GDT_CFloat64\n\n\ninstance (RealFloat a, Storable a) => Storable (Complex a) where\n sizeOf _ = sizeOf (undefined :: a) * 2\n alignment _ = alignment (undefined :: a)\n \n {-# SPECIALIZE INLINE peek :: Ptr (Complex Float) -> IO (Complex Float) #-}\n {-# SPECIALIZE INLINE peek :: Ptr (Complex Double) -> IO (Complex Double) #-}\n peek p = (:+) <$> peekElemOff (castPtr p) 0 <*> peekElemOff (castPtr p) 1\n\n {-# SPECIALIZE INLINE\n poke :: Ptr (Complex Float) -> Complex Float -> IO () #-}\n {-# SPECIALIZE INLINE\n poke :: Ptr (Complex Double) -> Complex Double -> IO () #-}\n poke p v = pokeElemOff (castPtr p) 0 (realPart v) >>\n pokeElemOff (castPtr p) 1 (imagPart v)\n\n\n\nreadBand :: (Storable a, HasDatatype (Ptr a))\n => RasterBand\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> IO (Maybe (Vector a))\nreadBand band xoff yoff sx sy bx by pxs lns = do\n fp <- mallocForeignPtrArray (bx * by)\n err <- withForeignPtr fp $ \\ptr -> do\n _ <- {#call GDALRasterAdviseRead as ^#}\n band\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (datatype ptr))\n (castPtr nullPtr)\n {#call GDALRasterIO as ^#}\n band\n (fromEnumC GF_Read) \n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (datatype ptr))\n (fromIntegral pxs)\n (fromIntegral lns)\n case toEnumC err of\n CE_None -> return $ Just $ unsafeFromForeignPtr0 fp (bx * by)\n _ -> return Nothing\n \nwriteBand :: (Storable a, HasDatatype (Ptr a))\n => RasterBand\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Int -> Int\n -> Vector a\n -> IO (Error)\nwriteBand band xoff yoff sx sy bx by pxs lns vec = do\n let nElems = bx * by\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len\n then return CE_Failure\n else withForeignPtr fp $ \\ptr -> liftM toEnumC $\n {#call GDALRasterIO as ^#}\n band\n (fromEnumC GF_Write) \n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (datatype ptr))\n (fromIntegral pxs)\n (fromIntegral lns)\n\ndata Block where\n Block :: (Typeable a, Storable a) => Vector a -> Block\n\nreadBlock :: (Storable a, Typeable a)\n => RasterBand -> Int -> Int -> MaybeIOVector a\nreadBlock b x y = do\n block <- readBlock' b x y\n liftM (maybe Nothing (\\(Block a) -> cast a)) $ readBlock' b x y\n\n\nreadBlock' :: RasterBand -> Int -> Int -> IO (Maybe Block)\nreadBlock' b x y = \n case bandDatatype b of\n GDT_Byte ->\n maybeReturn Block (readIt b x y :: MaybeIOVector Word8)\n GDT_Int16 ->\n maybeReturn Block (readIt b x y :: MaybeIOVector Int16)\n GDT_Int32 ->\n maybeReturn Block (readIt b x y :: MaybeIOVector Int32)\n GDT_Float32 ->\n maybeReturn Block (readIt b x y :: MaybeIOVector Float)\n GDT_Float64 ->\n maybeReturn Block (readIt b x y :: MaybeIOVector Double)\n GDT_CInt16 ->\n maybeReturn Block (readIt b x y :: MaybeIOVector (Complex Float))\n GDT_CInt32 ->\n maybeReturn Block (readIt b x y :: MaybeIOVector (Complex Double))\n GDT_CFloat32 ->\n maybeReturn Block (readIt b x y :: MaybeIOVector (Complex Float))\n GDT_CFloat64 ->\n maybeReturn Block (readIt b x y :: MaybeIOVector (Complex Double))\n _ -> return Nothing\n where\n maybeReturn f act = act >>= maybe (return Nothing) (return . Just . f)\n readIt b x y = do\n let l = blockLen b\n rb = {#call GDALReadBlock as ^#} b (fromIntegral x) (fromIntegral y)\n f <- mallocForeignPtrArray l\n e <- withForeignPtr f (rb . castPtr)\n if toEnumC e == CE_None\n then return $ Just $ unsafeFromForeignPtr0 f l\n else return Nothing\n\ntype MaybeIOVector a = IO (Maybe (Vector a))\n\nwriteBlock :: (Storable a, Typeable a)\n => RasterBand\n -> Int -> Int\n -> Vector a\n -> IO (Error)\nwriteBlock b x y vec = do\n let nElems = blockLen b\n (fp, len) = unsafeToForeignPtr0 vec\n if nElems \/= len || typeOf vec \/= typeOfBand b\n then return CE_Failure\n else withForeignPtr fp $ \\ptr -> liftM toEnumC $\n {#call GDALWriteBlock as ^#}\n b\n (fromIntegral x)\n (fromIntegral y)\n (castPtr ptr)\n\ntypeOfBand = typeOfdatatype . bandDatatype\n\ntypeOfdatatype dt =\n case dt of\n GDT_Byte -> typeOf (undefined :: Vector Word8)\n GDT_Int16 -> typeOf (undefined :: Vector Int16)\n GDT_Int32 -> typeOf (undefined :: Vector Int32)\n GDT_Float32 -> typeOf (undefined :: Vector Float)\n GDT_Float64 -> typeOf (undefined :: Vector Double)\n GDT_CInt16 -> typeOf (undefined :: Vector (Complex Float))\n GDT_CInt32 -> typeOf (undefined :: Vector (Complex Double))\n GDT_CFloat32 -> typeOf (undefined :: Vector (Complex Float))\n GDT_CFloat64 -> typeOf (undefined :: Vector (Complex Double))\n _ -> typeOf (undefined :: Bool) -- will never match a vector\n\nfromEnumC :: Enum a => a -> CInt\nfromEnumC = fromIntegral . fromEnum\n\ntoEnumC :: Enum a => CInt -> a\ntoEnumC = toEnum . fromIntegral\n\n\ntoOptionList :: [(String,String)] -> IO (Ptr CString)\ntoOptionList opts = foldM folder nullPtr opts\n where folder acc (k,v) = withCString k $ \\k' -> withCString v $ \\v' ->\n {#call unsafe CSLSetNameValue as ^#} acc k' v'\n\ntype Mutex = MVar ()\n\nnewMutex :: IO Mutex\nnewMutex = newMVar ()\n\n\nacquireMutex :: Mutex -> IO ()\nacquireMutex = takeMVar\n\nreleaseMutex :: Mutex -> IO ()\nreleaseMutex m = putMVar m ()\n\nwithMutex m action = finally (acquireMutex m >> action) (releaseMutex m)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"9c7725018655bfbb89b84a4a397224f30feb3512","subject":"Fix SourceStyleScheme docs.","message":"Fix SourceStyleScheme docs.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"Graphics\/UI\/Gtk\/SourceView\/SourceStyleScheme.chs","new_file":"Graphics\/UI\/Gtk\/SourceView\/SourceStyleScheme.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceStyleScheme\n--\n-- Author : Peter Gavin\n-- derived from sourceview bindings by Axel Simon and Duncan Coutts\n--\n-- Created: 18 December 2008\n--\n-- Copyright (C) 2004-2008 Peter Gavin, Duncan Coutts, Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\nmodule Graphics.UI.Gtk.SourceView.SourceStyleScheme (\n-- * Description\n-- | 'SourceStyleScheme' contains all the text styles to be used in 'SourceView' and\n-- 'SourceBuffer'. For instance, it contains text styles for syntax highlighting, it may contain\n-- foreground and background color for non-highlighted text, color for the line numbers, etc.\n-- \n-- Style schemes are stored in XML files. The format of a scheme file is the documented in the style\n-- scheme reference.\n\n-- * Types\n SourceStyleScheme,\n\n-- * Methods \n castToSourceStyleScheme,\n sourceStyleSchemeGetId,\n sourceStyleSchemeGetName,\n sourceStyleSchemeGetDescription,\n sourceStyleSchemeGetAuthors,\n sourceStyleSchemeGetFilename,\n sourceStyleSchemeGetStyle,\n\n-- * Attributes \n sourceStyleSchemeDescription,\n sourceStyleSchemeFilename,\n sourceStyleSchemeId,\n sourceStyleSchemeName,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(constructNewGObject)\nimport System.Glib.Attributes\n{#import System.Glib.Properties#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\nimport Graphics.UI.Gtk.SourceView.SourceStyle\n{#import Graphics.UI.Gtk.SourceView.SourceStyle.Internal#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | \n-- \nsourceStyleSchemeGetId :: SourceStyleScheme\n -> IO String -- ^ returns scheme id. \nsourceStyleSchemeGetId ss =\n {#call source_style_scheme_get_id#} ss >>= peekUTFString\n\n-- | \n-- \nsourceStyleSchemeGetName :: SourceStyleScheme \n -> IO String -- ^ returns scheme name. \nsourceStyleSchemeGetName ss =\n {#call source_style_scheme_get_name#} ss >>= peekUTFString\n\n-- | \n-- \nsourceStyleSchemeGetDescription :: SourceStyleScheme \n -> IO String -- ^ returns scheme description (if defined) or empty. \nsourceStyleSchemeGetDescription ss =\n {#call source_style_scheme_get_description#} ss >>= peekUTFString\n\n-- |\n--\nsourceStyleSchemeGetAuthors :: SourceStyleScheme \n -> IO [String] -- ^ returns an array containing the scheme authors or empty if no author is specified by the style scheme.\nsourceStyleSchemeGetAuthors ss =\n {#call source_style_scheme_get_authors#} ss >>= peekUTFStringArray0\n\n-- | \n-- \nsourceStyleSchemeGetFilename :: SourceStyleScheme \n -> IO String -- ^ returns scheme file name if the scheme was created parsing a style scheme file or empty in the other cases.\nsourceStyleSchemeGetFilename ss =\n {#call source_style_scheme_get_filename#} ss >>= peekUTFString\n\n-- | \n-- \nsourceStyleSchemeGetStyle :: SourceStyleScheme \n -> String -- ^ @styleId@ id of the style to retrieve.\n -> IO SourceStyle -- ^ returns style which corresponds to @styleId@ in the scheme\nsourceStyleSchemeGetStyle ss id = do\n styleObj <- makeNewGObject mkSourceStyleObject $\n withUTFString id ({#call source_style_scheme_get_style#} ss)\n sourceStyleFromObject styleObj\n\n-- | Style scheme description.\n-- \n-- Default value: \\\"\\\"\n--\nsourceStyleSchemeDescription :: ReadAttr SourceStyleScheme String\nsourceStyleSchemeDescription = readAttrFromStringProperty \"description\"\n\n-- | Style scheme filename or 'Nothing'.\n-- \n-- Default value: \\\"\\\"\n--\nsourceStyleSchemeFilename :: ReadAttr SourceStyleScheme FilePath\nsourceStyleSchemeFilename = readAttrFromStringProperty \"filename\"\n\n-- | Style scheme id, a unique string used to identify the style scheme in 'SourceStyleSchemeManager'.\n-- \n-- Default value: \\\"\\\"\n--\nsourceStyleSchemeId :: ReadAttr SourceStyleScheme String\nsourceStyleSchemeId = readAttrFromStringProperty \"id\"\n\n-- | Style scheme name, a translatable string to present to user.\n-- \n-- Default value: \\\"\\\"\n--\nsourceStyleSchemeName :: ReadAttr SourceStyleScheme String\nsourceStyleSchemeName = readAttrFromStringProperty \"name\"\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) SourceStyleScheme\n--\n-- Author : Peter Gavin\n-- derived from sourceview bindings by Axel Simon and Duncan Coutts\n--\n-- Created: 18 December 2008\n--\n-- Copyright (C) 2004-2008 Peter Gavin, Duncan Coutts, Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\nmodule Graphics.UI.Gtk.SourceView.SourceStyleScheme (\n SourceStyleScheme,\n castToSourceStyleScheme,\n sourceStyleSchemeGetId,\n sourceStyleSchemeGetName,\n sourceStyleSchemeGetDescription,\n sourceStyleSchemeGetAuthors,\n sourceStyleSchemeGetFilename,\n sourceStyleSchemeGetStyle,\n sourceStyleSchemeDescription,\n sourceStyleSchemeFilename,\n sourceStyleSchemeId,\n sourceStyleSchemeName,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t(constructNewGObject)\nimport System.Glib.Attributes\n{#import System.Glib.Properties#}\n{#import Graphics.UI.Gtk.SourceView.Types#}\nimport Graphics.UI.Gtk.SourceView.SourceStyle\n{#import Graphics.UI.Gtk.SourceView.SourceStyle.Internal#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- | \n-- \nsourceStyleSchemeGetId :: SourceStyleScheme -> IO String\nsourceStyleSchemeGetId ss =\n {#call source_style_scheme_get_id#} ss >>= peekUTFString\n\n-- | \n-- \nsourceStyleSchemeGetName :: SourceStyleScheme -> IO String\nsourceStyleSchemeGetName ss =\n {#call source_style_scheme_get_name#} ss >>= peekUTFString\n\n-- | \n-- \nsourceStyleSchemeGetDescription :: SourceStyleScheme -> IO String\nsourceStyleSchemeGetDescription ss =\n {#call source_style_scheme_get_description#} ss >>= peekUTFString\n\n-- |\n--\nsourceStyleSchemeGetAuthors :: SourceStyleScheme -> IO [String]\nsourceStyleSchemeGetAuthors ss =\n {#call source_style_scheme_get_authors#} ss >>= peekUTFStringArray0\n\n-- | \n-- \nsourceStyleSchemeGetFilename :: SourceStyleScheme -> IO String\nsourceStyleSchemeGetFilename ss =\n {#call source_style_scheme_get_filename#} ss >>= peekUTFString\n\n-- | \n-- \nsourceStyleSchemeGetStyle :: SourceStyleScheme -> String -> IO SourceStyle\nsourceStyleSchemeGetStyle ss id = do\n styleObj <- makeNewGObject mkSourceStyleObject $\n withUTFString id ({#call source_style_scheme_get_style#} ss)\n sourceStyleFromObject styleObj\n\n-- |\n--\nsourceStyleSchemeDescription :: ReadAttr SourceStyleScheme String\nsourceStyleSchemeDescription = readAttrFromStringProperty \"description\"\n\n-- |\n--\nsourceStyleSchemeFilename :: ReadAttr SourceStyleScheme FilePath\nsourceStyleSchemeFilename = readAttrFromStringProperty \"filename\"\n\n-- |\n--\nsourceStyleSchemeId :: ReadAttr SourceStyleScheme String\nsourceStyleSchemeId = readAttrFromStringProperty \"id\"\n\n-- |\n--\nsourceStyleSchemeName :: ReadAttr SourceStyleScheme String\nsourceStyleSchemeName = readAttrFromStringProperty \"name\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"2ddf6a4a65d23699e4f266671401e901c421493f","subject":"gnomevfs: add function S.G.V.Volume.volumeUnmount","message":"gnomevfs: add function S.G.V.Volume.volumeUnmount","repos":"vincenthz\/webkit","old_file":"gnomevfs\/System\/Gnome\/VFS\/Volume.chs","new_file":"gnomevfs\/System\/Gnome\/VFS\/Volume.chs","new_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to libgnomevfs -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GnomeVFS, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GnomeVFS documentation,\n-- Copyright (c) 2001 Seth Nickell . The\n-- documentation is covered by the GNU Free Documentation License,\n-- version 1.2.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.Gnome.VFS.Volume (\n \n-- * Types\n -- | An abstraction for a mounted filesystem or network location.\n Volume,\n VolumeClass,\n VolumeID,\n -- | Safely cast an object to a 'Volume'.\n castToVolume,\n \n-- * Volume Operations\n volumeCompare,\n volumeEject,\n volumeGetActivationURI,\n volumeGetDevicePath,\n volumeGetDeviceType,\n volumeGetDisplayName,\n volumeGetDrive,\n volumeGetFilesystemType,\n volumeGetHalUDI,\n volumeGetIcon,\n volumeGetID,\n volumeGetVolumeType,\n volumeHandlesTrash,\n volumeIsMounted,\n volumeIsReadOnly,\n volumeIsUserVisible,\n volumeUnmount\n \n ) where\n\nimport Control.Exception\nimport Control.Monad (liftM)\nimport System.Glib.UTFString\nimport System.Glib.FFI\n{#import System.Gnome.VFS.Marshal#}\n{#import System.Gnome.VFS.Types#}\n\n{# context lib = \"gnomevfs\" prefix = \"gnome_vfs\" #}\n\n-- | Compares two 'Volume' objects @a@ and @b@. Two 'Volume'\n-- objects referring to different volumes are guaranteed to not\n-- return 'EQ' when comparing them. If they refer to the same volume 'EQ'\n-- is returned.\n-- \n-- The resulting gint should be used to determine the order in which\n-- @a@ and @b@ are displayed in graphical user interfaces.\n-- \n-- The comparison algorithm first of all peeks the device type of\n-- @a@ and @b@, they will be sorted in the following order:\n-- \n-- * Magnetic and opto-magnetic volumes (ZIP, floppy)\n-- \n-- * Optical volumes (CD, DVD)\n-- \n-- * External volumes (USB sticks, music players)\n-- \n-- * Mounted hard disks\n-- \n-- * Network mounts\n-- \n-- * Other volumes\n-- \n-- Afterwards, the display name of @a@ and @b@ is compared using a\n-- locale-sensitive sorting algorithm.\n-- \n-- If two volumes have the same display name, their unique ID is\n-- compared which can be queried using 'volumeGetID'.\nvolumeCompare :: (VolumeClass volume1, VolumeClass volume2)\n => volume1\n -> volume2\n -> IO Ordering\nvolumeCompare a b =\n do result <- liftM fromIntegral $ {# call volume_compare #} (castToVolume a) (castToVolume b)\n let ordering | result < 0 = LT\n | result > 0 = GT\n | otherwise = EQ\n return ordering\n\n-- Requests ejection of a 'Volume'.\n-- \n-- Before the unmount operation is executed, the\n-- 'Volume' object's @pre-unmount@ signal is emitted.\n-- \n-- If the volume is a mount point, i.e. its type is\n-- 'VolumeTypeMountpoint', it is unmounted, and if it refers to a\n-- disk, it is also ejected.\n-- \n-- If the volume is a special VFS mount, i.e. its type is\n-- 'VolumeTypeMount', it is ejected.\n-- \n-- If the volume is a connected server, it is removed from the list of\n-- connected servers.\n-- \n-- Otherwise, no further action is done.\nvolumeEject :: VolumeClass volume\n => volume -- ^ @volume@ - the volume to eject\n -> VolumeOpSuccessCallback -- ^ @successCallback@ - the\n -- callback to call once\n -- the operation has\n -- completed successfully\n -> VolumeOpFailureCallback -- ^ @failureCallback@ - the\n -- callback to call if the\n -- operation fails\n -> IO ()\nvolumeEject volume successCallback failureCallback =\n do cCallback <- volumeOpCallbackMarshal successCallback failureCallback\n {# call volume_eject #} (castToVolume volume) cCallback $ castFunPtrToPtr cCallback\n\nmarshalString cAction volume =\n cAction (castToVolume volume) >>= readUTFString\nmarshalMaybeString cAction volume =\n cAction (castToVolume volume) >>= maybePeek readUTFString\n\n-- | Returns the activation URI of @volume@.\n-- \n-- The returned URI usually refers to a valid location. You can\n-- check the validity of the location by calling 'uriFromString'\n-- with the URI, and checking whether the return value is not\n-- 'Nothing'.\nvolumeGetActivationURI :: VolumeClass volume\n => volume -- ^ @volume@ - the volume to query\n -> IO TextURI -- ^ the volume's activation URI.\nvolumeGetActivationURI =\n marshalString {# call volume_get_activation_uri #}\n\n-- | Returns the device path of a 'Volume' object.\n-- \n-- For HAL volumes, this returns the value of the volume's\n-- @block.device@ key. For UNIX mounts, it returns the @mntent@'s\n-- @mnt_fsname@ entry.\n-- \n-- Otherwise, it returns 'Nothing'.\nvolumeGetDevicePath :: VolumeClass volume =>\n volume -- ^ @volume@ - the volume object to query\n -> IO String -- ^ the volume's device path\nvolumeGetDevicePath =\n marshalString {# call volume_get_device_path #}\n\n-- | Returns the 'DeviceType' of a 'Volume' object.\nvolumeGetDeviceType :: VolumeClass volume =>\n volume -- ^ @volume@ - the volume object to query\n -> IO DeviceType -- the volume's device type\nvolumeGetDeviceType volume =\n liftM cToEnum $ {# call volume_get_device_type #} (castToVolume volume)\n\n-- | Returns the display name of a 'Volume' object.\nvolumeGetDisplayName :: VolumeClass volume =>\n volume -- ^ @volume@ - the volume object to query\n -> IO String -- ^ the volume's display name\nvolumeGetDisplayName =\n marshalString {# call volume_get_display_name #}\n\n-- | Returns the 'Drive' that @volume@ is on.\nvolumeGetDrive :: VolumeClass volume =>\n volume -- ^ @volume@ - the volume object to query\n -> IO Drive -- ^ the containing drive\nvolumeGetDrive volume =\n {# call volume_get_drive #} (castToVolume volume) >>= newDrive\n\n-- | Returns a string describing the file system on @volume@, or\n-- 'Nothing' if no information on the underlying file system is\n-- available.\n-- \n-- The file system may be used to provide special functionality that\n-- depends on the file system type, for instance to determine\n-- whether trashing is supported (cf. 'volumeHandlesTrash').\n-- \n-- For HAL mounts, this returns the value of the @\\\"volume.fstype\\\"@\n-- key, for traditional UNIX mounts it is set to the mntent's\n-- mnt_type key, for connected servers, 'Nothing' is returned.\nvolumeGetFilesystemType :: VolumeClass volume =>\n volume -- ^ @volume@ - the\n -- volume object to query\n -> IO (Maybe String) -- ^ a string describing\n -- the filesystem type,\n -- or 'Nothing' if no\n -- information is\n -- available\nvolumeGetFilesystemType =\n marshalMaybeString {# call volume_get_filesystem_type #}\n\n-- | Returns the HAL UDI of a 'Volume' object.\n-- \n-- For HAL volumes, this matches the value of the @info.udi@ key,\n-- for other volumes it is 'Nothing'.\nvolumeGetHalUDI :: VolumeClass volume =>\n volume -- ^ @volume@ - the volume object to query\n -> IO (Maybe String) -- ^ the volume's HAL UDI\nvolumeGetHalUDI =\n marshalMaybeString {# call volume_get_hal_udi #}\n\n-- | Returns the icon filename for a 'Volume' object.\nvolumeGetIcon :: VolumeClass volume =>\n volume -- ^ @volume@ - a volume object\n -> IO FilePath -- ^ the icon that should be used for this volume\nvolumeGetIcon =\n marshalString {# call volume_get_icon #}\n\n-- | Returns a unique identifier for a 'Volume' object.\nvolumeGetID :: VolumeClass volume =>\n volume -- ^ @volume@ - a volume object\n -> IO VolumeID -- ^ a unique identifier for the volume\nvolumeGetID volume =\n {# call volume_get_id #} (castToVolume volume)\n\n-- | Returns the volume type of @volume@.\nvolumeGetVolumeType :: VolumeClass volume =>\n volume -- ^ @volume@ - the volume object to query\n -> IO VolumeType -- ^ the volume's volume type\nvolumeGetVolumeType volume =\n liftM cToEnum $ {# call volume_get_volume_type #} (castToVolume volume)\n\nmarshalBool cAction volume =\n liftM toBool $ cAction (castToVolume volume)\n\n-- | Returns whether the file system on a volume supports trashing of\n-- files.\n-- \n-- If the volume has an AutoFS file system (i.e.,\n-- 'volumeGetDeviceType' returns 'DeviceTypeAutofs'), or if the\n-- volume is mounted read-only (i.e., 'volumeIsReadOnly' returns\n-- 'True'), it is assumed to not support trashing of files.\n-- \n-- Otherwise, if the volume provides file system information, it is\n-- determined whether the file system supports trashing of\n-- files.\nvolumeHandlesTrash :: VolumeClass volume =>\n volume -- ^ @volume@ - \n -> IO Bool -- ^ 'True' if the volume handles trash, otherwise 'False'\nvolumeHandlesTrash =\n marshalBool {# call volume_handles_trash #}\n\n-- | Returns whether the file system on a volume is currently mounted.\n-- \n-- For HAL volumes, this reflects the value of the\n-- @\\\"volume.is_mounted\\\"@ key, for traditional UNIX mounts and\n-- connected servers, 'True' is returned, because their existence\n-- implies that they are mounted.\nvolumeIsMounted :: VolumeClass volume =>\n volume -- ^ @volume@ - \n -> IO Bool -- ^ 'True' if the volume is mounted, otherwise 'False'\nvolumeIsMounted =\n marshalBool {# call volume_is_mounted #}\n\n-- | Returns whether the file system on a volume is read-only.\n-- \n-- For HAL volumes, the @\\\"volume.is_mounted_read_only\\\"@ key is\n-- authoritative, for traditional UNIX mounts it returns TRUE if the\n-- mount was done with the @\\\"ro\\\"@ option. For servers, 'False' is\n-- returned.\nvolumeIsReadOnly :: VolumeClass volume =>\n volume -- ^ @volume@ - \n -> IO Bool -- ^ 'True' if the volume is read-only, otherwise 'False'\nvolumeIsReadOnly =\n marshalBool {# call volume_is_read_only #}\n\n-- | Returns a 'Bool' for whether a volume is user-visible. This should\n-- be used by applications to determine whether the volume should be\n-- listed in user interfaces listing available volumes.\nvolumeIsUserVisible :: VolumeClass volume =>\n volume -- @volume@ - \n -> IO Bool -- ^ 'True' if the volume is user visible, otherwise 'False'\nvolumeIsUserVisible =\n marshalBool {# call volume_is_user_visible #}\n\n-- Requests unmount of a 'Volume'.\n-- \n-- Note that 'volumeUnmount' may also unvoke 'volumeEject', if\n-- @volume@ signals that it should be ejected when it is unmounted.\n-- This may be true for CD-ROMs, USB sticks, and other devices,\n-- depending on the backend providing the volume.\nvolumeUnmount :: VolumeClass volume\n => volume -- ^ @volume@ - the volume to eject\n -> VolumeOpSuccessCallback -- ^ @successCallback@ - the\n -- callback to call once\n -- the operation has\n -- completed successfully\n -> VolumeOpFailureCallback -- ^ @failureCallback@ - the\n -- callback to call if the\n -- operation fails\n -> IO ()\nvolumeUnmount volume successCallback failureCallback =\n do cCallback <- volumeOpCallbackMarshal successCallback failureCallback\n {# call volume_unmount #} (castToVolume volume) cCallback $ castFunPtrToPtr cCallback\n","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to libgnomevfs -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GnomeVFS, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GnomeVFS documentation,\n-- Copyright (c) 2001 Seth Nickell . The\n-- documentation is covered by the GNU Free Documentation License,\n-- version 1.2.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.Gnome.VFS.Volume (\n \n-- * Types\n -- | An abstraction for a mounted filesystem or network location.\n Volume,\n VolumeClass,\n VolumeID,\n -- | Safely cast an object to a 'Volume'.\n castToVolume,\n \n-- * Volume Operations\n volumeCompare,\n volumeEject,\n volumeGetActivationURI,\n volumeGetDevicePath,\n volumeGetDeviceType,\n volumeGetDisplayName,\n volumeGetDrive,\n volumeGetFilesystemType,\n volumeGetHalUDI,\n volumeGetIcon,\n volumeGetID,\n volumeGetVolumeType,\n volumeHandlesTrash,\n volumeIsMounted,\n volumeIsReadOnly,\n volumeIsUserVisible\n \n ) where\n\nimport Control.Exception\nimport Control.Monad (liftM)\nimport System.Glib.UTFString\nimport System.Glib.FFI\n{#import System.Gnome.VFS.Marshal#}\n{#import System.Gnome.VFS.Types#}\n\n{# context lib = \"gnomevfs\" prefix = \"gnome_vfs\" #}\n\n-- | Compares two 'Volume' objects @a@ and @b@. Two 'Volume'\n-- objects referring to different volumes are guaranteed to not\n-- return 'EQ' when comparing them. If they refer to the same volume 'EQ'\n-- is returned.\n-- \n-- The resulting gint should be used to determine the order in which\n-- @a@ and @b@ are displayed in graphical user interfaces.\n-- \n-- The comparison algorithm first of all peeks the device type of\n-- @a@ and @b@, they will be sorted in the following order:\n-- \n-- * Magnetic and opto-magnetic volumes (ZIP, floppy)\n-- \n-- * Optical volumes (CD, DVD)\n-- \n-- * External volumes (USB sticks, music players)\n-- \n-- * Mounted hard disks\n-- \n-- * Network mounts\n-- \n-- * Other volumes\n-- \n-- Afterwards, the display name of @a@ and @b@ is compared using a\n-- locale-sensitive sorting algorithm.\n-- \n-- If two volumes have the same display name, their unique ID is\n-- compared which can be queried using 'volumeGetID'.\nvolumeCompare :: (VolumeClass volume1, VolumeClass volume2)\n => volume1\n -> volume2\n -> IO Ordering\nvolumeCompare a b =\n do result <- liftM fromIntegral $ {# call volume_compare #} (castToVolume a) (castToVolume b)\n let ordering | result < 0 = LT\n | result > 0 = GT\n | otherwise = EQ\n return ordering\n\n-- Requests ejection of a 'Volume'.\n-- \n-- Before the unmount operation is executed, the\n-- 'Volume' object's @pre-unmount@ signal is emitted.\n-- \n-- If the volume is a mount point, i.e. its type is\n-- 'VolumeTypeMountpoint', it is unmounted, and if it refers to a\n-- disk, it is also ejected.\n-- \n-- If the volume is a special VFS mount, i.e. its type is\n-- 'VolumeTypeMount', it is ejected.\n-- \n-- If the volume is a connected server, it is removed from the list of\n-- connected servers.\n-- \n-- Otherwise, no further action is done.\nvolumeEject :: VolumeClass volume\n => volume -- ^ @volume@ - the volume to eject\n -> VolumeOpSuccessCallback -- ^ @successCallback@ - the\n -- callback to call once\n -- the operation has\n -- completed successfully\n -> VolumeOpFailureCallback -- ^ @failureCallback@ - the\n -- callback to call if the\n -- operation fails\n -> IO ()\nvolumeEject volume successCallback failureCallback =\n do cCallback <- volumeOpCallbackMarshal successCallback failureCallback\n {# call volume_eject #} (castToVolume volume) cCallback $ castFunPtrToPtr cCallback\n\nmarshalString cAction volume =\n cAction (castToVolume volume) >>= readUTFString\nmarshalMaybeString cAction volume =\n cAction (castToVolume volume) >>= maybePeek readUTFString\n\n-- | Returns the activation URI of @volume@.\n-- \n-- The returned URI usually refers to a valid location. You can\n-- check the validity of the location by calling 'uriFromString'\n-- with the URI, and checking whether the return value is not\n-- 'Nothing'.\nvolumeGetActivationURI :: VolumeClass volume\n => volume -- ^ @volume@ - the volume to query\n -> IO TextURI -- ^ the volume's activation URI.\nvolumeGetActivationURI =\n marshalString {# call volume_get_activation_uri #}\n\n-- | Returns the device path of a 'Volume' object.\n-- \n-- For HAL volumes, this returns the value of the volume's\n-- @block.device@ key. For UNIX mounts, it returns the @mntent@'s\n-- @mnt_fsname@ entry.\n-- \n-- Otherwise, it returns 'Nothing'.\nvolumeGetDevicePath :: VolumeClass volume =>\n volume -- ^ @volume@ - the volume object to query\n -> IO String -- ^ the volume's device path\nvolumeGetDevicePath =\n marshalString {# call volume_get_device_path #}\n\n-- | Returns the 'DeviceType' of a 'Volume' object.\nvolumeGetDeviceType :: VolumeClass volume =>\n volume -- ^ @volume@ - the volume object to query\n -> IO DeviceType -- the volume's device type\nvolumeGetDeviceType volume =\n liftM cToEnum $ {# call volume_get_device_type #} (castToVolume volume)\n\n-- | Returns the display name of a 'Volume' object.\nvolumeGetDisplayName :: VolumeClass volume =>\n volume -- ^ @volume@ - the volume object to query\n -> IO String -- ^ the volume's display name\nvolumeGetDisplayName =\n marshalString {# call volume_get_display_name #}\n\n-- | Returns the 'Drive' that @volume@ is on.\nvolumeGetDrive :: VolumeClass volume =>\n volume -- ^ @volume@ - the volume object to query\n -> IO Drive -- ^ the containing drive\nvolumeGetDrive volume =\n {# call volume_get_drive #} (castToVolume volume) >>= newDrive\n\n-- | Returns a string describing the file system on @volume@, or\n-- 'Nothing' if no information on the underlying file system is\n-- available.\n-- \n-- The file system may be used to provide special functionality that\n-- depends on the file system type, for instance to determine\n-- whether trashing is supported (cf. 'volumeHandlesTrash').\n-- \n-- For HAL mounts, this returns the value of the @\\\"volume.fstype\\\"@\n-- key, for traditional UNIX mounts it is set to the mntent's\n-- mnt_type key, for connected servers, 'Nothing' is returned.\nvolumeGetFilesystemType :: VolumeClass volume =>\n volume -- ^ @volume@ - the\n -- volume object to query\n -> IO (Maybe String) -- ^ a string describing\n -- the filesystem type,\n -- or 'Nothing' if no\n -- information is\n -- available\nvolumeGetFilesystemType =\n marshalMaybeString {# call volume_get_filesystem_type #}\n\n-- | Returns the HAL UDI of a 'Volume' object.\n-- \n-- For HAL volumes, this matches the value of the @info.udi@ key,\n-- for other volumes it is 'Nothing'.\nvolumeGetHalUDI :: VolumeClass volume =>\n volume -- ^ @volume@ - the volume object to query\n -> IO (Maybe String) -- ^ the volume's HAL UDI\nvolumeGetHalUDI =\n marshalMaybeString {# call volume_get_hal_udi #}\n\n-- | Returns the icon filename for a 'Volume' object.\nvolumeGetIcon :: VolumeClass volume =>\n volume -- ^ @volume@ - a volume object\n -> IO FilePath -- ^ the icon that should be used for this volume\nvolumeGetIcon =\n marshalString {# call volume_get_icon #}\n\n-- | Returns a unique identifier for a 'Volume' object.\nvolumeGetID :: VolumeClass volume =>\n volume -- ^ @volume@ - a volume object\n -> IO VolumeID -- ^ a unique identifier for the volume\nvolumeGetID volume =\n {# call volume_get_id #} (castToVolume volume)\n\n-- | Returns the volume type of @volume@.\nvolumeGetVolumeType :: VolumeClass volume =>\n volume -- ^ @volume@ - the volume object to query\n -> IO VolumeType -- ^ the volume's volume type\nvolumeGetVolumeType volume =\n liftM cToEnum $ {# call volume_get_volume_type #} (castToVolume volume)\n\nmarshalBool cAction volume =\n liftM toBool $ cAction (castToVolume volume)\n\n-- | Returns whether the file system on a volume supports trashing of\n-- files.\n-- \n-- If the volume has an AutoFS file system (i.e.,\n-- 'volumeGetDeviceType' returns 'DeviceTypeAutofs'), or if the\n-- volume is mounted read-only (i.e., 'volumeIsReadOnly' returns\n-- 'True'), it is assumed to not support trashing of files.\n-- \n-- Otherwise, if the volume provides file system information, it is\n-- determined whether the file system supports trashing of\n-- files.\nvolumeHandlesTrash :: VolumeClass volume =>\n volume -- ^ @volume@ - \n -> IO Bool -- ^ 'True' if the volume handles trash, otherwise 'False'\nvolumeHandlesTrash =\n marshalBool {# call volume_handles_trash #}\n\n-- | Returns whether the file system on a volume is currently mounted.\n-- \n-- For HAL volumes, this reflects the value of the\n-- @\\\"volume.is_mounted\\\"@ key, for traditional UNIX mounts and\n-- connected servers, 'True' is returned, because their existence\n-- implies that they are mounted.\nvolumeIsMounted :: VolumeClass volume =>\n volume -- ^ @volume@ - \n -> IO Bool -- ^ 'True' if the volume is mounted, otherwise 'False'\nvolumeIsMounted =\n marshalBool {# call volume_is_mounted #}\n\n-- | Returns whether the file system on a volume is read-only.\n-- \n-- For HAL volumes, the @\\\"volume.is_mounted_read_only\\\"@ key is\n-- authoritative, for traditional UNIX mounts it returns TRUE if the\n-- mount was done with the @\\\"ro\\\"@ option. For servers, 'False' is\n-- returned.\nvolumeIsReadOnly :: VolumeClass volume =>\n volume -- ^ @volume@ - \n -> IO Bool -- ^ 'True' if the volume is read-only, otherwise 'False'\nvolumeIsReadOnly =\n marshalBool {# call volume_is_read_only #}\n\n-- | Returns a 'Bool' for whether a volume is user-visible. This should\n-- be used by applications to determine whether the volume should be\n-- listed in user interfaces listing available volumes.\nvolumeIsUserVisible :: VolumeClass volume =>\n volume -- @volume@ - \n -> IO Bool -- ^ 'True' if the volume is user visible, otherwise 'False'\nvolumeIsUserVisible =\n marshalBool {# call volume_is_user_visible #}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"077cc6f368a2caf4d0de4114156944a5894f4b60","subject":"Unswap middle\/right mouse buttons.","message":"Unswap middle\/right mouse buttons.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/FL.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/FL.chs","new_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n\nmodule Graphics.UI.FLTK.LowLevel.FL\n (\n Option(..),\n ClipboardContents(..),\n scrollbarSize,\n setScrollbarSize,\n selectionOwner,\n setSelectionOwner,\n run,\n replRun,\n check,\n ready,\n option,\n setOption,\n lock,\n unlock,\n awake,\n awakeToHandler,\n addAwakeHandler_,\n getAwakeHandler_,\n display,\n ownColormap,\n getSystemColors,\n foreground,\n background,\n background2,\n setScheme,\n getScheme,\n reloadScheme,\n isScheme,\n setFirstWindow,\n nextWindow,\n setGrab,\n getMouse,\n eventStates,\n extract,\n extractEventStates,\n handle,\n handle_,\n belowmouse,\n setBelowmouse,\n setPushed,\n setFocus,\n setHandler,\n toRectangle,\n fromRectangle,\n screenBounds,\n screenDPI,\n screenWorkArea,\n setColorRgb,\n toAttribute,\n release,\n setVisibleFocus,\n visibleFocus,\n setDndTextOps,\n dndTextOps,\n deleteWidget,\n doWidgetDeletion,\n watchWidgetPointer,\n releaseWidgetPointer,\n clearWidgetPointer,\n version,\n help,\n visual,\n#if !defined(__APPLE__) && defined(GLSUPPORT)\n glVisual,\n glVisualWithAlist,\n#endif\n wait,\n setWait,\n waitFor,\n readqueue,\n addTimeout,\n repeatTimeout,\n hasTimeout,\n removeTimeout,\n addCheck,\n hasCheck,\n removeCheck,\n addIdle,\n hasIdle,\n removeIdle,\n damage,\n redraw,\n flush,\n firstWindow,\n modal,\n grab,\n getKey,\n compose,\n composeReset,\n testShortcut,\n enableIm,\n disableIm,\n pushed,\n focus,\n copyToClipboard,\n copyToSelectionBuffer,\n copyLengthToClipboard,\n copyLengthToSelectionBuffer,\n pasteImageFromSelectionBuffer,\n pasteFromSelectionBuffer,\n pasteImageFromClipboard,\n pasteFromClipboard,\n dnd,\n x,\n y,\n w,\n h,\n screenCount,\n setColor,\n getColor,\n getColorRgb,\n#if !defined(__APPLE__)\n removeFromColormap,\n#endif\n -- * Box\n BoxtypeSpec(..),\n getBoxtype,\n setBoxtype,\n boxDx,\n boxDy,\n boxDw,\n boxDh,\n adjustBoundsByBoxtype,\n boxDifferences,\n drawBoxActive,\n -- * Fonts\n getFontName,\n getFont,\n getFontSizes,\n setFontToString,\n setFontToFont,\n setFonts,\n -- * File Descriptor Callbacks\n addFd,\n addFdWhen,\n removeFd,\n removeFdWhen,\n -- * Events\n event,\n eventShift,\n eventCtrl,\n eventCommand,\n eventAlt,\n eventButtons,\n eventButton1,\n eventButton2,\n eventButton3,\n eventX,\n eventY,\n eventPosition,\n eventXRoot,\n eventYRoot,\n eventRootPosition,\n eventDx,\n eventDy,\n eventClicks,\n setEventClicks,\n eventIsClick,\n setEventIsClick,\n eventButton,\n eventState,\n containsEventState,\n eventKey,\n eventOriginalKey,\n eventKeyPressed,\n eventInsideRegion,\n eventInsideWidget,\n eventDispatch,\n setEventDispatch,\n eventText,\n eventLength,\n eventClipboardContents,\n setBoxColor,\n boxColor,\n abiVersion,\n apiVersion,\n abiCheck,\n localCtrl,\n localMeta,\n localAlt,\n localShift\n#ifdef GLSUPPORT\n , useHighResGL\n , setUseHighResGL\n#endif\n , insertionPointLocation\n , resetMarkedText\n , runChecks\n , screenDriver\n , systemDriver\n , screenXYWH\n , setProgramShouldQuit\n , getProgramShouldQuit\n )\nwhere\n#include \"Fl_C.h\"\nimport C2HS hiding (cFromEnum, cToBool,cToEnum,cFromBool)\nimport Data.IORef\n\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Hierarchy hiding (\n setVisibleFocus,\n handle,\n redraw,\n flush,\n testShortcut,\n copy,\n setColor,\n getColor,\n focus,\n display,\n setScrollbarSize\n )\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\nimport qualified Data.Text.Foreign as TF\nimport qualified System.IO.Unsafe as Unsafe (unsafePerformIO)\nimport Control.Exception(catch, throw, AsyncException(UserInterrupt))\nimport Control.Monad(forever)\n#c\n enum Option {\n OptionArrowFocus = OPTION_ARROW_FOCUS,\n OptionVisibleFocus = OPTION_VISIBLE_FOCUS,\n OptionDndText = OPTION_DND_TEXT,\n OptionShowTooltips = OPTION_SHOW_TOOLTIPS,\n OptionLast = OPTION_LAST\n };\n#endc\n\n{#enum Option {} deriving (Show) #}\n\nptrToGlobalEventHandler :: IORef (FunPtr GlobalEventHandlerPrim)\nptrToGlobalEventHandler = Unsafe.unsafePerformIO $ do\n initialHandler <- toGlobalEventHandlerPrim (\\_ -> return (-1))\n newIORef initialHandler\n\n-- | Contents of the clipboard following a copy or cut. Can be either an <.\/Graphics-UI-FLTK-LowLevel-Image.html Image> or plain 'T.Text'.\ndata ClipboardContents =\n ClipboardContentsImage (Maybe (Ref Image))\n | ClipboardContentsPlainText (Maybe T.Text)\n\ntype EventDispatchPrim = (CInt ->\n Ptr () ->\n IO CInt)\nforeign import ccall \"wrapper\"\n wrapEventDispatchPrim :: EventDispatchPrim ->\n IO (FunPtr EventDispatchPrim)\nforeign import ccall \"dynamic\"\n unwrapEventDispatchPrim :: FunPtr EventDispatchPrim -> EventDispatchPrim\n\nrun :: IO Int\nrun = {#call Fl_run as fl_run #} >>= return . fromIntegral\n\ncheck :: IO Int\ncheck = {#call Fl_check as fl_check #} >>= return . fromIntegral\n\nready :: IO Int\nready = {#call Fl_ready as fl_ready #} >>= return . fromIntegral\n\n\noption :: Option -> IO Bool\noption o = {#call Fl_option as fl_option #} (cFromEnum o) >>= \\(c::CInt) -> return $ cToBool $ ((fromIntegral c) :: Int)\n\nsetOption :: Option -> Bool -> IO ()\nsetOption o t = {#call Fl_set_option as fl_set_option #} (cFromEnum o) (Graphics.UI.FLTK.LowLevel.Utils.cFromBool t)\n\nlock :: IO Bool\nlock = {#call Fl_lock as fl_lock #} >>= return . cToBool\n\nunlock :: IO ()\nunlock = {#call Fl_unlock as fl_unlock #}\n\nawake :: IO ()\nawake = {#call Fl_awake as fl_awake #}\n\nawakeToHandler :: IO ()\nawakeToHandler = {#call Fl_awake_to_handler as fl_awake_to_handler #}\n\n{# fun Fl_add_awake_handler_ as addAwakeHandler'\n {id `FunPtr CallbackPrim', id `(Ptr ())'} -> `Int' #}\naddAwakeHandler_ :: GlobalCallback -> IO (Either AwakeRingFull ())\naddAwakeHandler_ awakeHandler =\n do\n callbackPtr <- toGlobalCallbackPrim awakeHandler\n res <- addAwakeHandler' callbackPtr nullPtr\n return (successOrAwakeRingFull res)\n\n{# fun Fl_get_awake_handler_ as getAwakeHandler_'\n {id `Ptr (FunPtr CallbackPrim)', id `Ptr (Ptr ())'} -> `Int' #}\ngetAwakeHandler_ :: IO GlobalCallback\ngetAwakeHandler_ =\n alloca $ \\ptrToFunPtr ->\n alloca $ \\ptrToUD -> do\n _ <- getAwakeHandler_' ptrToFunPtr ptrToUD\n funPtr <- peek ptrToFunPtr\n return $ unwrapGlobalCallbackPtr $ castFunPtr funPtr\n\n{# fun Fl_version as version\n {} -> `Double' #}\n{# fun Fl_help as help' {} -> `CString' #}\nhelp :: IO T.Text\nhelp = help' >>= cStringToText\n\ndisplay :: T.Text -> IO ()\ndisplay text = TF.withCStringLen text $ \\(str,_) -> {#call Fl_display as fl_display #} str\n{# fun Fl_visual as visual\n {cFromEnum `Mode'} -> `Bool' cToBool #}\n#if !defined(__APPLE__) && defined(GLSUPPORT)\n-- | Only available if on a non OSX platform and if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{# fun Fl_gl_visual as glVisual\n {cFromEnum `Mode'} -> `Bool' cToBool #}\n-- | Only available if on a non OSX platform and if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{# fun Fl_gl_visual_with_alist as glVisualWithAlist\n {cFromEnum `Mode', id `Ptr CInt'} -> `Bool' cToBool #}\n#endif\n\nownColormap :: IO ()\nownColormap = {#call Fl_own_colormap as fl_own_colormap #}\n\ngetSystemColors :: IO ()\ngetSystemColors = {#call Fl_get_system_colors as fl_get_system_colors #}\n\nforeground :: RGB -> IO ()\nforeground (r,g,b) = {#call Fl_foreground as fl_foreground #}\n (fromIntegral r)\n (fromIntegral g)\n (fromIntegral b)\nbackground :: RGB -> IO ()\nbackground (r,g,b) = {#call Fl_background as fl_background #}\n (fromIntegral r)\n (fromIntegral g)\n (fromIntegral b)\nbackground2 :: RGB -> IO ()\nbackground2 (r,g,b) = {#call Fl_background2 as fl_background2 #}\n (fromIntegral r)\n (fromIntegral g)\n (fromIntegral b)\n\n{# fun pure Fl_scheme as getScheme' {} -> `CString' #}\ngetScheme :: IO T.Text\ngetScheme = cStringToText getScheme'\n\nsetScheme :: T.Text -> IO Int\nsetScheme sch = TF.withCStringLen sch $ \\(str,_) -> {#call Fl_set_scheme as fl_set_scheme #} str >>= return . fromIntegral\n{# fun pure Fl_reload_scheme as reloadScheme {} -> `Int' #}\nisScheme :: T.Text -> IO Bool\nisScheme sch = TF.withCStringLen sch $ \\(str,_) -> {#call Fl_is_scheme as fl_is_scheme #} str >>= return . toBool\n{# fun Fl_wait as wait\n { } -> `Int' #}\n{# fun Fl_set_wait as waitFor\n { `Double' } -> `Double' #}\n\nsetWait :: Double -> IO Double\nsetWait = waitFor\n{# fun Fl_scrollbar_size as scrollbarSize\n { } -> `Int' #}\n{# fun Fl_set_scrollbar_size as setScrollbarSize\n { `Int' } -> `()' #}\n\n{# fun Fl_readqueue as readqueue' { } -> `Ptr ()' #}\nreadqueue :: IO (Maybe (Ref Widget))\nreadqueue = readqueue' >>= toMaybeRef\n{# fun Fl_add_timeout as addTimeout'\n { `Double', id `FunPtr CallbackPrim' } -> `()' supressWarningAboutRes #}\n\n-- | Returns a function pointer so it can be freed with `freeHaskellFunPtr`, please don't invoke it.\naddTimeout :: Double -> GlobalCallback -> IO (FunPtr CallbackPrim)\naddTimeout t cb = do\n fp <- toGlobalCallbackPrim cb\n addTimeout' t fp\n return fp\n\n{# fun Fl_repeat_timeout as repeatTimeout'\n { `Double',id `FunPtr CallbackPrim' } -> `()' supressWarningAboutRes #}\n-- | Returns a function pointer so it can be freed with `freeHaskellFunPtr`, please don't invoke it.\nrepeatTimeout :: Double -> GlobalCallback -> IO (FunPtr CallbackPrim)\nrepeatTimeout t cb = do\n fp <- toGlobalCallbackPrim cb\n repeatTimeout' t fp\n return fp\n\n{# fun Fl_has_timeout as hasTimeout\n { id `FunPtr CallbackPrim' } -> `Bool' toBool #}\n\n{# fun Fl_remove_timeout as removeTimeout\n { id `FunPtr CallbackPrim' } -> `()' supressWarningAboutRes #}\n\n{# fun Fl_add_check as addCheck'\n { id `FunPtr CallbackPrim' } -> `()' supressWarningAboutRes #}\n-- | Returns a function pointer so it can be freed with `freeHaskellFunPtr`, please don't invoke it.\naddCheck :: GlobalCallback -> IO (FunPtr CallbackPrim)\naddCheck cb = do\n fp <- toGlobalCallbackPrim cb\n addCheck' fp\n return fp\n\n{# fun Fl_has_check as hasCheck\n { id `FunPtr CallbackPrim' } -> `Bool' toBool #}\n{# fun Fl_remove_check as removeCheck\n { id `FunPtr CallbackPrim' } -> `()' supressWarningAboutRes #}\n\n{# fun Fl_add_idle as addIdle'\n { id `FunPtr CallbackPrim' } -> `()' supressWarningAboutRes #}\n-- | Returns a function pointer so it can be freed with `freeHaskellFunPtr`, please don't invoke it.\naddIdle :: GlobalCallback -> IO (FunPtr CallbackPrim)\naddIdle cb = do\n fp <- toGlobalCallbackPrim cb\n addIdle' fp\n return fp\n\n{# fun Fl_has_idle as hasIdle\n { id `FunPtr CallbackPrim' } -> `Bool' toBool #}\n\n{# fun Fl_remove_idle as removeIdle\n { id `FunPtr CallbackPrim' } -> `()' supressWarningAboutRes #}\n\n{# fun Fl_damage as damage\n { } -> `Int' #}\n{# fun Fl_redraw as redraw\n { } -> `()' supressWarningAboutRes #}\n{# fun Fl_flush as flush\n { } -> `()' supressWarningAboutRes #}\n{# fun Fl_first_window as firstWindow' { } -> `Ptr ()' #}\nfirstWindow :: IO (Maybe (Ref Window))\nfirstWindow = firstWindow' >>= toMaybeRef\n\n{# fun Fl_set_first_window as setFirstWindow'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetFirstWindow :: (Parent a WindowBase) => Ref a -> IO ()\nsetFirstWindow wp =\n withRef wp setFirstWindow'\n{# fun Fl_next_window as nextWindow' { id `Ptr ()' } -> `Ptr ()' #}\nnextWindow :: Ref a -> IO (Maybe (Ref Window))\nnextWindow currWindow = withRef currWindow (\\ptr -> nextWindow' ptr >>= toMaybeRef)\n\n{# fun Fl_modal as modal' { } -> `Ptr ()' #}\nmodal :: IO (Maybe (Ref Widget))\nmodal = modal' >>= toMaybeRef\n\n{# fun Fl_grab as grab' { } -> `Ptr ()' #}\ngrab :: IO (Maybe (Ref Widget))\ngrab = grab' >>= toMaybeRef\n\n{# fun Fl_set_grab as setGrab'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetGrab :: (Parent a WindowBase) => Ref a -> IO ()\nsetGrab wp = withRef wp setGrab'\n{# fun Fl_event as event\n { } -> `Event' cToEnum #}\n{# fun Fl_event_x as eventX'\n { } -> `Int'#}\neventX :: IO X\neventX = eventX' >>= return . X\n{# fun Fl_event_y as eventY'\n { } -> `Int'#}\neventY :: IO Y\neventY = eventY' >>= return . Y\n{# fun Fl_event_x_root as eventXRoot'\n { } -> `Int' #}\neventPosition :: IO Position\neventPosition = do\n x' <- eventX\n y' <- eventY\n return (Position x' y')\n\neventXRoot :: IO X\neventXRoot = eventXRoot' >>= return . X\n{# fun Fl_event_y_root as eventYRoot'\n { } -> `Int' #}\neventYRoot :: IO Y\neventYRoot = eventYRoot' >>= return . Y\n\neventRootPosition :: IO Position\neventRootPosition = do\n x' <- eventXRoot\n y' <- eventYRoot\n return (Position x' y')\n{# fun Fl_event_dx as eventDx\n { } -> `Int' #}\n{# fun Fl_event_dy as eventDy\n { } -> `Int' #}\n{# fun Fl_get_mouse as getMouse'\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv*\n } -> `()' #}\ngetMouse :: IO Position\ngetMouse = do\n (x_pos,y_pos) <- getMouse'\n return $ (Position (X x_pos) (Y y_pos))\n{# fun Fl_event_clicks as eventClicks\n { } -> `Int'#}\n{# fun Fl_set_event_clicks as setEventClicks\n { `Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_event_is_click as eventIsClick\n { } -> `Bool' toBool #}\n{# fun Fl_set_event_is_click as setEventIsClick\n { `Int' } -> `()' supressWarningAboutRes #}\n\n{# fun Fl_event_button as eventButton'\n { } -> `Int' #}\neventButton :: IO (Maybe MouseButton)\neventButton = do\n mb <- eventButton'\n case mb of\n mb' | mb' == (fromEnum Mouse_Left) -> return (Just Mouse_Left)\n mb' | mb' == (fromEnum Mouse_Middle) -> return (Just Mouse_Middle)\n mb' | mb' == (fromEnum Mouse_Right) -> return (Just Mouse_Right)\n _ -> return Nothing\n\neventStates :: [EventState]\neventStates = [\n Kb_ShiftState,\n Kb_CapsLockState,\n Kb_CtrlState,\n Kb_AltState,\n Kb_NumLockState,\n Kb_MetaState,\n Kb_ScrollLockState,\n Mouse_Button1State,\n Mouse_Button2State,\n Mouse_Button3State\n ]\nextractEventStates :: CInt -> [EventState]\nextractEventStates = extract eventStates\n\n{# fun Fl_event_state as eventState\n { } -> `[EventState]' extractEventStates #}\n{# fun Fl_contains_event_state as containsEventState\n {cFromEnum `EventState' } -> `Bool' toBool #}\n{# fun Fl_event_key as eventKey\n { } -> `KeyType' cToKeyType #}\n{# fun Fl_event_original_key as eventOriginalKey\n { } -> `KeyType' cToKeyType #}\n{# fun Fl_event_key_pressed as eventKeyPressed\n {cFromKeyType `KeyType' } -> `Bool' toBool #}\n{# fun Fl_get_key as getKey\n {cFromKeyType `KeyType' } -> `Bool' toBool #}\n{# fun Fl_event_text as eventText' { } -> `CString' #}\neventText :: IO T.Text\neventText = eventText' >>= cStringToText\n{# fun Fl_event_length as eventLength\n { } -> `Int' #}\n\n{# fun Fl_event_clipboard as flEventClipboard' { } -> `Ptr ()' #}\n{# fun Fl_event_clipboard_type as flEventClipboardType' { } -> `CString' #}\neventClipboardContents :: IO (Maybe ClipboardContents)\neventClipboardContents = do\n typeString <- flEventClipboardType' >>= cStringToText\n if (T.length typeString == 0)\n then return Nothing\n else case typeString of\n s | (T.unpack s == \"Fl::clipboard_image\") -> do\n stringContents <- flEventClipboard' >>= cStringToText . castPtr\n return (if (T.length stringContents == 0)\n then (Just (ClipboardContentsPlainText Nothing))\n else (Just (ClipboardContentsPlainText (Just stringContents))))\n s | (T.unpack s == \"Fl::clipboard_plain_text\") -> do\n imageRef <- flEventClipboard' >>= toMaybeRef\n return (Just (ClipboardContentsImage imageRef))\n _ -> error \"eventClipboardContents :: The type of the clipboard contents must be either the string \\\"Fl::clipboard_image\\\" or \\\"Fl::clipboard_plain_image\\\".\"\n\n{# fun Fl_compose as compose\n { alloca- `Int' peekIntConv* } -> `Bool' toBool #}\n{# fun Fl_compose_reset as composeReset\n { } -> `()' supressWarningAboutRes #}\n{# fun Fl_event_inside_region as eventInsideRegion'\n { `Int',`Int',`Int',`Int' } -> `Int' #}\neventInsideRegion :: Rectangle -> IO Event\neventInsideRegion (Rectangle\n (Position\n (X x_pos)\n (Y y_pos))\n (Size\n (Width width)\n (Height height))) =\n do\n eventNum <- eventInsideRegion' x_pos y_pos width height\n return $ toEnum eventNum\n{# fun Fl_event_inside_widget as eventInsideWidget'\n { id `Ptr ()' } -> `Int' #}\neventInsideWidget :: (Parent a WidgetBase) => Ref a -> IO Event\neventInsideWidget wp =\n withRef wp (\\ptr -> do\n eventNum <- eventInsideWidget' (castPtr ptr)\n return $ toEnum eventNum)\n{# fun Fl_test_shortcut as testShortcut\n { id `FlShortcut' } -> `Bool' toBool #}\n{# fun Fl_enable_im as enableIm\n {} -> `()' supressWarningAboutRes #}\n{# fun Fl_disable_im as disableIm\n {} -> `()' supressWarningAboutRes #}\n{# fun Fl_handle as handle'\n { `Int',id `Ptr ()' } -> `Int' #}\nhandle :: (Parent a WindowBase) => Event -> Ref a -> IO (Either UnknownEvent ())\nhandle e wp =\n withRef wp (handle' (cFromEnum e)) >>= return . successOrUnknownEvent\n{# fun Fl_handle_ as handle_'\n { `Int',id `Ptr ()' } -> `Int' #}\nhandle_ :: (Parent a WindowBase) => Event -> Ref a -> IO (Either UnknownEvent ())\nhandle_ e wp =\n withRef wp (handle_' (cFromEnum e)) >>= return . successOrUnknownEvent\n{# fun Fl_belowmouse as belowmouse' { } -> `Ptr ()' #}\nbelowmouse :: IO (Maybe (Ref Widget))\nbelowmouse = belowmouse' >>= toMaybeRef\n{# fun Fl_set_belowmouse as setBelowmouse'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetBelowmouse :: (Parent a WidgetBase) => Ref a -> IO ()\nsetBelowmouse wp = withRef wp setBelowmouse'\n{# fun Fl_pushed as pushed'\n { } -> `Ptr ()' #}\npushed :: IO (Maybe (Ref Widget))\npushed = pushed' >>= toMaybeRef\n{# fun Fl_set_pushed as setPushed'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetPushed :: (Parent a WidgetBase) => Ref a -> IO ()\nsetPushed wp = withRef wp setPushed'\n{# fun Fl_focus as focus' { } -> `Ptr ()' #}\nfocus :: IO (Maybe (Ref Widget))\nfocus = focus' >>= toMaybeRef\n{# fun Fl_set_focus as setFocus'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetFocus :: (Parent a WidgetBase) => Ref a -> IO ()\nsetFocus wp = withRef wp setFocus'\n{# fun Fl_selection_owner as selectionOwner' { } -> `Ptr ()' #}\nselectionOwner :: IO (Maybe (Ref Widget))\nselectionOwner = selectionOwner' >>= toMaybeRef\n{# fun Fl_set_selection_owner as setSelection_Owner'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetSelectionOwner :: (Parent a WidgetBase) => Ref a -> IO ()\nsetSelectionOwner wp = withRef wp setSelection_Owner'\n{# fun Fl_add_handler as addHandler'\n { id `FunPtr GlobalEventHandlerPrim' } -> `()' supressWarningAboutRes #}\n{# fun Fl_remove_handler as removeHandler'\n { id `FunPtr GlobalEventHandlerPrim' } -> `()' supressWarningAboutRes #}\nsetHandler :: GlobalEventHandlerF -> IO ()\nsetHandler eh = do\n newGlobalEventHandler <- toGlobalEventHandlerPrim eh\n curr <- do\n old <- readIORef ptrToGlobalEventHandler\n writeIORef ptrToGlobalEventHandler newGlobalEventHandler\n return old\n freeHaskellFunPtr curr\n removeHandler' curr\n addHandler' newGlobalEventHandler\n\n{# fun Fl_set_event_dispatch as setEventDispatch'\n { id `Ptr (FunPtr EventDispatchPrim)' } -> `()' supressWarningAboutRes #}\n{# fun Fl_event_dispatch as eventDispatch'\n { } -> `FunPtr EventDispatchPrim' id #}\neventDispatch :: (Parent a WidgetBase) =>\n IO (Event -> Ref a -> IO (Either UnknownEvent ()))\neventDispatch =\n do\n funPtr <- eventDispatch'\n return (\\e window ->\n withRef\n window\n (\\ptr ->\n let eventNum = fromIntegral (fromEnum e)\n fun = unwrapEventDispatchPrim funPtr\n in fun eventNum (castPtr ptr) >>=\n return . successOrUnknownEvent . fromIntegral\n )\n )\n\nsetEventDispatch ::\n (Parent a WidgetBase) =>\n (Event -> Ref a -> IO (Either UnknownEvent ())) -> IO ()\nsetEventDispatch ed = do\n do\n let toPrim = (\\e ptr ->\n let eventEnum = toEnum $ fromIntegral e\n in do\n obj <- toRef ptr\n result <- ed eventEnum obj\n case result of\n Left _ -> return 0\n _ -> return 1\n )\n callbackPtr <- wrapEventDispatchPrim toPrim\n ptrToCallbackPtr <- new callbackPtr\n poke ptrToCallbackPtr callbackPtr\n setEventDispatch' ptrToCallbackPtr\n\n{# fun Fl_copy as copy' { `CString',`Int' } -> `()' supressWarningAboutRes #}\ncopyToClipboard :: T.Text -> IO ()\ncopyToClipboard t = withText t (\\s' -> copy' s' 0)\n\ncopyToSelectionBuffer :: T.Text -> IO ()\ncopyToSelectionBuffer t = withText t (\\s' -> copy' s' 1)\n\n{# fun Fl_copy_with_destination as copyWithDestination { `CString',`Int',`Int' } -> `()' supressWarningAboutRes #}\n\ncopyLengthToClipboard :: T.Text -> Int -> IO ()\ncopyLengthToClipboard t l = withText t (\\s' -> copyWithDestination s' l 0)\n\ncopyLengthToSelectionBuffer :: T.Text -> Int -> IO ()\ncopyLengthToSelectionBuffer t l = withText t (\\s' -> copyWithDestination s' l 1)\n\n{# fun Fl_paste_with_source_type as pasteWithSourceType { id `Ptr ()',`Int', `CString' } -> `()' supressWarningAboutRes #}\n\npasteImageFromSelectionBuffer :: (Parent a WidgetBase) => Ref a -> IO ()\npasteImageFromSelectionBuffer widget = withRef widget (\\widgetPtr -> withText (T.pack \"Fl::clipboard_image\") (\\t -> pasteWithSourceType widgetPtr 0 t))\n\npasteFromSelectionBuffer :: (Parent a WidgetBase) => Ref a -> IO ()\npasteFromSelectionBuffer widget = withRef widget (\\widgetPtr -> withText (T.pack \"Fl::clipboard_plain_text\") (\\t -> pasteWithSourceType widgetPtr 0 t))\n\npasteImageFromClipboard :: (Parent a WidgetBase) => Ref a -> IO ()\npasteImageFromClipboard widget = withRef widget (\\widgetPtr -> withText (T.pack \"Fl::clipboard_image\") (\\t -> pasteWithSourceType widgetPtr 1 t))\n\npasteFromClipboard :: (Parent a WidgetBase) => Ref a -> IO ()\npasteFromClipboard widget = withRef widget (\\widgetPtr -> withText (T.pack \"Fl::clipboard_plain_text\") (\\t -> pasteWithSourceType widgetPtr 1 t))\n\n{# fun Fl_dnd as dnd\n { } -> `Int' #}\n{# fun Fl_x as x\n { } -> `Int' #}\n{# fun Fl_y as y\n { } -> `Int' #}\n{# fun Fl_w as w\n { } -> `Int' #}\n{# fun Fl_h as h\n { } -> `Int' #}\n{# fun Fl_screen_count as screenCount\n { } -> `Int' #}\n\n{# fun Fl_screen_xywh as screenXYWH\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv*\n } -> `()' #}\n{# fun Fl_screen_xywh_with_mxmy as screenXYWYWithMXMY\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int',\n `Int'\n } -> `()' #}\n{# fun Fl_screen_xywh_with_n as screenXYWNWithN\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int'\n } -> `()' #}\n{# fun Fl_screen_xywh_with_mxmymwmh as screenXYWHWithNMXMYMWMH\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int',\n `Int',\n `Int',\n `Int'\n } -> `()' #}\n\nscreenBounds :: Maybe ScreenLocation -> IO Rectangle\nscreenBounds location =\n case location of\n (Just (Intersect (Rectangle (Position (X x_pos) (Y y_pos)) (Size (Width width) (Height height))))) ->\n screenXYWHWithNMXMYMWMH x_pos y_pos width height >>= return . toRectangle\n (Just (ScreenPosition (Position (X x_pos) (Y y_pos)))) ->\n screenXYWYWithMXMY x_pos y_pos >>= return . toRectangle\n (Just (ScreenNumber n)) ->\n screenXYWNWithN n >>= return . toRectangle\n Nothing ->\n screenXYWH >>= return . toRectangle\n\n{# fun Fl_screen_dpi as screenDpi'\n { alloca- `Float' peekFloatConv*,\n alloca- `Float' peekFloatConv* }\n -> `()' #}\n{# fun Fl_screen_dpi_with_n as screenDpiWithN'\n { alloca- `Float' peekFloatConv*,\n alloca- `Float' peekFloatConv*,\n `Int' }\n -> `()' #}\n\nscreenDPI :: Maybe Int -> IO DPI\nscreenDPI (Just n) = do\n (dpiX, dpiY) <- screenDpiWithN' n\n return $ DPI dpiX dpiY\nscreenDPI Nothing = do\n (dpiX, dpiY) <- screenDpi'\n return $ DPI dpiX dpiY\n\n{# fun Fl_screen_work_area_with_mx_my as screenWorkAreaWithMXMY'\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int',\n `Int'\n }\n -> `()' #}\n{# fun Fl_screen_work_area_with_n as screenWorkAreaWithN'\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int'\n }\n -> `()' #}\n{# fun Fl_screen_work_area as screenWorkArea'\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv*\n }\n -> `()' id- #}\nscreenWorkArea :: Maybe ScreenLocation -> IO Rectangle\nscreenWorkArea location =\n case location of\n (Just (Intersect (Rectangle (Position (X x_pos) (Y y_pos)) _))) ->\n screenWorkAreaWithMXMY' x_pos y_pos >>= return . toRectangle\n (Just (ScreenPosition (Position (X x_pos) (Y y_pos)))) ->\n screenWorkAreaWithMXMY' x_pos y_pos >>= return . toRectangle\n (Just (ScreenNumber n)) ->\n screenWorkAreaWithN' n >>= return . toRectangle\n Nothing ->\n screenWorkArea' >>= return . toRectangle\n\nsetColorRgb :: Color -> Word8 -> Word8 -> Word8 -> IO ()\nsetColorRgb c r g b = {#call Fl_set_color_rgb as fl_set_color_rgb #}\n (cFromColor c)\n (fromIntegral r)\n (fromIntegral g)\n (fromIntegral b)\n{# fun Fl_set_color as setColor\n { cFromColor `Color', cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_get_color as getColor\n { cFromColor `Color' } -> `Color' cToColor #}\n{# fun Fl_get_color_rgb as getColorRgb'\n {\n cFromColor `Color',\n alloca- `CUChar' peekIntConv*,\n alloca- `CUChar' peekIntConv*,\n alloca- `CUChar' peekIntConv*\n } -> `()' supressWarningAboutRes #}\ngetColorRgb :: Color -> IO RGB\ngetColorRgb c = do\n (_,r,g,b) <- getColorRgb' c\n return (r,g,b)\n\n#if !defined(__APPLE__)\n{# fun Fl_free_color as freeColor'\n { cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_free_color_with_overlay as freeColorWithOverlay'\n { cFromColor `Color', `Int' } -> `()' supressWarningAboutRes #}\nremoveFromColormap :: Maybe Color -> Color -> IO ()\nremoveFromColormap (Just (Color overlay)) c = freeColorWithOverlay' c (fromIntegral overlay)\nremoveFromColormap Nothing c = freeColor' c\n#endif\n{# fun Fl_get_font as getFont' { cFromFont `Font' } -> `CString' #}\ngetFont :: Font -> IO T.Text\ngetFont f = getFont' f >>= cStringToText\n\n{# fun Fl_get_font_name_with_attributes as getFontNameWithAttributes' { cFromFont `Font', alloca- `Maybe FontAttribute' toAttribute* } -> `CString' #}\ngetFontName :: Font -> IO (T.Text, Maybe FontAttribute)\ngetFontName f = do\n (str, fa) <- getFontNameWithAttributes' f\n t <- cStringToText str\n return (t, fa)\n\ntoAttribute :: Ptr CInt -> IO (Maybe FontAttribute)\ntoAttribute ptr =\n do\n attributeCode <- peekIntConv ptr\n return $ cToFontAttribute attributeCode\n{# fun Fl_get_font_sizes as getFontSizes'\n { cFromFont `Font', id `Ptr (Ptr CInt)' } -> `CInt' #}\ngetFontSizes :: Font -> IO [FontSize]\ngetFontSizes font = do\n arrPtr <- (newArray [] :: IO (Ptr (Ptr CInt)))\n arrLength <- getFontSizes' font arrPtr\n zeroth <- peekElemOff arrPtr 0\n if (arrLength == 0) then return []\n else do\n (sizes :: [CInt]) <-\n mapM\n (\n \\offset -> do\n size <- peek (advancePtr zeroth offset)\n return size\n )\n [0 .. ((fromIntegral arrLength) - 1)]\n return (map FontSize sizes)\n\n{# fun Fl_set_font_by_string as setFontToString'\n { cFromFont `Font', `CString' } -> `()' supressWarningAboutRes #}\nsetFontToString :: Font -> T.Text -> IO ()\nsetFontToString f t = withText t (\\t' -> setFontToString' f t')\n{# fun Fl_set_font_by_font as setFontToFont\n { cFromFont `Font',cFromFont `Font' } -> `()' supressWarningAboutRes #}\n{# fun Fl_set_fonts as setFonts'\n { } -> `Int' #}\n{# fun Fl_set_fonts_with_string as setFontsWithString'\n { id `Ptr CChar' } -> `Int' #}\nsetFonts :: Maybe T.Text -> IO Int\nsetFonts (Just xstarName) = withText xstarName (\\starNamePtr -> setFontsWithString' starNamePtr)\nsetFonts Nothing = setFonts'\n\n{# fun Fl_add_fd_with_when as addFdWhen'\n {\n `CInt',\n `CInt',\n id `FunPtr FDHandlerPrim'\n } -> `()' #}\n\naddFdWhen :: CInt -> [FdWhen] -> FDHandler -> IO ()\naddFdWhen fd fdWhens handler = do\n fPtr <- toFDHandlerPrim handler\n addFdWhen' fd (fromIntegral . combine $ fdWhens) fPtr\n\n{# fun Fl_add_fd as addFd'\n {\n `CInt',\n id `FunPtr FDHandlerPrim'\n } -> `()' #}\n\naddFd :: CInt -> FDHandler -> IO ()\naddFd fd handler = do\n fPtr <- toFDHandlerPrim handler\n addFd' fd fPtr\n\n{# fun Fl_remove_fd_with_when as removeFdWhen' { `CInt', `CInt'} -> `()' #}\nremoveFdWhen :: CInt -> [FdWhen] -> IO ()\nremoveFdWhen fd fdWhens =\n removeFdWhen' fd (fromIntegral . combine $ fdWhens)\n\n{# fun Fl_remove_fd as removeFd' { `CInt' } -> `()' #}\nremoveFd :: CInt -> IO ()\nremoveFd fd = removeFd' fd\n\n{# fun Fl_get_boxtype as getBoxtype\n { cFromEnum `Boxtype' } -> `FunPtr BoxDrawFPrim' id #}\n\n{# fun Fl_set_boxtype as setBoxtype'\n {\n cFromEnum `Boxtype',\n id `FunPtr BoxDrawFPrim',\n `Word8',\n `Word8',\n `Word8',\n `Word8'\n } -> `()' supressWarningAboutRes #}\n{# fun Fl_set_boxtype_by_boxtype as setBoxtypeByBoxtype'\n {\n cFromEnum `Boxtype',\n cFromEnum `Boxtype'\n } -> `()' supressWarningAboutRes #}\n\ndata BoxtypeSpec = FromSpec BoxDrawF Word8 Word8 Word8 Word8\n | FromBoxtype Boxtype\n | FromFunPtr (FunPtr BoxDrawFPrim) Word8 Word8 Word8 Word8\nsetBoxtype :: Boxtype -> BoxtypeSpec -> IO ()\nsetBoxtype bt (FromSpec f dx dy dw dh) =\n do\n funPtr <- wrapBoxDrawFPrim (toBoxDrawFPrim f)\n setBoxtype' bt funPtr dx dy dw dh\nsetBoxtype bt (FromBoxtype template) =\n setBoxtypeByBoxtype' bt template\nsetBoxtype bt (FromFunPtr funPtr dx dy dw dh) =\n setBoxtype' bt funPtr dx dy dw dh\n\n{# fun Fl_box_dx as boxDx\n { cFromEnum `Boxtype' } -> `Int' #}\n{# fun Fl_box_dy as boxDy\n { cFromEnum `Boxtype' } -> `Int' #}\n{# fun Fl_box_dw as boxDw\n { cFromEnum `Boxtype' } -> `Int' #}\n{# fun Fl_box_dh as boxDh\n { cFromEnum `Boxtype' } -> `Int' #}\n\nadjustBoundsByBoxtype :: Rectangle -> Boxtype -> IO Rectangle\nadjustBoundsByBoxtype rect bt =\n let (x',y',w',h') = fromRectangle rect\n in do\n dx <- boxDx bt\n dy <- boxDy bt\n dw <- boxDw bt\n dh <- boxDh bt\n return (toRectangle (x'+dx,y'+dy,w'-dw,h'-dh))\n\nboxDifferences :: Rectangle -> Rectangle -> (Int, Int, Int, Int)\nboxDifferences r1 r2 =\n let (r1x,r1y,r1w,r1h) = fromRectangle r1\n (r2x,r2y,r2w,r2h) = fromRectangle r2\n in (r2x-r1x,r2y-r1y,r1w-r2w,r1h-r2h)\n\n{# fun Fl_draw_box_active as drawBoxActive\n { } -> `Bool' toBool #}\n{# fun Fl_event_shift as eventShift\n { } -> `Bool' toBool #}\n{# fun Fl_event_ctrl as eventCtrl\n { } -> `Bool' toBool #}\n{# fun Fl_event_command as eventCommand\n { } -> `Bool' toBool #}\n{# fun Fl_event_alt as eventAlt\n { } -> `Bool' toBool #}\n{# fun Fl_event_buttons as eventButtons\n { } -> `Bool' toBool #}\n{# fun Fl_event_button1 as eventButton1\n { } -> `Bool' toBool #}\n{# fun Fl_event_button2 as eventButton2\n { } -> `Bool' toBool #}\n{# fun Fl_event_button3 as eventButton3\n { } -> `Bool' toBool #}\nrelease :: IO ()\nrelease = {#call Fl_release as fl_release #}\nsetVisibleFocus :: Bool -> IO ()\nsetVisibleFocus = {#call Fl_set_visible_focus as fl_set_visible_focus #} . cFromBool\nvisibleFocus :: IO Bool\nvisibleFocus = {#call Fl_visible_focus as fl_visible_focus #} >>= return . cToBool\nsetDndTextOps :: Bool -> IO ()\nsetDndTextOps = {#call Fl_set_dnd_text_ops as fl_set_dnd_text_ops #} . fromBool\ndndTextOps :: IO Option\ndndTextOps = {#call Fl_dnd_text_ops as fl_dnd_text_ops #} >>= return . cToEnum\ndeleteWidget :: (Parent a WidgetBase) => Ref a -> IO ()\ndeleteWidget wptr =\n swapRef wptr $ \\ptr -> do\n {#call Fl_delete_widget as fl_delete_widget #} ptr\n return nullPtr\ndoWidgetDeletion :: IO ()\ndoWidgetDeletion = {#call Fl_do_widget_deletion as fl_do_widget_deletion #}\nwatchWidgetPointer :: (Parent a WidgetBase) => Ref a -> IO ()\nwatchWidgetPointer wp = withRef wp {#call Fl_watch_widget_pointer as fl_Watch_widget_Pointer #}\nreleaseWidgetPointer :: (Parent a WidgetBase) => Ref a -> IO ()\nreleaseWidgetPointer wp = withRef wp {#call Fl_release_widget_pointer as fl_release_widget_pointer #}\nclearWidgetPointer :: (Parent a WidgetBase) => Ref a -> IO ()\nclearWidgetPointer wp = withRef wp {#call Fl_clear_widget_pointer as fl_Clear_Widget_Pointer #}\n-- | Only available on FLTK version 1.3.4 and above.\nsetBoxColor :: Color -> IO ()\nsetBoxColor c = {#call Fl_set_box_color as fl_set_box_color #} (cFromColor c)\n-- | Only available on FLTK version 1.3.4 and above.\nboxColor :: Color -> IO Color\nboxColor c = {#call Fl_box_color as fl_box_color #} (cFromColor c) >>= return . cToColor\n-- | Only available on FLTK version 1.3.4 and above.\nabiVersion :: IO Int\nabiVersion = {#call Fl_abi_version as fl_abi_version #} >>= return . fromIntegral\n-- | Only available on FLTK version 1.3.4 and above.\nabiCheck :: Int -> IO Int\nabiCheck v = {#call Fl_abi_check as fl_abi_check #} (fromIntegral v) >>= return . fromIntegral\n-- | Only available on FLTK version 1.3.4 and above.\napiVersion :: IO Int\napiVersion = {#call Fl_abi_version as fl_abi_version #} >>= return . fromIntegral\n-- | Only available on FLTK version 1.3.4 and above.\nlocalCtrl :: IO T.Text\nlocalCtrl = {#call Fl_local_ctrl as fl_local_ctrl #} >>= cStringToText\n-- | Only available on FLTK version 1.3.4 and above.\nlocalAlt :: IO T.Text\nlocalAlt = {#call Fl_local_alt as fl_local_alt #} >>= cStringToText\n-- | Only available on FLTK version 1.3.4 and above.\nlocalMeta :: IO T.Text\nlocalMeta = {#call Fl_local_meta as fl_local_meta #} >>= cStringToText\n-- | Only available on FLTK version 1.3.4 and above.\nlocalShift :: IO T.Text\nlocalShift = {#call Fl_local_shift as fl_local_shift #} >>= cStringToText\n#ifdef GLSUPPORT\n-- | Only available on FLTK version 1.3.4 and above if GL is enabled with 'stack build --flag fltkhs:opengl'\nuseHighResGL :: IO Bool\nuseHighResGL = {#call Fl_use_high_res_GL as fl_use_high_res_GL #} >>= return . cToBool\n-- | Only available on FLTK version 1.3.4 and above if GL is enabled with 'stack build --flag fltkhs:opengl'\nsetUseHighResGL :: Bool -> IO ()\nsetUseHighResGL use' = {#call Fl_set_use_high_res_GL as fl_set_use_high_res_GL #} (cFromBool use')\n#endif\ninsertionPointLocation :: Position -> Height -> IO ()\ninsertionPointLocation (Position (X x') (Y y')) (Height h')\n = {#call Fl_insertion_point_location as fl_insertion_point_location #} (fromIntegral x') (fromIntegral y') (fromIntegral h')\nresetMarkedText :: IO ()\nresetMarkedText = {#call Fl_reset_marked_text as fl_reset_marked_text #}\nrunChecks :: IO ()\nrunChecks = {#call Fl_run_checks as fl_run_checks #}\nscreenDriver :: IO (Maybe (Ref ScreenDriver))\nscreenDriver = {#call Fl_screen_driver as fl_screen_driver #} >>= toMaybeRef\nsystemDriver :: IO (Maybe (Ref SystemDriver))\nsystemDriver = {#call Fl_system_driver as fl_system_driver #} >>= toMaybeRef\nsetProgramShouldQuit :: Bool -> IO ()\nsetProgramShouldQuit = {#call Fl_set_program_should_quit as fl_set_program_should_quit #} . cFromBool\ngetProgramShouldQuit :: IO Bool\ngetProgramShouldQuit = {#call Fl_get_program_should_quit as fl_get_program_should_quit #} >>= return . cToBool\n\n\n-- | Use this function to run a GUI in GHCi.\nreplRun :: IO ()\nreplRun = do\n flush\n w <- firstWindow\n case w of\n Just _ ->\n catch (forever (waitFor 0.01))\n (\\e -> if (e == UserInterrupt)\n then do\n wM <- firstWindow\n case wM of\n Just w' -> allToplevelWindows [] (Just w') >>= mapM_ deleteWidget\n Nothing -> return ()\n flush\n else throw e)\n Nothing -> return ()\n where\n allToplevelWindows :: [Ref Window] -> Maybe (Ref Window) -> IO [Ref Window]\n allToplevelWindows ws (Just w) = nextWindow w >>= allToplevelWindows (w:ws)\n allToplevelWindows ws Nothing = return ws\n","old_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n\nmodule Graphics.UI.FLTK.LowLevel.FL\n (\n Option(..),\n ClipboardContents(..),\n scrollbarSize,\n setScrollbarSize,\n selectionOwner,\n setSelectionOwner,\n run,\n replRun,\n check,\n ready,\n option,\n setOption,\n lock,\n unlock,\n awake,\n awakeToHandler,\n addAwakeHandler_,\n getAwakeHandler_,\n display,\n ownColormap,\n getSystemColors,\n foreground,\n background,\n background2,\n setScheme,\n getScheme,\n reloadScheme,\n isScheme,\n setFirstWindow,\n nextWindow,\n setGrab,\n getMouse,\n eventStates,\n extract,\n extractEventStates,\n handle,\n handle_,\n belowmouse,\n setBelowmouse,\n setPushed,\n setFocus,\n setHandler,\n toRectangle,\n fromRectangle,\n screenBounds,\n screenDPI,\n screenWorkArea,\n setColorRgb,\n toAttribute,\n release,\n setVisibleFocus,\n visibleFocus,\n setDndTextOps,\n dndTextOps,\n deleteWidget,\n doWidgetDeletion,\n watchWidgetPointer,\n releaseWidgetPointer,\n clearWidgetPointer,\n version,\n help,\n visual,\n#if !defined(__APPLE__) && defined(GLSUPPORT)\n glVisual,\n glVisualWithAlist,\n#endif\n wait,\n setWait,\n waitFor,\n readqueue,\n addTimeout,\n repeatTimeout,\n hasTimeout,\n removeTimeout,\n addCheck,\n hasCheck,\n removeCheck,\n addIdle,\n hasIdle,\n removeIdle,\n damage,\n redraw,\n flush,\n firstWindow,\n modal,\n grab,\n getKey,\n compose,\n composeReset,\n testShortcut,\n enableIm,\n disableIm,\n pushed,\n focus,\n copyToClipboard,\n copyToSelectionBuffer,\n copyLengthToClipboard,\n copyLengthToSelectionBuffer,\n pasteImageFromSelectionBuffer,\n pasteFromSelectionBuffer,\n pasteImageFromClipboard,\n pasteFromClipboard,\n dnd,\n x,\n y,\n w,\n h,\n screenCount,\n setColor,\n getColor,\n getColorRgb,\n#if !defined(__APPLE__)\n removeFromColormap,\n#endif\n -- * Box\n BoxtypeSpec(..),\n getBoxtype,\n setBoxtype,\n boxDx,\n boxDy,\n boxDw,\n boxDh,\n adjustBoundsByBoxtype,\n boxDifferences,\n drawBoxActive,\n -- * Fonts\n getFontName,\n getFont,\n getFontSizes,\n setFontToString,\n setFontToFont,\n setFonts,\n -- * File Descriptor Callbacks\n addFd,\n addFdWhen,\n removeFd,\n removeFdWhen,\n -- * Events\n event,\n eventShift,\n eventCtrl,\n eventCommand,\n eventAlt,\n eventButtons,\n eventButton1,\n eventButton2,\n eventButton3,\n eventX,\n eventY,\n eventPosition,\n eventXRoot,\n eventYRoot,\n eventRootPosition,\n eventDx,\n eventDy,\n eventClicks,\n setEventClicks,\n eventIsClick,\n setEventIsClick,\n eventButton,\n eventState,\n containsEventState,\n eventKey,\n eventOriginalKey,\n eventKeyPressed,\n eventInsideRegion,\n eventInsideWidget,\n eventDispatch,\n setEventDispatch,\n eventText,\n eventLength,\n eventClipboardContents,\n setBoxColor,\n boxColor,\n abiVersion,\n apiVersion,\n abiCheck,\n localCtrl,\n localMeta,\n localAlt,\n localShift\n#ifdef GLSUPPORT\n , useHighResGL\n , setUseHighResGL\n#endif\n , insertionPointLocation\n , resetMarkedText\n , runChecks\n , screenDriver\n , systemDriver\n , screenXYWH\n , setProgramShouldQuit\n , getProgramShouldQuit\n )\nwhere\n#include \"Fl_C.h\"\nimport C2HS hiding (cFromEnum, cToBool,cToEnum,cFromBool)\nimport Data.IORef\n\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Hierarchy hiding (\n setVisibleFocus,\n handle,\n redraw,\n flush,\n testShortcut,\n copy,\n setColor,\n getColor,\n focus,\n display,\n setScrollbarSize\n )\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\nimport qualified Data.Text.Foreign as TF\nimport qualified System.IO.Unsafe as Unsafe (unsafePerformIO)\nimport Control.Exception(catch, throw, AsyncException(UserInterrupt))\nimport Control.Monad(forever)\n#c\n enum Option {\n OptionArrowFocus = OPTION_ARROW_FOCUS,\n OptionVisibleFocus = OPTION_VISIBLE_FOCUS,\n OptionDndText = OPTION_DND_TEXT,\n OptionShowTooltips = OPTION_SHOW_TOOLTIPS,\n OptionLast = OPTION_LAST\n };\n#endc\n\n{#enum Option {} deriving (Show) #}\n\nptrToGlobalEventHandler :: IORef (FunPtr GlobalEventHandlerPrim)\nptrToGlobalEventHandler = Unsafe.unsafePerformIO $ do\n initialHandler <- toGlobalEventHandlerPrim (\\_ -> return (-1))\n newIORef initialHandler\n\n-- | Contents of the clipboard following a copy or cut. Can be either an <.\/Graphics-UI-FLTK-LowLevel-Image.html Image> or plain 'T.Text'.\ndata ClipboardContents =\n ClipboardContentsImage (Maybe (Ref Image))\n | ClipboardContentsPlainText (Maybe T.Text)\n\ntype EventDispatchPrim = (CInt ->\n Ptr () ->\n IO CInt)\nforeign import ccall \"wrapper\"\n wrapEventDispatchPrim :: EventDispatchPrim ->\n IO (FunPtr EventDispatchPrim)\nforeign import ccall \"dynamic\"\n unwrapEventDispatchPrim :: FunPtr EventDispatchPrim -> EventDispatchPrim\n\nrun :: IO Int\nrun = {#call Fl_run as fl_run #} >>= return . fromIntegral\n\ncheck :: IO Int\ncheck = {#call Fl_check as fl_check #} >>= return . fromIntegral\n\nready :: IO Int\nready = {#call Fl_ready as fl_ready #} >>= return . fromIntegral\n\n\noption :: Option -> IO Bool\noption o = {#call Fl_option as fl_option #} (cFromEnum o) >>= \\(c::CInt) -> return $ cToBool $ ((fromIntegral c) :: Int)\n\nsetOption :: Option -> Bool -> IO ()\nsetOption o t = {#call Fl_set_option as fl_set_option #} (cFromEnum o) (Graphics.UI.FLTK.LowLevel.Utils.cFromBool t)\n\nlock :: IO Bool\nlock = {#call Fl_lock as fl_lock #} >>= return . cToBool\n\nunlock :: IO ()\nunlock = {#call Fl_unlock as fl_unlock #}\n\nawake :: IO ()\nawake = {#call Fl_awake as fl_awake #}\n\nawakeToHandler :: IO ()\nawakeToHandler = {#call Fl_awake_to_handler as fl_awake_to_handler #}\n\n{# fun Fl_add_awake_handler_ as addAwakeHandler'\n {id `FunPtr CallbackPrim', id `(Ptr ())'} -> `Int' #}\naddAwakeHandler_ :: GlobalCallback -> IO (Either AwakeRingFull ())\naddAwakeHandler_ awakeHandler =\n do\n callbackPtr <- toGlobalCallbackPrim awakeHandler\n res <- addAwakeHandler' callbackPtr nullPtr\n return (successOrAwakeRingFull res)\n\n{# fun Fl_get_awake_handler_ as getAwakeHandler_'\n {id `Ptr (FunPtr CallbackPrim)', id `Ptr (Ptr ())'} -> `Int' #}\ngetAwakeHandler_ :: IO GlobalCallback\ngetAwakeHandler_ =\n alloca $ \\ptrToFunPtr ->\n alloca $ \\ptrToUD -> do\n _ <- getAwakeHandler_' ptrToFunPtr ptrToUD\n funPtr <- peek ptrToFunPtr\n return $ unwrapGlobalCallbackPtr $ castFunPtr funPtr\n\n{# fun Fl_version as version\n {} -> `Double' #}\n{# fun Fl_help as help' {} -> `CString' #}\nhelp :: IO T.Text\nhelp = help' >>= cStringToText\n\ndisplay :: T.Text -> IO ()\ndisplay text = TF.withCStringLen text $ \\(str,_) -> {#call Fl_display as fl_display #} str\n{# fun Fl_visual as visual\n {cFromEnum `Mode'} -> `Bool' cToBool #}\n#if !defined(__APPLE__) && defined(GLSUPPORT)\n-- | Only available if on a non OSX platform and if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{# fun Fl_gl_visual as glVisual\n {cFromEnum `Mode'} -> `Bool' cToBool #}\n-- | Only available if on a non OSX platform and if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{# fun Fl_gl_visual_with_alist as glVisualWithAlist\n {cFromEnum `Mode', id `Ptr CInt'} -> `Bool' cToBool #}\n#endif\n\nownColormap :: IO ()\nownColormap = {#call Fl_own_colormap as fl_own_colormap #}\n\ngetSystemColors :: IO ()\ngetSystemColors = {#call Fl_get_system_colors as fl_get_system_colors #}\n\nforeground :: RGB -> IO ()\nforeground (r,g,b) = {#call Fl_foreground as fl_foreground #}\n (fromIntegral r)\n (fromIntegral g)\n (fromIntegral b)\nbackground :: RGB -> IO ()\nbackground (r,g,b) = {#call Fl_background as fl_background #}\n (fromIntegral r)\n (fromIntegral g)\n (fromIntegral b)\nbackground2 :: RGB -> IO ()\nbackground2 (r,g,b) = {#call Fl_background2 as fl_background2 #}\n (fromIntegral r)\n (fromIntegral g)\n (fromIntegral b)\n\n{# fun pure Fl_scheme as getScheme' {} -> `CString' #}\ngetScheme :: IO T.Text\ngetScheme = cStringToText getScheme'\n\nsetScheme :: T.Text -> IO Int\nsetScheme sch = TF.withCStringLen sch $ \\(str,_) -> {#call Fl_set_scheme as fl_set_scheme #} str >>= return . fromIntegral\n{# fun pure Fl_reload_scheme as reloadScheme {} -> `Int' #}\nisScheme :: T.Text -> IO Bool\nisScheme sch = TF.withCStringLen sch $ \\(str,_) -> {#call Fl_is_scheme as fl_is_scheme #} str >>= return . toBool\n{# fun Fl_wait as wait\n { } -> `Int' #}\n{# fun Fl_set_wait as waitFor\n { `Double' } -> `Double' #}\n\nsetWait :: Double -> IO Double\nsetWait = waitFor\n{# fun Fl_scrollbar_size as scrollbarSize\n { } -> `Int' #}\n{# fun Fl_set_scrollbar_size as setScrollbarSize\n { `Int' } -> `()' #}\n\n{# fun Fl_readqueue as readqueue' { } -> `Ptr ()' #}\nreadqueue :: IO (Maybe (Ref Widget))\nreadqueue = readqueue' >>= toMaybeRef\n{# fun Fl_add_timeout as addTimeout'\n { `Double', id `FunPtr CallbackPrim' } -> `()' supressWarningAboutRes #}\n\n-- | Returns a function pointer so it can be freed with `freeHaskellFunPtr`, please don't invoke it.\naddTimeout :: Double -> GlobalCallback -> IO (FunPtr CallbackPrim)\naddTimeout t cb = do\n fp <- toGlobalCallbackPrim cb\n addTimeout' t fp\n return fp\n\n{# fun Fl_repeat_timeout as repeatTimeout'\n { `Double',id `FunPtr CallbackPrim' } -> `()' supressWarningAboutRes #}\n-- | Returns a function pointer so it can be freed with `freeHaskellFunPtr`, please don't invoke it.\nrepeatTimeout :: Double -> GlobalCallback -> IO (FunPtr CallbackPrim)\nrepeatTimeout t cb = do\n fp <- toGlobalCallbackPrim cb\n repeatTimeout' t fp\n return fp\n\n{# fun Fl_has_timeout as hasTimeout\n { id `FunPtr CallbackPrim' } -> `Bool' toBool #}\n\n{# fun Fl_remove_timeout as removeTimeout\n { id `FunPtr CallbackPrim' } -> `()' supressWarningAboutRes #}\n\n{# fun Fl_add_check as addCheck'\n { id `FunPtr CallbackPrim' } -> `()' supressWarningAboutRes #}\n-- | Returns a function pointer so it can be freed with `freeHaskellFunPtr`, please don't invoke it.\naddCheck :: GlobalCallback -> IO (FunPtr CallbackPrim)\naddCheck cb = do\n fp <- toGlobalCallbackPrim cb\n addCheck' fp\n return fp\n\n{# fun Fl_has_check as hasCheck\n { id `FunPtr CallbackPrim' } -> `Bool' toBool #}\n{# fun Fl_remove_check as removeCheck\n { id `FunPtr CallbackPrim' } -> `()' supressWarningAboutRes #}\n\n{# fun Fl_add_idle as addIdle'\n { id `FunPtr CallbackPrim' } -> `()' supressWarningAboutRes #}\n-- | Returns a function pointer so it can be freed with `freeHaskellFunPtr`, please don't invoke it.\naddIdle :: GlobalCallback -> IO (FunPtr CallbackPrim)\naddIdle cb = do\n fp <- toGlobalCallbackPrim cb\n addIdle' fp\n return fp\n\n{# fun Fl_has_idle as hasIdle\n { id `FunPtr CallbackPrim' } -> `Bool' toBool #}\n\n{# fun Fl_remove_idle as removeIdle\n { id `FunPtr CallbackPrim' } -> `()' supressWarningAboutRes #}\n\n{# fun Fl_damage as damage\n { } -> `Int' #}\n{# fun Fl_redraw as redraw\n { } -> `()' supressWarningAboutRes #}\n{# fun Fl_flush as flush\n { } -> `()' supressWarningAboutRes #}\n{# fun Fl_first_window as firstWindow' { } -> `Ptr ()' #}\nfirstWindow :: IO (Maybe (Ref Window))\nfirstWindow = firstWindow' >>= toMaybeRef\n\n{# fun Fl_set_first_window as setFirstWindow'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetFirstWindow :: (Parent a WindowBase) => Ref a -> IO ()\nsetFirstWindow wp =\n withRef wp setFirstWindow'\n{# fun Fl_next_window as nextWindow' { id `Ptr ()' } -> `Ptr ()' #}\nnextWindow :: Ref a -> IO (Maybe (Ref Window))\nnextWindow currWindow = withRef currWindow (\\ptr -> nextWindow' ptr >>= toMaybeRef)\n\n{# fun Fl_modal as modal' { } -> `Ptr ()' #}\nmodal :: IO (Maybe (Ref Widget))\nmodal = modal' >>= toMaybeRef\n\n{# fun Fl_grab as grab' { } -> `Ptr ()' #}\ngrab :: IO (Maybe (Ref Widget))\ngrab = grab' >>= toMaybeRef\n\n{# fun Fl_set_grab as setGrab'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetGrab :: (Parent a WindowBase) => Ref a -> IO ()\nsetGrab wp = withRef wp setGrab'\n{# fun Fl_event as event\n { } -> `Event' cToEnum #}\n{# fun Fl_event_x as eventX'\n { } -> `Int'#}\neventX :: IO X\neventX = eventX' >>= return . X\n{# fun Fl_event_y as eventY'\n { } -> `Int'#}\neventY :: IO Y\neventY = eventY' >>= return . Y\n{# fun Fl_event_x_root as eventXRoot'\n { } -> `Int' #}\neventPosition :: IO Position\neventPosition = do\n x' <- eventX\n y' <- eventY\n return (Position x' y')\n\neventXRoot :: IO X\neventXRoot = eventXRoot' >>= return . X\n{# fun Fl_event_y_root as eventYRoot'\n { } -> `Int' #}\neventYRoot :: IO Y\neventYRoot = eventYRoot' >>= return . Y\n\neventRootPosition :: IO Position\neventRootPosition = do\n x' <- eventXRoot\n y' <- eventYRoot\n return (Position x' y')\n{# fun Fl_event_dx as eventDx\n { } -> `Int' #}\n{# fun Fl_event_dy as eventDy\n { } -> `Int' #}\n{# fun Fl_get_mouse as getMouse'\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv*\n } -> `()' #}\ngetMouse :: IO Position\ngetMouse = do\n (x_pos,y_pos) <- getMouse'\n return $ (Position (X x_pos) (Y y_pos))\n{# fun Fl_event_clicks as eventClicks\n { } -> `Int'#}\n{# fun Fl_set_event_clicks as setEventClicks\n { `Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_event_is_click as eventIsClick\n { } -> `Bool' toBool #}\n{# fun Fl_set_event_is_click as setEventIsClick\n { `Int' } -> `()' supressWarningAboutRes #}\n\n{# fun Fl_event_button as eventButton'\n { } -> `Int' #}\neventButton :: IO (Maybe MouseButton)\neventButton = do\n mb <- eventButton'\n case mb of\n mb' | mb' == (fromEnum Mouse_Left) -> return (Just Mouse_Left)\n mb' | mb' == (fromEnum Mouse_Middle) -> return (Just Mouse_Right)\n mb' | mb' == (fromEnum Mouse_Right) -> return (Just Mouse_Middle)\n _ -> return Nothing\n\neventStates :: [EventState]\neventStates = [\n Kb_ShiftState,\n Kb_CapsLockState,\n Kb_CtrlState,\n Kb_AltState,\n Kb_NumLockState,\n Kb_MetaState,\n Kb_ScrollLockState,\n Mouse_Button1State,\n Mouse_Button2State,\n Mouse_Button3State\n ]\nextractEventStates :: CInt -> [EventState]\nextractEventStates = extract eventStates\n\n{# fun Fl_event_state as eventState\n { } -> `[EventState]' extractEventStates #}\n{# fun Fl_contains_event_state as containsEventState\n {cFromEnum `EventState' } -> `Bool' toBool #}\n{# fun Fl_event_key as eventKey\n { } -> `KeyType' cToKeyType #}\n{# fun Fl_event_original_key as eventOriginalKey\n { } -> `KeyType' cToKeyType #}\n{# fun Fl_event_key_pressed as eventKeyPressed\n {cFromKeyType `KeyType' } -> `Bool' toBool #}\n{# fun Fl_get_key as getKey\n {cFromKeyType `KeyType' } -> `Bool' toBool #}\n{# fun Fl_event_text as eventText' { } -> `CString' #}\neventText :: IO T.Text\neventText = eventText' >>= cStringToText\n{# fun Fl_event_length as eventLength\n { } -> `Int' #}\n\n{# fun Fl_event_clipboard as flEventClipboard' { } -> `Ptr ()' #}\n{# fun Fl_event_clipboard_type as flEventClipboardType' { } -> `CString' #}\neventClipboardContents :: IO (Maybe ClipboardContents)\neventClipboardContents = do\n typeString <- flEventClipboardType' >>= cStringToText\n if (T.length typeString == 0)\n then return Nothing\n else case typeString of\n s | (T.unpack s == \"Fl::clipboard_image\") -> do\n stringContents <- flEventClipboard' >>= cStringToText . castPtr\n return (if (T.length stringContents == 0)\n then (Just (ClipboardContentsPlainText Nothing))\n else (Just (ClipboardContentsPlainText (Just stringContents))))\n s | (T.unpack s == \"Fl::clipboard_plain_text\") -> do\n imageRef <- flEventClipboard' >>= toMaybeRef\n return (Just (ClipboardContentsImage imageRef))\n _ -> error \"eventClipboardContents :: The type of the clipboard contents must be either the string \\\"Fl::clipboard_image\\\" or \\\"Fl::clipboard_plain_image\\\".\"\n\n{# fun Fl_compose as compose\n { alloca- `Int' peekIntConv* } -> `Bool' toBool #}\n{# fun Fl_compose_reset as composeReset\n { } -> `()' supressWarningAboutRes #}\n{# fun Fl_event_inside_region as eventInsideRegion'\n { `Int',`Int',`Int',`Int' } -> `Int' #}\neventInsideRegion :: Rectangle -> IO Event\neventInsideRegion (Rectangle\n (Position\n (X x_pos)\n (Y y_pos))\n (Size\n (Width width)\n (Height height))) =\n do\n eventNum <- eventInsideRegion' x_pos y_pos width height\n return $ toEnum eventNum\n{# fun Fl_event_inside_widget as eventInsideWidget'\n { id `Ptr ()' } -> `Int' #}\neventInsideWidget :: (Parent a WidgetBase) => Ref a -> IO Event\neventInsideWidget wp =\n withRef wp (\\ptr -> do\n eventNum <- eventInsideWidget' (castPtr ptr)\n return $ toEnum eventNum)\n{# fun Fl_test_shortcut as testShortcut\n { id `FlShortcut' } -> `Bool' toBool #}\n{# fun Fl_enable_im as enableIm\n {} -> `()' supressWarningAboutRes #}\n{# fun Fl_disable_im as disableIm\n {} -> `()' supressWarningAboutRes #}\n{# fun Fl_handle as handle'\n { `Int',id `Ptr ()' } -> `Int' #}\nhandle :: (Parent a WindowBase) => Event -> Ref a -> IO (Either UnknownEvent ())\nhandle e wp =\n withRef wp (handle' (cFromEnum e)) >>= return . successOrUnknownEvent\n{# fun Fl_handle_ as handle_'\n { `Int',id `Ptr ()' } -> `Int' #}\nhandle_ :: (Parent a WindowBase) => Event -> Ref a -> IO (Either UnknownEvent ())\nhandle_ e wp =\n withRef wp (handle_' (cFromEnum e)) >>= return . successOrUnknownEvent\n{# fun Fl_belowmouse as belowmouse' { } -> `Ptr ()' #}\nbelowmouse :: IO (Maybe (Ref Widget))\nbelowmouse = belowmouse' >>= toMaybeRef\n{# fun Fl_set_belowmouse as setBelowmouse'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetBelowmouse :: (Parent a WidgetBase) => Ref a -> IO ()\nsetBelowmouse wp = withRef wp setBelowmouse'\n{# fun Fl_pushed as pushed'\n { } -> `Ptr ()' #}\npushed :: IO (Maybe (Ref Widget))\npushed = pushed' >>= toMaybeRef\n{# fun Fl_set_pushed as setPushed'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetPushed :: (Parent a WidgetBase) => Ref a -> IO ()\nsetPushed wp = withRef wp setPushed'\n{# fun Fl_focus as focus' { } -> `Ptr ()' #}\nfocus :: IO (Maybe (Ref Widget))\nfocus = focus' >>= toMaybeRef\n{# fun Fl_set_focus as setFocus'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetFocus :: (Parent a WidgetBase) => Ref a -> IO ()\nsetFocus wp = withRef wp setFocus'\n{# fun Fl_selection_owner as selectionOwner' { } -> `Ptr ()' #}\nselectionOwner :: IO (Maybe (Ref Widget))\nselectionOwner = selectionOwner' >>= toMaybeRef\n{# fun Fl_set_selection_owner as setSelection_Owner'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetSelectionOwner :: (Parent a WidgetBase) => Ref a -> IO ()\nsetSelectionOwner wp = withRef wp setSelection_Owner'\n{# fun Fl_add_handler as addHandler'\n { id `FunPtr GlobalEventHandlerPrim' } -> `()' supressWarningAboutRes #}\n{# fun Fl_remove_handler as removeHandler'\n { id `FunPtr GlobalEventHandlerPrim' } -> `()' supressWarningAboutRes #}\nsetHandler :: GlobalEventHandlerF -> IO ()\nsetHandler eh = do\n newGlobalEventHandler <- toGlobalEventHandlerPrim eh\n curr <- do\n old <- readIORef ptrToGlobalEventHandler\n writeIORef ptrToGlobalEventHandler newGlobalEventHandler\n return old\n freeHaskellFunPtr curr\n removeHandler' curr\n addHandler' newGlobalEventHandler\n\n{# fun Fl_set_event_dispatch as setEventDispatch'\n { id `Ptr (FunPtr EventDispatchPrim)' } -> `()' supressWarningAboutRes #}\n{# fun Fl_event_dispatch as eventDispatch'\n { } -> `FunPtr EventDispatchPrim' id #}\neventDispatch :: (Parent a WidgetBase) =>\n IO (Event -> Ref a -> IO (Either UnknownEvent ()))\neventDispatch =\n do\n funPtr <- eventDispatch'\n return (\\e window ->\n withRef\n window\n (\\ptr ->\n let eventNum = fromIntegral (fromEnum e)\n fun = unwrapEventDispatchPrim funPtr\n in fun eventNum (castPtr ptr) >>=\n return . successOrUnknownEvent . fromIntegral\n )\n )\n\nsetEventDispatch ::\n (Parent a WidgetBase) =>\n (Event -> Ref a -> IO (Either UnknownEvent ())) -> IO ()\nsetEventDispatch ed = do\n do\n let toPrim = (\\e ptr ->\n let eventEnum = toEnum $ fromIntegral e\n in do\n obj <- toRef ptr\n result <- ed eventEnum obj\n case result of\n Left _ -> return 0\n _ -> return 1\n )\n callbackPtr <- wrapEventDispatchPrim toPrim\n ptrToCallbackPtr <- new callbackPtr\n poke ptrToCallbackPtr callbackPtr\n setEventDispatch' ptrToCallbackPtr\n\n{# fun Fl_copy as copy' { `CString',`Int' } -> `()' supressWarningAboutRes #}\ncopyToClipboard :: T.Text -> IO ()\ncopyToClipboard t = withText t (\\s' -> copy' s' 0)\n\ncopyToSelectionBuffer :: T.Text -> IO ()\ncopyToSelectionBuffer t = withText t (\\s' -> copy' s' 1)\n\n{# fun Fl_copy_with_destination as copyWithDestination { `CString',`Int',`Int' } -> `()' supressWarningAboutRes #}\n\ncopyLengthToClipboard :: T.Text -> Int -> IO ()\ncopyLengthToClipboard t l = withText t (\\s' -> copyWithDestination s' l 0)\n\ncopyLengthToSelectionBuffer :: T.Text -> Int -> IO ()\ncopyLengthToSelectionBuffer t l = withText t (\\s' -> copyWithDestination s' l 1)\n\n{# fun Fl_paste_with_source_type as pasteWithSourceType { id `Ptr ()',`Int', `CString' } -> `()' supressWarningAboutRes #}\n\npasteImageFromSelectionBuffer :: (Parent a WidgetBase) => Ref a -> IO ()\npasteImageFromSelectionBuffer widget = withRef widget (\\widgetPtr -> withText (T.pack \"Fl::clipboard_image\") (\\t -> pasteWithSourceType widgetPtr 0 t))\n\npasteFromSelectionBuffer :: (Parent a WidgetBase) => Ref a -> IO ()\npasteFromSelectionBuffer widget = withRef widget (\\widgetPtr -> withText (T.pack \"Fl::clipboard_plain_text\") (\\t -> pasteWithSourceType widgetPtr 0 t))\n\npasteImageFromClipboard :: (Parent a WidgetBase) => Ref a -> IO ()\npasteImageFromClipboard widget = withRef widget (\\widgetPtr -> withText (T.pack \"Fl::clipboard_image\") (\\t -> pasteWithSourceType widgetPtr 1 t))\n\npasteFromClipboard :: (Parent a WidgetBase) => Ref a -> IO ()\npasteFromClipboard widget = withRef widget (\\widgetPtr -> withText (T.pack \"Fl::clipboard_plain_text\") (\\t -> pasteWithSourceType widgetPtr 1 t))\n\n{# fun Fl_dnd as dnd\n { } -> `Int' #}\n{# fun Fl_x as x\n { } -> `Int' #}\n{# fun Fl_y as y\n { } -> `Int' #}\n{# fun Fl_w as w\n { } -> `Int' #}\n{# fun Fl_h as h\n { } -> `Int' #}\n{# fun Fl_screen_count as screenCount\n { } -> `Int' #}\n\n{# fun Fl_screen_xywh as screenXYWH\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv*\n } -> `()' #}\n{# fun Fl_screen_xywh_with_mxmy as screenXYWYWithMXMY\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int',\n `Int'\n } -> `()' #}\n{# fun Fl_screen_xywh_with_n as screenXYWNWithN\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int'\n } -> `()' #}\n{# fun Fl_screen_xywh_with_mxmymwmh as screenXYWHWithNMXMYMWMH\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int',\n `Int',\n `Int',\n `Int'\n } -> `()' #}\n\nscreenBounds :: Maybe ScreenLocation -> IO Rectangle\nscreenBounds location =\n case location of\n (Just (Intersect (Rectangle (Position (X x_pos) (Y y_pos)) (Size (Width width) (Height height))))) ->\n screenXYWHWithNMXMYMWMH x_pos y_pos width height >>= return . toRectangle\n (Just (ScreenPosition (Position (X x_pos) (Y y_pos)))) ->\n screenXYWYWithMXMY x_pos y_pos >>= return . toRectangle\n (Just (ScreenNumber n)) ->\n screenXYWNWithN n >>= return . toRectangle\n Nothing ->\n screenXYWH >>= return . toRectangle\n\n{# fun Fl_screen_dpi as screenDpi'\n { alloca- `Float' peekFloatConv*,\n alloca- `Float' peekFloatConv* }\n -> `()' #}\n{# fun Fl_screen_dpi_with_n as screenDpiWithN'\n { alloca- `Float' peekFloatConv*,\n alloca- `Float' peekFloatConv*,\n `Int' }\n -> `()' #}\n\nscreenDPI :: Maybe Int -> IO DPI\nscreenDPI (Just n) = do\n (dpiX, dpiY) <- screenDpiWithN' n\n return $ DPI dpiX dpiY\nscreenDPI Nothing = do\n (dpiX, dpiY) <- screenDpi'\n return $ DPI dpiX dpiY\n\n{# fun Fl_screen_work_area_with_mx_my as screenWorkAreaWithMXMY'\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int',\n `Int'\n }\n -> `()' #}\n{# fun Fl_screen_work_area_with_n as screenWorkAreaWithN'\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int'\n }\n -> `()' #}\n{# fun Fl_screen_work_area as screenWorkArea'\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv*\n }\n -> `()' id- #}\nscreenWorkArea :: Maybe ScreenLocation -> IO Rectangle\nscreenWorkArea location =\n case location of\n (Just (Intersect (Rectangle (Position (X x_pos) (Y y_pos)) _))) ->\n screenWorkAreaWithMXMY' x_pos y_pos >>= return . toRectangle\n (Just (ScreenPosition (Position (X x_pos) (Y y_pos)))) ->\n screenWorkAreaWithMXMY' x_pos y_pos >>= return . toRectangle\n (Just (ScreenNumber n)) ->\n screenWorkAreaWithN' n >>= return . toRectangle\n Nothing ->\n screenWorkArea' >>= return . toRectangle\n\nsetColorRgb :: Color -> Word8 -> Word8 -> Word8 -> IO ()\nsetColorRgb c r g b = {#call Fl_set_color_rgb as fl_set_color_rgb #}\n (cFromColor c)\n (fromIntegral r)\n (fromIntegral g)\n (fromIntegral b)\n{# fun Fl_set_color as setColor\n { cFromColor `Color', cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_get_color as getColor\n { cFromColor `Color' } -> `Color' cToColor #}\n{# fun Fl_get_color_rgb as getColorRgb'\n {\n cFromColor `Color',\n alloca- `CUChar' peekIntConv*,\n alloca- `CUChar' peekIntConv*,\n alloca- `CUChar' peekIntConv*\n } -> `()' supressWarningAboutRes #}\ngetColorRgb :: Color -> IO RGB\ngetColorRgb c = do\n (_,r,g,b) <- getColorRgb' c\n return (r,g,b)\n\n#if !defined(__APPLE__)\n{# fun Fl_free_color as freeColor'\n { cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_free_color_with_overlay as freeColorWithOverlay'\n { cFromColor `Color', `Int' } -> `()' supressWarningAboutRes #}\nremoveFromColormap :: Maybe Color -> Color -> IO ()\nremoveFromColormap (Just (Color overlay)) c = freeColorWithOverlay' c (fromIntegral overlay)\nremoveFromColormap Nothing c = freeColor' c\n#endif\n{# fun Fl_get_font as getFont' { cFromFont `Font' } -> `CString' #}\ngetFont :: Font -> IO T.Text\ngetFont f = getFont' f >>= cStringToText\n\n{# fun Fl_get_font_name_with_attributes as getFontNameWithAttributes' { cFromFont `Font', alloca- `Maybe FontAttribute' toAttribute* } -> `CString' #}\ngetFontName :: Font -> IO (T.Text, Maybe FontAttribute)\ngetFontName f = do\n (str, fa) <- getFontNameWithAttributes' f\n t <- cStringToText str\n return (t, fa)\n\ntoAttribute :: Ptr CInt -> IO (Maybe FontAttribute)\ntoAttribute ptr =\n do\n attributeCode <- peekIntConv ptr\n return $ cToFontAttribute attributeCode\n{# fun Fl_get_font_sizes as getFontSizes'\n { cFromFont `Font', id `Ptr (Ptr CInt)' } -> `CInt' #}\ngetFontSizes :: Font -> IO [FontSize]\ngetFontSizes font = do\n arrPtr <- (newArray [] :: IO (Ptr (Ptr CInt)))\n arrLength <- getFontSizes' font arrPtr\n zeroth <- peekElemOff arrPtr 0\n if (arrLength == 0) then return []\n else do\n (sizes :: [CInt]) <-\n mapM\n (\n \\offset -> do\n size <- peek (advancePtr zeroth offset)\n return size\n )\n [0 .. ((fromIntegral arrLength) - 1)]\n return (map FontSize sizes)\n\n{# fun Fl_set_font_by_string as setFontToString'\n { cFromFont `Font', `CString' } -> `()' supressWarningAboutRes #}\nsetFontToString :: Font -> T.Text -> IO ()\nsetFontToString f t = withText t (\\t' -> setFontToString' f t')\n{# fun Fl_set_font_by_font as setFontToFont\n { cFromFont `Font',cFromFont `Font' } -> `()' supressWarningAboutRes #}\n{# fun Fl_set_fonts as setFonts'\n { } -> `Int' #}\n{# fun Fl_set_fonts_with_string as setFontsWithString'\n { id `Ptr CChar' } -> `Int' #}\nsetFonts :: Maybe T.Text -> IO Int\nsetFonts (Just xstarName) = withText xstarName (\\starNamePtr -> setFontsWithString' starNamePtr)\nsetFonts Nothing = setFonts'\n\n{# fun Fl_add_fd_with_when as addFdWhen'\n {\n `CInt',\n `CInt',\n id `FunPtr FDHandlerPrim'\n } -> `()' #}\n\naddFdWhen :: CInt -> [FdWhen] -> FDHandler -> IO ()\naddFdWhen fd fdWhens handler = do\n fPtr <- toFDHandlerPrim handler\n addFdWhen' fd (fromIntegral . combine $ fdWhens) fPtr\n\n{# fun Fl_add_fd as addFd'\n {\n `CInt',\n id `FunPtr FDHandlerPrim'\n } -> `()' #}\n\naddFd :: CInt -> FDHandler -> IO ()\naddFd fd handler = do\n fPtr <- toFDHandlerPrim handler\n addFd' fd fPtr\n\n{# fun Fl_remove_fd_with_when as removeFdWhen' { `CInt', `CInt'} -> `()' #}\nremoveFdWhen :: CInt -> [FdWhen] -> IO ()\nremoveFdWhen fd fdWhens =\n removeFdWhen' fd (fromIntegral . combine $ fdWhens)\n\n{# fun Fl_remove_fd as removeFd' { `CInt' } -> `()' #}\nremoveFd :: CInt -> IO ()\nremoveFd fd = removeFd' fd\n\n{# fun Fl_get_boxtype as getBoxtype\n { cFromEnum `Boxtype' } -> `FunPtr BoxDrawFPrim' id #}\n\n{# fun Fl_set_boxtype as setBoxtype'\n {\n cFromEnum `Boxtype',\n id `FunPtr BoxDrawFPrim',\n `Word8',\n `Word8',\n `Word8',\n `Word8'\n } -> `()' supressWarningAboutRes #}\n{# fun Fl_set_boxtype_by_boxtype as setBoxtypeByBoxtype'\n {\n cFromEnum `Boxtype',\n cFromEnum `Boxtype'\n } -> `()' supressWarningAboutRes #}\n\ndata BoxtypeSpec = FromSpec BoxDrawF Word8 Word8 Word8 Word8\n | FromBoxtype Boxtype\n | FromFunPtr (FunPtr BoxDrawFPrim) Word8 Word8 Word8 Word8\nsetBoxtype :: Boxtype -> BoxtypeSpec -> IO ()\nsetBoxtype bt (FromSpec f dx dy dw dh) =\n do\n funPtr <- wrapBoxDrawFPrim (toBoxDrawFPrim f)\n setBoxtype' bt funPtr dx dy dw dh\nsetBoxtype bt (FromBoxtype template) =\n setBoxtypeByBoxtype' bt template\nsetBoxtype bt (FromFunPtr funPtr dx dy dw dh) =\n setBoxtype' bt funPtr dx dy dw dh\n\n{# fun Fl_box_dx as boxDx\n { cFromEnum `Boxtype' } -> `Int' #}\n{# fun Fl_box_dy as boxDy\n { cFromEnum `Boxtype' } -> `Int' #}\n{# fun Fl_box_dw as boxDw\n { cFromEnum `Boxtype' } -> `Int' #}\n{# fun Fl_box_dh as boxDh\n { cFromEnum `Boxtype' } -> `Int' #}\n\nadjustBoundsByBoxtype :: Rectangle -> Boxtype -> IO Rectangle\nadjustBoundsByBoxtype rect bt =\n let (x',y',w',h') = fromRectangle rect\n in do\n dx <- boxDx bt\n dy <- boxDy bt\n dw <- boxDw bt\n dh <- boxDh bt\n return (toRectangle (x'+dx,y'+dy,w'-dw,h'-dh))\n\nboxDifferences :: Rectangle -> Rectangle -> (Int, Int, Int, Int)\nboxDifferences r1 r2 =\n let (r1x,r1y,r1w,r1h) = fromRectangle r1\n (r2x,r2y,r2w,r2h) = fromRectangle r2\n in (r2x-r1x,r2y-r1y,r1w-r2w,r1h-r2h)\n\n{# fun Fl_draw_box_active as drawBoxActive\n { } -> `Bool' toBool #}\n{# fun Fl_event_shift as eventShift\n { } -> `Bool' toBool #}\n{# fun Fl_event_ctrl as eventCtrl\n { } -> `Bool' toBool #}\n{# fun Fl_event_command as eventCommand\n { } -> `Bool' toBool #}\n{# fun Fl_event_alt as eventAlt\n { } -> `Bool' toBool #}\n{# fun Fl_event_buttons as eventButtons\n { } -> `Bool' toBool #}\n{# fun Fl_event_button1 as eventButton1\n { } -> `Bool' toBool #}\n{# fun Fl_event_button2 as eventButton2\n { } -> `Bool' toBool #}\n{# fun Fl_event_button3 as eventButton3\n { } -> `Bool' toBool #}\nrelease :: IO ()\nrelease = {#call Fl_release as fl_release #}\nsetVisibleFocus :: Bool -> IO ()\nsetVisibleFocus = {#call Fl_set_visible_focus as fl_set_visible_focus #} . cFromBool\nvisibleFocus :: IO Bool\nvisibleFocus = {#call Fl_visible_focus as fl_visible_focus #} >>= return . cToBool\nsetDndTextOps :: Bool -> IO ()\nsetDndTextOps = {#call Fl_set_dnd_text_ops as fl_set_dnd_text_ops #} . fromBool\ndndTextOps :: IO Option\ndndTextOps = {#call Fl_dnd_text_ops as fl_dnd_text_ops #} >>= return . cToEnum\ndeleteWidget :: (Parent a WidgetBase) => Ref a -> IO ()\ndeleteWidget wptr =\n swapRef wptr $ \\ptr -> do\n {#call Fl_delete_widget as fl_delete_widget #} ptr\n return nullPtr\ndoWidgetDeletion :: IO ()\ndoWidgetDeletion = {#call Fl_do_widget_deletion as fl_do_widget_deletion #}\nwatchWidgetPointer :: (Parent a WidgetBase) => Ref a -> IO ()\nwatchWidgetPointer wp = withRef wp {#call Fl_watch_widget_pointer as fl_Watch_widget_Pointer #}\nreleaseWidgetPointer :: (Parent a WidgetBase) => Ref a -> IO ()\nreleaseWidgetPointer wp = withRef wp {#call Fl_release_widget_pointer as fl_release_widget_pointer #}\nclearWidgetPointer :: (Parent a WidgetBase) => Ref a -> IO ()\nclearWidgetPointer wp = withRef wp {#call Fl_clear_widget_pointer as fl_Clear_Widget_Pointer #}\n-- | Only available on FLTK version 1.3.4 and above.\nsetBoxColor :: Color -> IO ()\nsetBoxColor c = {#call Fl_set_box_color as fl_set_box_color #} (cFromColor c)\n-- | Only available on FLTK version 1.3.4 and above.\nboxColor :: Color -> IO Color\nboxColor c = {#call Fl_box_color as fl_box_color #} (cFromColor c) >>= return . cToColor\n-- | Only available on FLTK version 1.3.4 and above.\nabiVersion :: IO Int\nabiVersion = {#call Fl_abi_version as fl_abi_version #} >>= return . fromIntegral\n-- | Only available on FLTK version 1.3.4 and above.\nabiCheck :: Int -> IO Int\nabiCheck v = {#call Fl_abi_check as fl_abi_check #} (fromIntegral v) >>= return . fromIntegral\n-- | Only available on FLTK version 1.3.4 and above.\napiVersion :: IO Int\napiVersion = {#call Fl_abi_version as fl_abi_version #} >>= return . fromIntegral\n-- | Only available on FLTK version 1.3.4 and above.\nlocalCtrl :: IO T.Text\nlocalCtrl = {#call Fl_local_ctrl as fl_local_ctrl #} >>= cStringToText\n-- | Only available on FLTK version 1.3.4 and above.\nlocalAlt :: IO T.Text\nlocalAlt = {#call Fl_local_alt as fl_local_alt #} >>= cStringToText\n-- | Only available on FLTK version 1.3.4 and above.\nlocalMeta :: IO T.Text\nlocalMeta = {#call Fl_local_meta as fl_local_meta #} >>= cStringToText\n-- | Only available on FLTK version 1.3.4 and above.\nlocalShift :: IO T.Text\nlocalShift = {#call Fl_local_shift as fl_local_shift #} >>= cStringToText\n#ifdef GLSUPPORT\n-- | Only available on FLTK version 1.3.4 and above if GL is enabled with 'stack build --flag fltkhs:opengl'\nuseHighResGL :: IO Bool\nuseHighResGL = {#call Fl_use_high_res_GL as fl_use_high_res_GL #} >>= return . cToBool\n-- | Only available on FLTK version 1.3.4 and above if GL is enabled with 'stack build --flag fltkhs:opengl'\nsetUseHighResGL :: Bool -> IO ()\nsetUseHighResGL use' = {#call Fl_set_use_high_res_GL as fl_set_use_high_res_GL #} (cFromBool use')\n#endif\ninsertionPointLocation :: Position -> Height -> IO ()\ninsertionPointLocation (Position (X x') (Y y')) (Height h')\n = {#call Fl_insertion_point_location as fl_insertion_point_location #} (fromIntegral x') (fromIntegral y') (fromIntegral h')\nresetMarkedText :: IO ()\nresetMarkedText = {#call Fl_reset_marked_text as fl_reset_marked_text #}\nrunChecks :: IO ()\nrunChecks = {#call Fl_run_checks as fl_run_checks #}\nscreenDriver :: IO (Maybe (Ref ScreenDriver))\nscreenDriver = {#call Fl_screen_driver as fl_screen_driver #} >>= toMaybeRef\nsystemDriver :: IO (Maybe (Ref SystemDriver))\nsystemDriver = {#call Fl_system_driver as fl_system_driver #} >>= toMaybeRef\nsetProgramShouldQuit :: Bool -> IO ()\nsetProgramShouldQuit = {#call Fl_set_program_should_quit as fl_set_program_should_quit #} . cFromBool\ngetProgramShouldQuit :: IO Bool\ngetProgramShouldQuit = {#call Fl_get_program_should_quit as fl_get_program_should_quit #} >>= return . cToBool\n\n\n-- | Use this function to run a GUI in GHCi.\nreplRun :: IO ()\nreplRun = do\n flush\n w <- firstWindow\n case w of\n Just _ ->\n catch (forever (waitFor 0.01))\n (\\e -> if (e == UserInterrupt)\n then do\n wM <- firstWindow\n case wM of\n Just w' -> allToplevelWindows [] (Just w') >>= mapM_ deleteWidget\n Nothing -> return ()\n flush\n else throw e)\n Nothing -> return ()\n where\n allToplevelWindows :: [Ref Window] -> Maybe (Ref Window) -> IO [Ref Window]\n allToplevelWindows ws (Just w) = nextWindow w >>= allToplevelWindows (w:ws)\n allToplevelWindows ws Nothing = return ws\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"}
{"commit":"c95f4849d78fac1ac0645eb5d408d0eacb340a55","subject":"fix showCursor","message":"fix showCursor\n","repos":"abbradar\/MySDL","old_file":"src\/Graphics\/UI\/SDL\/Video\/Mouse.chs","new_file":"src\/Graphics\/UI\/SDL\/Video\/Mouse.chs","new_contents":"{-|\nDescription: Generic mouse control.\n-}\n\nmodule Graphics.UI.SDL.Video.Mouse\n ( MouseButton\n , MouseButtonState\n , getMouseState\n , getRelativeMouseState\n , getMouseGrab\n , setMouseGrab\n , getCursorShown\n , setCursorShown\n ) where\n\nimport Control.Monad\nimport Control.Applicative\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Storable (peek)\nimport Foreign.C.Types (CInt(..), CUInt(..))\nimport Foreign.Ptr (Ptr)\nimport Foreign.ForeignPtr (withForeignPtr)\nimport Foreign.Marshal.Utils\nimport Data.Word\nimport Control.Monad.IO.Class\n\nimport Graphics.UI.SDL.Types\nimport Graphics.UI.SDL.Video.Monad\nimport Graphics.UI.SDL.Video.Internal.Mouse\n\n{#import Graphics.UI.SDL.Video.Internal.Window #}\n{#import Graphics.UI.SDL.Internal.Prim #}\n\n#include \n\ngetMouseState' :: MonadSDLVideo m => IO (Word32, CInt, CInt) -> m (PosPoint, MouseButtonState)\ngetMouseState' call = liftIO $ do\n (f, (CInt x), (CInt y)) <- call\n return (P x y, mmaskToButtons f)\n\n-- | Get mouse state (absolute for the screen space).\ngetMouseState :: MonadSDLVideo m => m (PosPoint, MouseButtonState)\ngetMouseState = getMouseState' sDLGetMouseState\n where {#fun unsafe SDL_GetMouseState as ^\n { alloca- `CInt' peek*\n , alloca- `CInt' peek*\n } -> `Word32' #}\n\n-- | Get relative mouse state regarding to the last call.\ngetRelativeMouseState :: MonadSDLVideo m => m (PosPoint, MouseButtonState)\ngetRelativeMouseState = getMouseState' sDLGetRelativeMouseState\n where {#fun unsafe SDL_GetRelativeMouseState as ^\n { alloca- `CInt' peek*\n , alloca- `CInt' peek*\n } -> `Word32' #}\n\n-- | Check if mouse cursor is grabbed by a window.\ngetMouseGrab :: (MonadSDLVideo m, SDLWindow w) => w -> m Bool\ngetMouseGrab (toCWindow -> w) = liftIO $ fromSDLBool <$> sDLGetWindowGrab w\n where {#fun unsafe SDL_GetWindowGrab as ^\n { `CWindow' } -> `SDLBool' #}\n\n-- | Grab or ungrab mouse cursor.\nsetMouseGrab :: (MonadSDLVideo m, SDLWindow w) => Bool -> w -> m ()\nsetMouseGrab (toSDLBool -> s) (toCWindow -> w) = liftIO $ sDLSetWindowGrab w s\n where {#fun unsafe SDL_SetWindowGrab as ^\n { `CWindow', `SDLBool' } -> `()' #}\n\nshowCursor' :: MonadSDLVideo m => Int -> m Int\nshowCursor' i = liftIO $ sdlCall \"SDL_ShowCursor\" (sDLShowCursor i) (\/= -1)\n where {#fun unsafe SDL_ShowCursor as ^\n { `Int' } -> `Int' #}\n\n-- | Check if mouse cursor is hidden (globally).\ngetCursorShown :: MonadSDLVideo m => m Bool\ngetCursorShown = toBool <$> showCursor' (-1)\n\n-- | Hide or show a cursor.\nsetCursorShown :: MonadSDLVideo m => Bool -> m ()\nsetCursorShown = void . showCursor' . fromBool\n","old_contents":"{-|\nDescription: Generic mouse control.\n-}\n\nmodule Graphics.UI.SDL.Video.Mouse\n ( MouseButton\n , MouseButtonState\n , getMouseState\n , getRelativeMouseState\n , getMouseGrab\n , setMouseGrab\n , getCursorShown\n , setCursorShown\n ) where\n\nimport Control.Monad\nimport Control.Applicative\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Storable (peek)\nimport Foreign.C.Types (CInt(..), CUInt(..))\nimport Foreign.Ptr (Ptr)\nimport Foreign.ForeignPtr (withForeignPtr)\nimport Foreign.Marshal.Utils\nimport Data.Word\nimport Control.Monad.IO.Class\n\nimport Graphics.UI.SDL.Types\nimport Graphics.UI.SDL.Video.Monad\nimport Graphics.UI.SDL.Video.Internal.Mouse\n\n{#import Graphics.UI.SDL.Video.Internal.Window #}\n{#import Graphics.UI.SDL.Internal.Prim #}\n\n#include \n\ngetMouseState' :: MonadSDLVideo m => IO (Word32, CInt, CInt) -> m (PosPoint, MouseButtonState)\ngetMouseState' call = liftIO $ do\n (f, (CInt x), (CInt y)) <- call\n return (P x y, mmaskToButtons f)\n\n-- | Get mouse state (absolute for the screen space).\ngetMouseState :: MonadSDLVideo m => m (PosPoint, MouseButtonState)\ngetMouseState = getMouseState' sDLGetMouseState\n where {#fun unsafe SDL_GetMouseState as ^\n { alloca- `CInt' peek*\n , alloca- `CInt' peek*\n } -> `Word32' #}\n\n-- | Get relative mouse state regarding to the last call.\ngetRelativeMouseState :: MonadSDLVideo m => m (PosPoint, MouseButtonState)\ngetRelativeMouseState = getMouseState' sDLGetRelativeMouseState\n where {#fun unsafe SDL_GetRelativeMouseState as ^\n { alloca- `CInt' peek*\n , alloca- `CInt' peek*\n } -> `Word32' #}\n\n-- | Check if mouse cursor is grabbed by a window.\ngetMouseGrab :: (MonadSDLVideo m, SDLWindow w) => w -> m Bool\ngetMouseGrab (toCWindow -> w) = liftIO $ fromSDLBool <$> sDLGetWindowGrab w\n where {#fun unsafe SDL_GetWindowGrab as ^\n { `CWindow' } -> `SDLBool' #}\n\n-- | Grab or ungrab mouse cursor.\nsetMouseGrab :: (MonadSDLVideo m, SDLWindow w) => Bool -> w -> m ()\nsetMouseGrab (toSDLBool -> s) (toCWindow -> w) = liftIO $ sDLSetWindowGrab w s\n where {#fun unsafe SDL_SetWindowGrab as ^\n { `CWindow', `SDLBool' } -> `()' #}\n\nshowCursor' :: MonadSDLVideo m => Int -> m Int\nshowCursor' i = liftIO $ sdlCall \"SDL_ShowCursor\" (sDLShowCursor i) (\/= 1)\n where {#fun unsafe SDL_ShowCursor as ^\n { `Int' } -> `Int' #}\n\n-- | Check if mouse cursor is hidden (globally).\ngetCursorShown :: MonadSDLVideo m => m Bool\ngetCursorShown = toBool <$> showCursor' (-1)\n\n-- | Hide or show a cursor.\nsetCursorShown :: MonadSDLVideo m => Bool -> m ()\nsetCursorShown = void . showCursor' . fromBool\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"77c61e0d6f38e289f8f1c08107571bf7f1128163","subject":"gio: S.G.File: specify module exports","message":"gio: S.G.File: specify module exports","repos":"vincenthz\/webkit","old_file":"gio\/System\/GIO\/File.chs","new_file":"gio\/System\/GIO\/File.chs","new_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gio -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 13-Oct-2008\n--\n-- Copyright (c) 2008 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GIO, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GIO documentation,\n-- Copyright (c) 2001 Seth Nickell . The\n-- documentation is covered by the GNU Free Documentation License,\n-- version 1.2.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.GIO.File (\n File,\n FileClass,\n FileQueryInfoFlags,\n FileCreateFlags,\n FileCopyFlags,\n FileMonitorFlags,\n FilesystemPreviewType,\n FileProgressCallback,\n FileReadMoreCallback,\n fileNewForPath,\n fileNewForURI,\n fileNewForCommandlineArg,\n fileParseName,\n fileDup,\n fileEqual,\n fileGetBasename,\n fileGetPath,\n fileGetURI,\n fileGetParseName,\n fileGetChild,\n fileGetChildForDisplayName,\n fileHasPrefix,\n fileGetRelativePath,\n fileResolveRelativePath,\n fileIsNative,\n fileHasURIScheme,\n fileGetURIScheme,\n fileRead,\n fileReadAsync,\n fileReadFinish,\n fileAppendTo,\n fileCreate,\n fileReplace,\n fileAppendToAsync,\n fileAppendToFinish,\n fileCreateAsync,\n fileCreateFinish,\n fileReplaceAsync,\n fileReplaceFinish,\n fileQueryInfo,\n fileQueryInfoAsync,\n fileQueryExists,\n fileQueryFilesystemInfo\n ) where\n\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport Data.Typeable\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.UTFString\n\nimport System.GIO.Base\n{#import System.GIO.Types#}\n\n{# context lib = \"gio\" prefix = \"g\" #}\n\n{# enum GFileQueryInfoFlags as FileQueryInfoFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileQueryInfoFlags\n\n{# enum GFileCreateFlags as FileCreateFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCreateFlags\n\n{# enum GFileCopyFlags as FileCopyFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCopyFlags\n\n{# enum GFileMonitorFlags as FileMonitorFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileMonitorFlags\n\n{# enum GFilesystemPreviewType as FilesystemPreviewType {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\ntype FileProgressCallback = {# type goffset #} -> {# type goffset #} -> IO ()\ntype FileReadMoreCallback = BS.ByteString -> IO Bool\n\nfileNewForPath :: FilePath -> IO File\nfileNewForPath path =\n withUTFString path $ {# call file_new_for_path #} >=> takeGObject\n\nfileNewForURI :: String -> IO File\nfileNewForURI uri =\n withUTFString uri $ {# call file_new_for_uri #} >=> takeGObject\n\nfileNewForCommandlineArg :: String -> IO File\nfileNewForCommandlineArg arg =\n withUTFString arg $ {# call file_new_for_commandline_arg #} >=> takeGObject\n\nfileParseName :: String -> IO File\nfileParseName parseName =\n withUTFString parseName $ {# call file_parse_name #} >=> takeGObject\n\nfileDup :: FileClass file\n => file -> IO file\nfileDup =\n {# call file_dup #} . toFile >=> takeGObject . castPtr\n\nfileEqual :: (FileClass file1, FileClass file2)\n => file1 -> file2 -> IO Bool\nfileEqual file1 file2 =\n liftM toBool $ {# call file_equal #} (toFile file1) (toFile file2)\n\nfileGetBasename :: FileClass file => file -> IO String\nfileGetBasename =\n {# call file_get_basename #} . toFile >=> readUTFString\n\nfileGetPath :: FileClass file => file -> IO FilePath\nfileGetPath =\n {# call file_get_path #} . toFile >=> readUTFString\n\nfileGetURI :: FileClass file => file -> IO String\nfileGetURI =\n {# call file_get_uri #} . toFile >=> readUTFString\n\nfileGetParseName :: FileClass file => file -> IO String\nfileGetParseName =\n {# call file_get_parse_name #} . toFile >=> readUTFString\n\nfileGetParent :: FileClass file => file -> IO (Maybe File)\nfileGetParent =\n {# call file_get_parent #} . toFile >=> maybePeek takeGObject\n\nfileGetChild :: FileClass file => file -> String -> IO (Maybe File)\nfileGetChild file name =\n withUTFString name $ {# call file_get_child #} (toFile file) >=> maybePeek takeGObject\n\nfileGetChildForDisplayName :: FileClass file => file -> String -> IO File\nfileGetChildForDisplayName file displayName =\n withUTFString displayName $ \\cDisplayName ->\n propagateGError ({# call file_get_child_for_display_name #} (toFile file) cDisplayName) >>=\n takeGObject\n\nfileHasPrefix :: (FileClass file1, FileClass file2) => file1 -> file2 -> IO Bool\nfileHasPrefix file1 file2 =\n liftM toBool $ {# call file_has_prefix #} (toFile file1) (toFile file2)\n\nfileGetRelativePath :: (FileClass file1, FileClass file2) => file1 -> file2 -> IO FilePath\nfileGetRelativePath file1 file2 =\n {# call file_get_relative_path #} (toFile file1) (toFile file2) >>= readUTFString\n\nfileResolveRelativePath :: FileClass file => file -> FilePath -> IO (Maybe File)\nfileResolveRelativePath file relativePath =\n withUTFString relativePath $ \\cRelativePath ->\n {# call file_resolve_relative_path #} (toFile file) cRelativePath >>=\n maybePeek takeGObject\n\nfileIsNative :: FileClass file => file -> IO Bool\nfileIsNative =\n liftM toBool . {# call file_is_native #} . toFile\n\nfileHasURIScheme :: FileClass file => file -> String -> IO Bool\nfileHasURIScheme file uriScheme =\n withUTFString uriScheme $ \\cURIScheme ->\n liftM toBool $ {# call file_has_uri_scheme #} (toFile file) cURIScheme\n\nfileGetURIScheme :: FileClass file => file -> IO String\nfileGetURIScheme =\n {# call file_get_uri_scheme #} . toFile >=> readUTFString\n\nfileRead :: FileClass file => file -> Maybe Cancellable -> IO FileInputStream\nfileRead file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_read cFile cCancellable) >>= takeGObject\n where _ = {# call file_read #}\n\nfileReadAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReadAsync file ioPriority mbCancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject mbCancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_read_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_read_async #}\n\nfileReadFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInputStream\nfileReadFinish file asyncResult =\n propagateGError ({# call file_read_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileAppendTo :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileAppendTo file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_append_to cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_append_to #}\n\nfileCreate :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileCreate file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_create cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_create #}\n\nfileReplace :: FileClass file\n => file\n -> Maybe String\n -> Bool\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileReplace file etag makeBackup flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_replace cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_replace #}\n\nfileAppendToAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileAppendToAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_append_to_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_append_to_async #}\n\nfileAppendToFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileAppendToFinish file asyncResult =\n propagateGError ({# call file_append_to_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileCreateAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileCreateAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_create_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_create_async #}\n\nfileCreateFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileCreateFinish file asyncResult =\n propagateGError ({# call file_create_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileReplaceAsync :: FileClass file\n => file\n -> String\n -> Bool\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReplaceAsync file etag makeBackup flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_replace_async cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_replace_async #}\n\nfileReplaceFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileReplaceFinish file asyncResult =\n propagateGError ({# call file_replace_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileQueryInfo :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryInfo file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_info cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_query_info #}\n\nfileQueryInfoAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryInfoAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_info_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_info_async #}\n\nfileQueryExists :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Bool\nfileQueryExists file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n liftM toBool $ g_file_query_exists cFile cCancellable\n where _ = {# call file_query_exists #}\n\nfileQueryFilesystemInfo :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryFilesystemInfo file attributes cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_filesystem_info cFile cAttributes cCancellable) >>=\n takeGObject\n where _ = {# call file_query_filesystem_info #}\n","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gio -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 13-Oct-2008\n--\n-- Copyright (c) 2008 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GIO, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GIO documentation,\n-- Copyright (c) 2001 Seth Nickell . The\n-- documentation is covered by the GNU Free Documentation License,\n-- version 1.2.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.GIO.File where\n\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport Data.Typeable\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.UTFString\n\nimport System.GIO.Base\n{#import System.GIO.Types#}\n\n{# context lib = \"gio\" prefix = \"g\" #}\n\n{# enum GFileQueryInfoFlags as FileQueryInfoFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileQueryInfoFlags\n\n{# enum GFileCreateFlags as FileCreateFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCreateFlags\n\n{# enum GFileCopyFlags as FileCopyFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCopyFlags\n\n{# enum GFileMonitorFlags as FileMonitorFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileMonitorFlags\n\n{# enum GFilesystemPreviewType as FilesystemPreviewType {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\ntype FileProgressCallback = {# type goffset #} -> {# type goffset #} -> IO ()\ntype FileReadMoreCallback = BS.ByteString -> IO Bool\n\nfileNewForPath :: FilePath -> IO File\nfileNewForPath path =\n withUTFString path $ {# call file_new_for_path #} >=> takeGObject\n\nfileNewForURI :: String -> IO File\nfileNewForURI uri =\n withUTFString uri $ {# call file_new_for_uri #} >=> takeGObject\n\nfileNewForCommandlineArg :: String -> IO File\nfileNewForCommandlineArg arg =\n withUTFString arg $ {# call file_new_for_commandline_arg #} >=> takeGObject\n\nfileParseName :: String -> IO File\nfileParseName parseName =\n withUTFString parseName $ {# call file_parse_name #} >=> takeGObject\n\nfileDup :: FileClass file\n => file -> IO file\nfileDup =\n {# call file_dup #} . toFile >=> takeGObject . castPtr\n\nfileEqual :: (FileClass file1, FileClass file2)\n => file1 -> file2 -> IO Bool\nfileEqual file1 file2 =\n liftM toBool $ {# call file_equal #} (toFile file1) (toFile file2)\n\nfileGetBasename :: FileClass file => file -> IO String\nfileGetBasename =\n {# call file_get_basename #} . toFile >=> readUTFString\n\nfileGetPath :: FileClass file => file -> IO FilePath\nfileGetPath =\n {# call file_get_path #} . toFile >=> readUTFString\n\nfileGetURI :: FileClass file => file -> IO String\nfileGetURI =\n {# call file_get_uri #} . toFile >=> readUTFString\n\nfileGetParseName :: FileClass file => file -> IO String\nfileGetParseName =\n {# call file_get_parse_name #} . toFile >=> readUTFString\n\nfileGetParent :: FileClass file => file -> IO (Maybe File)\nfileGetParent =\n {# call file_get_parent #} . toFile >=> maybePeek takeGObject\n\nfileGetChild :: FileClass file => file -> String -> IO (Maybe File)\nfileGetChild file name =\n withUTFString name $ {# call file_get_child #} (toFile file) >=> maybePeek takeGObject\n\nfileGetChildForDisplayName :: FileClass file => file -> String -> IO File\nfileGetChildForDisplayName file displayName =\n withUTFString displayName $ \\cDisplayName ->\n propagateGError ({# call file_get_child_for_display_name #} (toFile file) cDisplayName) >>=\n takeGObject\n\nfileHasPrefix :: (FileClass file1, FileClass file2) => file1 -> file2 -> IO Bool\nfileHasPrefix file1 file2 =\n liftM toBool $ {# call file_has_prefix #} (toFile file1) (toFile file2)\n\nfileGetRelativePath :: (FileClass file1, FileClass file2) => file1 -> file2 -> IO FilePath\nfileGetRelativePath file1 file2 =\n {# call file_get_relative_path #} (toFile file1) (toFile file2) >>= readUTFString\n\nfileResolveRelativePath :: FileClass file => file -> FilePath -> IO (Maybe File)\nfileResolveRelativePath file relativePath =\n withUTFString relativePath $ \\cRelativePath ->\n {# call file_resolve_relative_path #} (toFile file) cRelativePath >>=\n maybePeek takeGObject\n\nfileIsNative :: FileClass file => file -> IO Bool\nfileIsNative =\n liftM toBool . {# call file_is_native #} . toFile\n\nfileHasURIScheme :: FileClass file => file -> String -> IO Bool\nfileHasURIScheme file uriScheme =\n withUTFString uriScheme $ \\cURIScheme ->\n liftM toBool $ {# call file_has_uri_scheme #} (toFile file) cURIScheme\n\nfileGetURIScheme :: FileClass file => file -> IO String\nfileGetURIScheme =\n {# call file_get_uri_scheme #} . toFile >=> readUTFString\n\nfileRead :: FileClass file => file -> Maybe Cancellable -> IO FileInputStream\nfileRead file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_read cFile cCancellable) >>= takeGObject\n where _ = {# call file_read #}\n\nfileReadAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReadAsync file ioPriority mbCancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject mbCancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_read_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_read_async #}\n\nfileReadFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInputStream\nfileReadFinish file asyncResult =\n propagateGError ({# call file_read_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileAppendTo :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileAppendTo file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_append_to cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_append_to #}\n\nfileCreate :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileCreate file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_create cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_create #}\n\nfileReplace :: FileClass file\n => file\n -> Maybe String\n -> Bool\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileReplace file etag makeBackup flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_replace cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_replace #}\n\nfileAppendToAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileAppendToAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_append_to_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_append_to_async #}\n\nfileAppendToFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileAppendToFinish file asyncResult =\n propagateGError ({# call file_append_to_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileCreateAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileCreateAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_create_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_create_async #}\n\nfileCreateFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileCreateFinish file asyncResult =\n propagateGError ({# call file_create_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileReplaceAsync :: FileClass file\n => file\n -> String\n -> Bool\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReplaceAsync file etag makeBackup flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_replace_async cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_replace_async #}\n\nfileReplaceFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileReplaceFinish file asyncResult =\n propagateGError ({# call file_replace_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileQueryInfo :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryInfo file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_info cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_query_info #}\n\nfileQueryInfoAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryInfoAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_info_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_info_async #}\n\nfileQueryExists :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Bool\nfileQueryExists file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n liftM toBool $ g_file_query_exists cFile cCancellable\n where _ = {# call file_query_exists #}\n\nfileQueryFilesystemInfo :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryFilesystemInfo file attributes cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_filesystem_info cFile cAttributes cCancellable) >>=\n takeGObject\n where _ = {# call file_query_filesystem_info #}\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"f29538bf92dd10d0a392ad6b3ff7f4ea9bb7a383","subject":"fixed import","message":"fixed import\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/OGRFeature.chs","new_file":"src\/GDAL\/Internal\/OGRFeature.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGRFeature (\n OGRFeature (..)\n , OGRFeatureDef (..)\n , OGRField (..)\n , OGRTimeZone (..)\n , Fid (..)\n , FieldType (..)\n , Field (..)\n , Feature (..)\n , FeatureH (..)\n , FieldDefnH (..)\n , FeatureDefnH (..)\n , Justification (..)\n\n , FeatureDef (..)\n , GeomFieldDef (..)\n , FieldDef (..)\n , fieldTypedAs\n , (.:)\n , (.=)\n , aGeom\n , aNullableGeom\n , theGeom\n , theNullableGeom\n , feature\n\n\n , featureToHandle\n , featureFromHandle\n , getFid\n\n , withFieldDefnH\n , fieldDefFromHandle\n , featureDefFromHandle\n , fieldDefsFromFeatureDefnH\n , geomFieldDefsFromFeatureDefnH\n#if SUPPORTS_MULTI_GEOM_FIELDS\n , GeomFieldDefnH (..)\n , withGeomFieldDefnH\n#endif\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\" #}\n\nimport Control.Applicative ((<$>), (<*>), pure)\nimport Control.Monad (liftM, liftM2, (>=>), (<=<), when, void)\nimport Control.Monad.Catch (bracket)\n\nimport Data.ByteString (ByteString)\nimport Data.ByteString.Char8 (packCStringLen)\nimport Data.ByteString.Unsafe (unsafeUseAsCStringLen)\nimport qualified Data.HashMap.Strict as HM\nimport Data.Int (Int32, Int64)\nimport Data.Monoid (mempty, (<>))\nimport Data.Proxy (Proxy(Proxy))\n\nimport Data.Text (Text)\nimport Data.Time.LocalTime (\n LocalTime(..)\n , TimeOfDay(..)\n , TimeZone(..)\n , minutesToTimeZone\n , utc\n )\nimport Data.Time ()\nimport Data.Time.Calendar (Day, fromGregorian, toGregorian)\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport qualified Data.Vector as V\n\nimport Foreign.C.Types (\n CInt(..)\n , CDouble(..)\n , CChar(..)\n , CUChar(..)\n , CLong(..)\n )\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (copyBytes, toBool)\nimport Foreign.Ptr (Ptr, castPtr, nullPtr)\nimport Foreign.Storable (Storable, sizeOf, peek, peekElemOff)\n#if GDAL_VERSION_MAJOR >= 2\nimport Foreign.C.Types (CLLong(..))\nimport Foreign.Marshal.Utils (fromBool)\n#endif\n\n\nimport GDAL.Internal.Util (\n toEnumC\n , fromEnumC\n , peekEncodedCString\n , useAsEncodedCString\n )\n{#import GDAL.Internal.OSR #}\n{#import GDAL.Internal.CPLError #}\n{#import GDAL.Internal.OGRGeometry #}\n{#import GDAL.Internal.OGRError #}\n\n#include \"gdal.h\"\n#include \"ogr_core.h\"\n#include \"ogr_api.h\"\n#include \"cpl_string.h\"\n\nnewtype Fid = Fid { unFid :: Int64 }\n deriving (Eq, Show, Num)\n\nclass OGRField a where\n fieldDef :: Proxy a -> FieldDef\n toField :: a -> Field\n fromField :: Field -> Either Text a\n\n(.:) :: OGRField a => Feature -> Text -> Either Text a\nfeat .: name =\n maybe (Left (\"fromFeature: field '\"<>name<>\"' not present\"))\n fromField\n (HM.lookup name (fFields feat))\n\n(.=) :: OGRField a => Text -> a -> (Text, Field)\nname .= value = (name, toField value)\n\nclass OGRFeature a where\n toFeature :: a -> Feature\n fromFeature :: Feature -> Either Text a\n\ntheGeom :: Feature -> Either Text Geometry\ntheGeom = maybe (Left \"Feature has no geometry\") Right . fGeom\n\ntheNullableGeom :: Feature -> Either Text (Maybe Geometry)\ntheNullableGeom = Right . fGeom\n\naGeom :: Feature -> Text -> Either Text Geometry\nfeat `aGeom` name =\n maybe (Left (\"fromFeature: geometry field '\"<>name<>\"' not present\"))\n (maybe (Left (\"fromFeature: geometry '\"<>name<>\"' is NULL\")) Right)\n (HM.lookup name (fGeoms feat))\n\naNullableGeom :: Feature -> Text -> Either Text (Maybe Geometry)\nfeat `aNullableGeom` name =\n maybe (Left (\"fromFeature: geometry field '\"<>name<>\"' not present\"))\n Right\n (HM.lookup name (fGeoms feat))\n\nclass OGRFeature a => OGRFeatureDef a where\n featureDef :: Proxy a -> FeatureDef\n\nfieldTypedAs :: forall a. OGRField a => Text -> a -> (Text, FieldDef)\nname `fieldTypedAs` _ = (name, fieldDef (Proxy :: Proxy a))\n\n{#enum FieldType {} omit (OFTMaxType) deriving (Eq,Show,Read,Bounded) #}\n\n{#enum Justification {}\n omit (JustifyUndefined)\n with prefix = \"OJ\"\n add prefix = \"Justify\"\n deriving (Eq,Show,Read,Bounded) #}\n\ndata Field\n = OGRInteger !Int32\n | OGRIntegerList !(St.Vector Int32)\n#if SUPPORTS_64_BIT_INT_FIELDS\n | OGRInteger64 !Int64\n | OGRInteger64List !(St.Vector Int64)\n#endif\n | OGRReal !Double\n | OGRRealList !(St.Vector Double)\n | OGRString !Text\n | OGRStringList !(V.Vector Text)\n | OGRBinary !ByteString\n | OGRDateTime !LocalTime !OGRTimeZone\n | OGRDate !Day\n | OGRTime !TimeOfDay\n | OGRNullField\n deriving (Show, Eq)\n\ndata OGRTimeZone\n = UnknownTimeZone\n | LocalTimeZone\n | KnownTimeZone !TimeZone\n deriving (Eq, Show)\n\ndata FieldDef\n = FieldDef {\n fldType :: !FieldType\n , fldWidth :: !(Maybe Int)\n , fldPrec :: !(Maybe Int)\n , fldJust :: !(Maybe Justification)\n , fldNullable :: !Bool\n } deriving (Show, Eq)\n\ndata GeomFieldDef\n = GeomFieldDef {\n gfdType :: !GeometryType\n , gfdSrs :: !(Maybe SpatialReference)\n , gfdNullable :: !Bool\n } deriving (Show, Eq)\n\ntype Map a = HM.HashMap Text a\n\ndata Feature\n = Feature {\n fFields :: !(Map Field)\n , fGeom :: !(Maybe Geometry)\n , fGeoms :: !(Map (Maybe Geometry))\n } deriving (Show, Eq)\n\nfeature :: Geometry -> [(Text,Field)] -> Feature\nfeature g fs =\n Feature { fFields = HM.fromList fs\n , fGeom = Just g\n , fGeoms = mempty\n }\n\ninstance OGRFeature Feature where\n toFeature = id\n fromFeature = Right\n\ndata FeatureDef\n = FeatureDef {\n fdName :: !Text\n , fdFields :: !FieldDefs\n , fdGeom :: !GeomFieldDef\n , fdGeoms :: !GeomFieldDefs\n } deriving (Show, Eq)\n\ntype FieldDefs = V.Vector (Text, FieldDef)\ntype GeomFieldDefs = V.Vector (Text, GeomFieldDef)\n\n\n{#pointer FeatureH newtype#}\n{#pointer FieldDefnH newtype#}\n{#pointer FeatureDefnH newtype#}\n\nderiving instance Eq FeatureH\n\nnullFeatureH :: FeatureH\nnullFeatureH = FeatureH nullPtr\n\n\nwithFieldDefnH :: Text -> FieldDef -> (FieldDefnH -> IO a) -> IO a\nwithFieldDefnH fldName FieldDef{..} f =\n useAsEncodedCString fldName $ \\pName ->\n bracket ({#call unsafe OGR_Fld_Create as ^#} pName (fromEnumC fldType))\n ({#call unsafe OGR_Fld_Destroy as ^#}) (\\p -> populate p >> f p)\n where\n populate h = do\n case fldWidth of\n Just w -> {#call unsafe OGR_Fld_SetWidth as ^#} h (fromIntegral w)\n Nothing -> return ()\n case fldPrec of\n Just p -> {#call unsafe OGR_Fld_SetPrecision as ^#} h (fromIntegral p)\n Nothing -> return ()\n case fldJust of\n Just j -> {#call unsafe OGR_Fld_SetJustify as ^#} h (fromEnumC j)\n Nothing -> return ()\n#if SUPPORTS_NULLABLE_FIELD_DEFS\n {#call unsafe OGR_Fld_SetNullable as ^#} h (fromBool fldNullable)\n#endif\n\nfieldDefFromHandle :: FieldDefnH -> IO FieldDef\nfieldDefFromHandle p =\n FieldDef\n <$> liftM toEnumC ({#call unsafe OGR_Fld_GetType as ^#} p)\n <*> liftM iToMaybe ({#call unsafe OGR_Fld_GetWidth as ^#} p)\n <*> liftM iToMaybe ({#call unsafe OGR_Fld_GetPrecision as ^#} p)\n <*> liftM jToMaybe ({#call unsafe OGR_Fld_GetJustify as ^#} p)\n#if SUPPORTS_NULLABLE_FIELD_DEFS\n <*> liftM toBool ({#call unsafe OGR_Fld_IsNullable as ^#} p)\n#else\n <*> pure True\n#endif\n where\n iToMaybe = (\\v -> if v==0 then Nothing else Just (fromIntegral v))\n jToMaybe = (\\j -> if j==0 then Nothing else Just (toEnumC j))\n\nfeatureDefFromHandle :: GeomFieldDef -> FeatureDefnH -> IO FeatureDef\nfeatureDefFromHandle gfd p = do\n#if SUPPORTS_MULTI_GEOM_FIELDS\n gfields <- geomFieldDefsFromFeatureDefnH p\n let (gfd', gfields')\n -- should not happen but just in case\n | V.null gfields = (gfd, gfields)\n -- ignore layer definition since it doesn't carry correct nullability\n -- info\n | otherwise = (snd (V.unsafeHead gfields), V.unsafeTail gfields)\n#else\n let (gfd', gfields') = (gfd, mempty)\n#endif\n FeatureDef\n <$> ({#call unsafe OGR_FD_GetName as ^#} p >>= peekEncodedCString)\n <*> fieldDefsFromFeatureDefnH p\n <*> pure gfd'\n <*> pure gfields'\n\nfieldDefsFromFeatureDefnH :: FeatureDefnH -> IO (V.Vector (Text, FieldDef))\nfieldDefsFromFeatureDefnH p = do\n nFields <- {#call unsafe OGR_FD_GetFieldCount as ^#} p\n V.generateM (fromIntegral nFields) $ \\i -> do\n fDef <- {#call unsafe OGR_FD_GetFieldDefn as ^#} p (fromIntegral i)\n liftM2 (,) (getFieldName fDef) (fieldDefFromHandle fDef)\n\n\ngeomFieldDefsFromFeatureDefnH\n :: FeatureDefnH -> IO (V.Vector (Text, GeomFieldDef))\n\n#if SUPPORTS_MULTI_GEOM_FIELDS\n\n{#pointer GeomFieldDefnH newtype#}\n\ngeomFieldDefsFromFeatureDefnH p = do\n nFields <- {#call unsafe OGR_FD_GetGeomFieldCount as ^#} p\n V.generateM (fromIntegral nFields) $\n gFldDef <=< ({#call unsafe OGR_FD_GetGeomFieldDefn as ^#} p . fromIntegral)\n where\n gFldDef g = do\n name <- {#call unsafe OGR_GFld_GetNameRef as ^#} g >>= peekEncodedCString\n gDef <- GeomFieldDef\n <$> liftM toEnumC ({#call unsafe OGR_GFld_GetType as ^#} g)\n <*> ({#call unsafe OGR_GFld_GetSpatialRef as ^#} g >>=\n maybeNewSpatialRefBorrowedHandle)\n#if SUPPORTS_NULLABLE_FIELD_DEFS\n <*> liftM toBool ({#call unsafe OGR_GFld_IsNullable as ^#} g)\n#else\n <*> pure True\n#endif\n return (name, gDef)\n\nwithGeomFieldDefnH :: Text -> GeomFieldDef -> (GeomFieldDefnH -> IO a) -> IO a\nwithGeomFieldDefnH gfdName GeomFieldDef{..} f =\n useAsEncodedCString gfdName $ \\pName ->\n bracket ({#call unsafe OGR_GFld_Create as ^#} pName (fromEnumC gfdType))\n ({#call unsafe OGR_GFld_Destroy as ^#}) (\\p -> populate p >> f p)\n where\n populate p = do\n withMaybeSpatialReference gfdSrs $\n {#call unsafe OGR_GFld_SetSpatialRef as ^#} p\n#if SUPPORTS_NULLABLE_FIELD_DEFS\n {#call unsafe OGR_GFld_SetNullable as ^#} p (fromBool gfdNullable)\n#endif\n\n#else\ngeomFieldDefsFromFeatureDefnH = const (return mempty)\n#endif -- SUPPORTS_MULTI_GEOM_FIELDS\n\nnullFID :: Fid\nnullFID = Fid ({#const OGRNullFID#})\n\nfeatureToHandle\n :: OGRFeature f\n => FeatureDefnH -> Maybe Fid -> f -> (FeatureH -> IO a) -> IO a\nfeatureToHandle fdH fId ft act =\n bracket ({#call unsafe OGR_F_Create as ^#} fdH)\n ({#call unsafe OGR_F_Destroy as ^#}) $ \\pF -> do\n case fId of\n Just (Fid fid) ->\n void $ {#call unsafe OGR_F_SetFID as ^#} pF (fromIntegral fid)\n Nothing -> return ()\n fieldDefs <- fieldDefsFromFeatureDefnH fdH\n flip imapM_ fieldDefs $ \\ix (name, _) -> do\n case HM.lookup name fFields of\n Just f -> setField f ix pF\n Nothing -> return ()\n case fGeom of\n Just g -> void $ withGeometry g ({#call unsafe OGR_F_SetGeometry as ^#} pF)\n Nothing -> return ()\n when (not (HM.null fGeoms)) $ do\n#if SUPPORTS_MULTI_GEOM_FIELDS\n geomFieldDefs <- geomFieldDefsFromFeatureDefnH fdH\n flip imapM_ (V.tail geomFieldDefs) $ \\ix (name, _) -> do\n case join (HM.lookup name fGeoms) of\n Just g ->\n void $ withGeometry g ({#call unsafe OGR_F_SetGeomField as ^#} pF (ix+1))\n Nothing ->\n return ()\n#else\n throwBindingException MultipleGeomFieldsNotSupported\n#endif\n act pF\n where Feature {..} = toFeature ft\n\nimapM :: (Monad m, Num a) => (a -> b -> m c) -> V.Vector b -> m (V.Vector c)\nimapM f v = V.mapM (uncurry f) (V.zip (V.enumFromN 0 (V.length v)) v)\n\nimapM_ :: (Monad m, Num a) => (a -> b -> m ()) -> V.Vector b -> m ()\nimapM_ f v = V.mapM_ (uncurry f) (V.zip (V.enumFromN 0 (V.length v)) v)\n\ngetFid :: FeatureH -> IO (Maybe Fid)\ngetFid pF = do\n mFid <- liftM fromIntegral ({#call unsafe OGR_F_GetFID as ^#} pF)\n return (if mFid == nullFID then Nothing else Just mFid)\n\nfeatureFromHandle\n :: OGRFeature a\n => FeatureDef -> IO FeatureH -> IO (Maybe (Maybe Fid, a))\nfeatureFromHandle FeatureDef{..} act =\n bracket act {#call unsafe OGR_F_Destroy as ^#} $ \\pF -> do\n if (pF == nullFeatureH)\n then return Nothing\n else do\n fid <- getFid pF\n fields <- flip imapM fdFields $ \\i (fldName, fd) -> do\n isSet <- liftM toBool ({#call unsafe OGR_F_IsFieldSet as ^#} pF i)\n if isSet\n then getField (fldType fd) i pF >>=\n maybe (throwBindingException (FieldParseError fldName))\n (\\f -> return (fldName, f))\n else return (fldName, OGRNullField)\n geomRef <- {#call unsafe OGR_F_StealGeometry as ^#} pF\n geom <- if geomRef \/= nullPtr\n then liftM Just (newGeometryHandle geomRef)\n else return Nothing\n#if SUPPORTS_MULTI_GEOM_FIELDS\n geoms <- flip imapM fdGeoms $ \\ix (gfdName, _) -> do\n pG <- {#call unsafe OGR_F_GetGeomFieldRef as ^#} pF (ix + 1)\n g <- if pG \/= nullPtr\n then liftM Just (cloneGeometry pG)\n else return Nothing\n return (gfdName, g)\n#else\n let geoms = mempty\n#endif\n either (throwBindingException . FromFeatureError)\n (\\f -> return (Just (fid,f)))\n (fromFeature Feature {\n fFields = HM.fromList (V.toList fields)\n , fGeom = geom\n , fGeoms = HM.fromList (V.toList geoms)\n })\n\n\n-- ############################################################################\n-- setField\n-- ############################################################################\n\nsetField :: Field -> CInt -> FeatureH -> IO ()\n\nsetField (OGRInteger v) ix f =\n {#call unsafe OGR_F_SetFieldInteger as ^#} f (fromIntegral ix) (fromIntegral v)\n\nsetField (OGRIntegerList v) ix f =\n St.unsafeWith v $\n {#call unsafe OGR_F_SetFieldIntegerList as ^#} f (fromIntegral ix)\n (fromIntegral (St.length v)) . castPtr\n\n#if SUPPORTS_64_BIT_INT_FIELDS\nsetField (OGRInteger64 v) ix f =\n {#call unsafe OGR_F_SetFieldInteger64 as ^#} f (fromIntegral ix) (fromIntegral v)\n\nsetField (OGRInteger64List v) ix f =\n St.unsafeWith v $\n {#call unsafe OGR_F_SetFieldInteger64List as ^#} f (fromIntegral ix)\n (fromIntegral (St.length v)) . castPtr\n#endif\n\nsetField (OGRReal v) ix f =\n {#call unsafe OGR_F_SetFieldDouble as ^#} f (fromIntegral ix) (realToFrac v)\n\nsetField (OGRRealList v) ix f =\n St.unsafeWith v $\n {#call unsafe OGR_F_SetFieldDoubleList as ^#} f (fromIntegral ix)\n (fromIntegral (St.length v)) . castPtr\n\nsetField (OGRString v) ix f = useAsEncodedCString v $\n {#call unsafe OGR_F_SetFieldString as ^#} f (fromIntegral ix)\n\nsetField (OGRStringList v) ix f =\n bracket createList {#call unsafe CSLDestroy as ^#} $\n {#call unsafe OGR_F_SetFieldStringList as ^#} f (fromIntegral ix)\n where\n createList = V.foldM' folder nullPtr v\n folder acc k =\n useAsEncodedCString k $ {#call unsafe CSLAddString as ^#} acc\n\nsetField (OGRBinary v) ix f = unsafeUseAsCStringLen v $ \\(p,l) ->\n {#call unsafe OGR_F_SetFieldBinary as ^#}\n f (fromIntegral ix) (fromIntegral l) (castPtr p)\n\nsetField (OGRDateTime (LocalTime day (TimeOfDay h mn s)) tz) ix f =\n {#call unsafe OGR_F_SetFieldDateTime as ^#} f (fromIntegral ix)\n (fromIntegral y) (fromIntegral m) (fromIntegral d)\n (fromIntegral h) (fromIntegral mn) (truncate s) (fromOGRTimeZone tz)\n where (y, m, d) = toGregorian day\n\nsetField (OGRDate day) ix f =\n {#call unsafe OGR_F_SetFieldDateTime as ^#} f (fromIntegral ix)\n (fromIntegral y) (fromIntegral m) (fromIntegral d) 0 0 0 (fromOGRTimeZone tz)\n where (y, m, d) = toGregorian day\n tz = UnknownTimeZone\n\nsetField (OGRTime (TimeOfDay h mn s)) ix f =\n {#call unsafe OGR_F_SetFieldDateTime as ^#} f (fromIntegral ix) 0 0 0\n (fromIntegral h) (fromIntegral mn) (truncate s) (fromOGRTimeZone tz)\n where tz = UnknownTimeZone\n\nsetField OGRNullField ix f = {#call unsafe OGR_F_UnsetField as ^#} f ix\n\n-- ############################################################################\n-- getField\n-- ############################################################################\n\ngetField :: FieldType -> CInt -> FeatureH -> IO (Maybe Field)\n\ngetField OFTInteger ix f =\n liftM (Just . OGRInteger . fromIntegral)\n ({#call unsafe OGR_F_GetFieldAsInteger as ^#} f ix)\n\ngetField OFTIntegerList ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsIntegerList as ^#} f ix lenP\n nElems <- peekIntegral lenP\n if nElems == 0\n then return (Just (OGRIntegerList mempty))\n else do\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CInt) (nElems * sizeOf (undefined :: CInt))\n liftM (Just . OGRIntegerList) (St.unsafeFreeze (Stm.unsafeCast vec))\n\n#if SUPPORTS_64_BIT_INT_FIELDS\ngetField OFTInteger64 ix f\n = liftM (Just . OGRInteger64 . fromIntegral)\n ({#call unsafe OGR_F_GetFieldAsInteger64 as ^#} f ix)\n\ngetField OFTInteger64List ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsInteger64List as ^#} f ix lenP\n nElems <- peekIntegral lenP\n if nElems == 0\n then return (Just (OGRInteger64List mempty))\n else do\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CLLong) (nElems * sizeOf (undefined :: CLLong))\n liftM (Just . OGRInteger64List) (St.unsafeFreeze (Stm.unsafeCast vec))\n#endif\n\ngetField OFTReal ix f\n = liftM (Just . OGRReal . realToFrac)\n ({#call unsafe OGR_F_GetFieldAsDouble as ^#} f ix)\n\ngetField OFTRealList ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsDoubleList as ^#} f ix lenP\n nElems <- peekIntegral lenP\n if nElems == 0\n then return (Just (OGRRealList mempty))\n else do\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CDouble) (nElems * sizeOf (undefined :: CDouble))\n liftM (Just . OGRRealList) (St.unsafeFreeze (Stm.unsafeCast vec))\n\ngetField OFTString ix f = liftM (Just . OGRString)\n (({#call unsafe OGR_F_GetFieldAsString as ^#} f ix) >>= peekEncodedCString)\n\ngetField OFTWideString ix f = getField OFTString ix f\n\ngetField OFTStringList ix f = liftM (Just . OGRStringList) $ do\n ptr <- {#call unsafe OGR_F_GetFieldAsStringList as ^#} f ix\n nElems <- liftM fromIntegral ({#call unsafe CSLCount as ^#} ptr)\n V.generateM nElems (peekElemOff ptr >=> peekEncodedCString)\n\ngetField OFTWideStringList ix f = getField OFTStringList ix f\n\ngetField OFTBinary ix f = alloca $ \\lenP -> do\n buf <- liftM castPtr ({#call unsafe OGR_F_GetFieldAsBinary as ^#} f ix lenP)\n nElems <- peekIntegral lenP\n liftM (Just . OGRBinary) (packCStringLen (buf, nElems))\n\ngetField OFTDateTime ix f =\n liftM (fmap (uncurry OGRDateTime)) (getDateTime ix f)\n\ngetField OFTDate ix f =\n liftM (fmap (\\(LocalTime d _,_) -> OGRDate d)) (getDateTime ix f)\n\ngetField OFTTime ix f =\n liftM (fmap (\\(LocalTime _ t,_) -> OGRTime t)) (getDateTime ix f)\n\n\ngetDateTime :: CInt -> FeatureH -> IO (Maybe (LocalTime, OGRTimeZone))\ngetDateTime ix f\n = alloca $ \\y -> alloca $ \\m -> alloca $ \\d ->\n alloca $ \\h -> alloca $ \\mn -> alloca $ \\s -> alloca $ \\pTz -> do\n ret <- {#call unsafe OGR_F_GetFieldAsDateTime as ^#} f ix y m d h mn s pTz\n if ret == 0\n then return Nothing\n else do\n day <- fromGregorian <$> peekIntegral y\n <*> peekIntegral m\n <*> peekIntegral d\n tod <- TimeOfDay <$> peekIntegral h\n <*> peekIntegral mn\n <*> peekIntegral s\n iTz <- peekIntegral pTz\n return (Just (LocalTime day tod, toOGRTimezone iTz))\n\ntoOGRTimezone :: CInt -> OGRTimeZone\ntoOGRTimezone tz =\n case tz of\n 0 -> UnknownTimeZone\n 1 -> LocalTimeZone\n 100 -> KnownTimeZone utc\n n -> KnownTimeZone (minutesToTimeZone ((fromIntegral n - 100) * 15))\n\nfromOGRTimeZone :: OGRTimeZone -> CInt\nfromOGRTimeZone UnknownTimeZone = 0\nfromOGRTimeZone LocalTimeZone = 1\nfromOGRTimeZone (KnownTimeZone tz) = truncate ((mins \/ 15) + 100)\n where mins = fromIntegral (timeZoneMinutes tz) :: Double\n\npeekIntegral :: (Storable a, Integral a, Num b) => Ptr a -> IO b\npeekIntegral = liftM fromIntegral . peek\n\ngetFieldName :: FieldDefnH -> IO Text\ngetFieldName =\n {#call unsafe OGR_Fld_GetNameRef as ^#} >=> peekEncodedCString\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGRFeature (\n OGRFeature (..)\n , OGRFeatureDef (..)\n , OGRField (..)\n , OGRTimeZone (..)\n , Fid (..)\n , FieldType (..)\n , Field (..)\n , Feature (..)\n , FeatureH (..)\n , FieldDefnH (..)\n , FeatureDefnH (..)\n , Justification (..)\n\n , FeatureDef (..)\n , GeomFieldDef (..)\n , FieldDef (..)\n , fieldTypedAs\n , (.:)\n , (.=)\n , aGeom\n , aNullableGeom\n , theGeom\n , theNullableGeom\n , feature\n\n\n , featureToHandle\n , featureFromHandle\n , getFid\n\n , withFieldDefnH\n , fieldDefFromHandle\n , featureDefFromHandle\n , fieldDefsFromFeatureDefnH\n , geomFieldDefsFromFeatureDefnH\n#if SUPPORTS_MULTI_GEOM_FIELDS\n , GeomFieldDefnH (..)\n , withGeomFieldDefnH\n#endif\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\" #}\n\nimport Control.Applicative ((<$>), (<*>), pure)\nimport Control.Monad (liftM, liftM2, (>=>), when, void)\nimport Control.Monad.Catch (bracket)\n\nimport Data.ByteString (ByteString)\nimport Data.ByteString.Char8 (packCStringLen)\nimport Data.ByteString.Unsafe (unsafeUseAsCStringLen)\nimport qualified Data.HashMap.Strict as HM\nimport Data.Int (Int32, Int64)\nimport Data.Monoid (mempty, (<>))\nimport Data.Proxy (Proxy(Proxy))\n\nimport Data.Text (Text)\nimport Data.Time.LocalTime (\n LocalTime(..)\n , TimeOfDay(..)\n , TimeZone(..)\n , minutesToTimeZone\n , utc\n )\nimport Data.Time ()\nimport Data.Time.Calendar (Day, fromGregorian, toGregorian)\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport qualified Data.Vector as V\n\nimport Foreign.C.Types (\n CInt(..)\n , CDouble(..)\n , CChar(..)\n , CUChar(..)\n , CLong(..)\n )\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (copyBytes, toBool)\nimport Foreign.Ptr (Ptr, castPtr, nullPtr)\nimport Foreign.Storable (Storable, sizeOf, peek, peekElemOff)\n#if GDAL_VERSION_MAJOR >= 2\nimport Foreign.C.Types (CLLong(..))\nimport Foreign.Marshal.Utils (fromBool)\n#endif\n\n\nimport GDAL.Internal.Util (\n toEnumC\n , fromEnumC\n , peekEncodedCString\n , useAsEncodedCString\n )\n{#import GDAL.Internal.OSR #}\n{#import GDAL.Internal.CPLError #}\n{#import GDAL.Internal.OGRGeometry #}\n{#import GDAL.Internal.OGRError #}\n\n#include \"gdal.h\"\n#include \"ogr_core.h\"\n#include \"ogr_api.h\"\n#include \"cpl_string.h\"\n\nnewtype Fid = Fid { unFid :: Int64 }\n deriving (Eq, Show, Num)\n\nclass OGRField a where\n fieldDef :: Proxy a -> FieldDef\n toField :: a -> Field\n fromField :: Field -> Either Text a\n\n(.:) :: OGRField a => Feature -> Text -> Either Text a\nfeat .: name =\n maybe (Left (\"fromFeature: field '\"<>name<>\"' not present\"))\n fromField\n (HM.lookup name (fFields feat))\n\n(.=) :: OGRField a => Text -> a -> (Text, Field)\nname .= value = (name, toField value)\n\nclass OGRFeature a where\n toFeature :: a -> Feature\n fromFeature :: Feature -> Either Text a\n\ntheGeom :: Feature -> Either Text Geometry\ntheGeom = maybe (Left \"Feature has no geometry\") Right . fGeom\n\ntheNullableGeom :: Feature -> Either Text (Maybe Geometry)\ntheNullableGeom = Right . fGeom\n\naGeom :: Feature -> Text -> Either Text Geometry\nfeat `aGeom` name =\n maybe (Left (\"fromFeature: geometry field '\"<>name<>\"' not present\"))\n (maybe (Left (\"fromFeature: geometry '\"<>name<>\"' is NULL\")) Right)\n (HM.lookup name (fGeoms feat))\n\naNullableGeom :: Feature -> Text -> Either Text (Maybe Geometry)\nfeat `aNullableGeom` name =\n maybe (Left (\"fromFeature: geometry field '\"<>name<>\"' not present\"))\n Right\n (HM.lookup name (fGeoms feat))\n\nclass OGRFeature a => OGRFeatureDef a where\n featureDef :: Proxy a -> FeatureDef\n\nfieldTypedAs :: forall a. OGRField a => Text -> a -> (Text, FieldDef)\nname `fieldTypedAs` _ = (name, fieldDef (Proxy :: Proxy a))\n\n{#enum FieldType {} omit (OFTMaxType) deriving (Eq,Show,Read,Bounded) #}\n\n{#enum Justification {}\n omit (JustifyUndefined)\n with prefix = \"OJ\"\n add prefix = \"Justify\"\n deriving (Eq,Show,Read,Bounded) #}\n\ndata Field\n = OGRInteger !Int32\n | OGRIntegerList !(St.Vector Int32)\n#if SUPPORTS_64_BIT_INT_FIELDS\n | OGRInteger64 !Int64\n | OGRInteger64List !(St.Vector Int64)\n#endif\n | OGRReal !Double\n | OGRRealList !(St.Vector Double)\n | OGRString !Text\n | OGRStringList !(V.Vector Text)\n | OGRBinary !ByteString\n | OGRDateTime !LocalTime !OGRTimeZone\n | OGRDate !Day\n | OGRTime !TimeOfDay\n | OGRNullField\n deriving (Show, Eq)\n\ndata OGRTimeZone\n = UnknownTimeZone\n | LocalTimeZone\n | KnownTimeZone !TimeZone\n deriving (Eq, Show)\n\ndata FieldDef\n = FieldDef {\n fldType :: !FieldType\n , fldWidth :: !(Maybe Int)\n , fldPrec :: !(Maybe Int)\n , fldJust :: !(Maybe Justification)\n , fldNullable :: !Bool\n } deriving (Show, Eq)\n\ndata GeomFieldDef\n = GeomFieldDef {\n gfdType :: !GeometryType\n , gfdSrs :: !(Maybe SpatialReference)\n , gfdNullable :: !Bool\n } deriving (Show, Eq)\n\ntype Map a = HM.HashMap Text a\n\ndata Feature\n = Feature {\n fFields :: !(Map Field)\n , fGeom :: !(Maybe Geometry)\n , fGeoms :: !(Map (Maybe Geometry))\n } deriving (Show, Eq)\n\nfeature :: Geometry -> [(Text,Field)] -> Feature\nfeature g fs =\n Feature { fFields = HM.fromList fs\n , fGeom = Just g\n , fGeoms = mempty\n }\n\ninstance OGRFeature Feature where\n toFeature = id\n fromFeature = Right\n\ndata FeatureDef\n = FeatureDef {\n fdName :: !Text\n , fdFields :: !FieldDefs\n , fdGeom :: !GeomFieldDef\n , fdGeoms :: !GeomFieldDefs\n } deriving (Show, Eq)\n\ntype FieldDefs = V.Vector (Text, FieldDef)\ntype GeomFieldDefs = V.Vector (Text, GeomFieldDef)\n\n\n{#pointer FeatureH newtype#}\n{#pointer FieldDefnH newtype#}\n{#pointer FeatureDefnH newtype#}\n\nderiving instance Eq FeatureH\n\nnullFeatureH :: FeatureH\nnullFeatureH = FeatureH nullPtr\n\n\nwithFieldDefnH :: Text -> FieldDef -> (FieldDefnH -> IO a) -> IO a\nwithFieldDefnH fldName FieldDef{..} f =\n useAsEncodedCString fldName $ \\pName ->\n bracket ({#call unsafe OGR_Fld_Create as ^#} pName (fromEnumC fldType))\n ({#call unsafe OGR_Fld_Destroy as ^#}) (\\p -> populate p >> f p)\n where\n populate h = do\n case fldWidth of\n Just w -> {#call unsafe OGR_Fld_SetWidth as ^#} h (fromIntegral w)\n Nothing -> return ()\n case fldPrec of\n Just p -> {#call unsafe OGR_Fld_SetPrecision as ^#} h (fromIntegral p)\n Nothing -> return ()\n case fldJust of\n Just j -> {#call unsafe OGR_Fld_SetJustify as ^#} h (fromEnumC j)\n Nothing -> return ()\n#if SUPPORTS_NULLABLE_FIELD_DEFS\n {#call unsafe OGR_Fld_SetNullable as ^#} h (fromBool fldNullable)\n#endif\n\nfieldDefFromHandle :: FieldDefnH -> IO FieldDef\nfieldDefFromHandle p =\n FieldDef\n <$> liftM toEnumC ({#call unsafe OGR_Fld_GetType as ^#} p)\n <*> liftM iToMaybe ({#call unsafe OGR_Fld_GetWidth as ^#} p)\n <*> liftM iToMaybe ({#call unsafe OGR_Fld_GetPrecision as ^#} p)\n <*> liftM jToMaybe ({#call unsafe OGR_Fld_GetJustify as ^#} p)\n#if SUPPORTS_NULLABLE_FIELD_DEFS\n <*> liftM toBool ({#call unsafe OGR_Fld_IsNullable as ^#} p)\n#else\n <*> pure True\n#endif\n where\n iToMaybe = (\\v -> if v==0 then Nothing else Just (fromIntegral v))\n jToMaybe = (\\j -> if j==0 then Nothing else Just (toEnumC j))\n\nfeatureDefFromHandle :: GeomFieldDef -> FeatureDefnH -> IO FeatureDef\nfeatureDefFromHandle gfd p = do\n#if SUPPORTS_MULTI_GEOM_FIELDS\n gfields <- geomFieldDefsFromFeatureDefnH p\n let (gfd', gfields')\n -- should not happen but just in case\n | V.null gfields = (gfd, gfields)\n -- ignore layer definition since it doesn't carry correct nullability\n -- info\n | otherwise = (snd (V.unsafeHead gfields), V.unsafeTail gfields)\n#else\n let (gfd', gfields') = (gfd, mempty)\n#endif\n FeatureDef\n <$> ({#call unsafe OGR_FD_GetName as ^#} p >>= peekEncodedCString)\n <*> fieldDefsFromFeatureDefnH p\n <*> pure gfd'\n <*> pure gfields'\n\nfieldDefsFromFeatureDefnH :: FeatureDefnH -> IO (V.Vector (Text, FieldDef))\nfieldDefsFromFeatureDefnH p = do\n nFields <- {#call unsafe OGR_FD_GetFieldCount as ^#} p\n V.generateM (fromIntegral nFields) $ \\i -> do\n fDef <- {#call unsafe OGR_FD_GetFieldDefn as ^#} p (fromIntegral i)\n liftM2 (,) (getFieldName fDef) (fieldDefFromHandle fDef)\n\n\ngeomFieldDefsFromFeatureDefnH\n :: FeatureDefnH -> IO (V.Vector (Text, GeomFieldDef))\n\n#if SUPPORTS_MULTI_GEOM_FIELDS\n\n{#pointer GeomFieldDefnH newtype#}\n\ngeomFieldDefsFromFeatureDefnH p = do\n nFields <- {#call unsafe OGR_FD_GetGeomFieldCount as ^#} p\n V.generateM (fromIntegral nFields) $\n gFldDef <=< ({#call unsafe OGR_FD_GetGeomFieldDefn as ^#} p . fromIntegral)\n where\n gFldDef g = do\n name <- {#call unsafe OGR_GFld_GetNameRef as ^#} g >>= peekEncodedCString\n gDef <- GeomFieldDef\n <$> liftM toEnumC ({#call unsafe OGR_GFld_GetType as ^#} g)\n <*> ({#call unsafe OGR_GFld_GetSpatialRef as ^#} g >>=\n maybeNewSpatialRefBorrowedHandle)\n#if SUPPORTS_NULLABLE_FIELD_DEFS\n <*> liftM toBool ({#call unsafe OGR_GFld_IsNullable as ^#} g)\n#else\n <*> pure True\n#endif\n return (name, gDef)\n\nwithGeomFieldDefnH :: Text -> GeomFieldDef -> (GeomFieldDefnH -> IO a) -> IO a\nwithGeomFieldDefnH gfdName GeomFieldDef{..} f =\n useAsEncodedCString gfdName $ \\pName ->\n bracket ({#call unsafe OGR_GFld_Create as ^#} pName (fromEnumC gfdType))\n ({#call unsafe OGR_GFld_Destroy as ^#}) (\\p -> populate p >> f p)\n where\n populate p = do\n withMaybeSpatialReference gfdSrs $\n {#call unsafe OGR_GFld_SetSpatialRef as ^#} p\n#if SUPPORTS_NULLABLE_FIELD_DEFS\n {#call unsafe OGR_GFld_SetNullable as ^#} p (fromBool gfdNullable)\n#endif\n\n#else\ngeomFieldDefsFromFeatureDefnH = const (return mempty)\n#endif -- SUPPORTS_MULTI_GEOM_FIELDS\n\nnullFID :: Fid\nnullFID = Fid ({#const OGRNullFID#})\n\nfeatureToHandle\n :: OGRFeature f\n => FeatureDefnH -> Maybe Fid -> f -> (FeatureH -> IO a) -> IO a\nfeatureToHandle fdH fId ft act =\n bracket ({#call unsafe OGR_F_Create as ^#} fdH)\n ({#call unsafe OGR_F_Destroy as ^#}) $ \\pF -> do\n case fId of\n Just (Fid fid) ->\n void $ {#call unsafe OGR_F_SetFID as ^#} pF (fromIntegral fid)\n Nothing -> return ()\n fieldDefs <- fieldDefsFromFeatureDefnH fdH\n flip imapM_ fieldDefs $ \\ix (name, _) -> do\n case HM.lookup name fFields of\n Just f -> setField f ix pF\n Nothing -> return ()\n case fGeom of\n Just g -> void $ withGeometry g ({#call unsafe OGR_F_SetGeometry as ^#} pF)\n Nothing -> return ()\n when (not (HM.null fGeoms)) $ do\n#if SUPPORTS_MULTI_GEOM_FIELDS\n geomFieldDefs <- geomFieldDefsFromFeatureDefnH fdH\n flip imapM_ (V.tail geomFieldDefs) $ \\ix (name, _) -> do\n case join (HM.lookup name fGeoms) of\n Just g ->\n void $ withGeometry g ({#call unsafe OGR_F_SetGeomField as ^#} pF (ix+1))\n Nothing ->\n return ()\n#else\n throwBindingException MultipleGeomFieldsNotSupported\n#endif\n act pF\n where Feature {..} = toFeature ft\n\nimapM :: (Monad m, Num a) => (a -> b -> m c) -> V.Vector b -> m (V.Vector c)\nimapM f v = V.mapM (uncurry f) (V.zip (V.enumFromN 0 (V.length v)) v)\n\nimapM_ :: (Monad m, Num a) => (a -> b -> m ()) -> V.Vector b -> m ()\nimapM_ f v = V.mapM_ (uncurry f) (V.zip (V.enumFromN 0 (V.length v)) v)\n\ngetFid :: FeatureH -> IO (Maybe Fid)\ngetFid pF = do\n mFid <- liftM fromIntegral ({#call unsafe OGR_F_GetFID as ^#} pF)\n return (if mFid == nullFID then Nothing else Just mFid)\n\nfeatureFromHandle\n :: OGRFeature a\n => FeatureDef -> IO FeatureH -> IO (Maybe (Maybe Fid, a))\nfeatureFromHandle FeatureDef{..} act =\n bracket act {#call unsafe OGR_F_Destroy as ^#} $ \\pF -> do\n if (pF == nullFeatureH)\n then return Nothing\n else do\n fid <- getFid pF\n fields <- flip imapM fdFields $ \\i (fldName, fd) -> do\n isSet <- liftM toBool ({#call unsafe OGR_F_IsFieldSet as ^#} pF i)\n if isSet\n then getField (fldType fd) i pF >>=\n maybe (throwBindingException (FieldParseError fldName))\n (\\f -> return (fldName, f))\n else return (fldName, OGRNullField)\n geomRef <- {#call unsafe OGR_F_StealGeometry as ^#} pF\n geom <- if geomRef \/= nullPtr\n then liftM Just (newGeometryHandle geomRef)\n else return Nothing\n#if SUPPORTS_MULTI_GEOM_FIELDS\n geoms <- flip imapM fdGeoms $ \\ix (gfdName, _) -> do\n pG <- {#call unsafe OGR_F_GetGeomFieldRef as ^#} pF (ix + 1)\n g <- if pG \/= nullPtr\n then liftM Just (cloneGeometry pG)\n else return Nothing\n return (gfdName, g)\n#else\n let geoms = mempty\n#endif\n either (throwBindingException . FromFeatureError)\n (\\f -> return (Just (fid,f)))\n (fromFeature Feature {\n fFields = HM.fromList (V.toList fields)\n , fGeom = geom\n , fGeoms = HM.fromList (V.toList geoms)\n })\n\n\n-- ############################################################################\n-- setField\n-- ############################################################################\n\nsetField :: Field -> CInt -> FeatureH -> IO ()\n\nsetField (OGRInteger v) ix f =\n {#call unsafe OGR_F_SetFieldInteger as ^#} f (fromIntegral ix) (fromIntegral v)\n\nsetField (OGRIntegerList v) ix f =\n St.unsafeWith v $\n {#call unsafe OGR_F_SetFieldIntegerList as ^#} f (fromIntegral ix)\n (fromIntegral (St.length v)) . castPtr\n\n#if SUPPORTS_64_BIT_INT_FIELDS\nsetField (OGRInteger64 v) ix f =\n {#call unsafe OGR_F_SetFieldInteger64 as ^#} f (fromIntegral ix) (fromIntegral v)\n\nsetField (OGRInteger64List v) ix f =\n St.unsafeWith v $\n {#call unsafe OGR_F_SetFieldInteger64List as ^#} f (fromIntegral ix)\n (fromIntegral (St.length v)) . castPtr\n#endif\n\nsetField (OGRReal v) ix f =\n {#call unsafe OGR_F_SetFieldDouble as ^#} f (fromIntegral ix) (realToFrac v)\n\nsetField (OGRRealList v) ix f =\n St.unsafeWith v $\n {#call unsafe OGR_F_SetFieldDoubleList as ^#} f (fromIntegral ix)\n (fromIntegral (St.length v)) . castPtr\n\nsetField (OGRString v) ix f = useAsEncodedCString v $\n {#call unsafe OGR_F_SetFieldString as ^#} f (fromIntegral ix)\n\nsetField (OGRStringList v) ix f =\n bracket createList {#call unsafe CSLDestroy as ^#} $\n {#call unsafe OGR_F_SetFieldStringList as ^#} f (fromIntegral ix)\n where\n createList = V.foldM' folder nullPtr v\n folder acc k =\n useAsEncodedCString k $ {#call unsafe CSLAddString as ^#} acc\n\nsetField (OGRBinary v) ix f = unsafeUseAsCStringLen v $ \\(p,l) ->\n {#call unsafe OGR_F_SetFieldBinary as ^#}\n f (fromIntegral ix) (fromIntegral l) (castPtr p)\n\nsetField (OGRDateTime (LocalTime day (TimeOfDay h mn s)) tz) ix f =\n {#call unsafe OGR_F_SetFieldDateTime as ^#} f (fromIntegral ix)\n (fromIntegral y) (fromIntegral m) (fromIntegral d)\n (fromIntegral h) (fromIntegral mn) (truncate s) (fromOGRTimeZone tz)\n where (y, m, d) = toGregorian day\n\nsetField (OGRDate day) ix f =\n {#call unsafe OGR_F_SetFieldDateTime as ^#} f (fromIntegral ix)\n (fromIntegral y) (fromIntegral m) (fromIntegral d) 0 0 0 (fromOGRTimeZone tz)\n where (y, m, d) = toGregorian day\n tz = UnknownTimeZone\n\nsetField (OGRTime (TimeOfDay h mn s)) ix f =\n {#call unsafe OGR_F_SetFieldDateTime as ^#} f (fromIntegral ix) 0 0 0\n (fromIntegral h) (fromIntegral mn) (truncate s) (fromOGRTimeZone tz)\n where tz = UnknownTimeZone\n\nsetField OGRNullField ix f = {#call unsafe OGR_F_UnsetField as ^#} f ix\n\n-- ############################################################################\n-- getField\n-- ############################################################################\n\ngetField :: FieldType -> CInt -> FeatureH -> IO (Maybe Field)\n\ngetField OFTInteger ix f =\n liftM (Just . OGRInteger . fromIntegral)\n ({#call unsafe OGR_F_GetFieldAsInteger as ^#} f ix)\n\ngetField OFTIntegerList ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsIntegerList as ^#} f ix lenP\n nElems <- peekIntegral lenP\n if nElems == 0\n then return (Just (OGRIntegerList mempty))\n else do\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CInt) (nElems * sizeOf (undefined :: CInt))\n liftM (Just . OGRIntegerList) (St.unsafeFreeze (Stm.unsafeCast vec))\n\n#if SUPPORTS_64_BIT_INT_FIELDS\ngetField OFTInteger64 ix f\n = liftM (Just . OGRInteger64 . fromIntegral)\n ({#call unsafe OGR_F_GetFieldAsInteger64 as ^#} f ix)\n\ngetField OFTInteger64List ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsInteger64List as ^#} f ix lenP\n nElems <- peekIntegral lenP\n if nElems == 0\n then return (Just (OGRInteger64List mempty))\n else do\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CLLong) (nElems * sizeOf (undefined :: CLLong))\n liftM (Just . OGRInteger64List) (St.unsafeFreeze (Stm.unsafeCast vec))\n#endif\n\ngetField OFTReal ix f\n = liftM (Just . OGRReal . realToFrac)\n ({#call unsafe OGR_F_GetFieldAsDouble as ^#} f ix)\n\ngetField OFTRealList ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsDoubleList as ^#} f ix lenP\n nElems <- peekIntegral lenP\n if nElems == 0\n then return (Just (OGRRealList mempty))\n else do\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CDouble) (nElems * sizeOf (undefined :: CDouble))\n liftM (Just . OGRRealList) (St.unsafeFreeze (Stm.unsafeCast vec))\n\ngetField OFTString ix f = liftM (Just . OGRString)\n (({#call unsafe OGR_F_GetFieldAsString as ^#} f ix) >>= peekEncodedCString)\n\ngetField OFTWideString ix f = getField OFTString ix f\n\ngetField OFTStringList ix f = liftM (Just . OGRStringList) $ do\n ptr <- {#call unsafe OGR_F_GetFieldAsStringList as ^#} f ix\n nElems <- liftM fromIntegral ({#call unsafe CSLCount as ^#} ptr)\n V.generateM nElems (peekElemOff ptr >=> peekEncodedCString)\n\ngetField OFTWideStringList ix f = getField OFTStringList ix f\n\ngetField OFTBinary ix f = alloca $ \\lenP -> do\n buf <- liftM castPtr ({#call unsafe OGR_F_GetFieldAsBinary as ^#} f ix lenP)\n nElems <- peekIntegral lenP\n liftM (Just . OGRBinary) (packCStringLen (buf, nElems))\n\ngetField OFTDateTime ix f =\n liftM (fmap (uncurry OGRDateTime)) (getDateTime ix f)\n\ngetField OFTDate ix f =\n liftM (fmap (\\(LocalTime d _,_) -> OGRDate d)) (getDateTime ix f)\n\ngetField OFTTime ix f =\n liftM (fmap (\\(LocalTime _ t,_) -> OGRTime t)) (getDateTime ix f)\n\n\ngetDateTime :: CInt -> FeatureH -> IO (Maybe (LocalTime, OGRTimeZone))\ngetDateTime ix f\n = alloca $ \\y -> alloca $ \\m -> alloca $ \\d ->\n alloca $ \\h -> alloca $ \\mn -> alloca $ \\s -> alloca $ \\pTz -> do\n ret <- {#call unsafe OGR_F_GetFieldAsDateTime as ^#} f ix y m d h mn s pTz\n if ret == 0\n then return Nothing\n else do\n day <- fromGregorian <$> peekIntegral y\n <*> peekIntegral m\n <*> peekIntegral d\n tod <- TimeOfDay <$> peekIntegral h\n <*> peekIntegral mn\n <*> peekIntegral s\n iTz <- peekIntegral pTz\n return (Just (LocalTime day tod, toOGRTimezone iTz))\n\ntoOGRTimezone :: CInt -> OGRTimeZone\ntoOGRTimezone tz =\n case tz of\n 0 -> UnknownTimeZone\n 1 -> LocalTimeZone\n 100 -> KnownTimeZone utc\n n -> KnownTimeZone (minutesToTimeZone ((fromIntegral n - 100) * 15))\n\nfromOGRTimeZone :: OGRTimeZone -> CInt\nfromOGRTimeZone UnknownTimeZone = 0\nfromOGRTimeZone LocalTimeZone = 1\nfromOGRTimeZone (KnownTimeZone tz) = truncate ((mins \/ 15) + 100)\n where mins = fromIntegral (timeZoneMinutes tz) :: Double\n\npeekIntegral :: (Storable a, Integral a, Num b) => Ptr a -> IO b\npeekIntegral = liftM fromIntegral . peek\n\ngetFieldName :: FieldDefnH -> IO Text\ngetFieldName =\n {#call unsafe OGR_Fld_GetNameRef as ^#} >=> peekEncodedCString\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"b0ffd017aac581a86aadff51df86eea88c458fc9","subject":"Image Format struct","message":"Image Format struct\n","repos":"IFCA\/opencl,IFCA\/opencl,Delan90\/opencl,Delan90\/opencl","old_file":"src\/System\/GPU\/OpenCL\/Types.chs","new_file":"src\/System\/GPU\/OpenCL\/Types.chs","new_contents":"-- -----------------------------------------------------------------------------\n-- This file is part of Haskell-Opencl.\n\n-- Haskell-Opencl is free software: you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation, either version 3 of the License, or\n-- (at your option) any later version.\n\n-- Haskell-Opencl is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n\n-- You should have received a copy of the GNU General Public License\n-- along with Haskell-Opencl. If not, see .\n-- -----------------------------------------------------------------------------\nmodule System.GPU.OpenCL.Types( \n ErrorCode(..), CLbool, CLint, CLuint, CLulong, CLPlatformInfo_, CLMem, \n CLProgram, CLEvent,\n CLDeviceType_, CLDeviceInfo_, CLContextInfo_, CLDeviceFPConfig(..), \n CLDeviceMemCacheType(..), CLDeviceExecCapability(..), CLDeviceLocalMemType(..),\n CLPlatformID, CLDeviceID, CLContext, CLCommandQueue, CLContextProperty_,\n CLDeviceType(..), CLCommandQueueProperty(..), CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType(..), CLCommandType_, \n CLCommandExecutionStatus(..), CLProfilingInfo(..), getProfilingInfoValue,\n CLCommandQueueProperty_, CLMemFlags_, CLImageFormat_p, CLMemObjectType_, \n CLMemInfo_, CLImageInfo_, CLImageFormat(..), getImageFormat, getDeviceTypeValue, \n getDeviceLocalMemType, getDeviceMemCacheType, getCommandType, \n getCommandExecutionStatus, bitmaskToDeviceTypes, bitmaskFromDeviceTypes, \n bitmaskToCommandQueueProperties, bitmaskFromCommandQueueProperties, \n bitmaskToFPConfig, bitmaskToExecCapability )\n where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Data.List( foldl' )\n\n#include \n\n-- -----------------------------------------------------------------------------\n\ntype CLPlatformID = {#type cl_platform_id#}\ntype CLDeviceID = {#type cl_device_id#}\ntype CLContext = {#type cl_context#}\ntype CLCommandQueue = {#type cl_command_queue#}\ntype CLMem = {#type cl_mem#}\ntype CLEvent = {#type cl_event#}\ntype CLProgram = {#type cl_program#}\n\ntype CLint = {#type cl_int#}\ntype CLuint = {#type cl_uint#}\ntype CLulong = {#type cl_ulong#}\ntype CLbool = {#type cl_bool#}\n\ntype CLPlatformInfo_ = {#type cl_platform_info#}\ntype CLDeviceType_ = {#type cl_device_type#}\ntype CLDeviceInfo_ = {#type cl_device_info#}\ntype CLDeviceFPConfig_ = {#type cl_device_fp_config#}\ntype CLDeviceMemCacheType_ = {#type cl_device_mem_cache_type#}\ntype CLDeviceLocalMemType_ = {#type cl_device_local_mem_type#}\ntype CLDeviceExecCapability_ = {#type cl_device_exec_capabilities#}\ntype CLContextInfo_ = {#type cl_context_info#}\ntype CLContextProperty_ = {#type cl_context_properties#}\ntype CLCommandQueueInfo_ = {#type cl_command_queue_info#}\ntype CLCommandQueueProperty_ = {#type cl_command_queue_properties#}\ntype CLEventInfo_ = {#type cl_event_info#}\ntype CLProfilingInfo_ = {#type cl_profiling_info#}\ntype CLCommandType_ = {#type cl_command_type#}\ntype CLMemFlags_ = {#type cl_mem_flags#}\ntype CLMemObjectType_ = {#type cl_mem_object_type#}\ntype CLMemInfo_ = {#type cl_mem_info#}\ntype CLImageInfo_ = {#type cl_image_info#}\n{#pointer *cl_image_format as CLImageFormat_p#}\n\ntype CLImageChannelOrder_ = {#type cl_channel_order#}\ntype CLImageChannelDataType_ = {#type cl_channel_type#}\n\nnewtype ErrorCode = ErrorCode CInt deriving( Eq )\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLDeviceType {\nCLDEVICE_TYPE_CPU=CL_DEVICE_TYPE_CPU,\nCLDEVICE_TYPE_GPU=CL_DEVICE_TYPE_GPU,\nCLDEVICE_TYPE_ACCELERATOR=CL_DEVICE_TYPE_ACCELERATOR,\nCLDEVICE_TYPE_DEFAULT=CL_DEVICE_TYPE_DEFAULT,\nCLDEVICE_TYPE_ALL=CL_DEVICE_TYPE_ALL\n };\n#endc\n\n{-|\n * 'CLDEVICE_TYPE_CPU', An OpenCL device that is the host processor. The host processor runs the OpenCL implementations and is a single or multi-core CPU.\n \n * 'CLDEVICE_TYPE_GPU', An OpenCL device that is a GPU. By this we mean that the device can also be used to accelerate a 3D API such as OpenGL or DirectX.\n \n * 'CLDEVICE_TYPE_ACCELERATOR', Dedicated OpenCL accelerators (for example the IBM CELL Blade). These devices communicate with the host processor using a peripheral interconnect such as PCIe.\n \n * 'CLDEVICE_TYPE_DEFAULT', The default OpenCL device in the system.\n \n * 'CLDEVICE_TYPE_ALL', All OpenCL devices available in the system.\n-}\n{#enum CLDeviceType {} deriving( Show ) #}\n\ngetDeviceTypeValue :: CLDeviceType -> CLDeviceType_\ngetDeviceTypeValue = fromIntegral . fromEnum\n\n#c\nenum CLCommandQueueProperty { \n CLQUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE=CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,\n CLQUEUE_PROFILING_ENABLE=CL_QUEUE_PROFILING_ENABLE\n };\n#endc\n\n{-|\n * 'CLQUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE', Determines whether the commands \nqueued in the command-queue are executed in-order or out-of-order. If set, the \ncommands in the command-queue are executed out-of-order. Otherwise, commands are \nexecuted in-order.\n \n * 'CLQUEUE_PROFILING_ENABLE', Enable or disable profiling of commands in the \ncommand-queue. If set, the profiling of commands is enabled. Otherwise profiling \nof commands is disabled. See 'clGetEventProfilingInfo' for more information.\n-}\n{#enum CLCommandQueueProperty {} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceFPConfig {\n CLFP_DENORM=CL_FP_DENORM, CLFP_INF_NAN=CL_FP_INF_NAN,\n CLFP_ROUND_TO_NEAREST=CL_FP_ROUND_TO_NEAREST,\n CLFP_ROUND_TO_ZERO=CL_FP_ROUND_TO_ZERO,\n CLFP_ROUND_TO_INF=CL_FP_ROUND_TO_INF, CLFP_FMA=CL_FP_FMA,\n };\n#endc\n\n{-|\n * 'CLFP_DENORM', denorms are supported.\n \n * 'CLFP_INF_NAN', INF and NaNs are supported.\n \n * 'CLFP_ROUND_TO_NEAREST', round to nearest even rounding mode supported.\n \n * 'CLFP_ROUND_TO_ZERO', round to zero rounding mode supported.\n \n * 'CLFP_ROUND_TO_INF', round to +ve and -ve infinity rounding modes supported.\n \n * 'CLFP_FMA', IEEE754-2008 fused multiply-add is supported.\n-}\n{#enum CLDeviceFPConfig {} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceExecCapability {\n CLEXEC_KERNEL=CL_EXEC_KERNEL,\n CLEXEC_NATIVE_KERNEL=CL_EXEC_NATIVE_KERNEL\n };\n#endc\n\n{-|\n * 'CLEXEC_KERNEL', The OpenCL device can execute OpenCL kernels.\n \n * 'CLEXEC_NATIVE_KERNEL', The OpenCL device can execute native kernels.\n-}\n{#enum CLDeviceExecCapability {} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceMemCacheType {\n CLNONE=CL_NONE,CLREAD_ONLY_CACHE=CL_READ_ONLY_CACHE,\n CLREAD_WRITE_CACHE=CL_READ_WRITE_CACHE\n };\n#endc\n\n{#enum CLDeviceMemCacheType {} deriving( Show ) #}\n\ngetDeviceMemCacheType :: CLDeviceMemCacheType_ -> Maybe CLDeviceMemCacheType\ngetDeviceMemCacheType = Just . toEnum . fromIntegral\n\n#c\nenum CLDeviceLocalMemType {\n CLLOCAL=CL_LOCAL, CLGLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {} deriving( Show ) #}\n\ngetDeviceLocalMemType :: CLDeviceLocalMemType_ -> Maybe CLDeviceLocalMemType\ngetDeviceLocalMemType = Just . toEnum . fromIntegral\n\n#c\nenum CLCommandType {\n CLCOMMAND_NDRANGE_KERNEL=CL_COMMAND_NDRANGE_KERNEL,\n CLCOMMAND_TASK=CL_COMMAND_TASK ,\n CLCOMMAND_NATIVE_KERNEL=CL_COMMAND_NATIVE_KERNEL,\n CLCOMMAND_READ_BUFFER=CL_COMMAND_READ_BUFFER,\n CLCOMMAND_WRITE_BUFFER=CL_COMMAND_WRITE_BUFFER,\n CLCOMMAND_COPY_BUFFER=CL_COMMAND_COPY_BUFFER,\n CLCOMMAND_READ_IMAGE=CL_COMMAND_READ_IMAGE,\n CLCOMMAND_WRITE_IMAGE=CL_COMMAND_WRITE_IMAGE,\n CLCOMMAND_COPY_IMAGE=CL_COMMAND_COPY_IMAGE,\n CLCOMMAND_COPY_BUFFER_TO_IMAGE=CL_COMMAND_COPY_BUFFER_TO_IMAGE,\n CLCOMMAND_COPY_IMAGE_TO_BUFFER=CL_COMMAND_COPY_IMAGE_TO_BUFFER,\n CLCOMMAND_MAP_BUFFER=CL_COMMAND_MAP_BUFFER,\n CLCOMMAND_MAP_IMAGE=CL_COMMAND_MAP_IMAGE,\n CLCOMMAND_UNMAP_MEM_OBJECT=CL_COMMAND_UNMAP_MEM_OBJECT,\n CLCOMMAND_MARKER=CL_COMMAND_MARKER,\n CLCOMMAND_ACQUIRE_GL_OBJECTS=CL_COMMAND_ACQUIRE_GL_OBJECTS,\n CLCOMMAND_RELEASE_GL_OBJECTS=CL_COMMAND_RELEASE_GL_OBJECTS\n };\n#endc\n\n-- | Command associated with an event.\n{#enum CLCommandType {} deriving( Show ) #}\n\ngetCommandType :: CLCommandType_ -> Maybe CLCommandType\ngetCommandType = Just . toEnum . fromIntegral\n\n#c\nenum CLCommandExecutionStatus {\n CLQUEUED=CL_QUEUED, CLSUBMITTED=CL_SUBMITTED, CLRUNNING=CL_RUNNING,\n CLCOMPLETE=CL_COMPLETE, CLEXEC_ERROR= -1\n };\n#endc\n\n{-|\n * 'CLQUEUED', command has been enqueued in the command-queue.\n\n * 'CLSUBMITTED', enqueued command has been submitted by the host to the \ndevice associated with the command-queue.\n\n * 'CLRUNNING', device is currently executing this command.\n \n * 'CLCOMPLETE', the command has completed.\n \n * 'CLEXEC_ERROR', command was abnormally terminated.\n-}\n{#enum CLCommandExecutionStatus {} deriving( Show ) #}\n\ngetCommandExecutionStatus :: CLint -> Maybe CLCommandExecutionStatus \ngetCommandExecutionStatus n \n | n < 0 = Just CLEXEC_ERROR\n | otherwise = Just . toEnum . fromIntegral $ n\n \n#c\nenum CLProfilingInfo {\n CLPROFILING_COMMAND_QUEUED=CL_PROFILING_COMMAND_QUEUED,\n CLPROFILING_COMMAND_SUBMIT=CL_PROFILING_COMMAND_SUBMIT,\n CLPROFILING_COMMAND_START=CL_PROFILING_COMMAND_START,\n CLPROFILING_COMMAND_END=CL_PROFILING_COMMAND_END\n };\n#endc\n\n{-| Specifies the profiling data.\n\n * 'CLPROFILING_COMMAND_QUEUED', A 64-bit value that describes the current \ndevice time counter in nanoseconds when the command identified by event is \nenqueued in a command-queue by the host.\n \n * 'CLPROFILING_COMMAND_SUBMIT', A 64-bit value that describes the current \ndevice time counter in nanoseconds when the command identified by event that has \nbeen enqueued is submitted by the host to the device associated with the \ncommandqueue.\n \n * 'CLPROFILING_COMMAND_START',\t A 64-bit value that describes the current \ndevice time counter in nanoseconds when the command identified by event starts \nexecution on the device.\n \n * 'CLPROFILING_COMMAND_END', A 64-bit value that describes the current device \ntime counter in nanoseconds when the command identified by event has finished \nexecution on the device.\n-}\n{#enum CLProfilingInfo {} deriving( Show ) #}\n\ngetProfilingInfoValue :: CLProfilingInfo -> CLProfilingInfo_\ngetProfilingInfoValue = fromIntegral . fromEnum\n\n-- -----------------------------------------------------------------------------\ngetImageChannelOrder :: CLImageFormat_p -> IO CLImageChannelOrder_\ngetImageChannelOrder = {#get cl_image_format->image_channel_order#}\n\ngetImageChannelDataType :: CLImageFormat_p -> IO CLImageChannelDataType_\ngetImageChannelDataType = {#get cl_image_format->image_channel_data_type#}\n\ndata CLImageFormat = CLImageFormat { \n image_channel_order :: CLImageChannelOrder_,\n image_channel_data_type :: CLImageChannelDataType_\n } deriving( Show )\n\ngetImageFormat :: CLImageFormat_p -> IO CLImageFormat\ngetImageFormat p = do\n order <- getImageChannelOrder p\n datatype <- getImageChannelDataType p\n return $ CLImageFormat order datatype\n \n-- -----------------------------------------------------------------------------\nbinaryFlags :: (Ord b, Enum b, Bounded b) => b -> [b]\nbinaryFlags m = map toEnum . takeWhile (<= (fromEnum m)) $ [1 `shiftL` n | n <- [0..]]\n \ntestMask :: Bits b => b -> b -> Bool\ntestMask mask v = (v .&. mask) == v\n\nbitmaskToDeviceTypes :: CLDeviceType_ -> [CLDeviceType]\nbitmaskToDeviceTypes mask = filter (testMask mask . fromIntegral . fromEnum) $ [CLDEVICE_TYPE_CPU,CLDEVICE_TYPE_GPU,CLDEVICE_TYPE_ACCELERATOR,CLDEVICE_TYPE_DEFAULT,CLDEVICE_TYPE_ALL]\n\nbitmaskFromDeviceTypes :: [CLDeviceType] -> CLDeviceType_\nbitmaskFromDeviceTypes = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\n \nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties mask = filter (testMask mask . fromIntegral . fromEnum) $ binaryFlags maxBound\n \nbitmaskFromCommandQueueProperties :: [CLCommandQueueProperty] -> CLCommandQueueProperty_\nbitmaskFromCommandQueueProperties = foldl' (.|.) 0 . map (fromIntegral.fromEnum)\n\nbitmaskToFPConfig :: CLDeviceFPConfig_ -> [CLDeviceFPConfig]\nbitmaskToFPConfig mask = filter (testMask mask . fromIntegral . fromEnum) $ binaryFlags maxBound\n\nbitmaskToExecCapability :: CLDeviceExecCapability_ -> [CLDeviceExecCapability]\nbitmaskToExecCapability mask = filter (testMask mask . fromIntegral . fromEnum) $ binaryFlags maxBound\n\n-- -----------------------------------------------------------------------------\n","old_contents":"-- -----------------------------------------------------------------------------\n-- This file is part of Haskell-Opencl.\n\n-- Haskell-Opencl is free software: you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation, either version 3 of the License, or\n-- (at your option) any later version.\n\n-- Haskell-Opencl is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n\n-- You should have received a copy of the GNU General Public License\n-- along with Haskell-Opencl. If not, see .\n-- -----------------------------------------------------------------------------\nmodule System.GPU.OpenCL.Types( \n ErrorCode(..), CLbool, CLint, CLuint, CLulong, CLPlatformInfo_, CLMem, \n CLProgram, CLEvent,\n CLDeviceType_, CLDeviceInfo_, CLContextInfo_, CLDeviceFPConfig(..), \n CLDeviceMemCacheType(..), CLDeviceExecCapability(..), CLDeviceLocalMemType(..),\n CLPlatformID, CLDeviceID, CLContext, CLCommandQueue, CLContextProperty_,\n CLDeviceType(..), CLCommandQueueProperty(..), CLCommandQueueInfo_, \n CLEventInfo_, CLProfilingInfo_, CLCommandType(..), CLCommandType_, \n CLCommandExecutionStatus(..), CLProfilingInfo(..), getProfilingInfoValue,\n CLCommandQueueProperty_, CLMemFlags_, CLImageFormat_p, CLMemObjectType_, \n CLMemInfo_, CLImageInfo_, getDeviceTypeValue, getDeviceLocalMemType, \n getDeviceMemCacheType, getCommandType, getCommandExecutionStatus, \n bitmaskToDeviceTypes, bitmaskFromDeviceTypes, bitmaskToCommandQueueProperties, \n bitmaskFromCommandQueueProperties, bitmaskToFPConfig, bitmaskToExecCapability )\n where\n\n-- -----------------------------------------------------------------------------\nimport Foreign( Ptr )\nimport Foreign.C.Types\nimport Data.List( foldl' )\nimport Data.Bits( Bits, shiftL, (.|.), (.&.) )\n\n#include \n\n-- -----------------------------------------------------------------------------\n\ntype CLPlatformID = {#type cl_platform_id#}\ntype CLDeviceID = {#type cl_device_id#}\ntype CLContext = {#type cl_context#}\ntype CLCommandQueue = {#type cl_command_queue#}\ntype CLMem = {#type cl_mem#}\ntype CLEvent = {#type cl_event#}\ntype CLProgram = {#type cl_program#}\n\ntype CLint = {#type cl_int#}\ntype CLuint = {#type cl_uint#}\ntype CLulong = {#type cl_ulong#}\ntype CLbool = {#type cl_bool#}\n\ntype CLPlatformInfo_ = {#type cl_platform_info#}\ntype CLDeviceType_ = {#type cl_device_type#}\ntype CLDeviceInfo_ = {#type cl_device_info#}\ntype CLDeviceFPConfig_ = {#type cl_device_fp_config#}\ntype CLDeviceMemCacheType_ = {#type cl_device_mem_cache_type#}\ntype CLDeviceLocalMemType_ = {#type cl_device_local_mem_type#}\ntype CLDeviceExecCapability_ = {#type cl_device_exec_capabilities#}\ntype CLContextInfo_ = {#type cl_context_info#}\ntype CLContextProperty_ = {#type cl_context_properties#}\ntype CLCommandQueueInfo_ = {#type cl_command_queue_info#}\ntype CLCommandQueueProperty_ = {#type cl_command_queue_properties#}\ntype CLEventInfo_ = {#type cl_event_info#}\ntype CLProfilingInfo_ = {#type cl_profiling_info#}\ntype CLCommandType_ = {#type cl_command_type#}\ntype CLMemFlags_ = {#type cl_mem_flags#}\ntype CLMemObjectType_ = {#type cl_mem_object_type#}\ntype CLMemInfo_ = {#type cl_mem_info#}\ntype CLImageInfo_ = {#type cl_image_info#}\n{#pointer *cl_image_format as CLImageFormat_p#}\n\ntype CLImageChannelOrder_ = {#type cl_channel_order#}\ntype CLImageChannelDataType_ = {#type cl_channel_type#}\n\nnewtype ErrorCode = ErrorCode CInt deriving( Eq )\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLDeviceType {\nCLDEVICE_TYPE_CPU=CL_DEVICE_TYPE_CPU,\nCLDEVICE_TYPE_GPU=CL_DEVICE_TYPE_GPU,\nCLDEVICE_TYPE_ACCELERATOR=CL_DEVICE_TYPE_ACCELERATOR,\nCLDEVICE_TYPE_DEFAULT=CL_DEVICE_TYPE_DEFAULT,\nCLDEVICE_TYPE_ALL=CL_DEVICE_TYPE_ALL\n };\n#endc\n\n{-|\n * 'CLDEVICE_TYPE_CPU', An OpenCL device that is the host processor. The host processor runs the OpenCL implementations and is a single or multi-core CPU.\n \n * 'CLDEVICE_TYPE_GPU', An OpenCL device that is a GPU. By this we mean that the device can also be used to accelerate a 3D API such as OpenGL or DirectX.\n \n * 'CLDEVICE_TYPE_ACCELERATOR', Dedicated OpenCL accelerators (for example the IBM CELL Blade). These devices communicate with the host processor using a peripheral interconnect such as PCIe.\n \n * 'CLDEVICE_TYPE_DEFAULT', The default OpenCL device in the system.\n \n * 'CLDEVICE_TYPE_ALL', All OpenCL devices available in the system.\n-}\n{#enum CLDeviceType {} deriving( Show ) #}\n\ngetDeviceTypeValue :: CLDeviceType -> CLDeviceType_\ngetDeviceTypeValue = fromIntegral . fromEnum\n\n#c\nenum CLCommandQueueProperty { \n CLQUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE=CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE,\n CLQUEUE_PROFILING_ENABLE=CL_QUEUE_PROFILING_ENABLE\n };\n#endc\n\n{-|\n * 'CLQUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE', Determines whether the commands \nqueued in the command-queue are executed in-order or out-of-order. If set, the \ncommands in the command-queue are executed out-of-order. Otherwise, commands are \nexecuted in-order.\n \n * 'CLQUEUE_PROFILING_ENABLE', Enable or disable profiling of commands in the \ncommand-queue. If set, the profiling of commands is enabled. Otherwise profiling \nof commands is disabled. See 'clGetEventProfilingInfo' for more information.\n-}\n{#enum CLCommandQueueProperty {} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceFPConfig {\n CLFP_DENORM=CL_FP_DENORM, CLFP_INF_NAN=CL_FP_INF_NAN,\n CLFP_ROUND_TO_NEAREST=CL_FP_ROUND_TO_NEAREST,\n CLFP_ROUND_TO_ZERO=CL_FP_ROUND_TO_ZERO,\n CLFP_ROUND_TO_INF=CL_FP_ROUND_TO_INF, CLFP_FMA=CL_FP_FMA,\n };\n#endc\n\n{-|\n * 'CLFP_DENORM', denorms are supported.\n \n * 'CLFP_INF_NAN', INF and NaNs are supported.\n \n * 'CLFP_ROUND_TO_NEAREST', round to nearest even rounding mode supported.\n \n * 'CLFP_ROUND_TO_ZERO', round to zero rounding mode supported.\n \n * 'CLFP_ROUND_TO_INF', round to +ve and -ve infinity rounding modes supported.\n \n * 'CLFP_FMA', IEEE754-2008 fused multiply-add is supported.\n-}\n{#enum CLDeviceFPConfig {} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceExecCapability {\n CLEXEC_KERNEL=CL_EXEC_KERNEL,\n CLEXEC_NATIVE_KERNEL=CL_EXEC_NATIVE_KERNEL\n };\n#endc\n\n{-|\n * 'CLEXEC_KERNEL', The OpenCL device can execute OpenCL kernels.\n \n * 'CLEXEC_NATIVE_KERNEL', The OpenCL device can execute native kernels.\n-}\n{#enum CLDeviceExecCapability {} deriving( Show, Bounded, Eq, Ord ) #}\n\n#c\nenum CLDeviceMemCacheType {\n CLNONE=CL_NONE,CLREAD_ONLY_CACHE=CL_READ_ONLY_CACHE,\n CLREAD_WRITE_CACHE=CL_READ_WRITE_CACHE\n };\n#endc\n\n{#enum CLDeviceMemCacheType {} deriving( Show ) #}\n\ngetDeviceMemCacheType :: CLDeviceMemCacheType_ -> Maybe CLDeviceMemCacheType\ngetDeviceMemCacheType = Just . toEnum . fromIntegral\n\n#c\nenum CLDeviceLocalMemType {\n CLLOCAL=CL_LOCAL, CLGLOBAL=CL_GLOBAL\n };\n#endc\n\n{#enum CLDeviceLocalMemType {} deriving( Show ) #}\n\ngetDeviceLocalMemType :: CLDeviceLocalMemType_ -> Maybe CLDeviceLocalMemType\ngetDeviceLocalMemType = Just . toEnum . fromIntegral\n\n#c\nenum CLCommandType {\n CLCOMMAND_NDRANGE_KERNEL=CL_COMMAND_NDRANGE_KERNEL,\n CLCOMMAND_TASK=CL_COMMAND_TASK ,\n CLCOMMAND_NATIVE_KERNEL=CL_COMMAND_NATIVE_KERNEL,\n CLCOMMAND_READ_BUFFER=CL_COMMAND_READ_BUFFER,\n CLCOMMAND_WRITE_BUFFER=CL_COMMAND_WRITE_BUFFER,\n CLCOMMAND_COPY_BUFFER=CL_COMMAND_COPY_BUFFER,\n CLCOMMAND_READ_IMAGE=CL_COMMAND_READ_IMAGE,\n CLCOMMAND_WRITE_IMAGE=CL_COMMAND_WRITE_IMAGE,\n CLCOMMAND_COPY_IMAGE=CL_COMMAND_COPY_IMAGE,\n CLCOMMAND_COPY_BUFFER_TO_IMAGE=CL_COMMAND_COPY_BUFFER_TO_IMAGE,\n CLCOMMAND_COPY_IMAGE_TO_BUFFER=CL_COMMAND_COPY_IMAGE_TO_BUFFER,\n CLCOMMAND_MAP_BUFFER=CL_COMMAND_MAP_BUFFER,\n CLCOMMAND_MAP_IMAGE=CL_COMMAND_MAP_IMAGE,\n CLCOMMAND_UNMAP_MEM_OBJECT=CL_COMMAND_UNMAP_MEM_OBJECT,\n CLCOMMAND_MARKER=CL_COMMAND_MARKER,\n CLCOMMAND_ACQUIRE_GL_OBJECTS=CL_COMMAND_ACQUIRE_GL_OBJECTS,\n CLCOMMAND_RELEASE_GL_OBJECTS=CL_COMMAND_RELEASE_GL_OBJECTS\n };\n#endc\n\n-- | Command associated with an event.\n{#enum CLCommandType {} deriving( Show ) #}\n\ngetCommandType :: CLCommandType_ -> Maybe CLCommandType\ngetCommandType = Just . toEnum . fromIntegral\n\n#c\nenum CLCommandExecutionStatus {\n CLQUEUED=CL_QUEUED, CLSUBMITTED=CL_SUBMITTED, CLRUNNING=CL_RUNNING,\n CLCOMPLETE=CL_COMPLETE, CLEXEC_ERROR= -1\n };\n#endc\n\n{-|\n * 'CLQUEUED', command has been enqueued in the command-queue.\n\n * 'CLSUBMITTED', enqueued command has been submitted by the host to the \ndevice associated with the command-queue.\n\n * 'CLRUNNING', device is currently executing this command.\n \n * 'CLCOMPLETE', the command has completed.\n \n * 'CLEXEC_ERROR', command was abnormally terminated.\n-}\n{#enum CLCommandExecutionStatus {} deriving( Show ) #}\n\ngetCommandExecutionStatus :: CLint -> Maybe CLCommandExecutionStatus \ngetCommandExecutionStatus n \n | n < 0 = Just CLEXEC_ERROR\n | otherwise = Just . toEnum . fromIntegral $ n\n \n#c\nenum CLProfilingInfo {\n CLPROFILING_COMMAND_QUEUED=CL_PROFILING_COMMAND_QUEUED,\n CLPROFILING_COMMAND_SUBMIT=CL_PROFILING_COMMAND_SUBMIT,\n CLPROFILING_COMMAND_START=CL_PROFILING_COMMAND_START,\n CLPROFILING_COMMAND_END=CL_PROFILING_COMMAND_END\n };\n#endc\n\n{-| Specifies the profiling data.\n\n * 'CLPROFILING_COMMAND_QUEUED', A 64-bit value that describes the current \ndevice time counter in nanoseconds when the command identified by event is \nenqueued in a command-queue by the host.\n \n * 'CLPROFILING_COMMAND_SUBMIT', A 64-bit value that describes the current \ndevice time counter in nanoseconds when the command identified by event that has \nbeen enqueued is submitted by the host to the device associated with the \ncommandqueue.\n \n * 'CLPROFILING_COMMAND_START',\t A 64-bit value that describes the current \ndevice time counter in nanoseconds when the command identified by event starts \nexecution on the device.\n \n * 'CLPROFILING_COMMAND_END', A 64-bit value that describes the current device \ntime counter in nanoseconds when the command identified by event has finished \nexecution on the device.\n-}\n{#enum CLProfilingInfo {} deriving( Show ) #}\n\ngetProfilingInfoValue :: CLProfilingInfo -> CLProfilingInfo_\ngetProfilingInfoValue = fromIntegral . fromEnum\n\n-- -----------------------------------------------------------------------------\nbinaryFlags :: (Ord b, Enum b, Bounded b) => b -> [b]\nbinaryFlags m = map toEnum . takeWhile (<= (fromEnum m)) $ [1 `shiftL` n | n <- [0..]]\n \ntestMask :: Bits b => b -> b -> Bool\ntestMask mask v = (v .&. mask) == v\n\nbitmaskToDeviceTypes :: CLDeviceType_ -> [CLDeviceType]\nbitmaskToDeviceTypes mask = filter (testMask mask . fromIntegral . fromEnum) $ [CLDEVICE_TYPE_CPU,CLDEVICE_TYPE_GPU,CLDEVICE_TYPE_ACCELERATOR,CLDEVICE_TYPE_DEFAULT,CLDEVICE_TYPE_ALL]\n\nbitmaskFromDeviceTypes :: [CLDeviceType] -> CLDeviceType_\nbitmaskFromDeviceTypes = foldl' (.|.) 0 . map (fromIntegral . fromEnum)\n \nbitmaskToCommandQueueProperties :: CLCommandQueueProperty_ -> [CLCommandQueueProperty]\nbitmaskToCommandQueueProperties mask = filter (testMask mask . fromIntegral . fromEnum) $ binaryFlags maxBound\n \nbitmaskFromCommandQueueProperties :: [CLCommandQueueProperty] -> CLCommandQueueProperty_\nbitmaskFromCommandQueueProperties = foldl' (.|.) 0 . map (fromIntegral.fromEnum)\n\nbitmaskToFPConfig :: CLDeviceFPConfig_ -> [CLDeviceFPConfig]\nbitmaskToFPConfig mask = filter (testMask mask . fromIntegral . fromEnum) $ binaryFlags maxBound\n\nbitmaskToExecCapability :: CLDeviceExecCapability_ -> [CLDeviceExecCapability]\nbitmaskToExecCapability mask = filter (testMask mask . fromIntegral . fromEnum) $ binaryFlags maxBound\n\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"518881fff2b9f9a4e49a7846d7cdf84b8a31cad1","subject":"use FilePath type synonynm","message":"use FilePath type synonynm\n\nIgnore-this: 7690cc0257d0dd03652c8336146c1fcc\n\ndarcs-hash:20100616042104-dcabc-5f2b2a88ae6f91b3520c260da46da4668d461a1f.gz\n","repos":"phaazon\/cuda,phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda","old_file":"Foreign\/CUDA\/Driver\/Module.chs","new_file":"Foreign\/CUDA\/Driver\/Module.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : (c) [2009..2010] Trevor L. McDonell\n-- License : BSD\n--\n-- Module management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Module\n (\n Module,\n JITOption(..), JITTarget(..), JITResult(..),\n getFun, getPtr, getTex,\n loadFile, loadData, loadDataEx, unload\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Ptr\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Exec\nimport Foreign.CUDA.Driver.Marshal (peekDevPtr)\nimport Foreign.CUDA.Driver.Texture hiding (getPtr)\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Unsafe.Coerce\n\nimport Control.Monad (liftM)\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as B\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A reference to a Module object, containing collections of device functions\n--\nnewtype Module = Module { useModule :: {# type CUmodule #}}\n\n\n-- |\n-- Just-in-time compilation options\n--\ndata JITOption\n = MaxRegisters Int -- ^ maximum number of registers per thread\n | ThreadsPerBlock Int -- ^ number of threads per block to target for\n | OptimisationLevel Int -- ^ level of optimisation to apply (1-4, default 4)\n | Target JITTarget -- ^ compilation target, otherwise determined from context\n-- | FallbackStrategy JITFallback\n deriving (Show)\n\n-- |\n-- Results of online compilation\n--\ndata JITResult = JITResult\n {\n jitTime :: Float, -- ^ milliseconds spent compiling PTX\n jitInfoLog :: ByteString, -- ^ information about PTX asembly\n jitErrorLog :: ByteString -- ^ compilation errors\n }\n deriving (Show)\n\n\n{# enum CUjit_option as JITOptionInternal\n { }\n with prefix=\"CU\" deriving (Eq, Show) #}\n\n{# enum CUjit_target as JITTarget\n { underscoreToCase }\n with prefix=\"CU_TARGET\" deriving (Eq, Show) #}\n\n{# enum CUjit_fallback as JITFallback\n { underscoreToCase }\n with prefix=\"CU_PREFER\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Module management\n--------------------------------------------------------------------------------\n\n-- |\n-- Returns a function handle\n--\ngetFun :: Module -> String -> IO Fun\ngetFun mdl fn = resultIfOk =<< cuModuleGetFunction mdl fn\n\n{# fun unsafe cuModuleGetFunction\n { alloca- `Fun' peekFun*\n , useModule `Module'\n , withCString* `String' } -> `Status' cToEnum #}\n where peekFun = liftM Fun . peek\n\n\n-- |\n-- Return a global pointer, and size of the global (in bytes)\n--\ngetPtr :: Module -> String -> IO (DevicePtr a, Int)\ngetPtr mdl name = do\n (status,dptr,bytes) <- cuModuleGetGlobal mdl name\n resultIfOk (status,(dptr,bytes))\n\n{# fun unsafe cuModuleGetGlobal\n { alloca- `DevicePtr a' peekDevPtr*\n , alloca- `Int' peekIntConv*\n , useModule `Module'\n , withCString* `String' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return a handle to a texture reference\n--\ngetTex :: Format a => Module -> String -> IO (Texture a)\ngetTex mdl name = do\n tex <- resultIfOk =<< cuModuleGetTexRef mdl name\n setFormat tex\n return tex\n\n{# fun unsafe cuModuleGetTexRef\n { alloca- `Texture a' peekTex*\n , useModule `Module'\n , withCString* `String' } -> `Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the specified file (either a ptx or cubin file) to\n-- create a new module, and load that module into the current context\n--\nloadFile :: FilePath -> IO Module\nloadFile ptx = resultIfOk =<< cuModuleLoad ptx\n\n{# fun unsafe cuModuleLoad\n { alloca- `Module' peekMod*\n , withCString* `FilePath' } -> `Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a new module, and load that module\n-- into the current context. The image (typically) is the contents of a cubin or\n-- ptx file as a NULL-terminated string.\n--\nloadData :: ByteString -> IO Module\nloadData img = resultIfOk =<< cuModuleLoadData img\n\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , useByteString* `ByteString' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load a module with online compiler options. The actual attributes of the\n-- compiled kernel can be probed using `requirements'.\n--\nloadDataEx :: ByteString -> [JITOption] -> IO (Module, JITResult)\nloadDataEx img options =\n allocaArray logSize $ \\p_ilog ->\n allocaArray logSize $ \\p_elog ->\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first\n , (JIT_INFO_LOG_BUFFER_SIZE_BYTES, logSize)\n , (JIT_ERROR_LOG_BUFFER_SIZE_BYTES, logSize)\n , (JIT_INFO_LOG_BUFFER, unsafeCoerce (p_ilog :: CString))\n , (JIT_ERROR_LOG_BUFFER, unsafeCoerce (p_elog :: CString)) ] ++ map unpack options in\n\n withArray (map cFromEnum opt) $ \\p_opts ->\n withArray (map unsafeCoerce val) $ \\p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img (length opt) p_opts p_vals\n infoLog <- B.packCString p_ilog\n errLog <- B.packCString p_elog\n time <- peek (castPtr p_vals)\n resultIfOk (s, (mdl, JITResult time infoLog errLog))\n\n where\n logSize = 2048\n\n unpack (MaxRegisters x) = (JIT_MAX_REGISTERS, x)\n unpack (ThreadsPerBlock x) = (JIT_THREADS_PER_BLOCK, x)\n unpack (OptimisationLevel x) = (JIT_OPTIMIZATION_LEVEL, x)\n unpack (Target x) = (JIT_TARGET, fromEnum x)\n\n\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , useByteString* `ByteString'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context\n--\nunload :: Module -> IO ()\nunload m = nothingIfOk =<< cuModuleUnload m\n\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\nuseByteString :: ByteString -> (Ptr a -> IO b) -> IO b\nuseByteString bs act = B.useAsCString bs $ \\p -> act (castPtr p)\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : (c) [2009..2010] Trevor L. McDonell\n-- License : BSD\n--\n-- Module management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Module\n (\n Module,\n JITOption(..), JITTarget(..), JITResult(..),\n getFun, getPtr, getTex,\n loadFile, loadData, loadDataEx, unload\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Ptr\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Exec\nimport Foreign.CUDA.Driver.Marshal (peekDevPtr)\nimport Foreign.CUDA.Driver.Texture hiding (getPtr)\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Unsafe.Coerce\n\nimport Control.Monad (liftM)\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as B\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A reference to a Module object, containing collections of device functions\n--\nnewtype Module = Module { useModule :: {# type CUmodule #}}\n\n\n-- |\n-- Just-in-time compilation options\n--\ndata JITOption\n = MaxRegisters Int -- ^ maximum number of registers per thread\n | ThreadsPerBlock Int -- ^ number of threads per block to target for\n | OptimisationLevel Int -- ^ level of optimisation to apply (1-4, default 4)\n | Target JITTarget -- ^ compilation target, otherwise determined from context\n-- | FallbackStrategy JITFallback\n deriving (Show)\n\n-- |\n-- Results of online compilation\n--\ndata JITResult = JITResult\n {\n jitTime :: Float, -- ^ milliseconds spent compiling PTX\n jitInfoLog :: ByteString, -- ^ information about PTX asembly\n jitErrorLog :: ByteString -- ^ compilation errors\n }\n deriving (Show)\n\n\n{# enum CUjit_option as JITOptionInternal\n { }\n with prefix=\"CU\" deriving (Eq, Show) #}\n\n{# enum CUjit_target as JITTarget\n { underscoreToCase }\n with prefix=\"CU_TARGET\" deriving (Eq, Show) #}\n\n{# enum CUjit_fallback as JITFallback\n { underscoreToCase }\n with prefix=\"CU_PREFER\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Module management\n--------------------------------------------------------------------------------\n\n-- |\n-- Returns a function handle\n--\ngetFun :: Module -> String -> IO Fun\ngetFun mdl fn = resultIfOk =<< cuModuleGetFunction mdl fn\n\n{# fun unsafe cuModuleGetFunction\n { alloca- `Fun' peekFun*\n , useModule `Module'\n , withCString* `String' } -> `Status' cToEnum #}\n where peekFun = liftM Fun . peek\n\n\n-- |\n-- Return a global pointer, and size of the global (in bytes)\n--\ngetPtr :: Module -> String -> IO (DevicePtr a, Int)\ngetPtr mdl name = do\n (status,dptr,bytes) <- cuModuleGetGlobal mdl name\n resultIfOk (status,(dptr,bytes))\n\n{# fun unsafe cuModuleGetGlobal\n { alloca- `DevicePtr a' peekDevPtr*\n , alloca- `Int' peekIntConv*\n , useModule `Module'\n , withCString* `String' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return a handle to a texture reference\n--\ngetTex :: Format a => Module -> String -> IO (Texture a)\ngetTex mdl name = do\n tex <- resultIfOk =<< cuModuleGetTexRef mdl name\n setFormat tex\n return tex\n\n{# fun unsafe cuModuleGetTexRef\n { alloca- `Texture a' peekTex*\n , useModule `Module'\n , withCString* `String' } -> `Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the specified file (either a ptx or cubin file) to\n-- create a new module, and load that module into the current context\n--\nloadFile :: String -> IO Module\nloadFile ptx = resultIfOk =<< cuModuleLoad ptx\n\n{# fun unsafe cuModuleLoad\n { alloca- `Module' peekMod*\n , withCString* `String' } -> `Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a new module, and load that module\n-- into the current context. The image (typically) is the contents of a cubin or\n-- ptx file as a NULL-terminated string.\n--\nloadData :: ByteString -> IO Module\nloadData img = resultIfOk =<< cuModuleLoadData img\n\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , useByteString* `ByteString' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load a module with online compiler options. The actual attributes of the\n-- compiled kernel can be probed using `requirements'.\n--\nloadDataEx :: ByteString -> [JITOption] -> IO (Module, JITResult)\nloadDataEx img options =\n allocaArray logSize $ \\p_ilog ->\n allocaArray logSize $ \\p_elog ->\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first\n , (JIT_INFO_LOG_BUFFER_SIZE_BYTES, logSize)\n , (JIT_ERROR_LOG_BUFFER_SIZE_BYTES, logSize)\n , (JIT_INFO_LOG_BUFFER, unsafeCoerce (p_ilog :: CString))\n , (JIT_ERROR_LOG_BUFFER, unsafeCoerce (p_elog :: CString)) ] ++ map unpack options in\n\n withArray (map cFromEnum opt) $ \\p_opts ->\n withArray (map unsafeCoerce val) $ \\p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img (length opt) p_opts p_vals\n infoLog <- B.packCString p_ilog\n errLog <- B.packCString p_elog\n time <- peek (castPtr p_vals)\n resultIfOk (s, (mdl, JITResult time infoLog errLog))\n\n where\n logSize = 2048\n\n unpack (MaxRegisters x) = (JIT_MAX_REGISTERS, x)\n unpack (ThreadsPerBlock x) = (JIT_THREADS_PER_BLOCK, x)\n unpack (OptimisationLevel x) = (JIT_OPTIMIZATION_LEVEL, x)\n unpack (Target x) = (JIT_TARGET, fromEnum x)\n\n\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , useByteString* `ByteString'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context\n--\nunload :: Module -> IO ()\nunload m = nothingIfOk =<< cuModuleUnload m\n\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\nuseByteString :: ByteString -> (Ptr a -> IO b) -> IO b\nuseByteString bs act = B.useAsCString bs $ \\p -> act (castPtr p)\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"7f59701dc6b27e24981d06806fb2664da1ab64e6","subject":"adjust iconLoaded signal","message":"adjust iconLoaded signal","repos":"vincenthz\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/WebView.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/WebView.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebView\n-- Author : Cjacker Huang\n-- Copyright : (c) 2009 Cjacker Huang \n-- Copyright : (c) 2010 Andy Stewart \n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Note:\n--\n-- Signal `window-object-cleared` can't bidning now, \n-- because it need JavaScriptCore that haven't binding.\n--\n-- Signal `create-plugin-widget` can't binding now, \n-- no idea how to binding `GHaskellTable`\n--\n--\n-- TODO:\n--\n-- `webViewGetHitTestResult`\n--\n-- The central class of the WebKit\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebView (\n-- * Description\n-- | WebKitWebView is the central class of the WebKitGTK+ API. It is a 'Widget' implementing the\n-- scrolling interface which means you can embed in a 'ScrolledWindow'. It is responsible for managing\n-- the drawing of the content, forwarding of events. You can load any URI into the WebKitWebView or any\n-- kind of data string. With WebKitWebSettings you can control various aspects of the rendering and\n-- loading of the content. Each WebKitWebView has exactly one WebKitWebFrame as main frame. A\n-- WebKitWebFrame can have n children.\n\n-- * Types\n WebView,\n WebViewClass,\n\n-- * Enums\n NavigationResponse(..),\n TargetInfo(..),\n LoadStatus(..),\n\n-- * Constructors\n webViewNew,\n\n-- * Methods\n-- ** Load\n webViewLoadUri,\n webViewLoadHtmlString,\n webViewLoadRequest,\n webViewLoadString,\n-- ** Reload\n webViewStopLoading,\n webViewReload,\n webViewReloadBypassCache,\n-- ** History\n webViewCanGoBack,\n webViewCanGoForward,\n webViewGoBack,\n webViewGoForward,\n webViewGetBackForwardList,\n webViewSetMaintainsBackForwardList,\n webViewGoToBackForwardItem,\n webViewCanGoBackOrForward,\n webViewGoBackOrForward,\n-- ** Zoom\n webViewGetZoomLevel,\n webViewSetZoomLevel,\n webViewZoomIn,\n webViewZoomOut,\n webViewGetFullContentZoom,\n webViewSetFullContentZoom,\n-- ** Clipboard\n webViewCanCutClipboard,\n webViewCanCopyClipboard,\n webViewCanPasteClipboard,\n webViewCutClipboard,\n webViewCopyClipboard,\n webViewPasteClipboard,\n-- ** Undo\/Redo\n webViewCanRedo,\n webViewCanUndo,\n webViewRedo,\n webViewUndo,\n-- ** Selection\n webViewDeleteSelection,\n webViewHasSelection,\n webViewSelectAll,\n-- ** Encoding\n webViewGetEncoding,\n webViewSetCustomEncoding,\n webViewGetCustomEncoding,\n-- ** Source Mode\n webViewGetViewSourceMode,\n webViewSetViewSourceMode,\n-- ** Transparent\n webViewGetTransparent,\n webViewSetTransparent,\n-- ** Target List\n webViewGetCopyTargetList,\n webViewGetPasteTargetList,\n-- ** Text Match\n webViewMarkTextMatches,\n webViewUnMarkTextMatches,\n webViewSetHighlightTextMatches,\n-- ** Other\n webViewExecuteScript,\n \n webViewCanShowMimeType,\n webViewGetEditable,\n webViewSetEditable,\n webViewGetInspector,\n\n webViewGetProgress,\n\n webViewSearchText,\n\n webViewMoveCursor,\n\n webViewGetMainFrame,\n webViewGetFocusedFrame,\n\n webViewSetWebSettings,\n webViewGetWebSettings,\n\n webViewGetWindowFeatures,\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n webViewGetIconUri,\n#endif\n\n webViewGetTitle,\n webViewGetUri,\n\n-- * Attributes\n webViewZoomLevel,\n webViewFullContentZoom,\n webViewEncoding,\n webViewCustomEncoding,\n webViewLoadStatus,\n webViewProgress,\n webViewTitle,\n webViewInspector,\n webViewWebSettings,\n webViewViewSourceMode,\n webViewTransparent,\n webViewEditable,\n webViewUri,\n webViewCopyTargetList,\n webViewPasteTargetList,\n webViewWindowFeatures,\n#if WEBKIT_CHECK_VERSION (1,1,18)\n webViewIconUri,\n#endif\n\n#if WEBKIT_CHECK_VERSION (1,1,20)\n webViewImContext,\n#endif\n \n-- * Signals\n loadStarted,\n loadCommitted,\n progressChanged,\n loadFinished,\n loadError,\n titleChanged,\n hoveringOverLink,\n createWebView,\n webViewReady,\n closeWebView,\n consoleMessage,\n copyClipboard,\n cutClipboard,\n pasteClipboard,\n populatePopup,\n printRequested,\n scriptAlert,\n scriptConfirm,\n scriptPrompt,\n statusBarTextChanged,\n selectAll,\n selectionChanged,\n setScrollAdjustments,\n databaseQuotaExceeded,\n documentLoadFinished,\n downloadRequested,\n#if WEBKIT_CHECK_VERSION (1,1,18)\n iconLoaded,\n#endif\n redo,\n undo,\n mimeTypePolicyDecisionRequested,\n moveCursor,\n navigationPolicyDecisionRequested,\n newWindowPolicyDecisionRequested,\n resourceRequestStarting,\n#if WEBKIT_CHECK_VERSION (1,1,23)\n geolocationPolicyDecisionCancelled,\n geolocationPolicyDecisionRequested,\n#endif\n) where\n\nimport Control.Monad\t\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GList\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GError \nimport Graphics.UI.Gtk.Gdk.Events\n\n{#import Graphics.UI.Gtk.Abstract.Object#}\t(makeNewObject)\n{#import Graphics.UI.Gtk.WebKit.Types#}\n{#import Graphics.UI.Gtk.WebKit.Signals#}\n{#import Graphics.UI.Gtk.WebKit.Internal#}\n{#import System.Glib.GObject#}\n{#import Graphics.UI.Gtk.General.Selection#} ( TargetList )\n{#import Graphics.UI.Gtk.MenuComboToolbar.Menu#}\n{#import Graphics.UI.Gtk.General.Enums#}\n\n{#context lib=\"webkit\" prefix =\"webkit\"#}\n\n------------------\n-- Enums\n\n{#enum NavigationResponse {underscoreToCase}#}\n\n{#enum WebViewTargetInfo as TargetInfo {underscoreToCase}#}\n\n{#enum LoadStatus {underscoreToCase}#}\n\n------------------\n-- Constructors\n\n\n-- | Create a new 'WebView' widget.\n-- \n-- It is a 'Widget' you can embed in a 'ScrolledWindow'.\n-- \n-- You can load any URI into the 'WebView' or any kind of data string.\nwebViewNew :: IO WebView \nwebViewNew = do\n isGthreadInited <- liftM toBool {#call g_thread_get_initialized#}\n if not isGthreadInited then {#call g_thread_init#} nullPtr \n else return ()\n makeNewObject mkWebView $ liftM castPtr {#call web_view_new#}\n\n\n-- | Apply 'WebSettings' to a given 'WebView'\n-- \n-- !!NOTE!!, currently lack of useful APIs of 'WebSettings' in webkitgtk.\n-- If you want to set the encoding, font family or font size of the 'WebView',\n-- please use related functions.\n\nwebViewSetWebSettings :: \n (WebViewClass self, WebSettingsClass settings) => self\n -> settings\n -> IO ()\nwebViewSetWebSettings webview websettings = \n {#call web_view_set_settings#} (toWebView webview) (toWebSettings websettings)\n\n-- | Return the 'WebSettings' currently used by 'WebView'.\nwebViewGetWebSettings :: \n WebViewClass self => self\n -> IO WebSettings\nwebViewGetWebSettings webview = \n makeNewGObject mkWebSettings $ {#call web_view_get_settings#} (toWebView webview)\n\n-- | Returns the instance of WebKitWebWindowFeatures held by the given WebKitWebView.\nwebViewGetWindowFeatures ::\n WebViewClass self => self\n -> IO WebWindowFeatures \nwebViewGetWindowFeatures webview =\n makeNewGObject mkWebWindowFeatures $ {#call web_view_get_window_features#} (toWebView webview)\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n-- | Obtains the URI for the favicon for the given WebKitWebView, or 'Nothing' if there is none.\n--\n-- * Since 1.1.18\nwebViewGetIconUri :: WebViewClass self => self -> IO (Maybe String)\nwebViewGetIconUri webview =\n {#call webkit_web_view_get_icon_uri #} (toWebView webview)\n >>= maybePeek peekUTFString\n#endif\n\n\n-- | Return the main 'WebFrame' of the given 'WebView'.\nwebViewGetMainFrame :: \n WebViewClass self => self\n -> IO WebFrame\nwebViewGetMainFrame webview = \n makeNewGObject mkWebFrame $ {#call web_view_get_main_frame#} (toWebView webview)\n\n-- | Return the focused 'WebFrame' of the given 'WebView'.\nwebViewGetFocusedFrame :: \n WebViewClass self => self\n -> IO WebFrame\nwebViewGetFocusedFrame webview = \n makeNewGObject mkWebFrame $ {#call web_view_get_focused_frame#} (toWebView webview)\n\n\n-- |Requests loading of the specified URI string in a 'WebView'\nwebViewLoadUri :: \n WebViewClass self => self \n -> String -- ^ @uri@ - an URI string.\n -> IO()\nwebViewLoadUri webview url =\n withCString url $ \\urlPtr -> {#call web_view_load_uri#}\n (toWebView webview)\n urlPtr\n\n-- |Determine whether 'WebView' has a previous history item.\nwebViewCanGoBack :: \n WebViewClass self => self\n -> IO Bool -- ^ True if able to move back, False otherwise.\nwebViewCanGoBack webview = \n liftM toBool $ {#call web_view_can_go_back#} (toWebView webview)\n\n-- |Determine whether 'WebView' has a next history item.\nwebViewCanGoForward :: \n WebViewClass self => self \n -> IO Bool -- ^ True if able to move forward, False otherwise.\nwebViewCanGoForward webview = \n liftM toBool $ {#call web_view_can_go_forward#} (toWebView webview)\n\n-- |Loads the previous history item.\nwebViewGoBack :: \n WebViewClass self => self\n -> IO () \nwebViewGoBack webview =\n {#call web_view_go_back#} (toWebView webview)\n\n-- |Loads the next history item.\nwebViewGoForward :: \n WebViewClass self => self\n -> IO ()\nwebViewGoForward webview =\n {#call web_view_go_forward#} (toWebView webview)\n\n-- |Set the 'WebView' to maintian a back or forward list of history items.\nwebViewSetMaintainsBackForwardList :: \n WebViewClass self => self \n -> Bool -- ^ @flag@ - to tell the view to maintain a back or forward list. \n -> IO()\nwebViewSetMaintainsBackForwardList webview flag = \n {#call web_view_set_maintains_back_forward_list#} \n (toWebView webview)\n (fromBool flag)\n\n-- |Return the 'WebBackForwardList'\nwebViewGetBackForwardList :: \n WebViewClass self => self\n -> IO WebBackForwardList\nwebViewGetBackForwardList webview = \n makeNewGObject mkWebBackForwardList $ \n {#call web_view_get_back_forward_list#} \n (toWebView webview)\n\n-- |Go to the specified 'WebHistoryItem'\n\nwebViewGoToBackForwardItem :: \n (WebViewClass self, WebHistoryItemClass item) => self \n -> item\n -> IO Bool -- ^ True if loading of item is successful, False if not.\nwebViewGoToBackForwardItem webview item = \n liftM toBool $ {#call web_view_go_to_back_forward_item#} (toWebView webview) (toWebHistoryItem item)\n\n-- |Determines whether 'WebView' has a history item of @steps@.\n--\n-- Negative values represent steps backward while positive values\n-- represent steps forward\n\nwebViewCanGoBackOrForward :: \n WebViewClass self => self\n -> Int -- ^ @steps@ - the number of steps \n -> IO Bool -- ^ True if able to move back or forward the given number of steps,\n -- False otherwise\nwebViewCanGoBackOrForward webview steps =\n liftM toBool $ \n {#call web_view_can_go_back_or_forward#} \n (toWebView webview)\n (fromIntegral steps)\n\n-- |Loads the history item that is the number of @steps@ away from the current item.\n--\n-- Negative values represent steps backward while positive values represent steps forward.\n\nwebViewGoBackOrForward :: \n WebViewClass self => self\n -> Int\n -> IO ()\nwebViewGoBackOrForward webview steps =\n {#call web_view_go_back_or_forward#} \n (toWebView webview)\n (fromIntegral steps)\n\n-- |Determines whether or not it is currently possible to redo the last editing command in the view\nwebViewCanRedo :: \n WebViewClass self => self\n -> IO Bool\nwebViewCanRedo webview = \n liftM toBool $\n {#call web_view_can_redo#} (toWebView webview)\n-- |Determines whether or not it is currently possible to undo the last editing command in the view\nwebViewCanUndo :: \n WebViewClass self => self\n -> IO Bool\nwebViewCanUndo webview =\n liftM toBool $\n {#call web_view_can_undo#} (toWebView webview)\n\n-- |Redoes the last editing command in the view, if possible.\nwebViewRedo :: \n WebViewClass self => self\n -> IO()\nwebViewRedo webview =\n {#call web_view_redo#} (toWebView webview)\n\n-- |Undoes the last editing command in the view, if possible.\nwebViewUndo :: \n WebViewClass self => self\n -> IO()\nwebViewUndo webview =\n {#call web_view_undo#} (toWebView webview)\n\n-- | Returns whether or not a @mimetype@ can be displayed using this view.\nwebViewCanShowMimeType :: \n WebViewClass self => self\n -> String -- ^ @mimetype@ - a MIME type\n -> IO Bool -- ^ True if the @mimetype@ can be displayed, otherwise False\nwebViewCanShowMimeType webview mime =\n withCString mime $ \\mimePtr ->\n liftM toBool $\n {#call web_view_can_show_mime_type#}\n (toWebView webview)\n mimePtr\n\n-- | Returns whether the user is allowed to edit the document.\nwebViewGetEditable :: \n WebViewClass self => self\n -> IO Bool\nwebViewGetEditable webview =\n liftM toBool $\n {#call web_view_get_editable#} (toWebView webview)\n\n-- | Sets whether allows the user to edit its HTML document.\nwebViewSetEditable :: \n WebViewClass self => self\n -> Bool\n -> IO ()\nwebViewSetEditable webview editable =\n {#call web_view_set_editable#} (toWebView webview) (fromBool editable)\n\n-- | Returns whether 'WebView' is in view source mode\nwebViewGetViewSourceMode :: \n WebViewClass self => self\n -> IO Bool\nwebViewGetViewSourceMode webview =\n liftM toBool $\n {#call web_view_get_view_source_mode#} (toWebView webview)\n\n-- | Set whether the view should be in view source mode. \n--\n-- Setting this mode to TRUE before loading a URI will display \n-- the source of the web page in a nice and readable format.\nwebViewSetViewSourceMode :: \n WebViewClass self => self\n -> Bool\n -> IO ()\nwebViewSetViewSourceMode webview mode =\n {#call web_view_set_view_source_mode#} (toWebView webview) (fromBool mode)\n\n-- | Returns whether the 'WebView' has a transparent background\nwebViewGetTransparent :: \n WebViewClass self => self\n -> IO Bool\nwebViewGetTransparent webview =\n liftM toBool $\n {#call web_view_get_transparent#} (toWebView webview)\n-- |Sets whether the WebKitWebView has a transparent background.\n--\n-- Pass False to have the 'WebView' draw a solid background (the default), \n-- otherwise pass True.\nwebViewSetTransparent :: \n WebViewClass self => self\n -> Bool\n -> IO ()\nwebViewSetTransparent webview trans =\n {#call web_view_set_transparent#} (toWebView webview) (fromBool trans)\n\n-- |Obtains the 'WebInspector' associated with the 'WebView'\nwebViewGetInspector :: \n WebViewClass self => self\n -> IO WebInspector\nwebViewGetInspector webview =\n makeNewGObject mkWebInspector $ {#call web_view_get_inspector#} (toWebView webview)\n\n-- |Requests loading of the specified asynchronous client request.\n--\n-- Creates a provisional data source that will transition to a committed data source once\n-- any data has been received. \n-- use 'webViewStopLoading' to stop the load.\n\nwebViewLoadRequest :: \n (WebViewClass self, NetworkRequestClass request) => self\n -> request\n -> IO()\nwebViewLoadRequest webview request =\n {#call web_view_load_request#} (toWebView webview) (toNetworkRequest request)\n\n\n\n\n-- |Returns the zoom level of 'WebView'\n--\n-- i.e. the factor by which elements in the page are scaled with respect to their original size.\n\nwebViewGetZoomLevel :: \n WebViewClass self => self\n -> IO Float -- ^ the zoom level of 'WebView'\nwebViewGetZoomLevel webview =\n liftM realToFrac $\n\t{#call web_view_get_zoom_level#} (toWebView webview)\n\n-- |Sets the zoom level of 'WebView'.\nwebViewSetZoomLevel :: \n WebViewClass self => self \n -> Float -- ^ @zoom_level@ - the new zoom level \n -> IO ()\nwebViewSetZoomLevel webview zlevel = \n {#call web_view_set_zoom_level#} (toWebView webview) (realToFrac zlevel)\n\n-- |Loading the @content@ string as html. The URI passed in base_uri has to be an absolute URI.\n\nwebViewLoadHtmlString :: \n WebViewClass self => self \n -> String -- ^ @content@ - the html string\n -> String -- ^ @base_uri@ - the base URI\n -> IO()\nwebViewLoadHtmlString webview htmlstr url =\n withCString htmlstr $ \\htmlPtr ->\n withCString url $ \\urlPtr ->\n {#call web_view_load_html_string#} (toWebView webview) htmlPtr urlPtr\n\n-- | Requests loading of the given @content@ with the specified @mime_type@, @encoding@ and @base_uri@.\n-- \n-- If @mime_type@ is @Nothing@, \"text\/html\" is assumed.\n--\n-- If @encoding@ is @Nothing@, \"UTF-8\" is assumed.\n--\nwebViewLoadString :: \n WebViewClass self => self \n -> String -- ^ @content@ - the content string to be loaded.\n -> (Maybe String) -- ^ @mime_type@ - the MIME type or @Nothing@. \n -> (Maybe String) -- ^ @encoding@ - the encoding or @Nothing@.\n -> String -- ^ @base_uri@ - the base URI for relative locations.\n -> IO()\nwebViewLoadString webview content mimetype encoding baseuri = \n withCString content $ \\contentPtr ->\n maybeWith withCString mimetype $ \\mimetypePtr ->\n maybeWith withCString encoding $ \\encodingPtr ->\n withCString baseuri $ \\baseuriPtr ->\n {#call web_view_load_string#} \n (toWebView webview)\n contentPtr\n mimetypePtr\n encodingPtr\n baseuriPtr\n\n-- |Returns the 'WebView' document title\nwebViewGetTitle :: \n WebViewClass self => self\n -> IO (Maybe String) -- ^ the title of 'WebView' or Nothing in case of failed.\nwebViewGetTitle webview =\n {#call web_view_get_title#} (toWebView webview) >>= maybePeek peekUTFString\n\n-- |Returns the current URI of the contents displayed by the 'WebView'\nwebViewGetUri :: \n WebViewClass self => self\n -> IO (Maybe String) -- ^ the URI of 'WebView' or Nothing in case of failed.\nwebViewGetUri webview = \n {#call web_view_get_uri#} (toWebView webview) >>= maybePeek peekUTFString\n\n\n-- | Stops and pending loads on the given data source.\nwebViewStopLoading :: \n WebViewClass self => self\n -> IO ()\nwebViewStopLoading webview = \n {#call web_view_stop_loading#} (toWebView webview)\n\n-- | Reloads the 'WebView'\nwebViewReload :: \n WebViewClass self => self\n -> IO ()\nwebViewReload webview = \n {#call web_view_reload#} (toWebView webview)\n\n-- | Reloads the 'WebView' without using any cached data.\nwebViewReloadBypassCache :: \n WebViewClass self => self\n -> IO()\nwebViewReloadBypassCache webview = \n {#call web_view_reload_bypass_cache#} (toWebView webview)\n\n-- | Increases the zoom level of 'WebView'.\nwebViewZoomIn :: \n WebViewClass self => self\n -> IO()\nwebViewZoomIn webview = \n {#call web_view_zoom_in#} (toWebView webview)\n\n-- | Decreases the zoom level of 'WebView'.\nwebViewZoomOut :: \n WebViewClass self => self\n -> IO()\nwebViewZoomOut webview = \n {#call web_view_zoom_out#} (toWebView webview)\n\n-- | Looks for a specified string inside 'WebView'\nwebViewSearchText :: \n WebViewClass self => self\n -> String -- ^ @text@ - a string to look for\n -> Bool -- ^ @case_sensitive@ - whether to respect the case of text\n -> Bool -- ^ @forward@ - whether to find forward or not\n -> Bool -- ^ @wrap@ - whether to continue looking at beginning\n -- after reaching the end\n -> IO Bool -- ^ True on success or False on failure\nwebViewSearchText webview text case_sensitive forward wrap =\n withCString text $ \\textPtr ->\n\tliftM toBool $\n {#call web_view_search_text#} \n (toWebView webview)\n textPtr\n (fromBool case_sensitive) \n (fromBool forward) \n (fromBool wrap)\n\n-- |Attempts to highlight all occurances of string inside 'WebView'\nwebViewMarkTextMatches :: \n WebViewClass self => self\n -> String -- ^ @string@ - a string to look for\n -> Bool -- ^ @case_sensitive@ - whether to respect the case of text\n -> Int -- ^ @limit@ - the maximum number of strings to look for or 0 for all\n -> IO Int -- ^ the number of strings highlighted\nwebViewMarkTextMatches webview text case_sensitive limit = \n withCString text $ \\textPtr ->\n\tliftM fromIntegral $ \n {#call web_view_mark_text_matches#} \n (toWebView webview)\n textPtr\n (fromBool case_sensitive)\n (fromIntegral limit)\n\n-- | Move the cursor in view as described by step and count.\nwebViewMoveCursor ::\n WebViewClass self => self\n -> MovementStep\n -> Int\n -> IO () \nwebViewMoveCursor webview step count =\n {#call web_view_move_cursor#} (toWebView webview) (fromIntegral $ fromEnum step) (fromIntegral count)\n\n-- | Removes highlighting previously set by 'webViewMarkTextMarches'\nwebViewUnMarkTextMatches :: \n WebViewClass self => self\n -> IO ()\nwebViewUnMarkTextMatches webview = \n {#call web_view_unmark_text_matches#} (toWebView webview)\n\n-- | Highlights text matches previously marked by 'webViewMarkTextMatches'\nwebViewSetHighlightTextMatches :: \n WebViewClass self => self\n -> Bool -- ^ @highlight@ - whether to highlight text matches \n -> IO ()\nwebViewSetHighlightTextMatches webview highlight =\n {#call web_view_set_highlight_text_matches#} \n (toWebView webview)\n (fromBool highlight)\n\n-- | Execute the script specified by @script@\nwebViewExecuteScript :: \n WebViewClass self => self \n -> String -- ^ @script@ - script to be executed\n -> IO()\nwebViewExecuteScript webview script =\n withCString script $ \\scriptPtr ->\n\t{#call web_view_execute_script#} (toWebView webview) scriptPtr\n\n-- | Determines whether can cuts the current selection\n-- inside 'WebView' to the clipboard\nwebViewCanCutClipboard :: \n WebViewClass self => self\n -> IO Bool\nwebViewCanCutClipboard webview = \n liftM toBool $ {#call web_view_can_cut_clipboard#} (toWebView webview)\n\n-- | Determines whether can copies the current selection\n-- inside 'WebView' to the clipboard\nwebViewCanCopyClipboard :: WebViewClass self => self -> IO Bool\nwebViewCanCopyClipboard webview = \n liftM toBool $ {#call web_view_can_copy_clipboard#} (toWebView webview)\n\n-- | Determines whether can pastes the current contents of the clipboard\n-- to the 'WebView'\nwebViewCanPasteClipboard :: WebViewClass self => self -> IO Bool\nwebViewCanPasteClipboard webview = \n liftM toBool $ {#call web_view_can_paste_clipboard#} (toWebView webview)\n\n-- | Cuts the current selection inside 'WebView' to the clipboard.\nwebViewCutClipboard :: WebViewClass self => self -> IO()\nwebViewCutClipboard webview = \n {#call web_view_cut_clipboard#} (toWebView webview)\n\n-- | Copies the current selection inside 'WebView' to the clipboard.\nwebViewCopyClipboard :: WebViewClass self => self -> IO()\nwebViewCopyClipboard webview = \n {#call web_view_copy_clipboard#} (toWebView webview)\n\n-- | Pastes the current contents of the clipboard to the 'WebView'\nwebViewPasteClipboard :: WebViewClass self => self -> IO()\nwebViewPasteClipboard webview = \n {#call web_view_paste_clipboard#} (toWebView webview)\n\n-- | Deletes the current selection inside the 'WebView'\nwebViewDeleteSelection :: WebViewClass self => self -> IO ()\nwebViewDeleteSelection webview = \n {#call web_view_delete_selection#} (toWebView webview)\n\n-- | Determines whether text was selected\nwebViewHasSelection :: WebViewClass self => self -> IO Bool\nwebViewHasSelection webview = \n liftM toBool $ {#call web_view_has_selection#} (toWebView webview)\n\n-- | Attempts to select everything inside the 'WebView'\nwebViewSelectAll :: WebViewClass self => self -> IO ()\nwebViewSelectAll webview = \n {#call web_view_select_all#} (toWebView webview)\n\n-- | Returns whether the zoom level affects only text or all elements.\nwebViewGetFullContentZoom :: \n WebViewClass self => self \n -> IO Bool -- ^ False if only text should be scaled(the default)\n -- True if the full content of the view should be scaled.\nwebViewGetFullContentZoom webview = \n liftM toBool $ {#call web_view_get_full_content_zoom#} (toWebView webview)\n\n-- | Sets whether the zoom level affects only text or all elements.\nwebViewSetFullContentZoom :: \n WebViewClass self => self \n -> Bool -- ^ @full_content_zoom@ - False if only text should be scaled (the default)\n -- True if the full content of the view should be scaled. \n -> IO ()\nwebViewSetFullContentZoom webview full =\n {#call web_view_set_full_content_zoom#} (toWebView webview) (fromBool full)\n\n-- | Returns the default encoding of the 'WebView'\nwebViewGetEncoding :: \n WebViewClass self => self \n -> IO (Maybe String) -- ^ the default encoding or @Nothing@ in case of failed\nwebViewGetEncoding webview =\n {#call web_view_get_encoding#} (toWebView webview) >>= maybePeek peekUTFString\n\n-- | Sets the current 'WebView' encoding, \n-- without modifying the default one, and reloads the page\nwebViewSetCustomEncoding :: \n WebViewClass self => self\n -> (Maybe String) -- ^ @encoding@ - the new encoding, \n -- or @Nothing@ to restore the default encoding. \n -> IO ()\nwebViewSetCustomEncoding webview encoding = \n maybeWith withCString encoding $ \\encodingPtr ->\n\t{#call web_view_set_custom_encoding#} (toWebView webview) encodingPtr\n\n-- | Returns the current encoding of 'WebView',not the default encoding.\nwebViewGetCustomEncoding :: \n WebViewClass self => self \n -> IO (Maybe String) -- ^ the current encoding string\n -- or @Nothing@ if there is none set.\nwebViewGetCustomEncoding webview = \n {#call web_view_get_custom_encoding#} (toWebView webview) >>= maybePeek peekUTFString\n\n-- | Determines the current status of the load.\nwebViewGetLoadStatus :: \n WebViewClass self => self \n -> IO LoadStatus -- ^ the current load status:'LoadStatus'\nwebViewGetLoadStatus webview = \n liftM (toEnum . fromIntegral) $ {#call web_view_get_load_status#} (toWebView webview)\n\n-- | Determines the current progress of the load\nwebViewGetProgress :: \n WebViewClass self => self \n -> IO Double -- ^ the load progress\nwebViewGetProgress webview =\n liftM realToFrac $ {#call web_view_get_progress#} (toWebView webview)\n\n-- | This function returns the list of targets this 'WebView' can provide for clipboard copying and as DND source. \n-- The targets in the list are added with values from the 'WebViewTargetInfo' enum, \n-- using 'targetListAdd' and 'targetListAddTextTargets'.\nwebViewGetCopyTargetList ::\n WebViewClass self => self \n -> IO (Maybe TargetList)\nwebViewGetCopyTargetList webview = do\n tlPtr <- {#call web_view_get_copy_target_list#} (toWebView webview)\n if tlPtr==nullPtr then return Nothing else liftM Just (mkTargetList tlPtr)\n\n-- | This function returns the list of targets this 'WebView' can provide for clipboard pasteing and as DND source. \n-- The targets in the list are added with values from the 'WebViewTargetInfo' enum, \n-- using 'targetListAdd' and 'targetListAddTextTargets'.\nwebViewGetPasteTargetList ::\n WebViewClass self => self \n -> IO (Maybe TargetList)\nwebViewGetPasteTargetList webview = do\n tlPtr <- {#call web_view_get_paste_target_list#} (toWebView webview)\n if tlPtr==nullPtr then return Nothing else liftM Just (mkTargetList tlPtr)\n\n-- * Attibutes\n\n-- | Zoom level of the 'WebView' instance\nwebViewZoomLevel :: WebViewClass self => Attr self Float\nwebViewZoomLevel = newAttr\n webViewGetZoomLevel\n webViewSetZoomLevel\n\n-- | Whether the full content is scaled when zooming\n--\n-- Default value: False\nwebViewFullContentZoom :: WebViewClass self => Attr self Bool\nwebViewFullContentZoom = newAttr\n webViewGetFullContentZoom\n webViewSetFullContentZoom\n\n-- | The default encoding of the 'WebView' instance\n--\n-- Default value: @Nothing@\nwebViewEncoding :: WebViewClass self => ReadAttr self (Maybe String)\nwebViewEncoding = readAttr webViewGetEncoding\n\n-- | Determines the current status of the load.\n--\n-- Default value: @LoadFinished@\nwebViewLoadStatus :: WebViewClass self => ReadAttr self LoadStatus\nwebViewLoadStatus = readAttr webViewGetLoadStatus\n\n-- |Determines the current progress of the load\n--\n-- Default Value: 1\nwebViewProgress :: WebViewClass self => ReadAttr self Double\nwebViewProgress = readAttr webViewGetProgress\n\n\n-- | The associated webSettings of the 'WebView' instance\nwebViewWebSettings :: WebViewClass self => Attr self WebSettings\nwebViewWebSettings = newAttr\n webViewGetWebSettings\n webViewSetWebSettings\n\n\n-- | Title of the 'WebView' instance\nwebViewTitle :: WebViewClass self => ReadAttr self (Maybe String)\nwebViewTitle = readAttr webViewGetTitle\n\n-- | The associated webInspector instance of the 'WebView'\nwebViewInspector :: WebViewClass self => ReadAttr self WebInspector\nwebViewInspector = readAttr webViewGetInspector\n\n\n-- | The custom encoding of the 'WebView' instance\n--\n-- Default value: @Nothing@\nwebViewCustomEncoding :: WebViewClass self => Attr self (Maybe String)\nwebViewCustomEncoding = newAttr\n webViewGetCustomEncoding\n webViewSetCustomEncoding\n\n-- | view source mode of the 'WebView' instance\nwebViewViewSourceMode :: WebViewClass self => Attr self Bool\nwebViewViewSourceMode = newAttr\n webViewGetViewSourceMode\n webViewSetViewSourceMode\n\n-- | transparent background of the 'WebView' instance\nwebViewTransparent :: WebViewClass self => Attr self Bool\nwebViewTransparent = newAttr\n webViewGetTransparent\n webViewSetTransparent\n\n-- | Whether content of the 'WebView' can be modified by the user\n--\n-- Default value: @False@\nwebViewEditable :: WebViewClass self => Attr self Bool\nwebViewEditable = newAttr\n webViewGetEditable\n webViewSetEditable\n\n-- | Returns the current URI of the contents displayed by the @web_view@.\n--\n-- Default value: Nothing\nwebViewUri :: WebViewClass self => ReadAttr self (Maybe String)\nwebViewUri = readAttr webViewGetUri\n\n-- | The list of targets this web view supports for clipboard copying.\nwebViewCopyTargetList :: WebViewClass self => ReadAttr self (Maybe TargetList)\nwebViewCopyTargetList = readAttr webViewGetCopyTargetList\n\n-- | The list of targets this web view supports for clipboard pasteing.\nwebViewPasteTargetList :: WebViewClass self => ReadAttr self (Maybe TargetList)\nwebViewPasteTargetList = readAttr webViewGetPasteTargetList\n\n-- | An associated 'WebWindowFeatures' instance.\nwebViewWindowFeatures :: WebViewClass self => Attr self WebWindowFeatures\nwebViewWindowFeatures = \n newAttrFromObjectProperty \"window-features\"\n {#call pure webkit_web_window_features_get_type#}\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n-- | The URI for the favicon for the WebKitWebView.\n-- \n-- Default value: 'Nothing'\n-- \n-- * Since 1.1.18\nwebViewIconUri :: WebViewClass self => ReadAttr self String\nwebViewIconUri = readAttrFromStringProperty \"icon-uri\"\n#endif\n\n#if WEBKIT_CHECK_VERSION (1,1,20)\n-- | The 'IMMulticontext' for the WebKitWebView.\n-- \n-- This is the input method context used for all text entry widgets inside the WebKitWebView. It can be\n-- used to generate context menu items for controlling the active input method.\n-- \n-- * Since 1.1.20\nwebViewImContext :: WebViewClass self => ReadAttr self IMContext\nwebViewImContext = \n readAttrFromObjectProperty \"im-context\"\n {#call pure gtk_im_context_get_type #}\n#endif\n\n-- * Signals\n\n-- | When Document title changed, this signal is emitted.\n--\n-- It can be used to set the Application 'Window' title.\n--\n-- the user function signature is (WebFrame->String->IO())\n--\n-- webframe - which 'WebFrame' changes the document title.\n--\n-- title - current title string.\ntitleChanged :: WebViewClass self => Signal self ( WebFrame -> String -> IO() )\ntitleChanged = \n Signal (connect_OBJECT_STRING__NONE \"title-changed\")\n\n\n-- | When the cursor is over a link, this signal is emitted.\n-- \n-- the user function signature is (Maybe String -> Maybe String -> IO () )\n-- \n-- title - the link's title or @Nothing@ in case of failure.\n--\n-- uri - the URI the link points to or @Nothing@ in case of failure.\nhoveringOverLink :: WebViewClass self => Signal self (Maybe String -> Maybe String -> IO())\nhoveringOverLink =\n Signal (connect_MSTRING_MSTRING__NONE \"hovering-over-link\")\n\n-- | When a 'WebFrame' begins to load, this signal is emitted\nloadStarted :: WebViewClass self => Signal self (WebFrame -> IO())\nloadStarted = Signal (connect_OBJECT__NONE \"load-started\")\n\n-- | When a 'WebFrame' loaded the first data, this signal is emitted\nloadCommitted :: WebViewClass self => Signal self (WebFrame -> IO())\nloadCommitted = Signal (connect_OBJECT__NONE \"load-committed\")\n\n\n-- | When the global progress changed, this signal is emitted\n--\n-- the global progress will be passed back to user function\nprogressChanged :: WebViewClass self => Signal self (Int-> IO())\nprogressChanged = \n Signal (connect_INT__NONE \"load-progress-changed\")\n\n-- | When loading finished, this signal is emitted\nloadFinished :: WebViewClass self => Signal self (WebFrame -> IO())\nloadFinished = \n Signal (connect_OBJECT__NONE \"load-finished\")\n\n-- | When An error occurred while loading. \n--\n-- By default, if the signal is not handled,\n-- the WebView will display a stock error page. \n--\n-- You need to handle the signal\n-- if you want to provide your own error page.\n-- \n-- The URI that triggered the error and the 'GError' will be passed back to user function.\nloadError :: WebViewClass self => Signal self (WebFrame -> String -> GError -> IO Bool)\nloadError = Signal (connect_OBJECT_STRING_BOXED__BOOL \"load-error\" peek)\n\ncreateWebView :: WebViewClass self => Signal self (WebFrame -> IO WebView)\ncreateWebView = Signal (connect_OBJECT__OBJECTPTR \"create-web-view\")\n\n-- | Emitted when closing a WebView is requested. \n--\n-- This occurs when a call is made from JavaScript's window.close function. \n-- The default signal handler does not do anything. \n-- It is the owner's responsibility to hide or delete the 'WebView', if necessary.\n-- \n-- User function should return True to stop the handlers from being invoked for the event \n-- or False to propagate the event furter\ncloseWebView :: WebViewClass self => Signal self (IO Bool)\ncloseWebView = \n Signal (connect_NONE__BOOL \"close-web-view\")\n\n-- | A JavaScript console message was created.\nconsoleMessage :: WebViewClass self => Signal self (String -> String -> Int -> String -> IO Bool)\nconsoleMessage = Signal (connect_STRING_STRING_INT_STRING__BOOL \"console-message\")\n\n-- | The 'copyClipboard' signal is a keybinding signal which gets emitted to copy the selection to the clipboard.\n--\n-- The default bindings for this signal are Ctrl-c and Ctrl-Insert.\ncopyClipboard :: WebViewClass self => Signal self (IO ())\ncopyClipboard = Signal (connect_NONE__NONE \"copy-clipboard\")\n\n-- | The 'cutClipboard' signal is a keybinding signal which gets emitted to cut the selection to the clipboard.\n--\n-- The default bindings for this signal are Ctrl-x and Shift-Delete.\ncutClipboard :: WebViewClass self => Signal self (IO ())\ncutClipboard = Signal (connect_NONE__NONE \"cut-clipboard\")\n\n-- | The 'pasteClipboard' signal is a keybinding signal which gets emitted to paste the contents of the clipboard into the Web view.\n--\n-- The default bindings for this signal are Ctrl-v and Shift-Insert.\npasteClipboard :: WebViewClass self => Signal self (IO ())\npasteClipboard = Signal (connect_NONE__NONE \"paste-clipboard\")\n\n-- | When a context menu is about to be displayed this signal is emitted.\npopulatePopup :: WebViewClass self => Signal self (Menu -> IO ())\npopulatePopup = Signal (connect_OBJECT__NONE \"populate-popup\")\n\n-- | Emitted when printing is requested by the frame, usually because of a javascript call. \n-- When handling this signal you should call 'webFramePrintFull' or 'webFramePrint' to do the actual printing.\n--\n-- The default handler will present a print dialog and carry a print operation. \n-- Notice that this means that if you intend to ignore a print\n-- request you must connect to this signal, and return True.\nprintRequested :: WebViewClass self => Signal self (WebFrame -> IO Bool)\nprintRequested = Signal (connect_OBJECT__BOOL \"print-requested\")\n\n-- | A JavaScript alert dialog was created.\nscriptAlert :: WebViewClass self => Signal self (WebFrame -> String -> IO Bool)\nscriptAlert = Signal (connect_OBJECT_STRING__BOOL \"scriptAlert\")\n\n-- | A JavaScript confirm dialog was created, providing Yes and No buttons.\nscriptConfirm :: WebViewClass self => Signal self (WebFrame -> String -> IO Bool)\nscriptConfirm = Signal (connect_OBJECT_STRING__BOOL \"script-confirm\")\n\n-- | A JavaScript prompt dialog was created, providing an entry to input text.\nscriptPrompt :: WebViewClass self => Signal self (WebFrame -> String -> String -> IO Bool)\nscriptPrompt = Signal (connect_OBJECT_STRING_STRING__BOOL \"script-prompt\")\n\n-- | When status-bar text changed, this signal will emitted.\nstatusBarTextChanged :: WebViewClass self => Signal self (String -> IO ())\nstatusBarTextChanged = Signal (connect_STRING__NONE \"status-bar-text-changed\")\n\n\n\n-- | The 'selectAll' signal is a keybinding signal which gets emitted to select the complete contents of the text view.\n-- \n-- The default bindings for this signal is Ctrl-a.\nselectAll :: WebViewClass self => Signal self (IO ())\nselectAll = Signal (connect_NONE__NONE \"select-all\")\n\n-- | When selection changed, this signal is emitted.\nselectionChanged :: WebViewClass self => Signal self (IO ())\nselectionChanged = Signal (connect_NONE__NONE \"selection-changed\")\n\n-- | When set scroll adjustments, this signal is emitted.\nsetScrollAdjustments :: WebViewClass self => Signal self (Adjustment -> Adjustment -> IO ())\nsetScrollAdjustments = Signal (connect_OBJECT_OBJECT__NONE \"set-scroll-adjustments\")\n\n-- | The 'databaseQuotaExceeded' signal will be emitted when a Web Database exceeds the quota of its security origin. \n-- This signal may be used to increase the size of the quota before the originating operation fails.\ndatabaseQuotaExceeded :: WebViewClass self => Signal self (WebFrame -> WebDatabase -> IO ())\ndatabaseQuotaExceeded = Signal (connect_OBJECT_OBJECT__NONE \"database-quota-exceeded\")\n\n-- | When document loading finished, this signal is emitted\ndocumentLoadFinished :: WebViewClass self => Signal self (WebFrame -> IO ())\ndocumentLoadFinished = Signal (connect_OBJECT__NONE \"document-load-finished\")\n\n\n-- | Emitted after new 'WebView' instance had been created in 'onCreateWebView' user function\n-- when the new 'WebView' should be displayed to the user.\n-- \n-- All the information about how the window should look, \n-- including size,position,whether the location, status and scroll bars should be displayed, \n-- is ready set.\nwebViewReady:: WebViewClass self => Signal self (IO Bool)\nwebViewReady =\n Signal (connect_NONE__BOOL \"web-view-ready\")\n\n-- | Emitted after A new 'Download' is being requested. \n--\n-- By default, if the signal is not handled, the download is cancelled.\n-- \n-- Notice that while handling this signal you must set the target URI using 'downloadSetDestinationUri'\n-- \n-- If you intend to handle downloads yourself, return False in user function.\ndownloadRequested :: WebViewClass self => Signal self (Download -> IO Bool)\ndownloadRequested =\n Signal (connect_OBJECT__BOOL \"download-requested\")\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n-- | Emitted after Icon loaded\niconLoaded :: WebViewClass self => Signal self (String -> IO ())\niconLoaded =\n Signal (connect_STRING__NONE \"icon-loaded\")\n#endif\n\n-- | The \"redo\" signal is a keybinding signal which gets emitted to redo the last editing command.\n--\n-- The default binding for this signal is Ctrl-Shift-z\nredo :: WebViewClass self => Signal self (IO ())\nredo =\n Signal (connect_NONE__NONE \"redo\")\n\n-- | The \"undo\" signal is a keybinding signal which gets emitted to undo the last editing command.\n--\n-- The default binding for this signal is Ctrl-z\nundo :: WebViewClass self => Signal self (IO ())\nundo =\n Signal (connect_NONE__NONE \"undo\")\n\n-- | Decide whether or not to display the given MIME type. \n-- If this signal is not handled, the default behavior is to show the content of the\n-- requested URI if WebKit can show this MIME type and the content disposition is not a download; \n-- if WebKit is not able to show the MIME type nothing happens.\n--\n-- Notice that if you return True, meaning that you handled the signal, \n-- you are expected to be aware of the \"Content-Disposition\" header. \n-- A value of \"attachment\" usually indicates a download regardless of the MIME type, \n-- see also soupMessageHeadersGetContentDisposition'\n-- And you must call 'webPolicyDecisionIgnore', 'webPolicyDecisionDownload', or 'webPolicyDecisionUse' \n-- on the 'webPolicyDecision' object.\nmimeTypePolicyDecisionRequested :: WebViewClass self => Signal self (WebFrame -> NetworkRequest -> String -> WebPolicyDecision -> IO Bool)\nmimeTypePolicyDecisionRequested = Signal (connect_OBJECT_OBJECT_STRING_OBJECT__BOOL \"mime-type-policy-decision-requested\")\n\n-- | The 'moveCursor' will be emitted to apply the cursor movement described by its parameters to the view.\nmoveCursor :: WebViewClass self => Signal self (MovementStep -> Int -> IO Bool)\nmoveCursor = Signal (connect_ENUM_INT__BOOL \"move-cursor\")\n\n-- | Emitted when frame requests a navigation to another page. \n-- If this signal is not handled, the default behavior is to allow the navigation.\n--\n-- Notice that if you return True, meaning that you handled the signal, \n-- you are expected to be aware of the \"Content-Disposition\" header. \n-- A value of \"attachment\" usually indicates a download regardless of the MIME type, \n-- see also soupMessageHeadersGetContentDisposition'\n-- And you must call 'webPolicyDecisionIgnore', 'webPolicyDecisionDownload', or 'webPolicyDecisionUse' \n-- on the 'webPolicyDecision' object.\nnavigationPolicyDecisionRequested :: WebViewClass self => Signal self (WebFrame -> NetworkRequest -> WebNavigationAction -> WebPolicyDecision -> IO Bool)\nnavigationPolicyDecisionRequested = Signal (connect_OBJECT_OBJECT_OBJECT_OBJECT__BOOL \"navigation-policy-decision-requested\")\n\n-- | Emitted when frame requests opening a new window. \n-- With this signal the browser can use the context of the request to decide about the new window. \n-- If the request is not handled the default behavior is to allow opening the new window to load the URI, \n-- which will cause a 'createWebView' signal emission where the browser handles the new window action \n-- but without information of the context that caused the navigation. \n-- The following 'navigationPolicyDecisionRequested' emissions will load the page \n-- after the creation of the new window just with the information of this new navigation context, \n-- without any information about the action that made this new window to be opened.\n--\n-- Notice that if you return True, meaning that you handled the signal, \n-- you are expected to be aware of the \"Content-Disposition\" header. \n-- A value of \"attachment\" usually indicates a download regardless of the MIME type, \n-- see also soupMessageHeadersGetContentDisposition'\n-- And you must call 'webPolicyDecisionIgnore', 'webPolicyDecisionDownload', or 'webPolicyDecisionUse' \n-- on the 'webPolicyDecision' object.\nnewWindowPolicyDecisionRequested :: WebViewClass self => Signal self (WebFrame -> NetworkRequest -> WebNavigationAction -> WebPolicyDecision -> IO Bool)\nnewWindowPolicyDecisionRequested = Signal (connect_OBJECT_OBJECT_OBJECT_OBJECT__BOOL \"new-window-policy-decision-requested\")\n\n-- | Emitted when a request is about to be sent. \n-- You can modify the request while handling this signal. \n-- You can set the URI in the 'NetworkRequest' object itself, \n-- and add\/remove\/replace headers using the SoupMessage object it carries, \n-- if it is present. See 'networkRequestGetMessage'. \n-- Setting the request URI to \"about:blank\" will effectively cause the request to load nothing, \n-- and can be used to disable the loading of specific resources.\n--\n-- Notice that information about an eventual redirect is available in response's SoupMessage, \n-- not in the SoupMessage carried by the request.\n-- If response is NULL, then this is not a redirected request.\n--\n-- The 'WebResource' object will be the same throughout all the lifetime of the resource, \n-- but the contents may change from inbetween signal emissions.\nresourceRequestStarting :: WebViewClass self => Signal self (WebFrame -> WebResource -> Maybe NetworkRequest -> Maybe NetworkResponse -> IO ())\nresourceRequestStarting = Signal (connect_OBJECT_OBJECT_MOBJECT_MOBJECT__NONE \"resource-request-starting\")\n\n#if WEBKIT_CHECK_VERSION (1,1,23)\n-- | When a frame wants to cancel geolocation permission it had requested before.\n--\n-- * Since 1.1.23 \ngeolocationPolicyDecisionCancelled :: WebViewClass self => Signal self (WebFrame -> IO ())\ngeolocationPolicyDecisionCancelled = Signal (connect_OBJECT__NONE \"geolocation-policy-decision-cancelled\")\n\n-- | When a frame wants to get its geolocation permission. The receiver must reply with a boolean wether\n-- it handled or not the request. If the request is not handled, default behaviour is to deny\n-- geolocation.\n-- \n-- * Since 1.1.23 \ngeolocationPolicyDecisionRequested :: WebViewClass self => Signal self (WebFrame -> GeolocationPolicyDecision -> IO ())\ngeolocationPolicyDecisionRequested = Signal (connect_OBJECT_OBJECT__NONE \"geolocation-policy-decision-requested\")\n#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebView\n-- Author : Cjacker Huang\n-- Copyright : (c) 2009 Cjacker Huang \n-- Copyright : (c) 2010 Andy Stewart \n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Note:\n--\n-- Signal `window-object-cleared` can't bidning now, \n-- because it need JavaScriptCore that haven't binding.\n--\n-- Signal `create-plugin-widget` can't binding now, \n-- no idea how to binding `GHaskellTable`\n--\n--\n-- TODO:\n--\n-- `webViewGetHitTestResult`\n--\n-- The central class of the WebKit\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebView (\n-- * Description\n-- | WebKitWebView is the central class of the WebKitGTK+ API. It is a 'Widget' implementing the\n-- scrolling interface which means you can embed in a 'ScrolledWindow'. It is responsible for managing\n-- the drawing of the content, forwarding of events. You can load any URI into the WebKitWebView or any\n-- kind of data string. With WebKitWebSettings you can control various aspects of the rendering and\n-- loading of the content. Each WebKitWebView has exactly one WebKitWebFrame as main frame. A\n-- WebKitWebFrame can have n children.\n\n-- * Types\n WebView,\n WebViewClass,\n\n-- * Enums\n NavigationResponse(..),\n TargetInfo(..),\n LoadStatus(..),\n\n-- * Constructors\n webViewNew,\n\n-- * Methods\n-- ** Load\n webViewLoadUri,\n webViewLoadHtmlString,\n webViewLoadRequest,\n webViewLoadString,\n-- ** Reload\n webViewStopLoading,\n webViewReload,\n webViewReloadBypassCache,\n-- ** History\n webViewCanGoBack,\n webViewCanGoForward,\n webViewGoBack,\n webViewGoForward,\n webViewGetBackForwardList,\n webViewSetMaintainsBackForwardList,\n webViewGoToBackForwardItem,\n webViewCanGoBackOrForward,\n webViewGoBackOrForward,\n-- ** Zoom\n webViewGetZoomLevel,\n webViewSetZoomLevel,\n webViewZoomIn,\n webViewZoomOut,\n webViewGetFullContentZoom,\n webViewSetFullContentZoom,\n-- ** Clipboard\n webViewCanCutClipboard,\n webViewCanCopyClipboard,\n webViewCanPasteClipboard,\n webViewCutClipboard,\n webViewCopyClipboard,\n webViewPasteClipboard,\n-- ** Undo\/Redo\n webViewCanRedo,\n webViewCanUndo,\n webViewRedo,\n webViewUndo,\n-- ** Selection\n webViewDeleteSelection,\n webViewHasSelection,\n webViewSelectAll,\n-- ** Encoding\n webViewGetEncoding,\n webViewSetCustomEncoding,\n webViewGetCustomEncoding,\n-- ** Source Mode\n webViewGetViewSourceMode,\n webViewSetViewSourceMode,\n-- ** Transparent\n webViewGetTransparent,\n webViewSetTransparent,\n-- ** Target List\n webViewGetCopyTargetList,\n webViewGetPasteTargetList,\n-- ** Text Match\n webViewMarkTextMatches,\n webViewUnMarkTextMatches,\n webViewSetHighlightTextMatches,\n-- ** Other\n webViewExecuteScript,\n \n webViewCanShowMimeType,\n webViewGetEditable,\n webViewSetEditable,\n webViewGetInspector,\n\n webViewGetProgress,\n\n webViewSearchText,\n\n webViewMoveCursor,\n\n webViewGetMainFrame,\n webViewGetFocusedFrame,\n\n webViewSetWebSettings,\n webViewGetWebSettings,\n\n webViewGetWindowFeatures,\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n webViewGetIconUri,\n#endif\n\n webViewGetTitle,\n webViewGetUri,\n\n-- * Attributes\n webViewZoomLevel,\n webViewFullContentZoom,\n webViewEncoding,\n webViewCustomEncoding,\n webViewLoadStatus,\n webViewProgress,\n webViewTitle,\n webViewInspector,\n webViewWebSettings,\n webViewViewSourceMode,\n webViewTransparent,\n webViewEditable,\n webViewUri,\n webViewCopyTargetList,\n webViewPasteTargetList,\n webViewWindowFeatures,\n#if WEBKIT_CHECK_VERSION (1,1,18)\n webViewIconUri,\n#endif\n\n#if WEBKIT_CHECK_VERSION (1,1,20)\n webViewImContext,\n#endif\n \n-- * Signals\n loadStarted,\n loadCommitted,\n progressChanged,\n loadFinished,\n loadError,\n titleChanged,\n hoveringOverLink,\n createWebView,\n webViewReady,\n closeWebView,\n consoleMessage,\n copyClipboard,\n cutClipboard,\n pasteClipboard,\n populatePopup,\n printRequested,\n scriptAlert,\n scriptConfirm,\n scriptPrompt,\n statusBarTextChanged,\n selectAll,\n selectionChanged,\n setScrollAdjustments,\n databaseQuotaExceeded,\n documentLoadFinished,\n downloadRequested,\n#if WEBKIT_CHECK_VERSION (1,1,18)\n iconLoaded,\n#endif\n redo,\n undo,\n mimeTypePolicyDecisionRequested,\n moveCursor,\n navigationPolicyDecisionRequested,\n newWindowPolicyDecisionRequested,\n resourceRequestStarting,\n#if WEBKIT_CHECK_VERSION (1,1,23)\n geolocationPolicyDecisionCancelled,\n geolocationPolicyDecisionRequested,\n#endif\n) where\n\nimport Control.Monad\t\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GList\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GError \nimport Graphics.UI.Gtk.Gdk.Events\n\n{#import Graphics.UI.Gtk.Abstract.Object#}\t(makeNewObject)\n{#import Graphics.UI.Gtk.WebKit.Types#}\n{#import Graphics.UI.Gtk.WebKit.Signals#}\n{#import Graphics.UI.Gtk.WebKit.Internal#}\n{#import System.Glib.GObject#}\n{#import Graphics.UI.Gtk.General.Selection#} ( TargetList )\n{#import Graphics.UI.Gtk.MenuComboToolbar.Menu#}\n{#import Graphics.UI.Gtk.General.Enums#}\n\n{#context lib=\"webkit\" prefix =\"webkit\"#}\n\n------------------\n-- Enums\n\n{#enum NavigationResponse {underscoreToCase}#}\n\n{#enum WebViewTargetInfo as TargetInfo {underscoreToCase}#}\n\n{#enum LoadStatus {underscoreToCase}#}\n\n------------------\n-- Constructors\n\n\n-- | Create a new 'WebView' widget.\n-- \n-- It is a 'Widget' you can embed in a 'ScrolledWindow'.\n-- \n-- You can load any URI into the 'WebView' or any kind of data string.\nwebViewNew :: IO WebView \nwebViewNew = do\n isGthreadInited <- liftM toBool {#call g_thread_get_initialized#}\n if not isGthreadInited then {#call g_thread_init#} nullPtr \n else return ()\n makeNewObject mkWebView $ liftM castPtr {#call web_view_new#}\n\n\n-- | Apply 'WebSettings' to a given 'WebView'\n-- \n-- !!NOTE!!, currently lack of useful APIs of 'WebSettings' in webkitgtk.\n-- If you want to set the encoding, font family or font size of the 'WebView',\n-- please use related functions.\n\nwebViewSetWebSettings :: \n (WebViewClass self, WebSettingsClass settings) => self\n -> settings\n -> IO ()\nwebViewSetWebSettings webview websettings = \n {#call web_view_set_settings#} (toWebView webview) (toWebSettings websettings)\n\n-- | Return the 'WebSettings' currently used by 'WebView'.\nwebViewGetWebSettings :: \n WebViewClass self => self\n -> IO WebSettings\nwebViewGetWebSettings webview = \n makeNewGObject mkWebSettings $ {#call web_view_get_settings#} (toWebView webview)\n\n-- | Returns the instance of WebKitWebWindowFeatures held by the given WebKitWebView.\nwebViewGetWindowFeatures ::\n WebViewClass self => self\n -> IO WebWindowFeatures \nwebViewGetWindowFeatures webview =\n makeNewGObject mkWebWindowFeatures $ {#call web_view_get_window_features#} (toWebView webview)\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n-- | Obtains the URI for the favicon for the given WebKitWebView, or 'Nothing' if there is none.\n--\n-- * Since 1.1.18\nwebViewGetIconUri :: WebViewClass self => self -> IO (Maybe String)\nwebViewGetIconUri webview =\n {#call webkit_web_view_get_icon_uri #} (toWebView webview)\n >>= maybePeek peekUTFString\n#endif\n\n\n-- | Return the main 'WebFrame' of the given 'WebView'.\nwebViewGetMainFrame :: \n WebViewClass self => self\n -> IO WebFrame\nwebViewGetMainFrame webview = \n makeNewGObject mkWebFrame $ {#call web_view_get_main_frame#} (toWebView webview)\n\n-- | Return the focused 'WebFrame' of the given 'WebView'.\nwebViewGetFocusedFrame :: \n WebViewClass self => self\n -> IO WebFrame\nwebViewGetFocusedFrame webview = \n makeNewGObject mkWebFrame $ {#call web_view_get_focused_frame#} (toWebView webview)\n\n\n-- |Requests loading of the specified URI string in a 'WebView'\nwebViewLoadUri :: \n WebViewClass self => self \n -> String -- ^ @uri@ - an URI string.\n -> IO()\nwebViewLoadUri webview url =\n withCString url $ \\urlPtr -> {#call web_view_load_uri#}\n (toWebView webview)\n urlPtr\n\n-- |Determine whether 'WebView' has a previous history item.\nwebViewCanGoBack :: \n WebViewClass self => self\n -> IO Bool -- ^ True if able to move back, False otherwise.\nwebViewCanGoBack webview = \n liftM toBool $ {#call web_view_can_go_back#} (toWebView webview)\n\n-- |Determine whether 'WebView' has a next history item.\nwebViewCanGoForward :: \n WebViewClass self => self \n -> IO Bool -- ^ True if able to move forward, False otherwise.\nwebViewCanGoForward webview = \n liftM toBool $ {#call web_view_can_go_forward#} (toWebView webview)\n\n-- |Loads the previous history item.\nwebViewGoBack :: \n WebViewClass self => self\n -> IO () \nwebViewGoBack webview =\n {#call web_view_go_back#} (toWebView webview)\n\n-- |Loads the next history item.\nwebViewGoForward :: \n WebViewClass self => self\n -> IO ()\nwebViewGoForward webview =\n {#call web_view_go_forward#} (toWebView webview)\n\n-- |Set the 'WebView' to maintian a back or forward list of history items.\nwebViewSetMaintainsBackForwardList :: \n WebViewClass self => self \n -> Bool -- ^ @flag@ - to tell the view to maintain a back or forward list. \n -> IO()\nwebViewSetMaintainsBackForwardList webview flag = \n {#call web_view_set_maintains_back_forward_list#} \n (toWebView webview)\n (fromBool flag)\n\n-- |Return the 'WebBackForwardList'\nwebViewGetBackForwardList :: \n WebViewClass self => self\n -> IO WebBackForwardList\nwebViewGetBackForwardList webview = \n makeNewGObject mkWebBackForwardList $ \n {#call web_view_get_back_forward_list#} \n (toWebView webview)\n\n-- |Go to the specified 'WebHistoryItem'\n\nwebViewGoToBackForwardItem :: \n (WebViewClass self, WebHistoryItemClass item) => self \n -> item\n -> IO Bool -- ^ True if loading of item is successful, False if not.\nwebViewGoToBackForwardItem webview item = \n liftM toBool $ {#call web_view_go_to_back_forward_item#} (toWebView webview) (toWebHistoryItem item)\n\n-- |Determines whether 'WebView' has a history item of @steps@.\n--\n-- Negative values represent steps backward while positive values\n-- represent steps forward\n\nwebViewCanGoBackOrForward :: \n WebViewClass self => self\n -> Int -- ^ @steps@ - the number of steps \n -> IO Bool -- ^ True if able to move back or forward the given number of steps,\n -- False otherwise\nwebViewCanGoBackOrForward webview steps =\n liftM toBool $ \n {#call web_view_can_go_back_or_forward#} \n (toWebView webview)\n (fromIntegral steps)\n\n-- |Loads the history item that is the number of @steps@ away from the current item.\n--\n-- Negative values represent steps backward while positive values represent steps forward.\n\nwebViewGoBackOrForward :: \n WebViewClass self => self\n -> Int\n -> IO ()\nwebViewGoBackOrForward webview steps =\n {#call web_view_go_back_or_forward#} \n (toWebView webview)\n (fromIntegral steps)\n\n-- |Determines whether or not it is currently possible to redo the last editing command in the view\nwebViewCanRedo :: \n WebViewClass self => self\n -> IO Bool\nwebViewCanRedo webview = \n liftM toBool $\n {#call web_view_can_redo#} (toWebView webview)\n-- |Determines whether or not it is currently possible to undo the last editing command in the view\nwebViewCanUndo :: \n WebViewClass self => self\n -> IO Bool\nwebViewCanUndo webview =\n liftM toBool $\n {#call web_view_can_undo#} (toWebView webview)\n\n-- |Redoes the last editing command in the view, if possible.\nwebViewRedo :: \n WebViewClass self => self\n -> IO()\nwebViewRedo webview =\n {#call web_view_redo#} (toWebView webview)\n\n-- |Undoes the last editing command in the view, if possible.\nwebViewUndo :: \n WebViewClass self => self\n -> IO()\nwebViewUndo webview =\n {#call web_view_undo#} (toWebView webview)\n\n-- | Returns whether or not a @mimetype@ can be displayed using this view.\nwebViewCanShowMimeType :: \n WebViewClass self => self\n -> String -- ^ @mimetype@ - a MIME type\n -> IO Bool -- ^ True if the @mimetype@ can be displayed, otherwise False\nwebViewCanShowMimeType webview mime =\n withCString mime $ \\mimePtr ->\n liftM toBool $\n {#call web_view_can_show_mime_type#}\n (toWebView webview)\n mimePtr\n\n-- | Returns whether the user is allowed to edit the document.\nwebViewGetEditable :: \n WebViewClass self => self\n -> IO Bool\nwebViewGetEditable webview =\n liftM toBool $\n {#call web_view_get_editable#} (toWebView webview)\n\n-- | Sets whether allows the user to edit its HTML document.\nwebViewSetEditable :: \n WebViewClass self => self\n -> Bool\n -> IO ()\nwebViewSetEditable webview editable =\n {#call web_view_set_editable#} (toWebView webview) (fromBool editable)\n\n-- | Returns whether 'WebView' is in view source mode\nwebViewGetViewSourceMode :: \n WebViewClass self => self\n -> IO Bool\nwebViewGetViewSourceMode webview =\n liftM toBool $\n {#call web_view_get_view_source_mode#} (toWebView webview)\n\n-- | Set whether the view should be in view source mode. \n--\n-- Setting this mode to TRUE before loading a URI will display \n-- the source of the web page in a nice and readable format.\nwebViewSetViewSourceMode :: \n WebViewClass self => self\n -> Bool\n -> IO ()\nwebViewSetViewSourceMode webview mode =\n {#call web_view_set_view_source_mode#} (toWebView webview) (fromBool mode)\n\n-- | Returns whether the 'WebView' has a transparent background\nwebViewGetTransparent :: \n WebViewClass self => self\n -> IO Bool\nwebViewGetTransparent webview =\n liftM toBool $\n {#call web_view_get_transparent#} (toWebView webview)\n-- |Sets whether the WebKitWebView has a transparent background.\n--\n-- Pass False to have the 'WebView' draw a solid background (the default), \n-- otherwise pass True.\nwebViewSetTransparent :: \n WebViewClass self => self\n -> Bool\n -> IO ()\nwebViewSetTransparent webview trans =\n {#call web_view_set_transparent#} (toWebView webview) (fromBool trans)\n\n-- |Obtains the 'WebInspector' associated with the 'WebView'\nwebViewGetInspector :: \n WebViewClass self => self\n -> IO WebInspector\nwebViewGetInspector webview =\n makeNewGObject mkWebInspector $ {#call web_view_get_inspector#} (toWebView webview)\n\n-- |Requests loading of the specified asynchronous client request.\n--\n-- Creates a provisional data source that will transition to a committed data source once\n-- any data has been received. \n-- use 'webViewStopLoading' to stop the load.\n\nwebViewLoadRequest :: \n (WebViewClass self, NetworkRequestClass request) => self\n -> request\n -> IO()\nwebViewLoadRequest webview request =\n {#call web_view_load_request#} (toWebView webview) (toNetworkRequest request)\n\n\n\n\n-- |Returns the zoom level of 'WebView'\n--\n-- i.e. the factor by which elements in the page are scaled with respect to their original size.\n\nwebViewGetZoomLevel :: \n WebViewClass self => self\n -> IO Float -- ^ the zoom level of 'WebView'\nwebViewGetZoomLevel webview =\n liftM realToFrac $\n\t{#call web_view_get_zoom_level#} (toWebView webview)\n\n-- |Sets the zoom level of 'WebView'.\nwebViewSetZoomLevel :: \n WebViewClass self => self \n -> Float -- ^ @zoom_level@ - the new zoom level \n -> IO ()\nwebViewSetZoomLevel webview zlevel = \n {#call web_view_set_zoom_level#} (toWebView webview) (realToFrac zlevel)\n\n-- |Loading the @content@ string as html. The URI passed in base_uri has to be an absolute URI.\n\nwebViewLoadHtmlString :: \n WebViewClass self => self \n -> String -- ^ @content@ - the html string\n -> String -- ^ @base_uri@ - the base URI\n -> IO()\nwebViewLoadHtmlString webview htmlstr url =\n withCString htmlstr $ \\htmlPtr ->\n withCString url $ \\urlPtr ->\n {#call web_view_load_html_string#} (toWebView webview) htmlPtr urlPtr\n\n-- | Requests loading of the given @content@ with the specified @mime_type@, @encoding@ and @base_uri@.\n-- \n-- If @mime_type@ is @Nothing@, \"text\/html\" is assumed.\n--\n-- If @encoding@ is @Nothing@, \"UTF-8\" is assumed.\n--\nwebViewLoadString :: \n WebViewClass self => self \n -> String -- ^ @content@ - the content string to be loaded.\n -> (Maybe String) -- ^ @mime_type@ - the MIME type or @Nothing@. \n -> (Maybe String) -- ^ @encoding@ - the encoding or @Nothing@.\n -> String -- ^ @base_uri@ - the base URI for relative locations.\n -> IO()\nwebViewLoadString webview content mimetype encoding baseuri = \n withCString content $ \\contentPtr ->\n maybeWith withCString mimetype $ \\mimetypePtr ->\n maybeWith withCString encoding $ \\encodingPtr ->\n withCString baseuri $ \\baseuriPtr ->\n {#call web_view_load_string#} \n (toWebView webview)\n contentPtr\n mimetypePtr\n encodingPtr\n baseuriPtr\n\n-- |Returns the 'WebView' document title\nwebViewGetTitle :: \n WebViewClass self => self\n -> IO (Maybe String) -- ^ the title of 'WebView' or Nothing in case of failed.\nwebViewGetTitle webview =\n {#call web_view_get_title#} (toWebView webview) >>= maybePeek peekUTFString\n\n-- |Returns the current URI of the contents displayed by the 'WebView'\nwebViewGetUri :: \n WebViewClass self => self\n -> IO (Maybe String) -- ^ the URI of 'WebView' or Nothing in case of failed.\nwebViewGetUri webview = \n {#call web_view_get_uri#} (toWebView webview) >>= maybePeek peekUTFString\n\n\n-- | Stops and pending loads on the given data source.\nwebViewStopLoading :: \n WebViewClass self => self\n -> IO ()\nwebViewStopLoading webview = \n {#call web_view_stop_loading#} (toWebView webview)\n\n-- | Reloads the 'WebView'\nwebViewReload :: \n WebViewClass self => self\n -> IO ()\nwebViewReload webview = \n {#call web_view_reload#} (toWebView webview)\n\n-- | Reloads the 'WebView' without using any cached data.\nwebViewReloadBypassCache :: \n WebViewClass self => self\n -> IO()\nwebViewReloadBypassCache webview = \n {#call web_view_reload_bypass_cache#} (toWebView webview)\n\n-- | Increases the zoom level of 'WebView'.\nwebViewZoomIn :: \n WebViewClass self => self\n -> IO()\nwebViewZoomIn webview = \n {#call web_view_zoom_in#} (toWebView webview)\n\n-- | Decreases the zoom level of 'WebView'.\nwebViewZoomOut :: \n WebViewClass self => self\n -> IO()\nwebViewZoomOut webview = \n {#call web_view_zoom_out#} (toWebView webview)\n\n-- | Looks for a specified string inside 'WebView'\nwebViewSearchText :: \n WebViewClass self => self\n -> String -- ^ @text@ - a string to look for\n -> Bool -- ^ @case_sensitive@ - whether to respect the case of text\n -> Bool -- ^ @forward@ - whether to find forward or not\n -> Bool -- ^ @wrap@ - whether to continue looking at beginning\n -- after reaching the end\n -> IO Bool -- ^ True on success or False on failure\nwebViewSearchText webview text case_sensitive forward wrap =\n withCString text $ \\textPtr ->\n\tliftM toBool $\n {#call web_view_search_text#} \n (toWebView webview)\n textPtr\n (fromBool case_sensitive) \n (fromBool forward) \n (fromBool wrap)\n\n-- |Attempts to highlight all occurances of string inside 'WebView'\nwebViewMarkTextMatches :: \n WebViewClass self => self\n -> String -- ^ @string@ - a string to look for\n -> Bool -- ^ @case_sensitive@ - whether to respect the case of text\n -> Int -- ^ @limit@ - the maximum number of strings to look for or 0 for all\n -> IO Int -- ^ the number of strings highlighted\nwebViewMarkTextMatches webview text case_sensitive limit = \n withCString text $ \\textPtr ->\n\tliftM fromIntegral $ \n {#call web_view_mark_text_matches#} \n (toWebView webview)\n textPtr\n (fromBool case_sensitive)\n (fromIntegral limit)\n\n-- | Move the cursor in view as described by step and count.\nwebViewMoveCursor ::\n WebViewClass self => self\n -> MovementStep\n -> Int\n -> IO () \nwebViewMoveCursor webview step count =\n {#call web_view_move_cursor#} (toWebView webview) (fromIntegral $ fromEnum step) (fromIntegral count)\n\n-- | Removes highlighting previously set by 'webViewMarkTextMarches'\nwebViewUnMarkTextMatches :: \n WebViewClass self => self\n -> IO ()\nwebViewUnMarkTextMatches webview = \n {#call web_view_unmark_text_matches#} (toWebView webview)\n\n-- | Highlights text matches previously marked by 'webViewMarkTextMatches'\nwebViewSetHighlightTextMatches :: \n WebViewClass self => self\n -> Bool -- ^ @highlight@ - whether to highlight text matches \n -> IO ()\nwebViewSetHighlightTextMatches webview highlight =\n {#call web_view_set_highlight_text_matches#} \n (toWebView webview)\n (fromBool highlight)\n\n-- | Execute the script specified by @script@\nwebViewExecuteScript :: \n WebViewClass self => self \n -> String -- ^ @script@ - script to be executed\n -> IO()\nwebViewExecuteScript webview script =\n withCString script $ \\scriptPtr ->\n\t{#call web_view_execute_script#} (toWebView webview) scriptPtr\n\n-- | Determines whether can cuts the current selection\n-- inside 'WebView' to the clipboard\nwebViewCanCutClipboard :: \n WebViewClass self => self\n -> IO Bool\nwebViewCanCutClipboard webview = \n liftM toBool $ {#call web_view_can_cut_clipboard#} (toWebView webview)\n\n-- | Determines whether can copies the current selection\n-- inside 'WebView' to the clipboard\nwebViewCanCopyClipboard :: WebViewClass self => self -> IO Bool\nwebViewCanCopyClipboard webview = \n liftM toBool $ {#call web_view_can_copy_clipboard#} (toWebView webview)\n\n-- | Determines whether can pastes the current contents of the clipboard\n-- to the 'WebView'\nwebViewCanPasteClipboard :: WebViewClass self => self -> IO Bool\nwebViewCanPasteClipboard webview = \n liftM toBool $ {#call web_view_can_paste_clipboard#} (toWebView webview)\n\n-- | Cuts the current selection inside 'WebView' to the clipboard.\nwebViewCutClipboard :: WebViewClass self => self -> IO()\nwebViewCutClipboard webview = \n {#call web_view_cut_clipboard#} (toWebView webview)\n\n-- | Copies the current selection inside 'WebView' to the clipboard.\nwebViewCopyClipboard :: WebViewClass self => self -> IO()\nwebViewCopyClipboard webview = \n {#call web_view_copy_clipboard#} (toWebView webview)\n\n-- | Pastes the current contents of the clipboard to the 'WebView'\nwebViewPasteClipboard :: WebViewClass self => self -> IO()\nwebViewPasteClipboard webview = \n {#call web_view_paste_clipboard#} (toWebView webview)\n\n-- | Deletes the current selection inside the 'WebView'\nwebViewDeleteSelection :: WebViewClass self => self -> IO ()\nwebViewDeleteSelection webview = \n {#call web_view_delete_selection#} (toWebView webview)\n\n-- | Determines whether text was selected\nwebViewHasSelection :: WebViewClass self => self -> IO Bool\nwebViewHasSelection webview = \n liftM toBool $ {#call web_view_has_selection#} (toWebView webview)\n\n-- | Attempts to select everything inside the 'WebView'\nwebViewSelectAll :: WebViewClass self => self -> IO ()\nwebViewSelectAll webview = \n {#call web_view_select_all#} (toWebView webview)\n\n-- | Returns whether the zoom level affects only text or all elements.\nwebViewGetFullContentZoom :: \n WebViewClass self => self \n -> IO Bool -- ^ False if only text should be scaled(the default)\n -- True if the full content of the view should be scaled.\nwebViewGetFullContentZoom webview = \n liftM toBool $ {#call web_view_get_full_content_zoom#} (toWebView webview)\n\n-- | Sets whether the zoom level affects only text or all elements.\nwebViewSetFullContentZoom :: \n WebViewClass self => self \n -> Bool -- ^ @full_content_zoom@ - False if only text should be scaled (the default)\n -- True if the full content of the view should be scaled. \n -> IO ()\nwebViewSetFullContentZoom webview full =\n {#call web_view_set_full_content_zoom#} (toWebView webview) (fromBool full)\n\n-- | Returns the default encoding of the 'WebView'\nwebViewGetEncoding :: \n WebViewClass self => self \n -> IO (Maybe String) -- ^ the default encoding or @Nothing@ in case of failed\nwebViewGetEncoding webview =\n {#call web_view_get_encoding#} (toWebView webview) >>= maybePeek peekUTFString\n\n-- | Sets the current 'WebView' encoding, \n-- without modifying the default one, and reloads the page\nwebViewSetCustomEncoding :: \n WebViewClass self => self\n -> (Maybe String) -- ^ @encoding@ - the new encoding, \n -- or @Nothing@ to restore the default encoding. \n -> IO ()\nwebViewSetCustomEncoding webview encoding = \n maybeWith withCString encoding $ \\encodingPtr ->\n\t{#call web_view_set_custom_encoding#} (toWebView webview) encodingPtr\n\n-- | Returns the current encoding of 'WebView',not the default encoding.\nwebViewGetCustomEncoding :: \n WebViewClass self => self \n -> IO (Maybe String) -- ^ the current encoding string\n -- or @Nothing@ if there is none set.\nwebViewGetCustomEncoding webview = \n {#call web_view_get_custom_encoding#} (toWebView webview) >>= maybePeek peekUTFString\n\n-- | Determines the current status of the load.\nwebViewGetLoadStatus :: \n WebViewClass self => self \n -> IO LoadStatus -- ^ the current load status:'LoadStatus'\nwebViewGetLoadStatus webview = \n liftM (toEnum . fromIntegral) $ {#call web_view_get_load_status#} (toWebView webview)\n\n-- | Determines the current progress of the load\nwebViewGetProgress :: \n WebViewClass self => self \n -> IO Double -- ^ the load progress\nwebViewGetProgress webview =\n liftM realToFrac $ {#call web_view_get_progress#} (toWebView webview)\n\n-- | This function returns the list of targets this 'WebView' can provide for clipboard copying and as DND source. \n-- The targets in the list are added with values from the 'WebViewTargetInfo' enum, \n-- using 'targetListAdd' and 'targetListAddTextTargets'.\nwebViewGetCopyTargetList ::\n WebViewClass self => self \n -> IO (Maybe TargetList)\nwebViewGetCopyTargetList webview = do\n tlPtr <- {#call web_view_get_copy_target_list#} (toWebView webview)\n if tlPtr==nullPtr then return Nothing else liftM Just (mkTargetList tlPtr)\n\n-- | This function returns the list of targets this 'WebView' can provide for clipboard pasteing and as DND source. \n-- The targets in the list are added with values from the 'WebViewTargetInfo' enum, \n-- using 'targetListAdd' and 'targetListAddTextTargets'.\nwebViewGetPasteTargetList ::\n WebViewClass self => self \n -> IO (Maybe TargetList)\nwebViewGetPasteTargetList webview = do\n tlPtr <- {#call web_view_get_paste_target_list#} (toWebView webview)\n if tlPtr==nullPtr then return Nothing else liftM Just (mkTargetList tlPtr)\n\n-- * Attibutes\n\n-- | Zoom level of the 'WebView' instance\nwebViewZoomLevel :: WebViewClass self => Attr self Float\nwebViewZoomLevel = newAttr\n webViewGetZoomLevel\n webViewSetZoomLevel\n\n-- | Whether the full content is scaled when zooming\n--\n-- Default value: False\nwebViewFullContentZoom :: WebViewClass self => Attr self Bool\nwebViewFullContentZoom = newAttr\n webViewGetFullContentZoom\n webViewSetFullContentZoom\n\n-- | The default encoding of the 'WebView' instance\n--\n-- Default value: @Nothing@\nwebViewEncoding :: WebViewClass self => ReadAttr self (Maybe String)\nwebViewEncoding = readAttr webViewGetEncoding\n\n-- | Determines the current status of the load.\n--\n-- Default value: @LoadFinished@\nwebViewLoadStatus :: WebViewClass self => ReadAttr self LoadStatus\nwebViewLoadStatus = readAttr webViewGetLoadStatus\n\n-- |Determines the current progress of the load\n--\n-- Default Value: 1\nwebViewProgress :: WebViewClass self => ReadAttr self Double\nwebViewProgress = readAttr webViewGetProgress\n\n\n-- | The associated webSettings of the 'WebView' instance\nwebViewWebSettings :: WebViewClass self => Attr self WebSettings\nwebViewWebSettings = newAttr\n webViewGetWebSettings\n webViewSetWebSettings\n\n\n-- | Title of the 'WebView' instance\nwebViewTitle :: WebViewClass self => ReadAttr self (Maybe String)\nwebViewTitle = readAttr webViewGetTitle\n\n-- | The associated webInspector instance of the 'WebView'\nwebViewInspector :: WebViewClass self => ReadAttr self WebInspector\nwebViewInspector = readAttr webViewGetInspector\n\n\n-- | The custom encoding of the 'WebView' instance\n--\n-- Default value: @Nothing@\nwebViewCustomEncoding :: WebViewClass self => Attr self (Maybe String)\nwebViewCustomEncoding = newAttr\n webViewGetCustomEncoding\n webViewSetCustomEncoding\n\n-- | view source mode of the 'WebView' instance\nwebViewViewSourceMode :: WebViewClass self => Attr self Bool\nwebViewViewSourceMode = newAttr\n webViewGetViewSourceMode\n webViewSetViewSourceMode\n\n-- | transparent background of the 'WebView' instance\nwebViewTransparent :: WebViewClass self => Attr self Bool\nwebViewTransparent = newAttr\n webViewGetTransparent\n webViewSetTransparent\n\n-- | Whether content of the 'WebView' can be modified by the user\n--\n-- Default value: @False@\nwebViewEditable :: WebViewClass self => Attr self Bool\nwebViewEditable = newAttr\n webViewGetEditable\n webViewSetEditable\n\n-- | Returns the current URI of the contents displayed by the @web_view@.\n--\n-- Default value: Nothing\nwebViewUri :: WebViewClass self => ReadAttr self (Maybe String)\nwebViewUri = readAttr webViewGetUri\n\n-- | The list of targets this web view supports for clipboard copying.\nwebViewCopyTargetList :: WebViewClass self => ReadAttr self (Maybe TargetList)\nwebViewCopyTargetList = readAttr webViewGetCopyTargetList\n\n-- | The list of targets this web view supports for clipboard pasteing.\nwebViewPasteTargetList :: WebViewClass self => ReadAttr self (Maybe TargetList)\nwebViewPasteTargetList = readAttr webViewGetPasteTargetList\n\n-- | An associated 'WebWindowFeatures' instance.\nwebViewWindowFeatures :: WebViewClass self => Attr self WebWindowFeatures\nwebViewWindowFeatures = \n newAttrFromObjectProperty \"window-features\"\n {#call pure webkit_web_window_features_get_type#}\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n-- | The URI for the favicon for the WebKitWebView.\n-- \n-- Default value: 'Nothing'\n-- \n-- * Since 1.1.18\nwebViewIconUri :: WebViewClass self => ReadAttr self String\nwebViewIconUri = readAttrFromStringProperty \"icon-uri\"\n#endif\n\n#if WEBKIT_CHECK_VERSION (1,1,20)\n-- | The 'IMMulticontext' for the WebKitWebView.\n-- \n-- This is the input method context used for all text entry widgets inside the WebKitWebView. It can be\n-- used to generate context menu items for controlling the active input method.\n-- \n-- * Since 1.1.20\nwebViewImContext :: WebViewClass self => ReadAttr self IMContext\nwebViewImContext = \n readAttrFromObjectProperty \"im-context\"\n {#call pure gtk_im_context_get_type #}\n#endif\n\n-- * Signals\n\n-- | When Document title changed, this signal is emitted.\n--\n-- It can be used to set the Application 'Window' title.\n--\n-- the user function signature is (WebFrame->String->IO())\n--\n-- webframe - which 'WebFrame' changes the document title.\n--\n-- title - current title string.\ntitleChanged :: WebViewClass self => Signal self ( WebFrame -> String -> IO() )\ntitleChanged = \n Signal (connect_OBJECT_STRING__NONE \"title-changed\")\n\n\n-- | When the cursor is over a link, this signal is emitted.\n-- \n-- the user function signature is (Maybe String -> Maybe String -> IO () )\n-- \n-- title - the link's title or @Nothing@ in case of failure.\n--\n-- uri - the URI the link points to or @Nothing@ in case of failure.\nhoveringOverLink :: WebViewClass self => Signal self (Maybe String -> Maybe String -> IO())\nhoveringOverLink =\n Signal (connect_MSTRING_MSTRING__NONE \"hovering-over-link\")\n\n-- | When a 'WebFrame' begins to load, this signal is emitted\nloadStarted :: WebViewClass self => Signal self (WebFrame -> IO())\nloadStarted = Signal (connect_OBJECT__NONE \"load-started\")\n\n-- | When a 'WebFrame' loaded the first data, this signal is emitted\nloadCommitted :: WebViewClass self => Signal self (WebFrame -> IO())\nloadCommitted = Signal (connect_OBJECT__NONE \"load-committed\")\n\n\n-- | When the global progress changed, this signal is emitted\n--\n-- the global progress will be passed back to user function\nprogressChanged :: WebViewClass self => Signal self (Int-> IO())\nprogressChanged = \n Signal (connect_INT__NONE \"load-progress-changed\")\n\n-- | When loading finished, this signal is emitted\nloadFinished :: WebViewClass self => Signal self (WebFrame -> IO())\nloadFinished = \n Signal (connect_OBJECT__NONE \"load-finished\")\n\n-- | When An error occurred while loading. \n--\n-- By default, if the signal is not handled,\n-- the WebView will display a stock error page. \n--\n-- You need to handle the signal\n-- if you want to provide your own error page.\n-- \n-- The URI that triggered the error and the 'GError' will be passed back to user function.\nloadError :: WebViewClass self => Signal self (WebFrame -> String -> GError -> IO Bool)\nloadError = Signal (connect_OBJECT_STRING_BOXED__BOOL \"load-error\" peek)\n\ncreateWebView :: WebViewClass self => Signal self (WebFrame -> IO WebView)\ncreateWebView = Signal (connect_OBJECT__OBJECTPTR \"create-web-view\")\n\n-- | Emitted when closing a WebView is requested. \n--\n-- This occurs when a call is made from JavaScript's window.close function. \n-- The default signal handler does not do anything. \n-- It is the owner's responsibility to hide or delete the 'WebView', if necessary.\n-- \n-- User function should return True to stop the handlers from being invoked for the event \n-- or False to propagate the event furter\ncloseWebView :: WebViewClass self => Signal self (IO Bool)\ncloseWebView = \n Signal (connect_NONE__BOOL \"close-web-view\")\n\n-- | A JavaScript console message was created.\nconsoleMessage :: WebViewClass self => Signal self (String -> String -> Int -> String -> IO Bool)\nconsoleMessage = Signal (connect_STRING_STRING_INT_STRING__BOOL \"console-message\")\n\n-- | The 'copyClipboard' signal is a keybinding signal which gets emitted to copy the selection to the clipboard.\n--\n-- The default bindings for this signal are Ctrl-c and Ctrl-Insert.\ncopyClipboard :: WebViewClass self => Signal self (IO ())\ncopyClipboard = Signal (connect_NONE__NONE \"copy-clipboard\")\n\n-- | The 'cutClipboard' signal is a keybinding signal which gets emitted to cut the selection to the clipboard.\n--\n-- The default bindings for this signal are Ctrl-x and Shift-Delete.\ncutClipboard :: WebViewClass self => Signal self (IO ())\ncutClipboard = Signal (connect_NONE__NONE \"cut-clipboard\")\n\n-- | The 'pasteClipboard' signal is a keybinding signal which gets emitted to paste the contents of the clipboard into the Web view.\n--\n-- The default bindings for this signal are Ctrl-v and Shift-Insert.\npasteClipboard :: WebViewClass self => Signal self (IO ())\npasteClipboard = Signal (connect_NONE__NONE \"paste-clipboard\")\n\n-- | When a context menu is about to be displayed this signal is emitted.\npopulatePopup :: WebViewClass self => Signal self (Menu -> IO ())\npopulatePopup = Signal (connect_OBJECT__NONE \"populate-popup\")\n\n-- | Emitted when printing is requested by the frame, usually because of a javascript call. \n-- When handling this signal you should call 'webFramePrintFull' or 'webFramePrint' to do the actual printing.\n--\n-- The default handler will present a print dialog and carry a print operation. \n-- Notice that this means that if you intend to ignore a print\n-- request you must connect to this signal, and return True.\nprintRequested :: WebViewClass self => Signal self (WebFrame -> IO Bool)\nprintRequested = Signal (connect_OBJECT__BOOL \"print-requested\")\n\n-- | A JavaScript alert dialog was created.\nscriptAlert :: WebViewClass self => Signal self (WebFrame -> String -> IO Bool)\nscriptAlert = Signal (connect_OBJECT_STRING__BOOL \"scriptAlert\")\n\n-- | A JavaScript confirm dialog was created, providing Yes and No buttons.\nscriptConfirm :: WebViewClass self => Signal self (WebFrame -> String -> IO Bool)\nscriptConfirm = Signal (connect_OBJECT_STRING__BOOL \"script-confirm\")\n\n-- | A JavaScript prompt dialog was created, providing an entry to input text.\nscriptPrompt :: WebViewClass self => Signal self (WebFrame -> String -> String -> IO Bool)\nscriptPrompt = Signal (connect_OBJECT_STRING_STRING__BOOL \"script-prompt\")\n\n-- | When status-bar text changed, this signal will emitted.\nstatusBarTextChanged :: WebViewClass self => Signal self (String -> IO ())\nstatusBarTextChanged = Signal (connect_STRING__NONE \"status-bar-text-changed\")\n\n\n\n-- | The 'selectAll' signal is a keybinding signal which gets emitted to select the complete contents of the text view.\n-- \n-- The default bindings for this signal is Ctrl-a.\nselectAll :: WebViewClass self => Signal self (IO ())\nselectAll = Signal (connect_NONE__NONE \"select-all\")\n\n-- | When selection changed, this signal is emitted.\nselectionChanged :: WebViewClass self => Signal self (IO ())\nselectionChanged = Signal (connect_NONE__NONE \"selection-changed\")\n\n-- | When set scroll adjustments, this signal is emitted.\nsetScrollAdjustments :: WebViewClass self => Signal self (Adjustment -> Adjustment -> IO ())\nsetScrollAdjustments = Signal (connect_OBJECT_OBJECT__NONE \"set-scroll-adjustments\")\n\n-- | The 'databaseQuotaExceeded' signal will be emitted when a Web Database exceeds the quota of its security origin. \n-- This signal may be used to increase the size of the quota before the originating operation fails.\ndatabaseQuotaExceeded :: WebViewClass self => Signal self (WebFrame -> WebDatabase -> IO ())\ndatabaseQuotaExceeded = Signal (connect_OBJECT_OBJECT__NONE \"database-quota-exceeded\")\n\n-- | When document loading finished, this signal is emitted\ndocumentLoadFinished :: WebViewClass self => Signal self (WebFrame -> IO ())\ndocumentLoadFinished = Signal (connect_OBJECT__NONE \"document-load-finished\")\n\n\n-- | Emitted after new 'WebView' instance had been created in 'onCreateWebView' user function\n-- when the new 'WebView' should be displayed to the user.\n-- \n-- All the information about how the window should look, \n-- including size,position,whether the location, status and scroll bars should be displayed, \n-- is ready set.\nwebViewReady:: WebViewClass self => Signal self (IO Bool)\nwebViewReady =\n Signal (connect_NONE__BOOL \"web-view-ready\")\n\n-- | Emitted after A new 'Download' is being requested. \n--\n-- By default, if the signal is not handled, the download is cancelled.\n-- \n-- Notice that while handling this signal you must set the target URI using 'downloadSetDestinationUri'\n-- \n-- If you intend to handle downloads yourself, return False in user function.\ndownloadRequested :: WebViewClass self => Signal self (Download -> IO Bool)\ndownloadRequested =\n Signal (connect_OBJECT__BOOL \"download-requested\")\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n-- | Emitted after Icon loaded\niconLoaded :: WebViewClass self => Signal self (IO ())\niconLoaded =\n Signal (connect_NONE__NONE \"icon-loaded\")\n#endif\n\n-- | The \"redo\" signal is a keybinding signal which gets emitted to redo the last editing command.\n--\n-- The default binding for this signal is Ctrl-Shift-z\nredo :: WebViewClass self => Signal self (IO ())\nredo =\n Signal (connect_NONE__NONE \"redo\")\n\n-- | The \"undo\" signal is a keybinding signal which gets emitted to undo the last editing command.\n--\n-- The default binding for this signal is Ctrl-z\nundo :: WebViewClass self => Signal self (IO ())\nundo =\n Signal (connect_NONE__NONE \"undo\")\n\n-- | Decide whether or not to display the given MIME type. \n-- If this signal is not handled, the default behavior is to show the content of the\n-- requested URI if WebKit can show this MIME type and the content disposition is not a download; \n-- if WebKit is not able to show the MIME type nothing happens.\n--\n-- Notice that if you return True, meaning that you handled the signal, \n-- you are expected to be aware of the \"Content-Disposition\" header. \n-- A value of \"attachment\" usually indicates a download regardless of the MIME type, \n-- see also soupMessageHeadersGetContentDisposition'\n-- And you must call 'webPolicyDecisionIgnore', 'webPolicyDecisionDownload', or 'webPolicyDecisionUse' \n-- on the 'webPolicyDecision' object.\nmimeTypePolicyDecisionRequested :: WebViewClass self => Signal self (WebFrame -> NetworkRequest -> String -> WebPolicyDecision -> IO Bool)\nmimeTypePolicyDecisionRequested = Signal (connect_OBJECT_OBJECT_STRING_OBJECT__BOOL \"mime-type-policy-decision-requested\")\n\n-- | The 'moveCursor' will be emitted to apply the cursor movement described by its parameters to the view.\nmoveCursor :: WebViewClass self => Signal self (MovementStep -> Int -> IO Bool)\nmoveCursor = Signal (connect_ENUM_INT__BOOL \"move-cursor\")\n\n-- | Emitted when frame requests a navigation to another page. \n-- If this signal is not handled, the default behavior is to allow the navigation.\n--\n-- Notice that if you return True, meaning that you handled the signal, \n-- you are expected to be aware of the \"Content-Disposition\" header. \n-- A value of \"attachment\" usually indicates a download regardless of the MIME type, \n-- see also soupMessageHeadersGetContentDisposition'\n-- And you must call 'webPolicyDecisionIgnore', 'webPolicyDecisionDownload', or 'webPolicyDecisionUse' \n-- on the 'webPolicyDecision' object.\nnavigationPolicyDecisionRequested :: WebViewClass self => Signal self (WebFrame -> NetworkRequest -> WebNavigationAction -> WebPolicyDecision -> IO Bool)\nnavigationPolicyDecisionRequested = Signal (connect_OBJECT_OBJECT_OBJECT_OBJECT__BOOL \"navigation-policy-decision-requested\")\n\n-- | Emitted when frame requests opening a new window. \n-- With this signal the browser can use the context of the request to decide about the new window. \n-- If the request is not handled the default behavior is to allow opening the new window to load the URI, \n-- which will cause a 'createWebView' signal emission where the browser handles the new window action \n-- but without information of the context that caused the navigation. \n-- The following 'navigationPolicyDecisionRequested' emissions will load the page \n-- after the creation of the new window just with the information of this new navigation context, \n-- without any information about the action that made this new window to be opened.\n--\n-- Notice that if you return True, meaning that you handled the signal, \n-- you are expected to be aware of the \"Content-Disposition\" header. \n-- A value of \"attachment\" usually indicates a download regardless of the MIME type, \n-- see also soupMessageHeadersGetContentDisposition'\n-- And you must call 'webPolicyDecisionIgnore', 'webPolicyDecisionDownload', or 'webPolicyDecisionUse' \n-- on the 'webPolicyDecision' object.\nnewWindowPolicyDecisionRequested :: WebViewClass self => Signal self (WebFrame -> NetworkRequest -> WebNavigationAction -> WebPolicyDecision -> IO Bool)\nnewWindowPolicyDecisionRequested = Signal (connect_OBJECT_OBJECT_OBJECT_OBJECT__BOOL \"new-window-policy-decision-requested\")\n\n-- | Emitted when a request is about to be sent. \n-- You can modify the request while handling this signal. \n-- You can set the URI in the 'NetworkRequest' object itself, \n-- and add\/remove\/replace headers using the SoupMessage object it carries, \n-- if it is present. See 'networkRequestGetMessage'. \n-- Setting the request URI to \"about:blank\" will effectively cause the request to load nothing, \n-- and can be used to disable the loading of specific resources.\n--\n-- Notice that information about an eventual redirect is available in response's SoupMessage, \n-- not in the SoupMessage carried by the request.\n-- If response is NULL, then this is not a redirected request.\n--\n-- The 'WebResource' object will be the same throughout all the lifetime of the resource, \n-- but the contents may change from inbetween signal emissions.\nresourceRequestStarting :: WebViewClass self => Signal self (WebFrame -> WebResource -> Maybe NetworkRequest -> Maybe NetworkResponse -> IO ())\nresourceRequestStarting = Signal (connect_OBJECT_OBJECT_MOBJECT_MOBJECT__NONE \"resource-request-starting\")\n\n#if WEBKIT_CHECK_VERSION (1,1,23)\n-- | When a frame wants to cancel geolocation permission it had requested before.\n--\n-- * Since 1.1.23 \ngeolocationPolicyDecisionCancelled :: WebViewClass self => Signal self (WebFrame -> IO ())\ngeolocationPolicyDecisionCancelled = Signal (connect_OBJECT__NONE \"geolocation-policy-decision-cancelled\")\n\n-- | When a frame wants to get its geolocation permission. The receiver must reply with a boolean wether\n-- it handled or not the request. If the request is not handled, default behaviour is to deny\n-- geolocation.\n-- \n-- * Since 1.1.23 \ngeolocationPolicyDecisionRequested :: WebViewClass self => Signal self (WebFrame -> GeolocationPolicyDecision -> IO ())\ngeolocationPolicyDecisionRequested = Signal (connect_OBJECT_OBJECT__NONE \"geolocation-policy-decision-requested\")\n#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"fc9c51a39dc703d49c1bfd2a643d6c731d741f56","subject":"Bindings for queryThread, isThreadMain","message":"Bindings for queryThread, isThreadMain\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Control\/Parallel\/MPI\/Internal.chs","new_file":"src\/Control\/Parallel\/MPI\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n\n#include \n#include \"compare.h\"\n#include \"init_wrapper.h\"\n\nmodule Control.Parallel.MPI.Internal\n ( init, initThread, queryThread, isThreadMain,\n finalize, send, bsend, ssend, rsend, recv,\n commRank, probe, commSize, commTestInter, commRemoteSize,\n commCompare, Compare(..),\n isend, ibsend, issend, irecv, bcast, barrier, wait, test,\n cancel, scatter, gather,\n scatterv, gatherv,\n allgather, allgatherv,\n alltoall, alltoallv,\n wtime, wtick\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\n\n{# context prefix = \"MPI\" #}\n\n{# enum Compare {underscoreToCase} deriving (Eq,Ord,Show) #}\n\ninit = {# call unsafe init_wrapper as init_wrapper_ #}\ninitThread = {# call unsafe init_wrapper_thread as init_wrapper_thread_ #}\nqueryThread = {# call unsafe Query_thread as queryThread_ #}\nisThreadMain = {# call unsafe Is_thread_main as isThreadMain_ #}\nfinalize = {# call unsafe Finalize as finalize_ #}\ncommSize = {# call unsafe Comm_size as commSize_ #}\ncommRank = {# call unsafe Comm_rank as commRank_ #}\ncommTestInter = {# call unsafe Comm_test_inter as commTestInter_ #}\ncommRemoteSize = {# call unsafe Comm_remote_size as commRemoteSize_ #}\ncommCompare = {# call unsafe Comm_compare as commCompare_ #}\nprobe = {# call Probe as probe_ #}\nsend = {# call unsafe Send as send_ #}\nbsend = {# call unsafe Bsend as bsend_ #}\nssend = {# call unsafe Ssend as ssend_ #}\nrsend = {# call unsafe Rsend as rsend_ #}\nrecv = {# call unsafe Recv as recv_ #}\nisend = {# call unsafe Isend as isend_ #}\nibsend = {# call unsafe Ibsend as ibsend_ #}\nissend = {# call unsafe Issend as issend_ #}\nirecv = {# call Irecv as irecv_ #}\nbcast = {# call unsafe Bcast as bcast_ #}\nbarrier = {# call unsafe Barrier as barrier_ #}\nwait = {# call unsafe Wait as wait_ #}\ntest = {# call unsafe Test as test_ #}\ncancel = {# call unsafe Cancel as cancel_ #}\nscatter = {# call unsafe Scatter as scatter_ #}\ngather = {# call unsafe Gather as gather_ #}\nscatterv = {# call unsafe Scatterv as scatterv_ #}\ngatherv = {# call unsafe Gatherv as gatherv_ #}\nallgather = {# call unsafe Allgather as allgather_ #}\nallgatherv = {# call unsafe Allgatherv as allgatherv_ #}\nalltoall = {# call unsafe Alltoall as alltoall_ #}\nalltoallv = {# call unsafe Alltoallv as alltoallv_ #}\nwtime = {# call unsafe Wtime as wtime_ #}\nwtick = {# call unsafe Wtick as wtick_ #}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n\n#include \n#include \"compare.h\"\n#include \"init_wrapper.h\"\n\nmodule Control.Parallel.MPI.Internal\n ( init, initThread, finalize, send, bsend, ssend, rsend, recv,\n commRank, probe, commSize, commTestInter, commRemoteSize,\n commCompare, Compare(..),\n isend, ibsend, issend, irecv, bcast, barrier, wait, test,\n cancel, scatter, gather,\n scatterv, gatherv,\n allgather, allgatherv,\n alltoall, alltoallv,\n wtime, wtick\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\n\n{# context prefix = \"MPI\" #}\n\n{# enum Compare {underscoreToCase} deriving (Eq,Ord,Show) #}\n\ninit = {# call unsafe init_wrapper as init_wrapper_ #}\ninitThread = {# call unsafe init_wrapper_thread as init_wrapper_thread_ #}\nfinalize = {# call unsafe Finalize as finalize_ #}\ncommSize = {# call unsafe Comm_size as commSize_ #}\ncommRank = {# call unsafe Comm_rank as commRank_ #}\ncommTestInter = {# call unsafe Comm_test_inter as commTestInter_ #}\ncommRemoteSize = {# call unsafe Comm_remote_size as commRemoteSize_ #}\ncommCompare = {# call unsafe Comm_compare as commCompare_ #}\nprobe = {# call Probe as probe_ #}\nsend = {# call unsafe Send as send_ #}\nbsend = {# call unsafe Bsend as bsend_ #}\nssend = {# call unsafe Ssend as ssend_ #}\nrsend = {# call unsafe Rsend as rsend_ #}\nrecv = {# call unsafe Recv as recv_ #}\nisend = {# call unsafe Isend as isend_ #}\nibsend = {# call unsafe Ibsend as ibsend_ #}\nissend = {# call unsafe Issend as issend_ #}\nirecv = {# call Irecv as irecv_ #}\nbcast = {# call unsafe Bcast as bcast_ #}\nbarrier = {# call unsafe Barrier as barrier_ #}\nwait = {# call unsafe Wait as wait_ #}\ntest = {# call unsafe Test as test_ #}\ncancel = {# call unsafe Cancel as cancel_ #}\nscatter = {# call unsafe Scatter as scatter_ #}\ngather = {# call unsafe Gather as gather_ #}\nscatterv = {# call unsafe Scatterv as scatterv_ #}\ngatherv = {# call unsafe Gatherv as gatherv_ #}\nallgather = {# call unsafe Allgather as allgather_ #}\nallgatherv = {# call unsafe Allgatherv as allgatherv_ #}\nalltoall = {# call unsafe Alltoall as alltoall_ #}\nalltoallv = {# call unsafe Alltoallv as alltoallv_ #}\nwtime = {# call unsafe Wtime as wtime_ #}\nwtick = {# call unsafe Wtick as wtick_ #}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"36d94d34c50675af3fe52252fe3ff78aebad6049","subject":"Add Haddocks","message":"Add Haddocks\n","repos":"cocreature\/nanovg-hs","old_file":"src\/NanoVG\/Internal.chs","new_file":"src\/NanoVG\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RecordWildCards #-}\nmodule NanoVG.Internal\n ( FileName(..)\n , Image(..)\n , Font(..)\n , Context(..)\n , Transformation(..)\n , Extent(..)\n , Color(..)\n , Paint(..)\n , Bounds(..)\n , GlyphPosition(..)\n , GlyphPositionPtr\n , TextRow(..)\n , TextRowPtr\n , CreateFlags(..)\n , Solidity(..)\n , LineCap(..)\n , Align(..)\n , Winding(..)\n , beginFrame\n , cancelFrame\n , endFrame\n -- * Color utils\n , rgb\n , rgbf\n , rgba\n , rgbaf\n , lerpRGBA\n , transRGBA\n , transRGBAf\n , hsl\n , hsla\n -- * State handling\n , save\n , restore\n , reset\n -- * Render styles\n , strokeColor\n , strokePaint\n , fillColor\n , fillPaint\n , miterLimit\n , strokeWidth\n , lineCap\n , lineJoin\n , globalAlpha\n -- * Transforms\n , resetTransform\n , transform\n , translate\n , rotate\n , skewX\n , skewY\n , scale\n , currentTransform\n , transformIdentity\n , transformTranslate\n , transformScale\n , transformRotate\n , transformSkewX\n , transformSkewY\n , transformMultiply\n , transformPremultiply\n , transformInverse\n , transformPoint\n , degToRad\n , radToDeg\n -- * Images\n , createImage\n , createImageMem\n , createImageRGBA\n , updateImage\n , imageSize\n , deleteImage\n -- * Paints\n , linearGradient\n , boxGradient\n , radialGradient\n , imagePattern\n -- * Scissoring\n , scissor\n , intersectScissor\n , resetScissor\n -- * Paths\n , beginPath\n , moveTo\n , lineTo\n , bezierTo\n , quadTo\n , arcTo\n , closePath\n , pathWinding\n , arc\n , rect\n , roundedRect\n , ellipse\n , circle\n , fill\n , stroke\n -- * Text\n , createFont\n , createFontMem\n , findFont\n , fontSize\n , fontBlur\n , textLetterSpacing\n , textLineHeight\n , textAlign\n , fontFaceId\n , fontFace\n , text\n , textBox\n , textBounds\n , textBoxBounds\n , textGlyphPositions\n , textMetrics\n , textBreakLines\n -- * GL\n , createGL3\n , deleteGL3\n , createImageFromHandleGL3\n , imageHandleGL3\n ) where\n\nimport Data.Bits hiding (rotate)\nimport Data.ByteString hiding (null)\nimport qualified Data.Set as S\nimport qualified Data.Text as T\nimport qualified Data.Text.Encoding as T\nimport Data.Word\nimport Foreign.C.String (CString)\nimport Foreign.C.Types\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Linear.Matrix\nimport Linear.V2\nimport Linear.V3\nimport Linear.V4\nimport Prelude hiding (null)\n\n-- For now only the GL3 backend is supported\n#define NANOVG_GL3\n-- We need to include this to define GLuint\n#include \"GL\/glew.h\"\n#include \"nanovg.h\"\n#include \"nanovg_gl.h\"\n#include \"nanovg_wrapper.h\"\n\n-- | Marshal a Haskell string into a NUL terminated C string using temporary storage.\nwithCString :: T.Text -> (CString -> IO b) -> IO b\nwithCString t = useAsCString (T.encodeUtf8 t)\n\n-- | Wrapper around 'useAsCStringLen' that uses 'CUChar's\nuseAsCStringLen' :: ByteString -> ((Ptr CUChar,CInt) -> IO a) -> IO a\nuseAsCStringLen' bs f = useAsCStringLen bs (\\(ptr,len) -> f (castPtr ptr,fromIntegral len))\n\n-- | Wrapper around 'useAsCStringLen'' that discards the length\nuseAsPtr :: ByteString -> (Ptr CUChar -> IO a) -> IO a\nuseAsPtr bs f = useAsCStringLen' bs (f . fst)\n\n-- | Marshalling helper for a constant zero\nzero :: Num a => (a -> b) -> b\nzero f = f 0\n\n-- | Marshalling helper for a constant 'nullPtr'\nnull :: (Ptr a -> b) -> b\nnull f = f nullPtr\n\n-- | Newtype to avoid accidental use of strings\nnewtype FileName = FileName { unwrapFileName :: T.Text }\n\n-- | Newtype to avoid accidental use of ints\nnewtype Image = Image {imageHandle :: CInt} deriving (Show,Read,Eq,Ord)\n\n-- | Newtype to avoid accidental use of ints\nnewtype Font = Font {fontHandle :: CInt} deriving (Show,Read,Eq,Ord)\n\n-- | Opaque context that needs to be passed around\n{#pointer *NVGcontext as Context newtype#}\n\n-- | Affine matrix\n--\n-- > [sx kx tx]\n-- > [ky sy ty]\n-- > [ 0 0 1]\nnewtype Transformation = Transformation (M23 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Transformation where\n sizeOf _ = sizeOf (0 :: CFloat) * 6\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peek p'\n b <- peekElemOff p' 1\n c <- peekElemOff p' 2\n d <- peekElemOff p' 3\n e <- peekElemOff p' 4\n f <- peekElemOff p' 5\n pure (Transformation\n (V2 (V3 a c e)\n (V3 b d f)))\n poke p (Transformation (V2 (V3 a c e) (V3 b d f))) =\n do let p' = castPtr p :: Ptr CFloat\n poke p' a\n pokeElemOff p' 1 b\n pokeElemOff p' 2 c\n pokeElemOff p' 3 d\n pokeElemOff p' 4 e\n pokeElemOff p' 5 f\n\nnewtype Extent = Extent (V2 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Extent where\n sizeOf _ = sizeOf (0 :: CFloat) * 2\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peekElemOff p' 0\n b <- peekElemOff p' 1\n pure (Extent (V2 a b))\n poke p (Extent (V2 a b)) =\n do let p' = castPtr p :: Ptr CFloat\n pokeElemOff p' 0 a\n pokeElemOff p' 1 b\n\n-- | rgba\ndata Color = Color !CFloat !CFloat !CFloat !CFloat deriving (Show,Read,Eq,Ord)\n\n{#pointer *NVGcolor as ColorPtr -> Color#}\n\ninstance Storable Color where\n sizeOf _ = sizeOf (0 :: CFloat) * 4\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n r <- peek p'\n g <- peekElemOff p' 1\n b <- peekElemOff p' 2\n a <- peekElemOff p' 3\n pure (Color r g b a)\n poke p (Color r g b a) =\n do let p' = castPtr p :: Ptr CFloat\n poke p' r\n pokeElemOff p' 1 g\n pokeElemOff p' 2 b\n pokeElemOff p' 3 a\n\ndata Paint =\n Paint {xform :: Transformation\n ,extent :: Extent\n ,radius :: !CFloat\n ,feather :: !CFloat\n ,innerColor :: !Color\n ,outerColor :: !Color\n ,image :: !Image} deriving (Show,Read,Eq,Ord)\n\n{#pointer *NVGpaint as PaintPtr -> Paint#}\n\ninstance Storable Paint where\n sizeOf _ = 76\n alignment _ = 4\n peek p =\n do xform <- peek (castPtr (p `plusPtr` {#offsetof NVGpaint->xform#}))\n extent <- peek (castPtr (p `plusPtr` {#offsetof NVGpaint->extent#}))\n radius <- {#get NVGpaint->radius#} p\n feather <- {#get NVGpaint->feather#} p\n innerColor <- peek (castPtr (p `plusPtr` 40))\n outerColor <- peek (castPtr (p `plusPtr` 56))\n image <- peek (castPtr (p `plusPtr` 72))\n pure (Paint xform extent radius feather innerColor outerColor (Image image))\n poke p (Paint{..}) =\n do poke (castPtr (p `plusPtr` {#offsetof NVGpaint->xform#})) xform\n poke (castPtr (p `plusPtr` {#offsetof NVGpaint->extent#})) extent\n {#set NVGpaint->radius#} p radius\n {#set NVGpaint->feather#} p feather\n poke (castPtr (p `plusPtr` 40)) innerColor\n poke (castPtr (p `plusPtr` 56)) outerColor\n poke (castPtr (p `plusPtr` 72)) (imageHandle image)\n\n{#enum NVGwinding as Winding\n {} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGsolidity as Solidity\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGlineCap as LineCap\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGalign as Align \n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\ndata GlyphPosition =\n GlyphPosition { -- | Pointer of the glyph in the input string.\n str :: !(Ptr CChar)\n -- | The x-coordinate of the logical glyph position.\n , glyphX :: !CFloat\n -- | The left bound of the glyph shape.\n , glyphPosMinX :: !CFloat\n -- | The right bound of the glyph shape.\n , glyphPosMaxX :: !CFloat} deriving (Show,Eq,Ord)\n\n{#pointer *NVGglyphPosition as GlyphPositionPtr -> GlyphPosition#}\n\ninstance Storable GlyphPosition where\n sizeOf _ = 24\n alignment _ = {#alignof NVGglyphPosition#}\n peek p =\n do str <- {#get NVGglyphPosition->str#} p\n x <- {#get NVGglyphPosition->x#} p\n minx <- {#get NVGglyphPosition->minx#} p\n maxx <- {#get NVGglyphPosition->maxx#} p\n pure (GlyphPosition str x minx maxx)\n poke p (GlyphPosition str x minx maxx) =\n do {#set NVGglyphPosition->str#} p str\n {#set NVGglyphPosition->x#} p x\n {#set NVGglyphPosition->minx#} p minx\n {#set NVGglyphPosition->maxx#} p maxx\n\ndata TextRow =\n TextRow { -- | Pointer to the input text where the row starts.\n start :: !(Ptr CChar)\n -- | Pointer to the input text where the row ends (one past the last character).\n , end :: !(Ptr CChar)\n -- | Pointer to the beginning of the next row.\n , next :: !(Ptr CChar)\n -- | Logical width of the row.\n , width :: !CFloat\n -- | Actual bounds of the row. Logical with and bounds can differ because of kerning and some parts over extending.\n , textRowMinX :: !CFloat\n , textRowMaxX :: !CFloat}\n deriving (Show,Eq,Ord)\n\ninstance Storable TextRow where\n sizeOf _ = 40\n alignment _ = {#alignof NVGtextRow#}\n peek p =\n do start <- {#get NVGtextRow->start#} p\n end <- {#get NVGtextRow->end#} p\n next <- {#get NVGtextRow->next#} p\n width <- {#get NVGtextRow->width#} p\n minX <- {#get NVGtextRow->minx#} p\n maxX <- {#get NVGtextRow->maxx#} p\n pure (TextRow start end next width minX maxX)\n poke p (TextRow {..}) =\n do {#set NVGtextRow->start#} p start\n {#set NVGtextRow->end#} p end\n {#set NVGtextRow->next#} p next\n {#set NVGtextRow->width#} p width\n {#set NVGtextRow->minx#} p textRowMinX\n {#set NVGtextRow->maxx#} p textRowMaxX\n\n{#pointer *NVGtextRow as TextRowPtr -> TextRow#}\n\n{#enum NVGimageFlags as ImageFlags\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n-- | Begin drawing a new frame\n--\n-- Calls to nanovg drawing API should be wrapped in 'beginFrame' & 'endFrame'.\n--\n-- 'beginFrame' defines the size of the window to render to in relation currently\n-- set viewport (i.e. glViewport on GL backends). Device pixel ration allows to\n-- control the rendering on Hi-DPI devices.\n--\n-- For example, GLFW returns two dimension for an opened window: window size and\n-- frame buffer size. In that case you would set windowWidth\/Height to the window size\n-- devicePixelRatio to: frameBufferWidth \/ windowWidth.\n{#fun unsafe nvgBeginFrame as beginFrame\n {`Context',`CInt',`CInt',`Float'} -> `()'#}\n\n-- | Cancels drawing the current frame.\n{#fun unsafe nvgCancelFrame as cancelFrame\n {`Context'} -> `()'#}\n\n-- | Ends drawing flushing remaining render state.\n{#fun unsafe nvgEndFrame as endFrame\n {`Context'} -> `()'#}\n\n-- | Returns a color value from red, green, blue values. Alpha will be set to 255 (1.0f).\n{#fun pure unsafe nvgRGB_ as rgb\n {id`CUChar',id`CUChar',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n-- | Returns a color value from red, green, blue values. Alpha will be set to 1.0f.\n{#fun pure unsafe nvgRGBf_ as rgbf\n {`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n-- | Returns a color value from red, green, blue and alpha values.\n{#fun pure unsafe nvgRGBA_ as rgba\n {id`CUChar',id`CUChar',id`CUChar',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n-- | Returns a color value from red, green, blue and alpha values.\n{#fun pure unsafe nvgRGBAf_ as rgbaf\n {`CFloat',`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n-- | Linearly interpolates from color c0 to c1, and returns resulting color value.\n{#fun pure unsafe nvgLerpRGBA_ as lerpRGBA\n {with*`Color',with*`Color',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n-- | Sets transparency of a color value.\n{#fun pure unsafe nvgTransRGBA_ as transRGBA\n {with*`Color',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n-- | Sets transparency of a color value.\n{#fun pure unsafe nvgTransRGBAf_ as transRGBAf\n {with*`Color',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n-- | Returns color value specified by hue, saturation and lightness.\n-- HSL values are all in range [0..1], alpha will be set to 255.\n{#fun pure unsafe nvgHSL_ as hsl\n {`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n-- | Returns color value specified by hue, saturation and lightness and alpha.\n-- HSL values are all in range [0..1], alpha in range [0..255]\n{#fun pure unsafe nvgHSLA_ as hsla\n {`CFloat',`CFloat',`CFloat',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n-- | Pushes and saves the current render state into a state stack.\n-- A matching 'restore' must be used to restore the state.\n\n{#fun unsafe nvgSave as save\n {`Context'} -> `()'#}\n\n-- | Pops and restores current render state.\n{#fun unsafe nvgRestore as restore\n {`Context'} -> `()'#}\n\n-- | Resets current render state to default values. Does not affect the render state stack.\n{#fun unsafe nvgReset as reset\n {`Context'} -> `()'#}\n\n-- | Sets current stroke style to a solid color.\n{#fun unsafe nvgStrokeColor_ as strokeColor\n {`Context',with*`Color'} -> `()'#}\n\n-- | Sets current stroke style to a paint, which can be a one of the gradients or a pattern.\n{#fun unsafe nvgStrokePaint_ as strokePaint\n {`Context',with*`Paint'} -> `()'#}\n\n-- | Sets current fill style to a solid color.\n{#fun unsafe nvgFillColor_ as fillColor\n {`Context',with*`Color'} -> `()'#}\n\n-- | Sets current fill style to a paint, which can be a one of the gradients or a pattern.\n{#fun unsafe nvgFillPaint_ as fillPaint\n {`Context',with*`Paint'} -> `()'#}\n\n-- | Sets the miter limit of the stroke style.\n-- Miter limit controls when a sharp corner is beveled.\n{#fun unsafe nvgMiterLimit as miterLimit\n {`Context',`CFloat'} -> `()'#}\n\n-- | Sets the stroke width of the stroke style.\n{#fun unsafe nvgStrokeWidth as strokeWidth\n {`Context',`CFloat'} -> `()'#}\n\n-- | Sets how the end of the line (cap) is drawn,\n-- Can be one of: 'Butt' (default), 'Round', 'Square'.\n{#fun unsafe nvgLineCap as lineCap\n {`Context',`LineCap'} -> `()'#}\n\n-- | Sets how sharp path corners are drawn.\n-- Can be one of 'Miter' (default), 'Round', 'Bevel.\n{#fun unsafe nvgLineJoin as lineJoin\n {`Context',`LineCap'} -> `()'#}\n\n-- | Sets the transparency applied to all rendered shapes.\n-- Already transparent paths will get proportionally more transparent as well.\n{#fun unsafe nvgGlobalAlpha as globalAlpha\n {`Context',`CFloat'} -> `()'#}\n\n-- | Resets current transform to a identity matrix.\n{#fun unsafe nvgResetTransform as resetTransform\n {`Context'} -> `()'#}\n\n-- | Premultiplies current coordinate system by specified matrix.\n-- The parameters are interpreted as matrix as follows:\n--\n-- > [a c e]\n-- > [b d f]\n-- > [0 0 1]\n{#fun unsafe nvgTransform as transform\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n-- | Translates current coordinate system.\n{#fun unsafe nvgTranslate as translate\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n-- | Rotates current coordinate system. Angle is specified in radians.\n{#fun unsafe nvgRotate as rotate\n {`Context',`CFloat'} -> `()'#}\n\n-- | Skews the current coordinate system along X axis. Angle is specified in radians.\n{#fun unsafe nvgSkewX as skewX\n {`Context',`CFloat'} -> `()'#}\n\n-- | Skews the current coordinate system along Y axis. Angle is specified in radians.\n{#fun unsafe nvgSkewY as skewY\n {`Context',`CFloat'} -> `()'#}\n\n-- | Scales the current coordinate system.\n{#fun unsafe nvgScale as scale\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\npeekTransformation :: Ptr CFloat -> IO Transformation\npeekTransformation = peek . castPtr\n\nallocaTransformation :: (Ptr CFloat -> IO b) -> IO b\nallocaTransformation f = alloca (\\(p :: Ptr Transformation) -> f (castPtr p))\n\nwithTransformation :: Transformation -> (Ptr CFloat -> IO b) -> IO b\nwithTransformation t f = with t (\\p -> f (castPtr p)) \n\n-- | Returns the current transformation matrix.\n{#fun unsafe nvgCurrentTransform as currentTransform\n {`Context',allocaTransformation-`Transformation'peekTransformation*} -> `()'#}\n\n-- | Sets the transform to identity matrix.\n{#fun unsafe nvgTransformIdentity as transformIdentity\n {allocaTransformation-`Transformation'peekTransformation*} -> `()'#}\n\n-- | Sets the transform to translation matrix matrix.\n{#fun unsafe nvgTransformTranslate as transformTranslate\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat',`CFloat'} -> `()'#}\n\n-- | Sets the transform to scale matrix.\n{#fun unsafe nvgTransformScale as transformScale\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat',`CFloat'} -> `()'#}\n\n-- | Sets the transform to rotate matrix. Angle is specified in radians.\n{#fun unsafe nvgTransformRotate as transformRotate\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n-- | Sets the transform to skew-x matrix. Angle is specified in radians.\n{#fun unsafe nvgTransformSkewX as transformSkewX\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n-- | Sets the transform to skew-y matrix. Angle is specified in radians.\n{#fun unsafe nvgTransformSkewY as transformSkewY\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n-- | Sets the transform to the result of multiplication of two transforms, of A = A*B.\n{#fun unsafe nvgTransformMultiply as transformMultiply\n {withTransformation*`Transformation'peekTransformation*,withTransformation*`Transformation'} -> `()'#}\n\n-- | Sets the transform to the result of multiplication of two transforms, of A = B*A.\n{#fun unsafe nvgTransformPremultiply as transformPremultiply\n {withTransformation*`Transformation'peekTransformation*,withTransformation*`Transformation'} -> `()'#}\n\n-- | Sets the destination to inverse of specified transform.\n-- Returns 1 if the inverse could be calculated, else 0.\n{#fun unsafe nvgTransformInverse as transformInverse\n {allocaTransformation-`Transformation'peekTransformation*,withTransformation*`Transformation'} -> `()'#}\n\n-- | Transform a point by given transform.\n{#fun pure unsafe nvgTransformPoint as transformPoint\n {alloca-`CFloat'peek*,alloca-`CFloat'peek*,withTransformation*`Transformation',`CFloat',`CFloat'} -> `()'#}\n\n-- | Converts degrees to radians.\n{#fun pure unsafe nvgDegToRad as degToRad\n {`CFloat'} -> `CFloat'#}\n\n-- | Converts radians to degrees.\n{#fun pure unsafe nvgRadToDeg as radToDeg\n {`CFloat'} -> `CFloat'#}\n\nsafeImage :: CInt -> Maybe Image\nsafeImage i\n | i < 0 = Nothing\n | otherwise = Just (Image i)\n\n-- | Creates image by loading it from the disk from specified file name.\n{#fun unsafe nvgCreateImage as createImage\n {`Context','withCString.unwrapFileName'*`FileName',`CInt'} -> `Maybe Image'safeImage#}\n\n-- | Creates image by loading it from the specified chunk of memory.\n{#fun unsafe nvgCreateImageMem as createImageMem\n {`Context',`ImageFlags',useAsCStringLen'*`ByteString'&} -> `Maybe Image'safeImage#}\n\n-- | Creates image from specified image data.\n{#fun unsafe nvgCreateImageRGBA as createImageRGBA\n {`Context',`CInt',`CInt',`ImageFlags',useAsPtr*`ByteString'} -> `Maybe Image'safeImage#}\n\n-- | Updates image data specified by image handle.\n{#fun unsafe nvgUpdateImage as updateImage\n {`Context',imageHandle`Image',useAsPtr*`ByteString'} -> `()'#}\n\n-- | Returns the dimensions of a created image.\n{#fun unsafe nvgImageSize as imageSize\n {`Context',imageHandle`Image',alloca-`CInt'peek*,alloca-`CInt'peek*} -> `()'#}\n\n-- | Deletes created image.\n{#fun unsafe nvgDeleteImage as deleteImage\n {`Context',imageHandle`Image'} -> `()'#}\n\n-- | Creates and returns a linear gradient. Parameters (sx,sy)-(ex,ey) specify the start and end coordinates\n-- of the linear gradient, icol specifies the start color and ocol the end color.\n-- The gradient is transformed by the current transform when it is passed to 'fillPaint' or 'strokePaint'.\n{#fun unsafe nvgLinearGradient_ as linearGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n-- | Creates and returns a box gradient. Box gradient is a feathered rounded rectangle, it is useful for rendering\n-- drop shadows or highlights for boxes. Parameters (x,y) define the top-left corner of the rectangle,\n-- (w,h) define the size of the rectangle, r defines the corner radius, and f feather. Feather defines how blurry\n-- the border of the rectangle is. Parameter icol specifies the inner color and ocol the outer color of the gradient.\n-- The gradient is transformed by the current transform when it is passed to 'fillPaint' or 'strokePaint'.\n{#fun unsafe nvgBoxGradient_ as boxGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n-- | Creates and returns a radial gradient. Parameters (cx,cy) specify the center, inr and outr specify\n-- the inner and outer radius of the gradient, icol specifies the start color and ocol the end color.\n-- The gradient is transformed by the current transform when it is passed to 'fillPaint' or 'strokePaint'.\n{#fun unsafe nvgRadialGradient_ as radialGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n-- | Creates and returns an image patter. Parameters (ox,oy) specify the left-top location of the image pattern,\n-- (ex,ey) the size of one image, angle rotation around the top-left corner, image is handle to the image to render.\n-- The gradient is transformed by the current transform when it is passed to 'fillPaint' or 'strokePaint'.\n{#fun unsafe nvgImagePattern_ as imagePattern\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',imageHandle`Image',`CFloat',alloca-`Paint'peek*} -> `()'#}\n\n-- | Sets the current scissor rectangle.\n-- The scissor rectangle is transformed by the current transform.\n{#fun unsafe nvgScissor as scissor\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n-- | Intersects current scissor rectangle with the specified rectangle.\n-- The scissor rectangle is transformed by the current transform.\n-- Note: in case the rotation of previous scissor rect differs from\n-- the current one, the intersection will be done between the specified\n-- rectangle and the previous scissor rectangle transformed in the current\n-- transform space. The resulting shape is always rectangle.\n{#fun unsafe nvgIntersectScissor as intersectScissor\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n-- | Reset and disables scissoring.\n{#fun unsafe nvgResetScissor as resetScissor\n {`Context'} -> `()'#}\n\n-- | Clears the current path and sub-paths.\n{#fun unsafe nvgBeginPath as beginPath\n {`Context'} -> `()'#}\n\n-- | Starts new sub-path with specified point as first point.\n{#fun unsafe nvgMoveTo as moveTo\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n-- | Adds line segment from the last point in the path to the specified point.\n{#fun unsafe nvgLineTo as lineTo\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n-- | Adds cubic bezier segment from last point in the path via two control points to the specified point.\n{#fun unsafe nvgBezierTo as bezierTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n-- | Adds quadratic bezier segment from last point in the path via a control point to the specified point\n{#fun unsafe nvgQuadTo as quadTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n-- | Adds an arc segment at the corner defined by the last path point, and two specified points.\n{#fun unsafe nvgArcTo as arcTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n-- | Closes current sub-path with a line segment.\n{#fun unsafe nvgClosePath as closePath\n {`Context'} -> `()'#}\n\n-- | Sets the current sub-path winding, see NVGwinding and NVGsolidity. \n{#fun unsafe nvgPathWinding as pathWinding\n {`Context', `CInt'} -> `()'#}\n\n-- | Creates new circle arc shaped sub-path. The arc center is at cx,cy, the arc radius is r,\n-- and the arc is drawn from angle a0 to a1, and swept in direction dir (NVG_CCW, or NVG_CW).\n-- Angles are specified in radians.\n{#fun unsafe nvgArc as arc\n {`Context',`CFloat',`CFloat', `CFloat', `CFloat', `CFloat', `Winding'} -> `()'#}\n\n-- | Creates new rectangle shaped sub-path.\n{#fun unsafe nvgRect as rect\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n-- | Creates new rounded rectangle shaped sub-path.\n{#fun unsafe nvgRoundedRect as roundedRect\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n-- | Creates new ellipse shaped sub-path.\n{#fun unsafe nvgEllipse as ellipse\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n-- | Creates new circle shaped sub-path. \n{#fun unsafe nvgCircle as circle\n {`Context',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n-- | Fills the current path with current fill style.\n{#fun unsafe nvgFill as fill\n {`Context'} -> `()'#}\n\n-- | Fills the current path with current stroke style.\n{#fun unsafe nvgStroke as stroke\n {`Context'} -> `()'#}\n\nsafeFont :: CInt -> Maybe Font\nsafeFont i\n | i < 0 = Nothing\n | otherwise = Just (Font i)\n\n-- | Creates font by loading it from the disk from specified file name.\n-- Returns handle to the font.\n{#fun unsafe nvgCreateFont as createFont\n {`Context',withCString*`T.Text','withCString.unwrapFileName'*`FileName'} -> `Maybe Font'safeFont#}\n\n-- | Creates image by loading it from the specified memory chunk.\n-- Returns handle to the font.\n{#fun unsafe nvgCreateFontMem as createFontMem\n {`Context',withCString*`T.Text',useAsCStringLen'*`ByteString'&,zero-`CInt'} -> `Maybe Font'safeFont#}\n\n-- | Finds a loaded font of specified name, and returns handle to it, or -1 if the font is not found.\n{#fun unsafe nvgFindFont as findFont\n {`Context', withCString*`T.Text'} -> `Maybe Font'safeFont#}\n\n-- | Sets the font size of current text style.\n{#fun unsafe nvgFontSize as fontSize\n {`Context',`CFloat'} -> `()'#}\n\n-- | Sets the blur of current text style.\n{#fun unsafe nvgFontBlur as fontBlur\n {`Context',`CFloat'} -> `()'#}\n\n-- | Sets the letter spacing of current text style.\n{#fun unsafe nvgTextLetterSpacing as textLetterSpacing\n {`Context',`CFloat'} -> `()'#}\n\n-- | Sets the proportional line height of current text style. The line height is specified as multiple of font size. \n{#fun unsafe nvgTextLineHeight as textLineHeight\n {`Context',`CFloat'} -> `()'#}\n\n-- | Sets the text align of current text style, see NVGalign for options.\n{#fun unsafe nvgTextAlign as textAlign\n {`Context',bitMask`S.Set Align'} -> `()'#}\n\n-- | Sets the font face based on specified id of current text style.\n{#fun unsafe nvgFontFaceId as fontFaceId\n {`Context',fontHandle`Font'} -> `()'#}\n\n-- | Sets the font face based on specified name of current text styl\n{#fun unsafe nvgFontFace as fontFace\n {`Context',withCString*`T.Text'} -> `()'#}\n\n-- | Draws text string at specified location. If end is specified only the sub-string up to the end is drawn.\n{#fun unsafe nvgText as text\n {`Context',`CFloat',`CFloat',id`Ptr CChar',id`Ptr CChar'} -> `()'#}\n\n-- | Draws multi-line text string at specified location wrapped at the specified width. If end is specified only the sub-string up to the end is drawn.\n-- | White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered.\n-- | Words longer than the max width are slit at nearest character (i.e. no hyphenation).\n{#fun unsafe nvgTextBox as textBox\n {`Context',`CFloat',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar'} -> `()'#}\n\nnewtype Bounds = Bounds (V4 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Bounds where\n sizeOf _ = sizeOf (0 :: CFloat) * 4\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peekElemOff p' 0\n b <- peekElemOff p' 1\n c <- peekElemOff p' 2\n d <- peekElemOff p' 3\n pure (Bounds (V4 a b c d))\n poke p (Bounds (V4 a b c d)) =\n do let p' = castPtr p :: Ptr CFloat\n pokeElemOff p' 0 a\n pokeElemOff p' 1 b\n pokeElemOff p' 2 c\n pokeElemOff p' 3 d\n\npeekBounds :: Ptr CFloat -> IO Bounds\npeekBounds = peek . castPtr\n\nallocaBounds :: (Ptr CFloat -> IO b) -> IO b\nallocaBounds f = alloca (\\(p :: Ptr Bounds) -> f (castPtr p))\n\n-- | Measures the specified text string. Parameter bounds should be a pointer to float[4],\n-- if the bounding box of the text should be returned. The bounds value are [xmin,ymin, xmax,ymax]\n-- Returns the horizontal advance of the measured text (i.e. where the next character should drawn).\n-- Measured values are returned in local coordinate space.\n{#fun unsafe nvgTextBounds as textBounds\n {`Context',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar', allocaBounds-`Bounds'peekBounds*} -> `()'#}\n\n-- | Measures the specified multi-text string. Parameter bounds should be a pointer to float[4],\n-- if the bounding box of the text should be returned. The bounds value are [xmin,ymin, xmax,ymax]\n-- Measured values are returned in local coordinate space.\n{#fun unsafe nvgTextBoxBounds as textBoxBounds\n {`Context',`CFloat',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar',allocaBounds-`Bounds'peekBounds*} -> `()'#}\n\n-- | Calculates the glyph x positions of the specified text. If end is specified only the sub-string will be used.\n-- Measured values are returned in local coordinate space.\n{#fun unsafe nvgTextGlyphPositions as textGlyphPositions\n {`Context',`CFloat',`CFloat',id`Ptr CChar',id`Ptr CChar',`GlyphPositionPtr', `CInt'} -> `CInt'#}\n\n-- | Returns the vertical metrics based on the current text style.\n-- Measured values are returned in local coordinate space.\n{#fun unsafe nvgTextMetrics as textMetrics\n {`Context',alloca-`CFloat'peek*,alloca-`CFloat'peek*,alloca-`CFloat'peek*} -> `()'#}\n\n-- | Breaks the specified text into lines. If end is specified only the sub-string will be used.\n-- White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered.\n-- Words longer than the max width are slit at nearest character (i.e. no hyphenation).\n{#fun unsafe nvgTextBreakLines as textBreakLines\n {`Context',id`Ptr CChar',id`Ptr CChar',`CFloat',`TextRowPtr',`CInt'} -> `CInt'#}\n\n{#enum NVGcreateFlags as CreateFlags\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\nbitMask :: Enum a => S.Set a -> CInt\nbitMask = S.fold (.|.) 0 . S.map (fromIntegral . fromEnum)\n\n{#fun unsafe nvgCreateGL3 as createGL3\n {bitMask`S.Set CreateFlags'} -> `Context'#}\n{#fun unsafe nvgDeleteGL3 as deleteGL3\n {`Context'} -> `()'#}\n\ntype GLuint = Word32\n\n{#fun unsafe nvglCreateImageFromHandleGL3 as createImageFromHandleGL3\n {`Context',fromIntegral`GLuint',`CInt',`CInt',`CreateFlags'} -> `Image'Image#}\n\n{#fun unsafe nvglImageHandleGL3 as imageHandleGL3\n {`Context',imageHandle`Image'} -> `GLuint'fromIntegral#}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RecordWildCards #-}\nmodule NanoVG.Internal where\n\nimport Data.Bits\nimport Data.ByteString hiding (null)\nimport qualified Data.Set as S\nimport qualified Data.Text as T\nimport qualified Data.Text.Encoding as T\nimport Data.Word\nimport Foreign.C.String (CString)\nimport Foreign.C.Types\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Linear.Matrix\nimport Linear.V2\nimport Linear.V3\nimport Linear.V4\nimport Prelude hiding (null)\n\n-- For now only the GL3 backend is supported\n#define NANOVG_GL3\n-- We need to include this to define GLuint\n#include \"GL\/glew.h\"\n#include \"nanovg.h\"\n#include \"nanovg_gl.h\"\n#include \"nanovg_wrapper.h\"\n\nwithCString :: T.Text -> (CString -> IO b) -> IO b\nwithCString t = useAsCString (T.encodeUtf8 t)\n\nuseAsCStringLen' :: ByteString -> ((Ptr CUChar,CInt) -> IO a) -> IO a\nuseAsCStringLen' bs f = useAsCStringLen bs (\\(ptr,len) -> f (castPtr ptr,fromIntegral len))\n\nuseAsPtr :: ByteString -> (Ptr CUChar -> IO a) -> IO a\nuseAsPtr bs f = useAsCStringLen bs (\\(ptr,_) -> f (castPtr ptr))\n\nzero :: Num a => (a -> b) -> b\nzero f = f 0\n\nnull :: (Ptr a -> b) -> b\nnull f = f nullPtr\n\nnewtype FileName = FileName { unwrapFileName :: T.Text }\n\nnewtype Image = Image {imageHandle :: CInt} deriving (Show,Read,Eq,Ord)\n\nnewtype Font = Font {fontHandle :: CInt} deriving (Show,Read,Eq,Ord)\n\n{#pointer *NVGcontext as Context newtype#}\n\nnewtype Transformation = Transformation (M23 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Transformation where\n sizeOf _ = sizeOf (0 :: CFloat) * 6\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peek p'\n b <- peekElemOff p' 1\n c <- peekElemOff p' 2\n d <- peekElemOff p' 3\n e <- peekElemOff p' 4\n f <- peekElemOff p' 5\n pure (Transformation\n (V2 (V3 a c e)\n (V3 b d f)))\n poke p (Transformation (V2 (V3 a c e) (V3 b d f))) =\n do let p' = castPtr p :: Ptr CFloat\n poke p' a\n pokeElemOff p' 1 b\n pokeElemOff p' 2 c\n pokeElemOff p' 3 d\n pokeElemOff p' 4 e\n pokeElemOff p' 5 f\n\nnewtype Extent = Extent (V2 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Extent where\n sizeOf _ = sizeOf (0 :: CFloat) * 2\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peekElemOff p' 0\n b <- peekElemOff p' 1\n pure (Extent (V2 a b))\n poke p (Extent (V2 a b)) =\n do let p' = castPtr p :: Ptr CFloat\n pokeElemOff p' 0 a\n pokeElemOff p' 1 b\n\n-- | rgba\ndata Color = Color !CFloat !CFloat !CFloat !CFloat deriving (Show,Read,Eq,Ord)\n\n{#pointer *NVGcolor as ColorPtr -> Color#}\n\ninstance Storable Color where\n sizeOf _ = sizeOf (0 :: CFloat) * 4\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n r <- peek p'\n g <- peekElemOff p' 1\n b <- peekElemOff p' 2\n a <- peekElemOff p' 3\n pure (Color r g b a)\n poke p (Color r g b a) =\n do let p' = castPtr p :: Ptr CFloat\n poke p' r\n pokeElemOff p' 1 g\n pokeElemOff p' 2 b\n pokeElemOff p' 3 a\n\ndata Paint =\n Paint {xform :: Transformation\n ,extent :: Extent\n ,radius :: !CFloat\n ,feather :: !CFloat\n ,innerColor :: !Color\n ,outerColor :: !Color\n ,image :: !Image} deriving (Show,Read,Eq,Ord)\n\n{#pointer *NVGpaint as PaintPtr -> Paint#}\n\ninstance Storable Paint where\n sizeOf _ = 76\n alignment _ = 4\n peek p =\n do xform <- peek (castPtr (p `plusPtr` {#offsetof NVGpaint->xform#}))\n extent <- peek (castPtr (p `plusPtr` {#offsetof NVGpaint->extent#}))\n radius <- {#get NVGpaint->radius#} p\n feather <- {#get NVGpaint->feather#} p\n innerColor <- peek (castPtr (p `plusPtr` 40))\n outerColor <- peek (castPtr (p `plusPtr` 56))\n image <- peek (castPtr (p `plusPtr` 72))\n pure (Paint xform extent radius feather innerColor outerColor (Image image))\n poke p (Paint{..}) =\n do poke (castPtr (p `plusPtr` {#offsetof NVGpaint->xform#})) xform\n poke (castPtr (p `plusPtr` {#offsetof NVGpaint->extent#})) extent\n {#set NVGpaint->radius#} p radius\n {#set NVGpaint->feather#} p feather\n poke (castPtr (p `plusPtr` 40)) innerColor\n poke (castPtr (p `plusPtr` 56)) outerColor\n poke (castPtr (p `plusPtr` 72)) (imageHandle image)\n\n{#enum NVGwinding as Winding\n {} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGsolidity as Solidity\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGlineCap as LineCap\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGalign as Align \n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\ndata GlyphPosition =\n GlyphPosition { str :: !(Ptr CChar)\n , glyphX :: !CFloat\n -- Remove prefix once GHC 8 is released\n , glyphPosMinX :: !CFloat\n , glyphPosMaxX :: !CFloat} deriving (Show,Eq,Ord)\n\n{#pointer *NVGglyphPosition as GlyphPositionPtr -> GlyphPosition#}\n\ninstance Storable GlyphPosition where\n sizeOf _ = 24\n alignment _ = {#alignof NVGglyphPosition#}\n peek p =\n do str <- {#get NVGglyphPosition->str#} p\n x <- {#get NVGglyphPosition->x#} p\n minx <- {#get NVGglyphPosition->minx#} p\n maxx <- {#get NVGglyphPosition->maxx#} p\n pure (GlyphPosition str x minx maxx)\n poke p (GlyphPosition str x minx maxx) =\n do {#set NVGglyphPosition->str#} p str\n {#set NVGglyphPosition->x#} p x\n {#set NVGglyphPosition->minx#} p minx\n {#set NVGglyphPosition->maxx#} p maxx\n\ndata TextRow =\n TextRow {start :: !(Ptr CChar)\n ,end :: !(Ptr CChar)\n ,next :: !(Ptr CChar)\n ,width :: !CFloat\n -- Remove prefix once GHC 8 is released\n ,textRowMinX :: !CFloat\n ,textRowMaxX :: !CFloat} deriving (Show,Eq,Ord)\n\ninstance Storable TextRow where\n sizeOf _ = 40\n alignment _ = {#alignof NVGtextRow#}\n peek p =\n do start <- {#get NVGtextRow->start#} p\n end <- {#get NVGtextRow->end#} p\n next <- {#get NVGtextRow->next#} p\n width <- {#get NVGtextRow->width#} p\n minX <- {#get NVGtextRow->minx#} p\n maxX <- {#get NVGtextRow->maxx#} p\n pure (TextRow start end next width minX maxX)\n poke p (TextRow {..}) =\n do {#set NVGtextRow->start#} p start\n {#set NVGtextRow->end#} p end\n {#set NVGtextRow->next#} p next\n {#set NVGtextRow->width#} p width\n {#set NVGtextRow->minx#} p textRowMinX\n {#set NVGtextRow->maxx#} p textRowMaxX\n\n{#pointer *NVGtextRow as TextRowPtr -> TextRow#}\n\n{#enum NVGimageFlags as ImageFlags\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#fun unsafe nvgBeginFrame as beginFrame\n {`Context',`CInt',`CInt',`Float'} -> `()'#}\n\n{#fun unsafe nvgCancelFrame as canelFrame\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgEndFrame as endFrame\n {`Context'} -> `()'#}\n\n{#fun pure unsafe nvgRGB_ as rgb\n {id`CUChar',id`CUChar',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgRGBf_ as rgbf\n {`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgRGBA_ as rgba\n {id`CUChar',id`CUChar',id`CUChar',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgRGBAf_ as rgbaf\n {`CFloat',`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgLerpRGBA_ as lerpRGBA\n {with*`Color',with*`Color',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgTransRGBA_ as transRGBA\n {with*`Color',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgTransRGBAf_ as transRGBAf\n {with*`Color',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgHSL_ as hsl\n {`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgHSLA_ as hsla\n {`CFloat',`CFloat',`CFloat',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun unsafe nvgSave as save\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgRestore as restore\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgReset as reset\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgStrokeColor_ as strokeColor\n {`Context',with*`Color'} -> `()'#}\n\n{#fun unsafe nvgStrokePaint_ as strokePaint\n {`Context',with*`Paint'} -> `()'#}\n\n{#fun unsafe nvgFillColor_ as fillColor\n {`Context',with*`Color'} -> `()'#}\n\n{#fun unsafe nvgFillPaint_ as fillPaint\n {`Context',with*`Paint'} -> `()'#}\n\n{#fun unsafe nvgMiterLimit as miterLimit\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgStrokeWidth as strokeWidth\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgLineCap as lineCap\n {`Context',`LineCap'} -> `()'#}\n\n{#fun unsafe nvgLineJoin as lineJoin\n {`Context',`LineCap'} -> `()'#}\n\n{#fun unsafe nvgGlobalAlpha as globalAlpha\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgResetTransform as resetTransform\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgTransform as transform\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTranslate as translate\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgRotate as rotate\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgSkewX as skewX\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgSkewY as skewY\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgScale as scale\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\npeekTransformation :: Ptr CFloat -> IO Transformation\npeekTransformation = peek . castPtr\n\nallocaTransformation :: (Ptr CFloat -> IO b) -> IO b\nallocaTransformation f = alloca (\\(p :: Ptr Transformation) -> f (castPtr p))\n\nwithTransformation :: Transformation -> (Ptr CFloat -> IO b) -> IO b\nwithTransformation t f = with t (\\p -> f (castPtr p)) \n\n{#fun unsafe nvgCurrentTransform as currentTransform\n {`Context',allocaTransformation-`Transformation'peekTransformation*} -> `()'#}\n\n{#fun unsafe nvgTransformIdentity as transformIdentity\n {allocaTransformation-`Transformation'peekTransformation*} -> `()'#}\n\n{#fun unsafe nvgTransformTranslate as transformTranslate\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformScale as transformScale\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformRotate as transformRotate\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformSkewX as transformSkewX\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformSkewY as transformSkewY\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformMultiply as transformMultiply\n {allocaTransformation-`Transformation'peekTransformation*,withTransformation*`Transformation'} -> `()'#}\n\n{#fun unsafe nvgTransformInverse as transformInverse\n {allocaTransformation-`Transformation'peekTransformation*,withTransformation*`Transformation'} -> `()'#}\n\n{#fun pure unsafe nvgTransformPoint as transformPoint\n {alloca-`CFloat'peek*,alloca-`CFloat'peek*,withTransformation*`Transformation',`CFloat',`CFloat'} -> `()'#}\n\n{#fun pure unsafe nvgDegToRad as degToRad\n {`CFloat'} -> `CFloat'#}\n\n{#fun pure unsafe nvgRadToDeg as radToDeg\n {`CFloat'} -> `CFloat'#}\n\nsafeImage :: CInt -> Maybe Image\nsafeImage i\n | i < 0 = Nothing\n | otherwise = Just (Image i)\n\n{#fun unsafe nvgCreateImage as createImage\n {`Context','withCString.unwrapFileName'*`FileName',`CInt'} -> `Maybe Image'safeImage#}\n\n{#fun unsafe nvgCreateImageMem as createImageMem\n {`Context',`ImageFlags',useAsCStringLen'*`ByteString'&} -> `Maybe Image'safeImage#}\n\n{#fun unsafe nvgCreateImageRGBA as createImageRGBA\n {`Context',`CInt',`CInt',`ImageFlags',useAsPtr*`ByteString'} -> `Maybe Image'safeImage#}\n\n{#fun unsafe nvgUpdateImage as updateImage\n {`Context',imageHandle`Image',useAsPtr*`ByteString'} -> `()'#}\n\n{#fun unsafe nvgImageSize as imageSize\n {`Context',imageHandle`Image',alloca-`CInt'peek*,alloca-`CInt'peek*} -> `()'#}\n\n{#fun unsafe nvgDeleteImage as deleteImage\n {`Context',imageHandle`Image'} -> `()'#}\n\n{#fun unsafe nvgLinearGradient_ as linearGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgBoxGradient_ as boxGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgRadialGradient_ as radialGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgImagePattern_ as imagePattern\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',imageHandle`Image',`CFloat',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgScissor as scissor\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgIntersectScissor as intersectScissor\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgResetScissor as resetScissor\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgBeginPath as beginPath\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgMoveTo as moveTo\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgLineTo as lineTo\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgBezierTo as bezierTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgQuadTo as quadTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgArcTo as arcTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgClosePath as closePath\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgPathWinding as pathWinding\n {`Context', `CInt'} -> `()'#}\n\n{#fun unsafe nvgArc as arc\n {`Context',`CFloat',`CFloat', `CFloat', `CFloat', `CFloat', `Winding'} -> `()'#}\n\n{#fun unsafe nvgRect as rect\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgRoundedRect as roundedRect\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgEllipse as ellipse\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgCircle as circle\n {`Context',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgFill as fill\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgStroke as stroke\n {`Context'} -> `()'#}\n\nsafeFont :: CInt -> Maybe Font\nsafeFont i\n | i < 0 = Nothing\n | otherwise = Just (Font i)\n\n{#fun unsafe nvgCreateFont as createFont\n {`Context',withCString*`T.Text','withCString.unwrapFileName'*`FileName'} -> `Maybe Font'safeFont#}\n\n{#fun unsafe nvgCreateFontMem as createFontMem\n {`Context',withCString*`T.Text',useAsCStringLen'*`ByteString'&,zero-`CInt'} -> `Maybe Font'safeFont#}\n\n{#fun unsafe nvgFindFont as findFont\n {`Context', withCString*`T.Text'} -> `Maybe Font'safeFont#}\n\n{#fun unsafe nvgFontSize as fontSize\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgFontBlur as fontBlur\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTextLetterSpacing as textLetterSpacing\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTextLineHeight as textLineHeight\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTextAlign as textAlign\n {`Context',bitMask`S.Set Align'} -> `()'#}\n\n{#fun unsafe nvgFontFaceId as fontFaceId\n {`Context',fontHandle`Font'} -> `()'#}\n\n{#fun unsafe nvgFontFace as fontFace\n {`Context',withCString*`T.Text'} -> `()'#}\n\n{#fun unsafe nvgText as text\n {`Context',`CFloat',`CFloat',id`Ptr CChar',id`Ptr CChar'} -> `()'#}\n\n{#fun unsafe nvgTextBox as textBox\n {`Context',`CFloat',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar'} -> `()'#}\n\nnewtype Bounds = Bounds (V4 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Bounds where\n sizeOf _ = sizeOf (0 :: CFloat) * 4\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peekElemOff p' 0\n b <- peekElemOff p' 1\n c <- peekElemOff p' 2\n d <- peekElemOff p' 3\n pure (Bounds (V4 a b c d))\n poke p (Bounds (V4 a b c d)) =\n do let p' = castPtr p :: Ptr CFloat\n pokeElemOff p' 0 a\n pokeElemOff p' 1 b\n pokeElemOff p' 2 c\n pokeElemOff p' 3 d\n\npeekBounds :: Ptr CFloat -> IO Bounds\npeekBounds = peek . castPtr\n\nallocaBounds :: (Ptr CFloat -> IO b) -> IO b\nallocaBounds f = alloca (\\(p :: Ptr Bounds) -> f (castPtr p))\n\nwithBounds :: Bounds -> (Ptr CFloat -> IO b) -> IO b\nwithBounds t f = with t (\\p -> f (castPtr p)) \n\n{#fun unsafe nvgTextBounds as textBounds\n {`Context',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar', allocaBounds-`Bounds'peekBounds*} -> `()'#}\n\n{#fun unsafe nvgTextBoxBounds as textBoxBounds\n {`Context',`CFloat',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar',allocaBounds-`Bounds'peekBounds*} -> `()'#}\n\n-- TODO: This should probably take a vector\n{#fun unsafe nvgTextGlyphPositions as textGlyphPositions\n {`Context',`CFloat',`CFloat',id`Ptr CChar',id`Ptr CChar',`GlyphPositionPtr', `CInt'} -> `CInt'#}\n\n{#fun unsafe nvgTextMetrics as textMetrics\n {`Context',alloca-`CFloat'peek*,alloca-`CFloat'peek*,alloca-`CFloat'peek*} -> `()'#}\n\n-- TODO: This should probably take a vector\n{#fun unsafe nvgTextBreakLines as textBreakLines\n {`Context',id`Ptr CChar',id`Ptr CChar',`CFloat',`TextRowPtr',`CInt'} -> `CInt'#}\n\n{#enum NVGcreateFlags as CreateFlags\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\nbitMask :: Enum a => S.Set a -> CInt\nbitMask = S.fold (.|.) 0 . S.map (fromIntegral . fromEnum)\n\n{#fun unsafe nvgCreateGL3 as createGL3\n {bitMask`S.Set CreateFlags'} -> `Context'#}\n{#fun unsafe nvgDeleteGL3 as deleteGL3\n {`Context'} -> `()'#}\n\ntype GLuint = Word32\n\n{#fun unsafe nvglCreateImageFromHandleGL3 as createImageFromHandleGL3\n {`Context',fromIntegral`GLuint',`CInt',`CInt',`CreateFlags'} -> `Image'Image#}\n\n{#fun unsafe nvglImageHandleGL3 as imageHandleGL3\n {`Context',imageHandle`Image'} -> `GLuint'fromIntegral#}\n","returncode":0,"stderr":"","license":"isc","lang":"C2hs Haskell"}
{"commit":"efe4e0f1d27bfc84ce5c3eea9921b841f2700cff","subject":"Fix a conflict in DrawWindow.","message":"Fix a conflict in DrawWindow.","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/DrawWindow.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Gdk\/DrawWindow.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) DrawWindow\n--\n-- Author : Axel Simon\n--\n-- Created: 5 November 2002\n--\n-- Copyright (C) 2002-2005 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- A 'DrawWindow' is a rectangular region on the screen.\n--\nmodule Graphics.UI.Gtk.Gdk.DrawWindow (\n-- A 'DrawWindow' is used to implement high-level objects such as 'Widget' and\n-- 'Window' on the Gtk+ level. \n--\n-- Most widgets draws its content into a 'DrawWindow', in particular\n-- 'DrawingArea' is nothing but a widget that contains a 'DrawWindow'.\n-- This object derives from 'Drawable' which defines the basic drawing\n-- primitives.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Drawable'\n-- | +----DrawWindow\n-- @\n--\n\n-- * Types\n DrawWindow,\n DrawWindowClass,\n castToDrawWindow,\n WindowState(..),\n NativeWindowId,\n-- * Methods\n drawWindowGetState,\n drawWindowClear,\n drawWindowClearArea,\n drawWindowClearAreaExpose,\n drawWindowRaise,\n drawWindowLower,\n drawWindowBeginPaintRect,\n drawWindowBeginPaintRegion,\n drawWindowEndPaint,\n drawWindowInvalidateRect,\n drawWindowInvalidateRegion,\n drawWindowGetUpdateArea,\n drawWindowFreezeUpdates,\n drawWindowThawUpdates,\n drawWindowProcessUpdates,\n#if GTK_CHECK_VERSION(2,4,0)\n drawWindowSetAcceptFocus,\n#endif\n drawWindowShapeCombineMask,\n drawWindowShapeCombineRegion,\n drawWindowSetChildShapes,\n drawWindowMergeChildShapes,\n drawWindowGetPointer,\n drawWindowGetPointerPos,\n drawWindowGetOrigin,\n drawWindowForeignNew\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags (toFlags)\nimport System.Glib.GObject (makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Gdk.Enums#}\n{#import Graphics.UI.Gtk.Gdk.Region#}\nimport Graphics.UI.Gtk.Gdk.EventM\t(Modifier, eventRegion)\nimport Graphics.UI.Gtk.General.Structs\nimport Graphics.UI.Gtk.Abstract.Widget\t(widgetSetDoubleBuffered)\n\n{# context lib=\"gdk\" prefix=\"gdk\" #}\n\n-- | Gets the bitwise OR of the currently active drawWindow state flags, from\n-- the 'WindowState' enumeration.\n-- \ndrawWindowGetState :: DrawWindowClass self => self\n -> IO [WindowState] -- ^ returns @DrawWindow@ flags\ndrawWindowGetState self =\n liftM (toFlags . fromIntegral) $\n {# call gdk_window_get_state #}\n (toDrawWindow self)\n\n-- | Scroll the contents of @DrawWindow@.\n--\n-- * Scroll both, pixels and children, by the given amount.\n-- @DrawWindow@ itself does not move. Portions of the window that the\n-- scroll operation brings inm from offscreen areas are invalidated. The\n-- invalidated region may be bigger than what would strictly be necessary. (For\n-- X11, a minimum area will be invalidated if the window has no subwindows, or\n-- if the edges of the window's parent do not extend beyond the edges of the\n-- drawWindow. In other cases, a multi-step process is used to scroll the window\n-- which may produce temporary visual artifacts and unnecessary invalidations.)\n-- \ndrawWindowScroll :: DrawWindowClass self => self\n -> Int -- ^ @dx@ - Amount to scroll in the X direction\n -> Int -- ^ @dy@ - Amount to scroll in the Y direction\n -> IO ()\ndrawWindowScroll self dx dy =\n {# call gdk_window_scroll #}\n (toDrawWindow self)\n (fromIntegral dx)\n (fromIntegral dy)\n\n\n-- | Clears an entire @DrawWindow@ to the background color or background pixmap.\n-- \ndrawWindowClear :: DrawWindowClass self => self -> IO ()\ndrawWindowClear self =\n {# call gdk_window_clear #}\n (toDrawWindow self)\n\n-- | Clears an area of @DrawWindow@ to the background color or background pixmap.\n-- \ndrawWindowClearArea :: DrawWindowClass self => self\n -> Int -- ^ @x@ - x coordinate of rectangle to clear\n -> Int -- ^ @y@ - y coordinate of rectangle to clear\n -> Int -- ^ @width@ - width of rectangle to clear\n -> Int -- ^ @height@ - height of rectangle to clear\n -> IO ()\ndrawWindowClearArea self x y width height =\n {# call gdk_window_clear_area #}\n (toDrawWindow self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- | Like 'drawWindowClearArea', but also generates an expose event for the\n-- cleared area.\n-- \ndrawWindowClearAreaExpose :: DrawWindowClass self => self\n -> Int -- ^ @x@ - x coordinate of rectangle to clear\n -> Int -- ^ @y@ - y coordinate of rectangle to clear\n -> Int -- ^ @width@ - width of rectangle to clear\n -> Int -- ^ @height@ - height of rectangle to clear\n -> IO ()\ndrawWindowClearAreaExpose self x y width height =\n {# call gdk_window_clear_area_e #}\n (toDrawWindow self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- | Raises @DrawWindow@ to the top of the Z-order (stacking order), so that other\n-- drawWindows with the same parent drawWindow appear below @DrawWindow@. This is true\n-- whether or not the drawWindows are visible.\n--\n-- If @DrawWindow@ is a toplevel, the window manager may choose to deny the\n-- request to move the drawWindow in the Z-order, 'drawWindowRaise' only requests the\n-- restack, does not guarantee it.\n-- \ndrawWindowRaise :: DrawWindowClass self => self -> IO ()\ndrawWindowRaise self =\n {# call gdk_window_raise #}\n (toDrawWindow self)\n\n-- | Lowers @DrawWindow@ to the bottom of the Z-order (stacking order), so that\n-- other windows with the same parent window appear above @DrawWindow@. This is\n-- true whether or not the other windows are visible.\n--\n-- If @DrawWindow@ is a toplevel, the window manager may choose to deny the\n-- request to move the drawWindow in the Z-order, 'drawWindowLower' only\n-- requests the restack, does not guarantee it.\n--\n-- Note that a widget is raised automatically when it is mapped, thus you\n-- need to call 'drawWindowLower' after\n -- 'Graphics.UI.Gtk.Abstract.Widget.widgetShow' if the window should\n-- not appear above other windows.\n--\ndrawWindowLower :: DrawWindowClass self => self -> IO ()\ndrawWindowLower self =\n {# call gdk_window_lower #}\n (toDrawWindow self)\n\n-- | Registers a drawWindow as a potential drop destination.\n-- \ndrawWindowRegisterDnd :: DrawWindowClass self => self -> IO ()\ndrawWindowRegisterDnd self =\n {# call gdk_window_register_dnd #}\n (toDrawWindow self)\n\n-- | A convenience wrapper around 'drawWindowBeginPaintRegion' which creates a\n-- rectangular region for you.\n--\n-- * See 'drawWindowBeginPaintRegion' for details.\n-- \ndrawWindowBeginPaintRect :: DrawWindowClass self => self\n -> Rectangle -- ^ @rectangle@ - rectangle you intend to draw to\n -> IO ()\ndrawWindowBeginPaintRect self rectangle = with rectangle $ \\rectPtr ->\n {#call gdk_window_begin_paint_rect#} (toDrawWindow self) (castPtr rectPtr)\n\n-- | Indicate that you are beginning the process of redrawing @region@.\n--\n-- * A\n-- backing store (offscreen buffer) large enough to contain @region@ will be\n-- created. The backing store will be initialized with the background color or\n-- background pixmap for @DrawWindow@. Then, all drawing operations performed on\n-- @DrawWindow@ will be diverted to the backing store. When you call\n-- 'drawWindowEndPaint', the backing store will be copied to @DrawWindow@, making it\n-- visible onscreen. Only the part of @DrawWindow@ contained in @region@ will be\n-- modified; that is, drawing operations are clipped to @region@.\n--\n-- The net result of all this is to remove flicker, because the user sees\n-- the finished product appear all at once when you call 'drawWindowEndPaint'. If\n-- you draw to @DrawWindow@ directly without calling 'drawWindowBeginPaintRegion', the\n-- user may see flicker as individual drawing operations are performed in\n-- sequence. The clipping and background-initializing features of\n-- 'drawWindowBeginPaintRegion' are conveniences for the programmer, so you can\n-- avoid doing that work yourself.\n--\n-- When using GTK+, the widget system automatically places calls to\n-- 'drawWindowBeginPaintRegion' and 'drawWindowEndPaint' around emissions of the\n-- @expose_event@ signal. That is, if you\\'re writing an expose event handler,\n-- you can assume that the exposed area in 'eventRegion' has already been\n-- cleared to the window background, is already set as the clip region, and\n-- already has a backing store. Therefore in most cases, application code need\n-- not call 'drawWindowBeginPaintRegion'. (You can disable the automatic calls\n-- around expose events on a widget-by-widget basis by calling\n-- 'widgetSetDoubleBuffered'.)\n--\n-- If you call this function multiple times before calling the matching\n-- 'drawWindowEndPaint', the backing stores are pushed onto a stack.\n-- 'drawWindowEndPaint' copies the topmost backing store onscreen, subtracts the\n-- topmost region from all other regions in the stack, and pops the stack. All\n-- drawing operations affect only the topmost backing store in the stack. One\n-- matching call to 'drawWindowEndPaint' is required for each call to\n-- 'drawWindowBeginPaintRegion'.\n-- \ndrawWindowBeginPaintRegion :: DrawWindowClass self => self\n -> Region -- ^ @region@ - region you intend to draw to\n -> IO ()\ndrawWindowBeginPaintRegion self region =\n {# call gdk_window_begin_paint_region #}\n (toDrawWindow self)\n region\n\n-- | Signal that drawing has finished.\n--\n-- * Indicates that the backing store created by the most recent call to\n-- 'drawWindowBeginPaintRegion' should be copied onscreen and deleted, leaving the\n-- next-most-recent backing store or no backing store at all as the active\n-- paint region. See 'drawWindowBeginPaintRegion' for full details. It is an error\n-- to call this function without a matching 'drawWindowBeginPaintRegion' first.\n-- \ndrawWindowEndPaint :: DrawWindowClass self => self -> IO ()\ndrawWindowEndPaint self =\n {# call gdk_window_end_paint #}\n (toDrawWindow self)\n\n-- | A convenience wrapper around 'drawWindowInvalidateRegion' which invalidates a\n-- rectangular region. See 'drawWindowInvalidateRegion' for details.\n-- \ndrawWindowInvalidateRect :: DrawWindowClass self => self\n -> Rectangle -- ^ @rect@ - rectangle to invalidate\n -> Bool -- ^ @invalidateChildren@ - whether to also invalidate\n -- child drawWindows\n -> IO ()\ndrawWindowInvalidateRect self rect invalidateChildren =\n with rect $ \\rectPtr ->\n {# call gdk_window_invalidate_rect #}\n (toDrawWindow self)\n (castPtr rectPtr)\n (fromBool invalidateChildren)\n\n-- | Adds @region@ to the update area for @DrawWindow@. The update area is the\n-- region that needs to be redrawn, or \\\"dirty region.\\\". During the\n-- next idle period of the main look, an expose even for this region\n-- will be created. An application would normally redraw\n-- the contents of @DrawWindow@ in response to those expose events.\n--\n-- The @invalidateChildren@ parameter controls whether the region of each\n-- child drawWindow that intersects @region@ will also be invalidated. If @False@,\n-- then the update area for child drawWindows will remain unaffected.\n-- \ndrawWindowInvalidateRegion :: DrawWindowClass self => self\n -> Region -- ^ @region@ - a \"Region\"\n -> Bool -- ^ @invalidateChildren@ - @True@ to also invalidate child\n -- drawWindows\n -> IO ()\ndrawWindowInvalidateRegion self region invalidateChildren =\n {# call gdk_window_invalidate_region #}\n (toDrawWindow self)\n region\n (fromBool invalidateChildren)\n\n-- | Ask for the dirty region of this window.\n--\n-- * Transfers ownership of the update area from @DrawWindow@ to the caller of the\n-- function. That is, after calling this function, @DrawWindow@ will no longer have\n-- an invalid\\\/dirty region; the update area is removed from @DrawWindow@ and\n-- handed to you. If this window has no update area, 'drawWindowGetUpdateArea' returns 'Nothing'.\n-- \ndrawWindowGetUpdateArea :: DrawWindowClass self => self\n -> IO (Maybe Region) -- ^ returns the update area for @DrawWindow@\ndrawWindowGetUpdateArea self = do\n reg <- {# call gdk_window_get_update_area #} (toDrawWindow self)\n if reg==nullPtr then return Nothing else liftM Just (makeNewRegion reg)\n\n-- | Temporarily freezes a drawWindow such that it won\\'t receive expose events.\n-- * The drawWindow will begin receiving expose events again when \n-- 'drawWindowThawUpdates'\n-- is called. If 'drawWindowFreezeUpdates' has been called more than once,\n-- 'drawWindowThawUpdates' must be called an equal number of times to begin\n-- processing exposes.\n-- \ndrawWindowFreezeUpdates :: DrawWindowClass self => self -> IO ()\ndrawWindowFreezeUpdates self =\n {# call gdk_window_freeze_updates #}\n (toDrawWindow self)\n\n-- | Thaws a drawWindow frozen with 'drawWindowFreezeUpdates'.\n-- \ndrawWindowThawUpdates :: DrawWindowClass self => self -> IO ()\ndrawWindowThawUpdates self =\n {# call gdk_window_thaw_updates #}\n (toDrawWindow self)\n\n-- | Sends one or more expose events to @DrawWindow@.\n--\n-- * The areas in each expose\n-- event will cover the entire update area for the window (see\n-- 'drawWindowInvalidateRegion' for details). Normally Gtk calls\n-- 'drawWindowProcessUpdates' on your behalf, so there's no need to call this\n-- function unless you want to force expose events to be delivered immediately\n-- and synchronously (vs. the usual case, where Gtk delivers them in an idle\n-- handler). Occasionally this is useful to produce nicer scrolling behavior,\n-- for example.\n-- \ndrawWindowProcessUpdates :: DrawWindowClass self => self\n -> Bool -- ^ @updateChildren@ - whether to also process updates for child\n -- drawWindows\n -> IO ()\ndrawWindowProcessUpdates self updateChildren =\n {# call gdk_window_process_updates #}\n (toDrawWindow self)\n (fromBool updateChildren)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Setting @acceptFocus@ to @False@ hints the desktop environment that the\n-- window doesn\\'t want to receive input focus.\n--\n-- On X, it is the responsibility of the drawWindow manager to interpret this\n-- hint. ICCCM-compliant drawWindow manager usually respect it.\n--\n-- * Available since Gdk version 2.4\n-- \ndrawWindowSetAcceptFocus :: DrawWindowClass self => self\n -> Bool -- ^ @acceptFocus@ - @True@ if the drawWindow should receive input focus\n -> IO ()\ndrawWindowSetAcceptFocus self acceptFocus =\n {# call gdk_window_set_accept_focus #}\n (toDrawWindow self)\n (fromBool acceptFocus)\n#endif\n\n-- | Applies a shape mask to window. Pixels in window corresponding to set\n-- bits in the mask will be visible; pixels in window corresponding to\n-- unset bits in the mask will be transparent. This gives a non-rectangular\n-- window.\n--\n-- * If @mask@ is @Nothing@, the shape mask will be unset, and the x\\\/y parameters\n-- are not used. The @mask@ must be a bitmap, that is, a 'Pixmap' of depth\n-- one.\n--\n-- * On the X11 platform, this uses an X server extension which is widely\n-- available on most common platforms, but not available on very old\n-- X servers, and occasionally the implementation will be buggy. \n-- On servers without the shape extension, this function will do nothing.\n-- On the Win32 platform the functionality is always present.\n--\n-- * This function works on both toplevel and child windows.\n--\ndrawWindowShapeCombineMask :: DrawWindowClass self => self\n -> Maybe Pixmap -- ^ @mask@ - region of drawWindow to be non-transparent\n -> Int -- ^ @offsetX@ - X position of @shapeRegion@ in @DrawWindow@\n -- coordinates\n -> Int -- ^ @offsetY@ - Y position of @shapeRegion@ in @DrawWindow@\n -- coordinates\n -> IO ()\ndrawWindowShapeCombineMask self (Just (Pixmap mask)) offsetX offsetY =\n withForeignPtr mask $ \\maskPtr ->\n {# call gdk_window_shape_combine_mask #}\n (toDrawWindow self)\n (castPtr maskPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\ndrawWindowShapeCombineMask self Nothing offsetX offsetY =\n {# call gdk_window_shape_combine_mask #}\n (toDrawWindow self)\n nullPtr\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n\n-- | Makes pixels in @DrawWindow@ outside @shapeRegion@ transparent.\n--\n-- * Makes pixels in @DrawWindow@ outside @shapeRegion@ transparent, so that\n-- the window may be nonrectangular.\n--\n-- If @shapeRegion@ is 'Nothing', the shape will be unset, so the whole\n-- 'DrawWindow' will be opaque again. The parameters @offsetX@ and @offsetY@\n-- are ignored if @shapeRegion@ is 'Nothing'.\n--\n-- On the X11 platform, this uses an X server extension which is widely\n-- available on most common platforms, but not available on very old X servers,\n-- and occasionally the implementation will be buggy. On servers without the\n-- shape extension, this function will do nothing.\n--\n-- This function works on both toplevel and child drawWindows.\n-- \ndrawWindowShapeCombineRegion :: DrawWindowClass self => self\n -> Maybe Region -- ^ @shapeRegion@ - region of drawWindow to be non-transparent\n -> Int -- ^ @offsetX@ - X position of @shapeRegion@ in @DrawWindow@\n -- coordinates\n -> Int -- ^ @offsetY@ - Y position of @shapeRegion@ in @DrawWindow@\n -- coordinates\n -> IO ()\ndrawWindowShapeCombineRegion self (Just reg) offsetX offsetY =\n {# call gdk_window_shape_combine_region #}\n (toDrawWindow self)\n reg\n (fromIntegral offsetX)\n (fromIntegral offsetY)\ndrawWindowShapeCombineRegion self Nothing offsetX offsetY =\n {# call gdk_window_shape_combine_region #}\n (toDrawWindow self)\n (Region nullForeignPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n-- | Sets the shape mask of @DrawWindow@ to the union of shape masks for all\n-- children of @DrawWindow@, ignoring the shape mask of @DrawWindow@ itself. Contrast\n-- with 'drawWindowMergeChildShapes' which includes the shape mask of @DrawWindow@ in\n-- the masks to be merged.\n-- \ndrawWindowSetChildShapes :: DrawWindowClass self => self -> IO ()\ndrawWindowSetChildShapes self =\n {# call gdk_window_set_child_shapes #}\n (toDrawWindow self)\n\n-- | Merges the shape masks for any child drawWindows into the shape mask for\n-- @DrawWindow@. i.e. the union of all masks for @DrawWindow@ and its children will\n-- become the new mask for @DrawWindow@. See 'drawWindowShapeCombineMask'.\n--\n-- This function is distinct from 'drawWindowSetChildShapes' because it includes\n-- @DrawWindow@'s shape mask in the set of shapes to be merged.\n-- \ndrawWindowMergeChildShapes :: DrawWindowClass self => self -> IO ()\ndrawWindowMergeChildShapes self =\n {# call gdk_window_merge_child_shapes #}\n (toDrawWindow self)\n\n-- Superseded by 'drawWindowGetPointerPos', won't be removed.\n-- Obtains the current pointer position and modifier state.\n--\n-- * The position is\n-- given in coordinates relative to the given window.\n-- \n-- * The return value is @Just (same, x, y, mod)@ where @same@ is @True@\n-- if the passed in window is the window over which the mouse currently\n-- resides.\n--\n-- * The return value is @Nothing@ if the mouse cursor is over a different\n-- application.\n--\ndrawWindowGetPointer :: DrawWindowClass self => self\n -> IO (Maybe (Bool, Int, Int, [Modifier]))\ndrawWindowGetPointer self =\n alloca $ \\xPtr -> alloca $ \\yPtr -> alloca $ \\mPtr -> do\n winPtr <- {# call gdk_window_get_pointer #} (toDrawWindow self)\n xPtr yPtr mPtr\n if winPtr==nullPtr then return Nothing else do\n same <- withForeignPtr (unDrawWindow (toDrawWindow self)) $ \\dPtr ->\n return (winPtr==dPtr)\n x <- peek xPtr\n y <- peek yPtr\n m <- peek mPtr\n return (Just (same, fromIntegral x, fromIntegral y,\n toFlags (fromIntegral m)))\n\n-- | Obtains the current pointer position and modifier state.\n--\n-- * The position is\n-- given in coordinates relative to the given window.\n-- \n-- * The return value is @(Just win, x, y, mod)@ where @win@ is the\n-- window over which the mouse currently resides and @mod@ denotes\n-- the keyboard modifiers currently being depressed.\n--\n-- * The return value is @Nothing@ for the window if the mouse cursor is \n-- not over a known window.\n--\ndrawWindowGetPointerPos :: DrawWindowClass self => self\n -> IO (Maybe DrawWindow, Int, Int, [Modifier])\ndrawWindowGetPointerPos self =\n alloca $ \\xPtr -> alloca $ \\yPtr -> alloca $ \\mPtr -> do\n winPtr <- {# call gdk_window_get_pointer #} (toDrawWindow self)\n xPtr yPtr mPtr\n x <- peek xPtr\n y <- peek yPtr\n m <- peek mPtr\n mWin <- if winPtr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkDrawWindow (return winPtr)\n return (mWin, fromIntegral x, fromIntegral y, toFlags (fromIntegral m))\n\n\n-- | Obtains the position of a window in screen coordinates.\n--\n-- You can use this to help convert a position between screen coordinates and\n-- local 'DrawWindow' relative coordinates.\n--\ndrawWindowGetOrigin :: DrawWindow\n -> IO (Int, Int) -- ^ @(x, y)@\ndrawWindowGetOrigin self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr -> do\n {# call gdk_window_get_origin #}\n (toDrawWindow self)\n xPtr\n yPtr\n x <- peek xPtr\n y <- peek yPtr\n return (fromIntegral x, fromIntegral y)\n\n\n-- | Get the handle to an exising window of the windowing system. The\n-- passed-in handle is a reference to a native window, that is, an Xlib XID\n-- for X windows and a HWND for Win32.\ndrawWindowForeignNew :: NativeWindowId -> IO (Maybe DrawWindow)\ndrawWindowForeignNew anid = maybeNull (makeNewGObject mkDrawWindow) $\n liftM castPtr $ {#call gdk_window_foreign_new#} (fromNativeWindowId anid)\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) DrawWindow\n--\n-- Author : Axel Simon\n--\n-- Created: 5 November 2002\n--\n-- Copyright (C) 2002-2005 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- A 'DrawWindow' is a rectangular region on the screen.\n--\nmodule Graphics.UI.Gtk.Gdk.DrawWindow (\n-- A 'DrawWindow' is used to implement high-level objects such as 'Widget' and\n-- 'Window' on the Gtk+ level. \n--\n-- Most widgets draws its content into a 'DrawWindow', in particular\n-- 'DrawingArea' is nothing but a widget that contains a 'DrawWindow'.\n-- This object derives from 'Drawable' which defines the basic drawing\n-- primitives.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Drawable'\n-- | +----DrawWindow\n-- @\n--\n\n-- * Types\n DrawWindow,\n DrawWindowClass,\n castToDrawWindow,\n WindowState(..),\n NativeWindowId,\n-- * Methods\n drawWindowGetState,\n drawWindowClear,\n drawWindowClearArea,\n drawWindowClearAreaExpose,\n drawWindowRaise,\n drawWindowLower,\n drawWindowBeginPaintRect,\n drawWindowBeginPaintRegion,\n drawWindowEndPaint,\n drawWindowInvalidateRect,\n drawWindowInvalidateRegion,\n drawWindowGetUpdateArea,\n drawWindowFreezeUpdates,\n drawWindowThawUpdates,\n drawWindowProcessUpdates,\n#if GTK_CHECK_VERSION(2,4,0)\n drawWindowSetAcceptFocus,\n#endif\n drawWindowShapeCombineMask,\n drawWindowShapeCombineRegion,\n drawWindowSetChildShapes,\n drawWindowMergeChildShapes,\n drawWindowGetPointer,\n drawWindowGetPointerPos,\n drawWindowGetOrigin,\n drawWindowForeignNew\n ) where\n\nimport Control.Monad (liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Flags (toFlags)\nimport System.Glib.GObject (makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Gdk.Enums#}\n{#import Graphics.UI.Gtk.Gdk.Region#}\nimport Graphics.UI.Gtk.Gdk.Events\t(Modifier)\nimport Graphics.UI.Gtk.General.Structs\nimport Graphics.UI.Gtk.Abstract.Widget\t(widgetSetDoubleBuffered)\n\n{# context lib=\"gdk\" prefix=\"gdk\" #}\n\n-- | Gets the bitwise OR of the currently active drawWindow state flags, from\n-- the 'WindowState' enumeration.\n-- \ndrawWindowGetState :: DrawWindowClass self => self\n -> IO [WindowState] -- ^ returns @DrawWindow@ flags\ndrawWindowGetState self =\n liftM (toFlags . fromIntegral) $\n {# call gdk_window_get_state #}\n (toDrawWindow self)\n\n-- | Scroll the contents of @DrawWindow@.\n--\n-- * Scroll both, pixels and children, by the given amount.\n-- @DrawWindow@ itself does not move. Portions of the window that the\n-- scroll operation brings inm from offscreen areas are invalidated. The\n-- invalidated region may be bigger than what would strictly be necessary. (For\n-- X11, a minimum area will be invalidated if the window has no subwindows, or\n-- if the edges of the window's parent do not extend beyond the edges of the\n-- drawWindow. In other cases, a multi-step process is used to scroll the window\n-- which may produce temporary visual artifacts and unnecessary invalidations.)\n-- \ndrawWindowScroll :: DrawWindowClass self => self\n -> Int -- ^ @dx@ - Amount to scroll in the X direction\n -> Int -- ^ @dy@ - Amount to scroll in the Y direction\n -> IO ()\ndrawWindowScroll self dx dy =\n {# call gdk_window_scroll #}\n (toDrawWindow self)\n (fromIntegral dx)\n (fromIntegral dy)\n\n\n-- | Clears an entire @DrawWindow@ to the background color or background pixmap.\n-- \ndrawWindowClear :: DrawWindowClass self => self -> IO ()\ndrawWindowClear self =\n {# call gdk_window_clear #}\n (toDrawWindow self)\n\n-- | Clears an area of @DrawWindow@ to the background color or background pixmap.\n-- \ndrawWindowClearArea :: DrawWindowClass self => self\n -> Int -- ^ @x@ - x coordinate of rectangle to clear\n -> Int -- ^ @y@ - y coordinate of rectangle to clear\n -> Int -- ^ @width@ - width of rectangle to clear\n -> Int -- ^ @height@ - height of rectangle to clear\n -> IO ()\ndrawWindowClearArea self x y width height =\n {# call gdk_window_clear_area #}\n (toDrawWindow self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- | Like 'drawWindowClearArea', but also generates an expose event for the\n-- cleared area.\n-- \ndrawWindowClearAreaExpose :: DrawWindowClass self => self\n -> Int -- ^ @x@ - x coordinate of rectangle to clear\n -> Int -- ^ @y@ - y coordinate of rectangle to clear\n -> Int -- ^ @width@ - width of rectangle to clear\n -> Int -- ^ @height@ - height of rectangle to clear\n -> IO ()\ndrawWindowClearAreaExpose self x y width height =\n {# call gdk_window_clear_area_e #}\n (toDrawWindow self)\n (fromIntegral x)\n (fromIntegral y)\n (fromIntegral width)\n (fromIntegral height)\n\n-- | Raises @DrawWindow@ to the top of the Z-order (stacking order), so that other\n-- drawWindows with the same parent drawWindow appear below @DrawWindow@. This is true\n-- whether or not the drawWindows are visible.\n--\n-- If @DrawWindow@ is a toplevel, the window manager may choose to deny the\n-- request to move the drawWindow in the Z-order, 'drawWindowRaise' only requests the\n-- restack, does not guarantee it.\n-- \ndrawWindowRaise :: DrawWindowClass self => self -> IO ()\ndrawWindowRaise self =\n {# call gdk_window_raise #}\n (toDrawWindow self)\n\n-- | Lowers @DrawWindow@ to the bottom of the Z-order (stacking order), so that\n-- other windows with the same parent window appear above @DrawWindow@. This is\n-- true whether or not the other windows are visible.\n--\n-- If @DrawWindow@ is a toplevel, the window manager may choose to deny the\n-- request to move the drawWindow in the Z-order, 'drawWindowLower' only\n-- requests the restack, does not guarantee it.\n--\n-- Note that a widget is raised automatically when it is mapped, thus you\n-- need to call 'drawWindowLower' after\n -- 'Graphics.UI.Gtk.Abstract.Widget.widgetShow' if the window should\n-- not appear above other windows.\n--\ndrawWindowLower :: DrawWindowClass self => self -> IO ()\ndrawWindowLower self =\n {# call gdk_window_lower #}\n (toDrawWindow self)\n\n-- | Registers a drawWindow as a potential drop destination.\n-- \ndrawWindowRegisterDnd :: DrawWindowClass self => self -> IO ()\ndrawWindowRegisterDnd self =\n {# call gdk_window_register_dnd #}\n (toDrawWindow self)\n\n-- | A convenience wrapper around 'drawWindowBeginPaintRegion' which creates a\n-- rectangular region for you.\n--\n-- * See 'drawWindowBeginPaintRegion' for details.\n-- \ndrawWindowBeginPaintRect :: DrawWindowClass self => self\n -> Rectangle -- ^ @rectangle@ - rectangle you intend to draw to\n -> IO ()\ndrawWindowBeginPaintRect self rectangle = with rectangle $ \\rectPtr ->\n {#call gdk_window_begin_paint_rect#} (toDrawWindow self) (castPtr rectPtr)\n\n-- | Indicate that you are beginning the process of redrawing @region@.\n--\n-- * A\n-- backing store (offscreen buffer) large enough to contain @region@ will be\n-- created. The backing store will be initialized with the background color or\n-- background pixmap for @DrawWindow@. Then, all drawing operations performed on\n-- @DrawWindow@ will be diverted to the backing store. When you call\n-- 'drawWindowEndPaint', the backing store will be copied to @DrawWindow@, making it\n-- visible onscreen. Only the part of @DrawWindow@ contained in @region@ will be\n-- modified; that is, drawing operations are clipped to @region@.\n--\n-- The net result of all this is to remove flicker, because the user sees\n-- the finished product appear all at once when you call 'drawWindowEndPaint'. If\n-- you draw to @DrawWindow@ directly without calling 'drawWindowBeginPaintRegion', the\n-- user may see flicker as individual drawing operations are performed in\n-- sequence. The clipping and background-initializing features of\n-- 'drawWindowBeginPaintRegion' are conveniences for the programmer, so you can\n-- avoid doing that work yourself.\n--\n-- When using GTK+, the widget system automatically places calls to\n-- 'drawWindowBeginPaintRegion' and 'drawWindowEndPaint' around emissions of the\n-- @expose_event@ signal. That is, if you\\'re writing an expose event handler,\n-- you can assume that the exposed area in 'eventRegion' has already been\n-- cleared to the window background, is already set as the clip region, and\n-- already has a backing store. Therefore in most cases, application code need\n-- not call 'drawWindowBeginPaintRegion'. (You can disable the automatic calls\n-- around expose events on a widget-by-widget basis by calling\n-- 'widgetSetDoubleBuffered'.)\n--\n-- If you call this function multiple times before calling the matching\n-- 'drawWindowEndPaint', the backing stores are pushed onto a stack.\n-- 'drawWindowEndPaint' copies the topmost backing store onscreen, subtracts the\n-- topmost region from all other regions in the stack, and pops the stack. All\n-- drawing operations affect only the topmost backing store in the stack. One\n-- matching call to 'drawWindowEndPaint' is required for each call to\n-- 'drawWindowBeginPaintRegion'.\n-- \ndrawWindowBeginPaintRegion :: DrawWindowClass self => self\n -> Region -- ^ @region@ - region you intend to draw to\n -> IO ()\ndrawWindowBeginPaintRegion self region =\n {# call gdk_window_begin_paint_region #}\n (toDrawWindow self)\n region\n\n-- | Signal that drawing has finished.\n--\n-- * Indicates that the backing store created by the most recent call to\n-- 'drawWindowBeginPaintRegion' should be copied onscreen and deleted, leaving the\n-- next-most-recent backing store or no backing store at all as the active\n-- paint region. See 'drawWindowBeginPaintRegion' for full details. It is an error\n-- to call this function without a matching 'drawWindowBeginPaintRegion' first.\n-- \ndrawWindowEndPaint :: DrawWindowClass self => self -> IO ()\ndrawWindowEndPaint self =\n {# call gdk_window_end_paint #}\n (toDrawWindow self)\n\n-- | A convenience wrapper around 'drawWindowInvalidateRegion' which invalidates a\n-- rectangular region. See 'drawWindowInvalidateRegion' for details.\n-- \ndrawWindowInvalidateRect :: DrawWindowClass self => self\n -> Rectangle -- ^ @rect@ - rectangle to invalidate\n -> Bool -- ^ @invalidateChildren@ - whether to also invalidate\n -- child drawWindows\n -> IO ()\ndrawWindowInvalidateRect self rect invalidateChildren =\n with rect $ \\rectPtr ->\n {# call gdk_window_invalidate_rect #}\n (toDrawWindow self)\n (castPtr rectPtr)\n (fromBool invalidateChildren)\n\n-- | Adds @region@ to the update area for @DrawWindow@. The update area is the\n-- region that needs to be redrawn, or \\\"dirty region.\\\". During the\n-- next idle period of the main look, an expose even for this region\n-- will be created. An application would normally redraw\n-- the contents of @DrawWindow@ in response to those expose events.\n--\n-- The @invalidateChildren@ parameter controls whether the region of each\n-- child drawWindow that intersects @region@ will also be invalidated. If @False@,\n-- then the update area for child drawWindows will remain unaffected.\n-- \ndrawWindowInvalidateRegion :: DrawWindowClass self => self\n -> Region -- ^ @region@ - a \"Region\"\n -> Bool -- ^ @invalidateChildren@ - @True@ to also invalidate child\n -- drawWindows\n -> IO ()\ndrawWindowInvalidateRegion self region invalidateChildren =\n {# call gdk_window_invalidate_region #}\n (toDrawWindow self)\n region\n (fromBool invalidateChildren)\n\n-- | Ask for the dirty region of this window.\n--\n-- * Transfers ownership of the update area from @DrawWindow@ to the caller of the\n-- function. That is, after calling this function, @DrawWindow@ will no longer have\n-- an invalid\\\/dirty region; the update area is removed from @DrawWindow@ and\n-- handed to you. If this window has no update area, 'drawWindowGetUpdateArea' returns 'Nothing'.\n-- \ndrawWindowGetUpdateArea :: DrawWindowClass self => self\n -> IO (Maybe Region) -- ^ returns the update area for @DrawWindow@\ndrawWindowGetUpdateArea self = do\n reg <- {# call gdk_window_get_update_area #} (toDrawWindow self)\n if reg==nullPtr then return Nothing else liftM Just (makeNewRegion reg)\n\n-- | Temporarily freezes a drawWindow such that it won\\'t receive expose events.\n-- * The drawWindow will begin receiving expose events again when \n-- 'drawWindowThawUpdates'\n-- is called. If 'drawWindowFreezeUpdates' has been called more than once,\n-- 'drawWindowThawUpdates' must be called an equal number of times to begin\n-- processing exposes.\n-- \ndrawWindowFreezeUpdates :: DrawWindowClass self => self -> IO ()\ndrawWindowFreezeUpdates self =\n {# call gdk_window_freeze_updates #}\n (toDrawWindow self)\n\n-- | Thaws a drawWindow frozen with 'drawWindowFreezeUpdates'.\n-- \ndrawWindowThawUpdates :: DrawWindowClass self => self -> IO ()\ndrawWindowThawUpdates self =\n {# call gdk_window_thaw_updates #}\n (toDrawWindow self)\n\n-- | Sends one or more expose events to @DrawWindow@.\n--\n-- * The areas in each expose\n-- event will cover the entire update area for the window (see\n-- 'drawWindowInvalidateRegion' for details). Normally Gtk calls\n-- 'drawWindowProcessUpdates' on your behalf, so there's no need to call this\n-- function unless you want to force expose events to be delivered immediately\n-- and synchronously (vs. the usual case, where Gtk delivers them in an idle\n-- handler). Occasionally this is useful to produce nicer scrolling behavior,\n-- for example.\n-- \ndrawWindowProcessUpdates :: DrawWindowClass self => self\n -> Bool -- ^ @updateChildren@ - whether to also process updates for child\n -- drawWindows\n -> IO ()\ndrawWindowProcessUpdates self updateChildren =\n {# call gdk_window_process_updates #}\n (toDrawWindow self)\n (fromBool updateChildren)\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Setting @acceptFocus@ to @False@ hints the desktop environment that the\n-- window doesn\\'t want to receive input focus.\n--\n-- On X, it is the responsibility of the drawWindow manager to interpret this\n-- hint. ICCCM-compliant drawWindow manager usually respect it.\n--\n-- * Available since Gdk version 2.4\n-- \ndrawWindowSetAcceptFocus :: DrawWindowClass self => self\n -> Bool -- ^ @acceptFocus@ - @True@ if the drawWindow should receive input focus\n -> IO ()\ndrawWindowSetAcceptFocus self acceptFocus =\n {# call gdk_window_set_accept_focus #}\n (toDrawWindow self)\n (fromBool acceptFocus)\n#endif\n\n-- | Applies a shape mask to window. Pixels in window corresponding to set\n-- bits in the mask will be visible; pixels in window corresponding to\n-- unset bits in the mask will be transparent. This gives a non-rectangular\n-- window.\n--\n-- * If @mask@ is @Nothing@, the shape mask will be unset, and the x\\\/y parameters\n-- are not used. The @mask@ must be a bitmap, that is, a 'Pixmap' of depth\n-- one.\n--\n-- * On the X11 platform, this uses an X server extension which is widely\n-- available on most common platforms, but not available on very old\n-- X servers, and occasionally the implementation will be buggy. \n-- On servers without the shape extension, this function will do nothing.\n-- On the Win32 platform the functionality is always present.\n--\n-- * This function works on both toplevel and child windows.\n--\ndrawWindowShapeCombineMask :: DrawWindowClass self => self\n -> Maybe Pixmap -- ^ @mask@ - region of drawWindow to be non-transparent\n -> Int -- ^ @offsetX@ - X position of @shapeRegion@ in @DrawWindow@\n -- coordinates\n -> Int -- ^ @offsetY@ - Y position of @shapeRegion@ in @DrawWindow@\n -- coordinates\n -> IO ()\ndrawWindowShapeCombineMask self (Just (Pixmap mask)) offsetX offsetY =\n withForeignPtr mask $ \\maskPtr ->\n {# call gdk_window_shape_combine_mask #}\n (toDrawWindow self)\n (castPtr maskPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\ndrawWindowShapeCombineMask self Nothing offsetX offsetY =\n {# call gdk_window_shape_combine_mask #}\n (toDrawWindow self)\n nullPtr\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n\n-- | Makes pixels in @DrawWindow@ outside @shapeRegion@ transparent.\n--\n-- * Makes pixels in @DrawWindow@ outside @shapeRegion@ transparent, so that\n-- the window may be nonrectangular.\n--\n-- If @shapeRegion@ is 'Nothing', the shape will be unset, so the whole\n-- 'DrawWindow' will be opaque again. The parameters @offsetX@ and @offsetY@\n-- are ignored if @shapeRegion@ is 'Nothing'.\n--\n-- On the X11 platform, this uses an X server extension which is widely\n-- available on most common platforms, but not available on very old X servers,\n-- and occasionally the implementation will be buggy. On servers without the\n-- shape extension, this function will do nothing.\n--\n-- This function works on both toplevel and child drawWindows.\n-- \ndrawWindowShapeCombineRegion :: DrawWindowClass self => self\n -> Maybe Region -- ^ @shapeRegion@ - region of drawWindow to be non-transparent\n -> Int -- ^ @offsetX@ - X position of @shapeRegion@ in @DrawWindow@\n -- coordinates\n -> Int -- ^ @offsetY@ - Y position of @shapeRegion@ in @DrawWindow@\n -- coordinates\n -> IO ()\ndrawWindowShapeCombineRegion self (Just reg) offsetX offsetY =\n {# call gdk_window_shape_combine_region #}\n (toDrawWindow self)\n reg\n (fromIntegral offsetX)\n (fromIntegral offsetY)\ndrawWindowShapeCombineRegion self Nothing offsetX offsetY =\n {# call gdk_window_shape_combine_region #}\n (toDrawWindow self)\n (Region nullForeignPtr)\n (fromIntegral offsetX)\n (fromIntegral offsetY)\n\n-- | Sets the shape mask of @DrawWindow@ to the union of shape masks for all\n-- children of @DrawWindow@, ignoring the shape mask of @DrawWindow@ itself. Contrast\n-- with 'drawWindowMergeChildShapes' which includes the shape mask of @DrawWindow@ in\n-- the masks to be merged.\n-- \ndrawWindowSetChildShapes :: DrawWindowClass self => self -> IO ()\ndrawWindowSetChildShapes self =\n {# call gdk_window_set_child_shapes #}\n (toDrawWindow self)\n\n-- | Merges the shape masks for any child drawWindows into the shape mask for\n-- @DrawWindow@. i.e. the union of all masks for @DrawWindow@ and its children will\n-- become the new mask for @DrawWindow@. See 'drawWindowShapeCombineMask'.\n--\n-- This function is distinct from 'drawWindowSetChildShapes' because it includes\n-- @DrawWindow@'s shape mask in the set of shapes to be merged.\n-- \ndrawWindowMergeChildShapes :: DrawWindowClass self => self -> IO ()\ndrawWindowMergeChildShapes self =\n {# call gdk_window_merge_child_shapes #}\n (toDrawWindow self)\n\n-- Superseded by 'drawWindowGetPointerPos', won't be removed.\n-- Obtains the current pointer position and modifier state.\n--\n-- * The position is\n-- given in coordinates relative to the given window.\n-- \n-- * The return value is @Just (same, x, y, mod)@ where @same@ is @True@\n-- if the passed in window is the window over which the mouse currently\n-- resides.\n--\n-- * The return value is @Nothing@ if the mouse cursor is over a different\n-- application.\n--\ndrawWindowGetPointer :: DrawWindowClass self => self\n -> IO (Maybe (Bool, Int, Int, [Modifier]))\ndrawWindowGetPointer self =\n alloca $ \\xPtr -> alloca $ \\yPtr -> alloca $ \\mPtr -> do\n winPtr <- {# call gdk_window_get_pointer #} (toDrawWindow self)\n xPtr yPtr mPtr\n if winPtr==nullPtr then return Nothing else do\n same <- withForeignPtr (unDrawWindow (toDrawWindow self)) $ \\dPtr ->\n return (winPtr==dPtr)\n x <- peek xPtr\n y <- peek yPtr\n m <- peek mPtr\n return (Just (same, fromIntegral x, fromIntegral y,\n toFlags (fromIntegral m)))\n\n-- | Obtains the current pointer position and modifier state.\n--\n-- * The position is\n-- given in coordinates relative to the given window.\n-- \n-- * The return value is @(Just win, x, y, mod)@ where @win@ is the\n-- window over which the mouse currently resides and @mod@ denotes\n-- the keyboard modifiers currently being depressed.\n--\n-- * The return value is @Nothing@ for the window if the mouse cursor is \n-- not over a known window.\n--\ndrawWindowGetPointerPos :: DrawWindowClass self => self\n -> IO (Maybe DrawWindow, Int, Int, [Modifier])\ndrawWindowGetPointerPos self =\n alloca $ \\xPtr -> alloca $ \\yPtr -> alloca $ \\mPtr -> do\n winPtr <- {# call gdk_window_get_pointer #} (toDrawWindow self)\n xPtr yPtr mPtr\n x <- peek xPtr\n y <- peek yPtr\n m <- peek mPtr\n mWin <- if winPtr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkDrawWindow (return winPtr)\n return (mWin, fromIntegral x, fromIntegral y, toFlags (fromIntegral m))\n\n\n-- | Obtains the position of a window in screen coordinates.\n--\n-- You can use this to help convert a position between screen coordinates and\n-- local 'DrawWindow' relative coordinates.\n--\ndrawWindowGetOrigin :: DrawWindow\n -> IO (Int, Int) -- ^ @(x, y)@\ndrawWindowGetOrigin self =\n alloca $ \\xPtr ->\n alloca $ \\yPtr -> do\n {# call gdk_window_get_origin #}\n (toDrawWindow self)\n xPtr\n yPtr\n x <- peek xPtr\n y <- peek yPtr\n return (fromIntegral x, fromIntegral y)\n\n\n-- | Get the handle to an exising window of the windowing system. The\n-- passed-in handle is a reference to a native window, that is, an Xlib XID\n-- for X windows and a HWND for Win32.\ndrawWindowForeignNew :: NativeWindowId -> IO (Maybe DrawWindow)\ndrawWindowForeignNew anid = maybeNull (makeNewGObject mkDrawWindow) $\n liftM castPtr $ {#call gdk_window_foreign_new#} (fromNativeWindowId anid)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"e45d9ae194b65cb5f85b3f872bec4b372202f66e","subject":"[project @ 2003-05-17 14:53:11 by as49]","message":"[project @ 2003-05-17 14:53:11 by as49]\n\nDoc fix.\n\ndarcs-hash:20030517145311-d90cf-2df61af2f823f61d743e9d2df79b0096862763a9.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/pango\/PangoLayout.chs","new_file":"gtk\/pango\/PangoLayout.chs","new_contents":"-- GIMP Toolkit (GTK) - text layout functions @entry PangoLayout@\n--\n-- Author : Axel Simon\n-- \n-- Created: 8 Feburary 2003\n--\n-- Version $Revision: 1.4 $ from $Date: 2003\/05\/17 14:53:11 $\n--\n-- Copyright (c) 1999..2003 Axel Simon\n--\n-- This file is free software; you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation; either version 2 of the License, or\n-- (at your option) any later version.\n--\n-- This file is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- * Functions to run the rendering pipeline.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * The Pango rendering pipeline takes a string of Unicode characters\n-- and converts it into glyphs. The functions described in this module\n-- accomplish various steps of this process.\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * Functions that are missing:\n-- pango_layout_set_attributes, pango_layout_get_attributes,\n-- pango_layout_set_font_description, pango_layout_set_tabs,\n-- pango_layout_get_tabs, pango_layout_get_log_attrs, \n-- pango_layout_iter_get_run\n--\n-- * The following functions cannot be bound easily due to Unicode\/UTF8 issues:\n-- pango_layout_xy_to_index, pango_layout_index_to_pos,\n-- pango_layout_get_cursor_pos, pango_layout_move_cursor_visually,\n-- pango_layout_iter_get_index, pango_layout_line_index_to_x,\n-- pango_layout_line_x_to_index, pango_layout_line_get_x_ranges\n--\n-- * These functions are not bound, because they're too easy:\n-- pango_layout_get_size, pango_layout_get_pixel_size,\n-- pango_layout_get_line \n--\nmodule PangoLayout(\n PangoLayout,\n layoutCopy,\n layoutGetContext,\n layoutContextChanged,\n layoutSetText,\n layoutGetText,\n layoutSetMarkup,\n layoutSetMarkupWithAccel,\n layoutSetWidth,\n layoutGetWidth,\n LayoutWrapMode(..),\n layoutSetWrap,\n layoutGetWrap,\n layoutSetIndent,\n layoutGetIndent,\n layoutSetSpacing,\n layoutGetSpacing,\n layoutSetJustify,\n layoutGetJustify,\n LayoutAlignment(..),\n layoutSetAlignment,\n layoutGetAlignment,\n layoutSetSingleParagraphMode,\n layoutGetSingleParagraphMode,\n layoutGetExtents,\n layoutGetPixelExtents,\n layoutGetLineCount,\n layoutGetLines,\n LayoutIter,\n layoutGetIter,\n layoutIterNextRun,\n layoutIterNextChar,\n layoutIterNextCluster,\n layoutIterNextLine,\n layoutIterAtLastLine,\n layoutIterGetBaseline,\n layoutIterGetLine,\n layoutIterGetCharExtents,\n layoutIterGetClusterExtents,\n layoutIterGetRunExtents,\n layoutIterGetLineYRange,\n layoutIterGetLineExtents,\n LayoutLine,\n layoutLineGetExtents,\n layoutLineGetPixelExtents\n ) where\n\nimport Monad (liftM)\nimport Foreign\nimport UTFCForeign\n{#import Hierarchy#}\nimport GObject (makeNewGObject)\nimport Markup\t(Markup)\nimport Char\t(ord, chr)\nimport Enums\nimport Structs\t(Rectangle)\nimport GList\t(readGSList)\n{#import PangoTypes#}\n\n{# context lib=\"pango\" prefix=\"pango\" #}\n\n-- @method layoutCopy@ Create a copy of the @ref data layout@.\n--\nlayoutCopy :: PangoLayout -> IO PangoLayout\nlayoutCopy pl = makeNewGObject mkPangoLayout \n\t\t ({#call unsafe layout_copy#} (toPangoLayout pl))\n\n-- @method layoutGetContext@ Retrieves the @ref data PangoContext@ from this\n-- layout.\n--\nlayoutGetContext :: PangoLayout -> IO PangoContext\nlayoutGetContext pl = makeNewGObject mkPangoContext\n\t\t ({#call unsafe layout_get_context#} pl)\n\n-- @method layoutContextChanged@ Signal a @ref data Context@ change.\n--\n-- * Forces recomputation of any state in the @ref data PangoLayout@ that\n-- might depend on the layout's context. This function should\n-- be called if you make changes to the context subsequent\n-- to creating the layout.\n--\nlayoutContextChanged :: PangoLayout -> IO ()\nlayoutContextChanged pl = {#call unsafe layout_context_changed#} pl\n\n-- @method layoutSetText@ Set the string in the layout.\n--\nlayoutSetText :: PangoLayout -> String -> IO ()\nlayoutSetText pl txt = withCStringLen txt $ \\(strPtr,len) ->\n {#call unsafe layout_set_text#} pl strPtr (fromIntegral len)\n\n-- @method layoutGetText@ Retrieve the string in the layout.\n--\nlayoutGetText :: PangoLayout -> IO String\nlayoutGetText pl = {#call unsafe layout_get_text#} pl >>= peekCString\n\n-- @method layoutSetMarkup@ Set the string in the layout.\n--\n-- * The string may include @ref data Markup@.\n--\nlayoutSetMarkup :: PangoLayout -> Markup -> IO ()\nlayoutSetMarkup pl txt = withCStringLen txt $ \\(strPtr,len) ->\n {#call unsafe layout_set_markup#} pl strPtr (fromIntegral len)\n\n-- @method layoutSetMarkupWithAccel@ Set the string in the layout.\n--\n-- * The string may include @ref data Markup@. Furthermore, any underscore\n-- character indicates that the next character should be\n-- marked as accelerator (i.e. underlined). A literal underscore character\n-- can be produced by placing it twice in the string.\n--\n-- * The character which follows the underscore is\n-- returned so it can be used to add the actual keyboard shortcut. \n--\nlayoutSetMarkupWithAccel :: PangoLayout -> Markup -> IO Char\nlayoutSetMarkupWithAccel pl txt =\n alloca $ \\chrPtr -> \n withCStringLen txt $ \\(strPtr,len) -> do\n {#call unsafe layout_set_markup_with_accel#} pl strPtr (fromIntegral len)\n (fromIntegral (ord '_')) chrPtr\n liftM (chr.fromIntegral) $ peek chrPtr\n\n\n-- there are a couple of functions missing here\n\n-- @method layoutSetWidth@ Set the width of this paragraph.\n--\n-- * Sets the width to which the lines of the @ref data PangoLayout@\n-- should be wrapped.\n--\n-- * @ref arg width@ is the desired width, or @literal -1@ to indicate that\n-- no wrapping should be performed.\n--\nlayoutSetWidth :: PangoLayout -> Int -> IO ()\nlayoutSetWidth pl width =\n {#call unsafe layout_set_width#} pl (fromIntegral width)\n\n-- @method layoutGetWidth@ Gets the width of this paragraph.\n--\n-- * Gets the width to which the lines of the @ref data PangoLayout@\n-- should be wrapped.\n--\n-- * Returns is the current width, or @literal -1@ to indicate that\n-- no wrapping is performed.\n--\nlayoutGetWidth :: PangoLayout -> IO Int\nlayoutGetWidth pl = liftM fromIntegral $ {#call unsafe layout_get_width#} pl\n\n\n-- @data LayoutWarpMode@ Enumerates how a line can be wrapped.\n--\n-- @variant WrapWholeWords@ Breaks lines only between words.\n--\n-- * This variant does not guarantee that the requested width is not\n-- exceeded. A word that is longer than the paragraph width is not\n-- split.\n\n-- @variant WrapAnywhere@ Break lines anywhere.\n--\n-- @variant WrapPartialWords@ Wrap within a word if it is the only one on\n-- this line.\n--\n-- * This option acts like @ref variant WrapWholeWords@ but will split\n-- a word if it is the only one on this line and it exceeds the\n-- specified width.\n--\n{#enum PangoWrapMode as LayoutWrapMode \n {underscoreToCase,\n PANGO_WRAP_WORD as WrapWholeWords,\n PANGO_WRAP_CHAR as WrapAnywhere,\n PANGO_WRAP_WORD_CHAR as WrapPartialWords}#}\n\n-- @method layoutSetWrap@ Set how this paragraph is wrapped.\n--\n-- * Sets the wrap style; the wrap style only has an effect if a width\n-- is set on the layout with @ref method layoutSetWidth@. To turn off\n-- wrapping, set the width to -1.\n--\nlayoutSetWrap :: PangoLayout -> LayoutWrapMode -> IO ()\nlayoutSetWrap pl wm =\n {#call unsafe layout_set_wrap#} pl ((fromIntegral.fromEnum) wm)\n\n\n-- @method layoutGetWrap@ Get the wrap mode for the layout.\n--\nlayoutGetWrap :: PangoLayout -> IO LayoutWrapMode\nlayoutGetWrap pl = liftM (toEnum.fromIntegral) $\n {#call unsafe layout_get_wrap#} pl\n\n-- @method layoutSetIndent@ Set the indentation of this paragraph.\n--\n-- * Sets the amount by which the first line should be shorter than\n-- the rest of the lines. This may be negative, in which case the\n-- subsequent lines will be shorter than the first line. (However, in\n-- either case, the entire width of the layout will be given by the\n-- value.\n--\nlayoutSetIndent :: PangoLayout -> Int -> IO ()\nlayoutSetIndent pl indent =\n {#call unsafe layout_set_indent#} pl (fromIntegral indent)\n\n-- @method layoutGetIndent@ Gets the indentation of this paragraph.\n--\n-- * Gets the amount by which the first line should be shorter than \n-- the rest of the lines.\n--\nlayoutGetIndent :: PangoLayout -> IO Int\nlayoutGetIndent pl = liftM fromIntegral $ {#call unsafe layout_get_indent#} pl\n\n\n-- @method layoutSetSpacing@ Set the spacing between lines of this paragraph.\n--\nlayoutSetSpacing :: PangoLayout -> Int -> IO ()\nlayoutSetSpacing pl spacing =\n {#call unsafe layout_set_spacing#} pl (fromIntegral spacing)\n\n-- @method layoutGetSpacing@ Gets the spacing between the lines.\n--\nlayoutGetSpacing :: PangoLayout -> IO Int\nlayoutGetSpacing pl = \n liftM fromIntegral $ {#call unsafe layout_get_spacing#} pl\n\n-- @method layoutSetJustify@ Set if text should be streched to fit width.\n--\n-- * Sets whether or not each complete line should be stretched to\n-- fill the entire width of the layout. This stretching is typically\n-- done by adding whitespace, but for some scripts (such as Arabic),\n-- the justification is done by extending the characters.\n--\nlayoutSetJustify :: PangoLayout -> Bool -> IO ()\nlayoutSetJustify pl j = {#call unsafe layout_set_justify#} pl (fromBool j)\n\n-- @method layoutGetJustify@ Retrieve the justification flag.\n--\n-- * See @ref method layoutSetJustify@.\n--\nlayoutGetJustify :: PangoLayout -> IO Bool\nlayoutGetJustify pl = liftM toBool $ {#call unsafe layout_get_justify#} pl\n\n-- @data LayoutAlignment@ Enumerate to which side incomplete lines are flushed.\n--\n{#enum PangoAlignment as LayoutAlignment {underscoreToCase}#}\n\n-- @method layoutSetAlignment@ Set how this paragraph is aligned.\n--\n-- * Sets the alignment for the layout (how partial lines are\n-- positioned within the horizontal space available.)\n--\nlayoutSetAlignment :: PangoLayout -> LayoutAlignment -> IO ()\nlayoutSetAlignment pl am =\n {#call unsafe layout_set_alignment#} pl ((fromIntegral.fromEnum) am)\n\n\n-- @method layoutGetAlignment@ Get the alignment for the layout.\n--\nlayoutGetAlignment :: PangoLayout -> IO LayoutAlignment\nlayoutGetAlignment pl = liftM (toEnum.fromIntegral) $\n {#call unsafe layout_get_alignment#} pl\n\n-- functions are missing here\n\n-- @method layoutSetSingleParagraphMode@ Honor newlines or not.\n--\n-- * If @ref arg honor@ is @literal True@, do not treat newlines and\n-- similar characters as paragraph separators; instead, keep all text in\n-- a single paragraph, and display a glyph for paragraph separator\n-- characters. Used when you want to allow editing of newlines on a\n-- single text line.\n--\nlayoutSetSingleParagraphMode :: PangoLayout -> Bool -> IO ()\nlayoutSetSingleParagraphMode pl honor = \n {#call unsafe layout_set_single_paragraph_mode#} pl (fromBool honor)\n\n-- @method layoutGetSingleParagraphMode@ Retrieve if newlines are honored.\n--\n-- * See @ref method layoutSetSingleParagraphMode@.\n--\nlayoutGetSingleParagraphMode :: PangoLayout -> IO Bool\nlayoutGetSingleParagraphMode pl = \n liftM toBool $ {#call unsafe layout_get_single_paragraph_mode#} pl\n\n-- a function is missing here\n\n-- @method layoutGetExtents@ Compute the physical size of the layout.\n--\n-- * Computes the logical and the ink size of the @ref data Layout@. The\n-- logical layout is used for positioning, the ink size is the smallest\n-- bounding box that includes all character pixels. The ink size can be\n-- smaller or larger that the logical layout.\n--\n-- * All values are in layout units. To get to device units (pixel for\n-- @ref data Drawable@s) divide by @ref constant pangoScale@.\n--\nlayoutGetExtents :: PangoLayout -> IO (Rectangle, Rectangle)\nlayoutGetExtents pl = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_get_extents#} pl (castPtr logPtr) (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n\n-- @method layoutGetPixelExtents@ Compute the physical size of the layout.\n--\n-- * Computes the logical and the ink size of the @ref data Layout@. The\n-- logical layout is used for positioning, the ink size is the smallest\n-- bounding box that includes all character pixels. The ink size can be\n-- smaller or larger that the logical layout.\n--\n-- * All values are in device units. This function is a wrapper around\n-- @ref method layoutGetExtents@ with scaling.\n--\nlayoutGetPixelExtents :: PangoLayout -> IO (Rectangle, Rectangle)\nlayoutGetPixelExtents pl = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_get_pixel_extents#} pl (castPtr logPtr) (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n-- @method layoutGetLineCount@ Ask for the number of lines in this layout.\n--\nlayoutGetLineCount :: PangoLayout -> IO Int\nlayoutGetLineCount pl = liftM fromIntegral $\n {#call unsafe layout_get_line_count#} pl\n\n-- @method layoutGetLines@ Extract the single lines of the layout.\n--\n-- * The lines of each layout are regenerated if any attribute changes.\n-- Thus the returned list does not reflect the current state of lines\n-- after a change has been made.\n--\nlayoutGetLines :: PangoLayout -> IO [LayoutLine]\nlayoutGetLines pl = do\n listPtr <- {#call unsafe layout_get_lines#} pl\n list <- readGSList listPtr\n mapM mkLayoutLine list\n\n-- @constructor layoutGetIter@ Create an iterator to examine a layout.\n--\nlayoutGetIter :: PangoLayout -> IO LayoutIter\nlayoutGetIter pl = do\n iterPtr <- {#call unsafe layout_get_iter#} pl\n liftM LayoutIter $ newForeignPtr iterPtr (layout_iter_free iterPtr)\n\n-- @method layoutNextRun@ Move to the next run.\n--\n-- * Returns @literal False@ if this was the last run in the layout.\n--\nlayoutIterNextRun :: LayoutIter -> IO Bool\nlayoutIterNextRun = liftM toBool . {#call unsafe layout_iter_next_run#}\n\n-- @method layoutNextChar@ Move to the next char.\n--\n-- * Returns @literal False@ if this was the last char in the layout.\n--\nlayoutIterNextChar :: LayoutIter -> IO Bool\nlayoutIterNextChar = liftM toBool . {#call unsafe layout_iter_next_char#}\n\n-- @method layoutNextCluster@ Move to the next cluster.\n--\n-- * Returns @literal False@ if this was the last cluster in the layout.\n--\nlayoutIterNextCluster :: LayoutIter -> IO Bool\nlayoutIterNextCluster = liftM toBool . {#call unsafe layout_iter_next_cluster#}\n\n-- @method layoutNextLine@ Move to the next line.\n--\n-- * Returns @literal False@ if this was the last line in the layout.\n--\nlayoutIterNextLine :: LayoutIter -> IO Bool\nlayoutIterNextLine = liftM toBool . {#call unsafe layout_iter_next_line#}\n\n-- @method layoutAtLastLine@ Check if the iterator is on the last line.\n--\n-- * Returns @literal True@ if the iterator is on the last line of this\n-- paragraph.\n--\nlayoutIterAtLastLine :: LayoutIter -> IO Bool\nlayoutIterAtLastLine = liftM toBool . {#call unsafe layout_iter_at_last_line#}\n\n-- @method layoutIterGetBaseline@ Query the vertical position within the\n-- layout.\n--\n-- * Gets the y position of the current line's baseline, in layout\n-- coordinates (origin at top left of the entire layout).\n--\nlayoutIterGetBaseline :: LayoutIter -> IO Int\nlayoutIterGetBaseline = \n liftM fromIntegral . {#call unsafe pango_layout_iter_get_baseline#}\n\n-- pango_layout_iter_get_run goes here\n\n-- @method layoutIterGetLine@ Extract the line under the iterator.\n--\nlayoutIterGetLine :: LayoutIter -> IO (Maybe LayoutLine)\nlayoutIterGetLine li = do\n llPtr <- liftM castPtr $ {#call unsafe pango_layout_iter_get_line#} li\n if (llPtr==nullPtr) then return Nothing else \n liftM Just $ mkLayoutLine llPtr\n\n-- @method layoutIterGetCharExtents@ Retrieve a rectangle surrounding\n-- a character.\n--\n-- * Get the extents of the current character in layout cooridnates\n-- (origin is the top left of the entire layout). Only logical extents\n-- can sensibly be obtained for characters. \n--\nlayoutIterGetCharExtents :: LayoutIter -> IO Rectangle\nlayoutIterGetCharExtents li = alloca $ \\logPtr -> \n {#call unsafe layout_iter_get_char_extents#} li (castPtr logPtr) >>\n peek logPtr\n\n-- @method layoutIterGetClusterExtents@ Compute the physical size of the\n-- cluster.\n--\n-- * Computes the logical and the ink size of the cluster pointed to by\n-- @ref data LayoutIter@.\n--\n-- * All values are in layoutIter units. To get to device units (pixel for\n-- @ref data Drawable@s) divide by @ref constant pangoScale@.\n--\nlayoutIterGetClusterExtents :: LayoutIter -> IO (Rectangle, Rectangle)\nlayoutIterGetClusterExtents li = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_iter_get_cluster_extents#} li (castPtr logPtr)\n (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n-- @method layoutIterGetRunExtents@ Compute the physical size of the run.\n--\n-- * Computes the logical and the ink size of the run pointed to by\n-- @ref data LayoutIter@.\n--\n-- * All values are in layoutIter units. To get to device units (pixel for\n-- @ref data Drawable@s) divide by @ref constant pangoScale@.\n--\nlayoutIterGetRunExtents :: LayoutIter -> IO (Rectangle, Rectangle)\nlayoutIterGetRunExtents li = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_iter_get_run_extents#} li (castPtr logPtr)\n (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n-- @method layoutIterGetLineYRange@ Retrieve vertical extent of this\n-- line.\n--\n-- * Divides the vertical space in the @ref data PangoLayout@ being\n-- iterated over between the lines in the layout, and returns the\n-- space belonging to the current line. A line's range includes the\n-- line's logical extents, plus half of the spacing above and below\n-- the line, if @ref method pangoLayoutSetSpacing@ has been called\n-- to set layout spacing. The y positions are in layout coordinates\n-- (origin at top left of the entire layout).\n--\n-- * The first element in the returned tuple is the start, the second is\n-- the end of this line.\n--\nlayoutIterGetLineYRange :: LayoutIter -> IO (Int,Int)\nlayoutIterGetLineYRange li = alloca $ \\sPtr -> alloca $ \\ePtr -> do\n {#call unsafe layout_iter_get_line_extents#} li (castPtr sPtr) (castPtr ePtr)\n start <- peek sPtr\n end <- peek ePtr\n return (start,end)\n\n-- @method layoutIterGetLineExtents@ Compute the physical size of the line.\n--\n-- * Computes the logical and the ink size of the line pointed to by\n-- @ref data LayoutIter@.\n--\n-- * Extents are in layout coordinates (origin is the top-left corner\n-- of the entire @ref data PangoLayout@). Thus the extents returned\n-- by this function will be the same width\/height but not at the\n-- same x\/y as the extents returned from @ref method\n-- pangoLayoutLineGetExtents@.\n--\nlayoutIterGetLineExtents :: LayoutIter -> IO (Rectangle, Rectangle)\nlayoutIterGetLineExtents li = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_iter_get_line_extents#} li (castPtr logPtr)\n (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n\n-- @method layoutLineGetExtents@ Compute the physical size of the line.\n--\n-- * Computes the logical and the ink size of the @ref data LayoutLine@. The\n-- logical layout is used for positioning, the ink size is the smallest\n-- bounding box that includes all character pixels. The ink size can be\n-- smaller or larger that the logical layout.\n--\n-- * All values are in layout units. To get to device units (pixel for\n-- @ref data Drawable@s) divide by @ref constant pangoScale@.\n--\nlayoutLineGetExtents :: LayoutLine -> IO (Rectangle, Rectangle)\nlayoutLineGetExtents pl = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_line_get_extents#} pl (castPtr logPtr) (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n-- @method layoutLineGetPixelExtents@ Compute the physical size of the line.\n--\n-- * Computes the logical and the ink size of the @ref data LayoutLine@. The\n-- logical layout is used for positioning, the ink size is the smallest\n-- bounding box that includes all character pixels. The ink size can be\n-- smaller or larger that the logical layout.\n--\n-- * All values are in device units. This function is a wrapper around\n-- @ref method layoutLineGetExtents@ with scaling.\n--\nlayoutLineGetPixelExtents :: LayoutLine -> IO (Rectangle, Rectangle)\nlayoutLineGetPixelExtents pl = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_line_get_pixel_extents#} pl\n (castPtr logPtr) (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n","old_contents":"-- GIMP Toolkit (GTK) - text layout functions @entry layout@\n--\n-- Author : Axel Simon\n-- \n-- Created: 8 Feburary 2003\n--\n-- Version $Revision: 1.3 $ from $Date: 2003\/05\/16 05:53:33 $\n--\n-- Copyright (c) 1999..2003 Axel Simon\n--\n-- This file is free software; you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation; either version 2 of the License, or\n-- (at your option) any later version.\n--\n-- This file is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- * Functions to run the rendering pipeline.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * The Pango rendering pipeline takes a string of Unicode characters\n-- and converts it into glyphs. The functions described in this module\n-- accomplish various steps of this process.\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * Functions that are missing:\n-- pango_layout_set_attributes, pango_layout_get_attributes,\n-- pango_layout_set_font_description, pango_layout_set_tabs,\n-- pango_layout_get_tabs, pango_layout_get_log_attrs, \n-- pango_layout_iter_get_run\n--\n-- * The following functions cannot be bound easily due to Unicode\/UTF8 issues:\n-- pango_layout_xy_to_index, pango_layout_index_to_pos,\n-- pango_layout_get_cursor_pos, pango_layout_move_cursor_visually,\n-- pango_layout_iter_get_index, pango_layout_line_index_to_x,\n-- pango_layout_line_x_to_index, pango_layout_line_get_x_ranges\n--\n-- * These functions are not bound, because they're too easy:\n-- pango_layout_get_size, pango_layout_get_pixel_size,\n-- pango_layout_get_line \n--\nmodule PangoLayout(\n PangoLayout,\n layoutCopy,\n layoutGetContext,\n layoutContextChanged,\n layoutSetText,\n layoutGetText,\n layoutSetMarkup,\n layoutSetMarkupWithAccel,\n layoutSetWidth,\n layoutGetWidth,\n LayoutWrapMode(..),\n layoutSetWrap,\n layoutGetWrap,\n layoutSetIndent,\n layoutGetIndent,\n layoutSetSpacing,\n layoutGetSpacing,\n layoutSetJustify,\n layoutGetJustify,\n LayoutAlignment(..),\n layoutSetAlignment,\n layoutGetAlignment,\n layoutSetSingleParagraphMode,\n layoutGetSingleParagraphMode,\n layoutGetExtents,\n layoutGetPixelExtents,\n layoutGetLineCount,\n layoutGetLines,\n LayoutIter,\n layoutGetIter,\n layoutIterNextRun,\n layoutIterNextChar,\n layoutIterNextCluster,\n layoutIterNextLine,\n layoutIterAtLastLine,\n layoutIterGetBaseline,\n layoutIterGetLine,\n layoutIterGetCharExtents,\n layoutIterGetClusterExtents,\n layoutIterGetRunExtents,\n layoutIterGetLineYRange,\n layoutIterGetLineExtents,\n LayoutLine,\n layoutLineGetExtents,\n layoutLineGetPixelExtents\n ) where\n\nimport Monad (liftM)\nimport Foreign\nimport UTFCForeign\n{#import Hierarchy#}\nimport GObject (makeNewGObject)\nimport Markup\t(Markup)\nimport Char\t(ord, chr)\nimport Enums\nimport Structs\t(Rectangle)\nimport GList\t(readGSList)\n{#import PangoTypes#}\n\n{# context lib=\"pango\" prefix=\"pango\" #}\n\n-- @method layoutCopy@ Create a copy of the @ref data layout@.\n--\nlayoutCopy :: PangoLayout -> IO PangoLayout\nlayoutCopy pl = makeNewGObject mkPangoLayout \n\t\t ({#call unsafe layout_copy#} (toPangoLayout pl))\n\n-- @method layoutGetContext@ Retrieves the @ref data PangoContext@ from this\n-- layout.\n--\nlayoutGetContext :: PangoLayout -> IO PangoContext\nlayoutGetContext pl = makeNewGObject mkPangoContext\n\t\t ({#call unsafe layout_get_context#} pl)\n\n-- @method layoutContextChanged@ Signal a @ref data Context@ change.\n--\n-- * Forces recomputation of any state in the @ref data PangoLayout@ that\n-- might depend on the layout's context. This function should\n-- be called if you make changes to the context subsequent\n-- to creating the layout.\n--\nlayoutContextChanged :: PangoLayout -> IO ()\nlayoutContextChanged pl = {#call unsafe layout_context_changed#} pl\n\n-- @method layoutSetText@ Set the string in the layout.\n--\nlayoutSetText :: PangoLayout -> String -> IO ()\nlayoutSetText pl txt = withCStringLen txt $ \\(strPtr,len) ->\n {#call unsafe layout_set_text#} pl strPtr (fromIntegral len)\n\n-- @method layoutGetText@ Retrieve the string in the layout.\n--\nlayoutGetText :: PangoLayout -> IO String\nlayoutGetText pl = {#call unsafe layout_get_text#} pl >>= peekCString\n\n-- @method layoutSetMarkup@ Set the string in the layout.\n--\n-- * The string may include @ref data Markup@.\n--\nlayoutSetMarkup :: PangoLayout -> Markup -> IO ()\nlayoutSetMarkup pl txt = withCStringLen txt $ \\(strPtr,len) ->\n {#call unsafe layout_set_markup#} pl strPtr (fromIntegral len)\n\n-- @method layoutSetMarkupWithAccel@ Set the string in the layout.\n--\n-- * The string may include @ref data Markup@. Furthermore, any underscore\n-- character indicates that the next character should be\n-- marked as accelerator (i.e. underlined). A literal underscore character\n-- can be produced by placing it twice in the string.\n--\n-- * The character which follows the underscore is\n-- returned so it can be used to add the actual keyboard shortcut. \n--\nlayoutSetMarkupWithAccel :: PangoLayout -> Markup -> IO Char\nlayoutSetMarkupWithAccel pl txt =\n alloca $ \\chrPtr -> \n withCStringLen txt $ \\(strPtr,len) -> do\n {#call unsafe layout_set_markup_with_accel#} pl strPtr (fromIntegral len)\n (fromIntegral (ord '_')) chrPtr\n liftM (chr.fromIntegral) $ peek chrPtr\n\n\n-- there are a couple of functions missing here\n\n-- @method layoutSetWidth@ Set the width of this paragraph.\n--\n-- * Sets the width to which the lines of the @ref data PangoLayout@\n-- should be wrapped.\n--\n-- * @ref arg width@ is the desired width, or @literal -1@ to indicate that\n-- no wrapping should be performed.\n--\nlayoutSetWidth :: PangoLayout -> Int -> IO ()\nlayoutSetWidth pl width =\n {#call unsafe layout_set_width#} pl (fromIntegral width)\n\n-- @method layoutGetWidth@ Gets the width of this paragraph.\n--\n-- * Gets the width to which the lines of the @ref data PangoLayout@\n-- should be wrapped.\n--\n-- * Returns is the current width, or @literal -1@ to indicate that\n-- no wrapping is performed.\n--\nlayoutGetWidth :: PangoLayout -> IO Int\nlayoutGetWidth pl = liftM fromIntegral $ {#call unsafe layout_get_width#} pl\n\n\n-- @data LayoutWarpMode@ Enumerates how a line can be wrapped.\n--\n-- @variant WrapWholeWords@ Breaks lines only between words.\n--\n-- * This variant does not guarantee that the requested width is not\n-- exceeded. A word that is longer than the paragraph width is not\n-- split.\n\n-- @variant WrapAnywhere@ Break lines anywhere.\n--\n-- @variant WrapPartialWords@ Wrap within a word if it is the only one on\n-- this line.\n--\n-- * This option acts like @ref variant WrapWholeWords@ but will split\n-- a word if it is the only one on this line and it exceeds the\n-- specified width.\n--\n{#enum PangoWrapMode as LayoutWrapMode \n {underscoreToCase,\n PANGO_WRAP_WORD as WrapWholeWords,\n PANGO_WRAP_CHAR as WrapAnywhere,\n PANGO_WRAP_WORD_CHAR as WrapPartialWords}#}\n\n-- @method layoutSetWrap@ Set how this paragraph is wrapped.\n--\n-- * Sets the wrap style; the wrap style only has an effect if a width\n-- is set on the layout with @ref method layoutSetWidth@. To turn off\n-- wrapping, set the width to -1.\n--\nlayoutSetWrap :: PangoLayout -> LayoutWrapMode -> IO ()\nlayoutSetWrap pl wm =\n {#call unsafe layout_set_wrap#} pl ((fromIntegral.fromEnum) wm)\n\n\n-- @method layoutGetWrap@ Get the wrap mode for the layout.\n--\nlayoutGetWrap :: PangoLayout -> IO LayoutWrapMode\nlayoutGetWrap pl = liftM (toEnum.fromIntegral) $\n {#call unsafe layout_get_wrap#} pl\n\n-- @method layoutSetIndent@ Set the indentation of this paragraph.\n--\n-- * Sets the amount by which the first line should be shorter than\n-- the rest of the lines. This may be negative, in which case the\n-- subsequent lines will be shorter than the first line. (However, in\n-- either case, the entire width of the layout will be given by the\n-- value.\n--\nlayoutSetIndent :: PangoLayout -> Int -> IO ()\nlayoutSetIndent pl indent =\n {#call unsafe layout_set_indent#} pl (fromIntegral indent)\n\n-- @method layoutGetIndent@ Gets the indentation of this paragraph.\n--\n-- * Gets the amount by which the first line should be shorter than \n-- the rest of the lines.\n--\nlayoutGetIndent :: PangoLayout -> IO Int\nlayoutGetIndent pl = liftM fromIntegral $ {#call unsafe layout_get_indent#} pl\n\n\n-- @method layoutSetSpacing@ Set the spacing between lines of this paragraph.\n--\nlayoutSetSpacing :: PangoLayout -> Int -> IO ()\nlayoutSetSpacing pl spacing =\n {#call unsafe layout_set_spacing#} pl (fromIntegral spacing)\n\n-- @method layoutGetSpacing@ Gets the spacing between the lines.\n--\nlayoutGetSpacing :: PangoLayout -> IO Int\nlayoutGetSpacing pl = \n liftM fromIntegral $ {#call unsafe layout_get_spacing#} pl\n\n-- @method layoutSetJustify@ Set if text should be streched to fit width.\n--\n-- * Sets whether or not each complete line should be stretched to\n-- fill the entire width of the layout. This stretching is typically\n-- done by adding whitespace, but for some scripts (such as Arabic),\n-- the justification is done by extending the characters.\n--\nlayoutSetJustify :: PangoLayout -> Bool -> IO ()\nlayoutSetJustify pl j = {#call unsafe layout_set_justify#} pl (fromBool j)\n\n-- @method layoutGetJustify@ Retrieve the justification flag.\n--\n-- * See @ref method layoutSetJustify@.\n--\nlayoutGetJustify :: PangoLayout -> IO Bool\nlayoutGetJustify pl = liftM toBool $ {#call unsafe layout_get_justify#} pl\n\n-- @data LayoutAlignment@ Enumerate to which side incomplete lines are flushed.\n--\n{#enum PangoAlignment as LayoutAlignment {underscoreToCase}#}\n\n-- @method layoutSetAlignment@ Set how this paragraph is aligned.\n--\n-- * Sets the alignment for the layout (how partial lines are\n-- positioned within the horizontal space available.)\n--\nlayoutSetAlignment :: PangoLayout -> LayoutAlignment -> IO ()\nlayoutSetAlignment pl am =\n {#call unsafe layout_set_alignment#} pl ((fromIntegral.fromEnum) am)\n\n\n-- @method layoutGetAlignment@ Get the alignment for the layout.\n--\nlayoutGetAlignment :: PangoLayout -> IO LayoutAlignment\nlayoutGetAlignment pl = liftM (toEnum.fromIntegral) $\n {#call unsafe layout_get_alignment#} pl\n\n-- functions are missing here\n\n-- @method layoutSetSingleParagraphMode@ Honor newlines or not.\n--\n-- * If @ref arg honor@ is @literal True@, do not treat newlines and\n-- similar characters as paragraph separators; instead, keep all text in\n-- a single paragraph, and display a glyph for paragraph separator\n-- characters. Used when you want to allow editing of newlines on a\n-- single text line.\n--\nlayoutSetSingleParagraphMode :: PangoLayout -> Bool -> IO ()\nlayoutSetSingleParagraphMode pl honor = \n {#call unsafe layout_set_single_paragraph_mode#} pl (fromBool honor)\n\n-- @method layoutGetSingleParagraphMode@ Retrieve if newlines are honored.\n--\n-- * See @ref method layoutSetSingleParagraphMode@.\n--\nlayoutGetSingleParagraphMode :: PangoLayout -> IO Bool\nlayoutGetSingleParagraphMode pl = \n liftM toBool $ {#call unsafe layout_get_single_paragraph_mode#} pl\n\n-- a function is missing here\n\n-- @method layoutGetExtents@ Compute the physical size of the layout.\n--\n-- * Computes the logical and the ink size of the @ref data Layout@. The\n-- logical layout is used for positioning, the ink size is the smallest\n-- bounding box that includes all character pixels. The ink size can be\n-- smaller or larger that the logical layout.\n--\n-- * All values are in layout units. To get to device units (pixel for\n-- @ref data Drawable@s) divide by @ref constant pangoScale@.\n--\nlayoutGetExtents :: PangoLayout -> IO (Rectangle, Rectangle)\nlayoutGetExtents pl = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_get_extents#} pl (castPtr logPtr) (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n\n-- @method layoutGetPixelExtents@ Compute the physical size of the layout.\n--\n-- * Computes the logical and the ink size of the @ref data Layout@. The\n-- logical layout is used for positioning, the ink size is the smallest\n-- bounding box that includes all character pixels. The ink size can be\n-- smaller or larger that the logical layout.\n--\n-- * All values are in device units. This function is a wrapper around\n-- @ref method layoutGetExtents@ with scaling.\n--\nlayoutGetPixelExtents :: PangoLayout -> IO (Rectangle, Rectangle)\nlayoutGetPixelExtents pl = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_get_pixel_extents#} pl (castPtr logPtr) (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n-- @method layoutGetLineCount@ Ask for the number of lines in this layout.\n--\nlayoutGetLineCount :: PangoLayout -> IO Int\nlayoutGetLineCount pl = liftM fromIntegral $\n {#call unsafe layout_get_line_count#} pl\n\n-- @method layoutGetLines@ Extract the single lines of the layout.\n--\n-- * The lines of each layout are regenerated if any attribute changes.\n-- Thus the returned list does not reflect the current state of lines\n-- after a change has been made.\n--\nlayoutGetLines :: PangoLayout -> IO [LayoutLine]\nlayoutGetLines pl = do\n listPtr <- {#call unsafe layout_get_lines#} pl\n list <- readGSList listPtr\n mapM mkLayoutLine list\n\n-- @constructor layoutGetIter@ Create an iterator to examine a layout.\n--\nlayoutGetIter :: PangoLayout -> IO LayoutIter\nlayoutGetIter pl = do\n iterPtr <- {#call unsafe layout_get_iter#} pl\n liftM LayoutIter $ newForeignPtr iterPtr (layout_iter_free iterPtr)\n\n-- @method layoutNextRun@ Move to the next run.\n--\n-- * Returns @literal False@ if this was the last run in the layout.\n--\nlayoutIterNextRun :: LayoutIter -> IO Bool\nlayoutIterNextRun = liftM toBool . {#call unsafe layout_iter_next_run#}\n\n-- @method layoutNextChar@ Move to the next char.\n--\n-- * Returns @literal False@ if this was the last char in the layout.\n--\nlayoutIterNextChar :: LayoutIter -> IO Bool\nlayoutIterNextChar = liftM toBool . {#call unsafe layout_iter_next_char#}\n\n-- @method layoutNextCluster@ Move to the next cluster.\n--\n-- * Returns @literal False@ if this was the last cluster in the layout.\n--\nlayoutIterNextCluster :: LayoutIter -> IO Bool\nlayoutIterNextCluster = liftM toBool . {#call unsafe layout_iter_next_cluster#}\n\n-- @method layoutNextLine@ Move to the next line.\n--\n-- * Returns @literal False@ if this was the last line in the layout.\n--\nlayoutIterNextLine :: LayoutIter -> IO Bool\nlayoutIterNextLine = liftM toBool . {#call unsafe layout_iter_next_line#}\n\n-- @method layoutAtLastLine@ Check if the iterator is on the last line.\n--\n-- * Returns @literal True@ if the iterator is on the last line of this\n-- paragraph.\n--\nlayoutIterAtLastLine :: LayoutIter -> IO Bool\nlayoutIterAtLastLine = liftM toBool . {#call unsafe layout_iter_at_last_line#}\n\n-- @method layoutIterGetBaseline@ Query the vertical position within the\n-- layout.\n--\n-- * Gets the y position of the current line's baseline, in layout\n-- coordinates (origin at top left of the entire layout).\n--\nlayoutIterGetBaseline :: LayoutIter -> IO Int\nlayoutIterGetBaseline = \n liftM fromIntegral . {#call unsafe pango_layout_iter_get_baseline#}\n\n-- pango_layout_iter_get_run goes here\n\n-- @method layoutIterGetLine@ Extract the line under the iterator.\n--\nlayoutIterGetLine :: LayoutIter -> IO (Maybe LayoutLine)\nlayoutIterGetLine li = do\n llPtr <- liftM castPtr $ {#call unsafe pango_layout_iter_get_line#} li\n if (llPtr==nullPtr) then return Nothing else \n liftM Just $ mkLayoutLine llPtr\n\n-- @method layoutIterGetCharExtents@ Retrieve a rectangle surrounding\n-- a character.\n--\n-- * Get the extents of the current character in layout cooridnates\n-- (origin is the top left of the entire layout). Only logical extents\n-- can sensibly be obtained for characters. \n--\nlayoutIterGetCharExtents :: LayoutIter -> IO Rectangle\nlayoutIterGetCharExtents li = alloca $ \\logPtr -> \n {#call unsafe layout_iter_get_char_extents#} li (castPtr logPtr) >>\n peek logPtr\n\n-- @method layoutIterGetClusterExtents@ Compute the physical size of the\n-- cluster.\n--\n-- * Computes the logical and the ink size of the cluster pointed to by\n-- @ref data LayoutIter@.\n--\n-- * All values are in layoutIter units. To get to device units (pixel for\n-- @ref data Drawable@s) divide by @ref constant pangoScale@.\n--\nlayoutIterGetClusterExtents :: LayoutIter -> IO (Rectangle, Rectangle)\nlayoutIterGetClusterExtents li = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_iter_get_cluster_extents#} li (castPtr logPtr)\n (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n-- @method layoutIterGetRunExtents@ Compute the physical size of the run.\n--\n-- * Computes the logical and the ink size of the run pointed to by\n-- @ref data LayoutIter@.\n--\n-- * All values are in layoutIter units. To get to device units (pixel for\n-- @ref data Drawable@s) divide by @ref constant pangoScale@.\n--\nlayoutIterGetRunExtents :: LayoutIter -> IO (Rectangle, Rectangle)\nlayoutIterGetRunExtents li = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_iter_get_run_extents#} li (castPtr logPtr)\n (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n-- @method layoutIterGetLineYRange@ Retrieve vertical extent of this\n-- line.\n--\n-- * Divides the vertical space in the @ref data PangoLayout@ being\n-- iterated over between the lines in the layout, and returns the\n-- space belonging to the current line. A line's range includes the\n-- line's logical extents, plus half of the spacing above and below\n-- the line, if @ref method pangoLayoutSetSpacing@ has been called\n-- to set layout spacing. The y positions are in layout coordinates\n-- (origin at top left of the entire layout).\n--\n-- * The first element in the returned tuple is the start, the second is\n-- the end of this line.\n--\nlayoutIterGetLineYRange :: LayoutIter -> IO (Int,Int)\nlayoutIterGetLineYRange li = alloca $ \\sPtr -> alloca $ \\ePtr -> do\n {#call unsafe layout_iter_get_line_extents#} li (castPtr sPtr) (castPtr ePtr)\n start <- peek sPtr\n end <- peek ePtr\n return (start,end)\n\n-- @method layoutIterGetLineExtents@ Compute the physical size of the line.\n--\n-- * Computes the logical and the ink size of the line pointed to by\n-- @ref data LayoutIter@.\n--\n-- * Extents are in layout coordinates (origin is the top-left corner\n-- of the entire @ref data PangoLayout@). Thus the extents returned\n-- by this function will be the same width\/height but not at the\n-- same x\/y as the extents returned from @ref method\n-- pangoLayoutLineGetExtents@.\n--\nlayoutIterGetLineExtents :: LayoutIter -> IO (Rectangle, Rectangle)\nlayoutIterGetLineExtents li = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_iter_get_line_extents#} li (castPtr logPtr)\n (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n\n-- @method layoutLineGetExtents@ Compute the physical size of the line.\n--\n-- * Computes the logical and the ink size of the @ref data LayoutLine@. The\n-- logical layout is used for positioning, the ink size is the smallest\n-- bounding box that includes all character pixels. The ink size can be\n-- smaller or larger that the logical layout.\n--\n-- * All values are in layout units. To get to device units (pixel for\n-- @ref data Drawable@s) divide by @ref constant pangoScale@.\n--\nlayoutLineGetExtents :: LayoutLine -> IO (Rectangle, Rectangle)\nlayoutLineGetExtents pl = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_line_get_extents#} pl (castPtr logPtr) (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n-- @method layoutLineGetPixelExtents@ Compute the physical size of the line.\n--\n-- * Computes the logical and the ink size of the @ref data LayoutLine@. The\n-- logical layout is used for positioning, the ink size is the smallest\n-- bounding box that includes all character pixels. The ink size can be\n-- smaller or larger that the logical layout.\n--\n-- * All values are in device units. This function is a wrapper around\n-- @ref method layoutLineGetExtents@ with scaling.\n--\nlayoutLineGetPixelExtents :: LayoutLine -> IO (Rectangle, Rectangle)\nlayoutLineGetPixelExtents pl = alloca $ \\logPtr -> alloca $ \\inkPtr -> do\n {#call unsafe layout_line_get_pixel_extents#} pl\n (castPtr logPtr) (castPtr inkPtr)\n log <- peek logPtr\n ink <- peek inkPtr\n return (log,ink)\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"3f967345eb87802260b1946a4abddcc263751c0f","subject":"gstreamer: M.S.G.Core.Clock: a few small doc fixes","message":"gstreamer: M.S.G.Core.Clock: a few small doc fixes\n\ndarcs-hash:20080212041232-21862-1ae5bebcbec3f9447a729bf4d3ec034bd305789c.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Clock.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Clock.chs","new_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gstreamer -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GStreamer, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GStreamer documentation.\n-- \n-- |\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\n-- \n-- Abstract class of global clocks.\nmodule Media.Streaming.GStreamer.Core.Clock (\n \n-- * Detail\n -- | GStreamer uses a global clock to synchronize the plugins in a\n -- pipeline. Different clock implementations are possible by\n -- implementing this abstract base class.\n -- \n -- The 'Clock' returns a monotonically increasing time with the\n -- method 'clockGetTime'. Its accuracy and base time depend\n -- on the specific clock implementation but time is always\n -- expressed in nanoseconds. Since the baseline of the clock is\n -- undefined, the clock time returned is not meaningful in itself,\n -- what matters are the deltas between two clock times. The time\n -- returned by a clock is called the absolute time.\n -- \n -- The pipeline uses the clock to calculate the stream\n -- time. Usually all renderers synchronize to the global clock\n -- using the buffer timestamps, the newsegment events and the\n -- element's base time, see GstPipeline.\n -- \n -- A clock implementation can support periodic and single shot\n -- clock notifications both synchronous and asynchronous.\n -- \n -- One first needs to create a 'ClockID' for the periodic or\n -- single shot notification using 'clockNewSingleShotID' or\n -- 'clockNewPeriodicID'.\n -- \n -- To perform a blocking wait for the specific time of the\n -- 'ClockID' use 'clockIDWait'. This calls can be interrupted with\n -- the 'clockIDUnschedule' call. If the blocking wait is\n -- unscheduled a return value of 'ClockUnscheduled' is returned.\n -- \n -- Periodic callbacks scheduled async will be repeadedly called\n -- automatically until it is unscheduled. To schedule a sync\n -- periodic callback, 'clockIDWait' should be called repeatedly.\n -- \n -- The async callbacks can happen from any thread, either provided\n -- by the core or from a streaming thread. The application should\n -- be prepared for this.\n -- \n -- A 'ClockID' that has been unscheduled cannot be used again for\n -- any wait operation; a new 'ClockID' should be created.\n -- \n -- It is possible to perform a blocking wait on the same 'ClockID'\n -- from multiple threads. However, registering the same 'ClockID'\n -- for multiple async notifications is not possible, the callback\n -- will only be called for the thread registering the entry last.\n -- \n -- These clock operations do not operate on the stream time, so\n -- the callbacks will also occur when not in the playing state as\n -- if the clock just keeps on running. Some clocks however do not\n -- progress when the element that provided the clock is not\n -- playing.\n -- \n -- When a clock has the 'ClockFlagCanSetMaster' flag set, it can\n -- be slaved to another 'Clock' with 'clockSetMaster'. The clock\n -- will then automatically be synchronized to this master clock by\n -- repeatedly sampling the master clock and the slave clock and\n -- recalibrating the slave clock with 'clockSetCalibration'. This\n -- feature is mostly useful for plugins that have an internal\n -- clock but must operate with another clock selected by the\n -- GstPipeline. They can track the offset and rate difference of\n -- their internal clock relative to the master clock by using the\n -- 'clockGetCalibration' function.\n -- \n -- The master\\\/slave synchronisation can be tuned with the\n -- the 'clockTimeout', 'clockWindowSize' and 'clockWindowThreshold' properties.\n -- The 'clockTimeout' property defines the interval to\n -- sample the master clock and run the calibration\n -- functions. 'clockWindowSize' defines the number of samples to\n -- use when calibrating and 'clockWindowThreshold' defines the\n -- minimum number of samples before the calibration is performed.\n\n-- * Types\n Clock,\n ClockClass,\n castToClock,\n toClock,\n \n -- | A time value measured in nanoseconds.\n ClockTime,\n \n -- | The 'ClockTime' value representing an invalid time.\n clockTimeNone,\n clockTimeIsValid,\n \n -- | The 'ClockTime' value representing 1 second, i.e. 1e9.\n second,\n -- | The 'ClockTime' value representing 1 millisecond, i.e. 1e6.\n msecond,\n -- | The 'ClockTime' value representing 1 microsecond, i.e. 1e3.\n usecond,\n -- | The 'ClockTime' value representing 1 nanosecond, i.e. 1.\n nsecond,\n -- | A value holding the difference between two 'ClockTime's.\n ClockTimeDiff,\n -- | An opaque identifier for a timer event.\n ClockID,\n -- | An enumeration type returned by 'clockIDWait'.\n ClockReturn(..),\n -- | The flags a 'Clock' may have.\n ClockFlags(..),\n clockGetFlags,\n clockSetFlags,\n clockUnsetFlags,\n\n-- * Clock Operations \n clockAddObservation,\n clockSetMaster,\n clockGetMaster,\n clockSetResolution,\n clockGetResolution,\n clockGetTime,\n clockNewSingleShotID,\n clockNewPeriodicID,\n clockGetInternalTime,\n clockGetCalibration,\n clockSetCalibration,\n clockIDGetTime,\n clockIDWait,\n clockIDUnschedule,\n \n-- * Clock Properties\n clockTimeout,\n clockWindowSize,\n clockWindowThreshold\n \n ) where\n\nimport Data.Ratio ( Ratio\n , (%)\n , numerator\n , denominator )\nimport Control.Monad ( liftM\n , liftM4)\n{#import Media.Streaming.GStreamer.Core.Types#}\nimport System.Glib.FFI\nimport System.Glib.Attributes ( Attr\n , newAttr )\nimport System.Glib.Properties\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\n-- | Get the flags set on the clock.\nclockGetFlags :: ClockClass clockT\n => clockT -- ^ @clock@\n -> IO [ClockFlags] -- ^ the flags currently set on the clock\nclockGetFlags = mkObjectGetFlags\n\n-- | Set the given flags on the clock.\nclockSetFlags :: ClockClass clockT\n => clockT -- ^ @clock@\n -> [ClockFlags] -- ^ @flags@ - the flags to be set\n -> IO ()\nclockSetFlags = mkObjectSetFlags\n\n-- | Unset the given flags on the clock.\nclockUnsetFlags :: ClockClass clockT\n => clockT -- ^ @clock@\n -> [ClockFlags] -- ^ @flags@ - the flags to be unset\n -> IO ()\nclockUnsetFlags = mkObjectUnsetFlags\n\n-- | Returns 'True' if the given 'ClockTime' is valid, and 'False'\n-- otherwise.\nclockTimeIsValid :: ClockTime -- ^ @clockTime@\n -> Bool -- ^ 'True' if @clockTime@ is valid, 'False' otherwise\nclockTimeIsValid = (\/= clockTimeNone)\n\n-- | The time master of the master clock and the time slave of the\n-- slave clock are added to the list of observations. If enough\n-- observations are available, a linear regression algorithm is run\n-- on the observations and clock is recalibrated.\n-- \n-- If a calibration is performed, the correlation coefficient of the\n-- interpolation will be returned. A value of 1.0 means the clocks\n-- are in perfect sync. This value can be used to control the\n-- sampling frequency of the master and slave clocks.\nclockAddObservation :: ClockClass clock\n => clock\n -> ClockTime\n -> ClockTime\n -> IO (Maybe Double)\nclockAddObservation clock slave master =\n alloca $ \\rSquaredPtr ->\n do success <- {# call clock_add_observation #} (toClock clock)\n (fromIntegral slave)\n (fromIntegral master)\n rSquaredPtr\n if toBool success\n then liftM (Just . realToFrac) $ peek rSquaredPtr\n else return Nothing\n\n-- | Set @master@ as the master clock for @clock@. The @clock@ will\n-- automatically be calibrated so that 'clockGetTime' reports the\n-- same time as the @master@ clock.\n-- \n-- A clock provider that slaves its clock to a master can get the\n-- current calibration values with 'clockGetCalibration'.\n-- \n-- The @master@ clock can be 'Nothing' in which case @clock@ will\n-- not be slaved any longer. It will, however, continue to report\n-- its time adjusted using the last configured rate and time\n-- offsets.\n-- \n-- Note that if @clock@ does not have the 'ClockFlagCanSetMaster'\n-- flag set, this function will not succeed and return 'False'.\nclockSetMaster :: (ClockClass clock, ClockClass master)\n => clock -- ^ @clock@\n -> Maybe master -- ^ @master@\n -> IO Bool -- ^ 'True' if @clock@ is capable of\n -- being slaved to the @master@ clock, otherwise 'False'\nclockSetMaster clock master =\n withObject (toClock clock) $ \\clockPtr ->\n maybeWith withObject (liftM toClock $ master) $ \\masterPtr ->\n liftM toBool $ gst_clock_set_master clockPtr masterPtr\n where\n _ = {# call clock_set_master #}\n\n-- | Return the master that @clock@ is slaved to, or 'Nothing' if\n-- @clock@ is not slaved.\nclockGetMaster :: ClockClass clock\n => clock -- ^ @clock@\n -> IO (Maybe Clock) -- ^ the master that @clock@ is slaved to, or 'Nothing'\nclockGetMaster clock =\n {# call clock_get_master #} (toClock clock) >>= maybePeek takeObject\n\n-- | Set the resolution of @clock@. Some clocks have the possibility\n-- to operate with different resolution at the expense of more\n-- resource usage. There is normally no need to change the default\n-- resolution of a clock. The resolution of a clock can only be\n-- changed if the clock has the 'ClockFlagCanSetResolution' flag\n-- set.\nclockSetResolution :: ClockClass clock\n => clock\n -> ClockTime\n -> IO ClockTime\nclockSetResolution clock resolution =\n liftM fromIntegral $\n {# call clock_set_resolution #} (toClock clock)\n (fromIntegral resolution)\n\n-- | Get the resolution of the @clock@. The resolution of the clock is\n-- the granularity of the values returned by 'clockGetTime'.\nclockGetResolution :: ClockClass clock\n => clock -- ^ @clock@\n -> IO ClockTime -- ^ the resolution currently set in @clock@\nclockGetResolution clock =\n liftM fromIntegral $\n {# call clock_get_resolution #} (toClock clock)\n\n-- | Gets the current time of @clock@. The time is always\n-- monotonically increasing and adjusted according to the current\n-- offset and rate.\nclockGetTime :: ClockClass clock\n => clock -- ^ @clock@\n -> IO ClockTime -- ^ the current time in @clock@\nclockGetTime clock =\n liftM fromIntegral $\n {# call clock_get_time #} (toClock clock)\n\n-- | Get a 'ClockID' from @clock@ to trigger a single shot\n-- notification at the requested time.\nclockNewSingleShotID :: ClockClass clock\n => clock -- ^ @clock@\n -> ClockTime -- ^ @clockTime@\n -> IO ClockID -- ^ a single shot notification id triggered at @clockTime@\nclockNewSingleShotID clock time =\n {# call clock_new_single_shot_id #} (toClock clock)\n (fromIntegral time) >>=\n takeClockID . castPtr\n\n-- | Get a 'ClockID' from @clock@ to trigger periodic\n-- notifications. The notifications will start at time @startTime@\n-- and then be fired at each @interval@ after.\nclockNewPeriodicID :: ClockClass clock\n => clock -- ^ @clock@\n -> ClockTime -- ^ @startTime@\n -> ClockTime -- ^ @interval@\n -> IO ClockID -- ^ a periodic notification id\nclockNewPeriodicID clock startTime interval =\n {# call clock_new_periodic_id #} (toClock clock)\n (fromIntegral startTime)\n (fromIntegral interval) >>=\n takeClockID . castPtr\n\n-- | Gets the current internal time of @clock@. The time is\n-- returned unadjusted in the offset and rate.\nclockGetInternalTime :: ClockClass clock\n => clock -- ^ @clock@\n -> IO ClockTime -- ^ the clock's internal time value\nclockGetInternalTime clock =\n liftM fromIntegral $\n {# call clock_get_internal_time #} (toClock clock)\n\n-- | Gets the internal rate and reference time of @clock@. See\n-- 'clockSetCalibration' for more information.\nclockGetCalibration :: ClockClass clock\n => clock -- ^ @clock@\n -> IO (ClockTime, ClockTime, Ratio ClockTime)\n -- ^ the clock's internal time, external (adjusted) time, and skew rate\nclockGetCalibration clock =\n alloca $ \\internalPtr ->\n alloca $ \\externalPtr ->\n alloca $ \\rateNumPtr ->\n alloca $ \\rateDenomPtr ->\n do {# call clock_get_calibration #} (toClock clock)\n internalPtr\n externalPtr\n rateNumPtr\n rateDenomPtr\n liftM4 (\\a b c d ->\n (fromIntegral a,\n fromIntegral b,\n fromIntegral c % fromIntegral d))\n (peek internalPtr)\n (peek externalPtr)\n (peek rateNumPtr)\n (peek rateDenomPtr)\n\n-- | Adjusts the rate and time of clock. A rate of @1 % 1@ is the\n-- normal speed of the clock. Larger values make the clock go\n-- faster.\n-- \n-- The parameters @internal@ and @external@ specifying that\n-- 'clockGetTime' should have returned @external@ when the clock had\n-- internal time @internal@. The parameter @internal@ should not be\n-- in the future; that is, it should be less than the value returned\n-- by 'clockGetInternalTime' when this function is called.\n-- \n-- Subsequent calls to 'clockGetTime' will return clock times\n-- computed as follows:\n-- \n-- > (clock_internal - internal) * rate + external\n-- \n-- Note that 'clockGetTime' always returns increasing values, so if\n-- the clock is moved backwards, 'clockGetTime' will report the\n-- previous value until the clock catches up.\nclockSetCalibration :: ClockClass clock\n => clock -- ^ @clock@\n -> ClockTime -- ^ @internal@\n -> ClockTime -- ^ @external@\n -> Ratio ClockTime -- ^ @rate@\n -> IO ()\nclockSetCalibration clock internal external rate =\n {# call clock_set_calibration #} (toClock clock)\n (fromIntegral internal)\n (fromIntegral external)\n (fromIntegral $ numerator rate)\n (fromIntegral $ denominator rate)\n\n-- | Get the time of @clockID@.\nclockIDGetTime :: ClockID -- ^ @clockID@\n -> IO ClockTime\nclockIDGetTime clockID =\n liftM fromIntegral $ withClockID clockID $\n {# call clock_id_get_time #} . castPtr\n\n-- | Perform a blocking wait on @clockID@. The parameter @clockID@\n-- should have been created with 'clockNewSingleShotID' or\n-- 'clockNewPeriodicID', and should not been unscheduled with a call\n-- to 'clockIDUnschedule'.\n-- \n-- If second value in the returned pair is not 'Nothing', it will\n-- contain the difference against the clock and the time of\n-- @clockID@ when this method was called. Positive values indicate\n-- how late @clockID@ was relative to the clock. Negative values\n-- indicate how much time was spend waiting on the clock before the\n-- function returned.\nclockIDWait :: ClockID -- ^ @clockID@\n -> IO (ClockReturn, Maybe ClockTimeDiff)\nclockIDWait clockID =\n alloca $ \\jitterPtr ->\n do result <- liftM cToEnum $ withClockID clockID $ \\clockIDPtr ->\n {# call clock_id_wait #} (castPtr clockIDPtr) jitterPtr\n jitter <- let peekJitter = liftM (Just . fromIntegral) $ peek jitterPtr\n in case result of\n ClockOk -> peekJitter\n ClockEarly -> peekJitter\n _ -> return Nothing\n return (result, jitter)\n\n-- | Cancel an outstanding request with @clockID@. After this call,\n-- @clockID@ cannot be used anymore to recieve notifications; you\n-- must create a new 'ClockID'.\nclockIDUnschedule :: ClockID -- ^ @clockID@\n -> IO ()\nclockIDUnschedule clockID =\n withClockID clockID $ {# call clock_id_unschedule #} . castPtr\n\nclockTimeout :: ClockClass clockT\n => Attr clockT ClockTime\nclockTimeout = newAttr\n (objectGetPropertyUInt64 \"timeout\")\n (objectSetPropertyUInt64 \"timeout\")\n\nclockWindowSize :: ClockClass clockT\n => Attr clockT Int\nclockWindowSize =\n newAttrFromIntProperty \"window-size\"\n\nclockWindowThreshold :: ClockClass clockT\n => Attr clockT Int\nclockWindowThreshold =\n newAttrFromIntProperty \"window-threshold\"\n","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gstreamer -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GStreamer, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GStreamer documentation.\n-- \n-- |\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\n-- \n-- Abstract class of global clocks.\nmodule Media.Streaming.GStreamer.Core.Clock (\n \n-- * Detail\n -- | GStreamer uses a global clock to synchronize the plugins in a\n -- pipeline. Different clock implementations are possible by\n -- implementing this abstract base class.\n -- \n -- The 'Clock' returns a monotonically increasing time with the\n -- method 'clockGetTime'. Its accuracy and base time depend\n -- on the specific clock implementation but time is always\n -- expressed in nanoseconds. Since the baseline of the clock is\n -- undefined, the clock time returned is not meaningful in itself,\n -- what matters are the deltas between two clock times. The time\n -- returned by a clock is called the absolute time.\n -- \n -- The pipeline uses the clock to calculate the stream\n -- time. Usually all renderers synchronize to the global clock\n -- using the buffer timestamps, the newsegment events and the\n -- element's base time, see GstPipeline.\n -- \n -- A clock implementation can support periodic and single shot\n -- clock notifications both synchronous and asynchronous.\n -- \n -- One first needs to create a 'ClockID' for the periodic or\n -- single shot notification using 'clockNewSingleShotID' or\n -- 'clockNewPeriodicID'.\n -- \n -- To perform a blocking wait for the specific time of the\n -- 'ClockID' use 'clockIDWait'. This calls can be interrupted with\n -- the 'clockIDUnschedule' call. If the blocking wait is\n -- unscheduled a return value of 'ClockUnscheduled' is returned.\n -- \n -- Periodic callbacks scheduled async will be repeadedly called\n -- automatically until it is unscheduled. To schedule a sync\n -- periodic callback, 'clockIDWait' should be called repeatedly.\n -- \n -- The async callbacks can happen from any thread, either provided\n -- by the core or from a streaming thread. The application should\n -- be prepared for this.\n -- \n -- A 'ClockID' that has been unscheduled cannot be used again for\n -- any wait operation; a new 'ClockID' should be created.\n -- \n -- It is possible to perform a blocking wait on the same 'ClockID'\n -- from multiple threads. However, registering the same 'ClockID'\n -- for multiple async notifications is not possible, the callback\n -- will only be called for the thread registering the entry last.\n -- \n -- These clock operations do not operate on the stream time, so\n -- the callbacks will also occur when not in the playing state as\n -- if the clock just keeps on running. Some clocks however do not\n -- progress when the element that provided the clock is not\n -- playing.\n -- \n -- When a clock has the 'ClockFlagCanSetMaster' flag set, it can\n -- be slaved to another 'Clock' with 'clockSetMaster'. The clock\n -- will then automatically be synchronized to this master clock by\n -- repeatedly sampling the master clock and the slave clock and\n -- recalibrating the slave clock with 'clockSetCalibration'. This\n -- feature is mostly useful for plugins that have an internal\n -- clock but must operate with another clock selected by the\n -- GstPipeline. They can track the offset and rate difference of\n -- their internal clock relative to the master clock by using the\n -- 'clockGetCalibration' function.\n -- \n -- The master\\\/slave synchronisation can be tuned with the\n -- the 'clockTimeout', 'clockWindowSize' and 'clockWindowThreshold' properties.\n -- The 'clockTimeout' property defines the interval to\n -- sample the master clock and run the calibration\n -- functions. 'clockWindowSize' defines the number of samples to\n -- use when calibrating and 'clockWindowThreshold' defines the\n -- minimum number of samples before the calibration is performed.\n\n-- * Types\n Clock,\n ClockClass,\n castToClock,\n toClock,\n \n -- | A time value measured in nanoseconds.\n ClockTime,\n \n -- | The 'ClockTime' value representing an invalid time.\n clockTimeNone,\n clockTimeIsValid,\n \n -- | The 'ClockTime' value representing 1 second, i.e. 1e9.\n second,\n -- | The 'ClockTime' value representing 1 millisecond, i.e. 1e6.\n msecond,\n -- | The 'ClockTime' value representing 1 microsecond, i.e. 1e3.\n usecond,\n -- | The 'ClockTime' value representing 1 nanosecond, i.e. 1.\n nsecond,\n -- | A value holding the difference between two 'ClockTime's.\n ClockTimeDiff,\n -- | An opaque identifier for a timer event.\n ClockID,\n -- | An enumeration type returned by 'clockIDWait'.\n ClockReturn(..),\n -- | The flags a 'Clock' may have.\n ClockFlags(..),\n clockGetFlags,\n clockSetFlags,\n clockUnsetFlags,\n\n-- * Clock Operations \n clockAddObservation,\n clockSetMaster,\n clockGetMaster,\n clockSetResolution,\n clockGetResolution,\n clockGetTime,\n clockNewSingleShotID,\n clockNewPeriodicID,\n clockGetInternalTime,\n clockGetCalibration,\n clockSetCalibration,\n clockIDGetTime,\n clockIDWait,\n clockIDUnschedule,\n \n-- * Clock Properties\n clockTimeout,\n clockWindowSize,\n clockWindowThreshold\n \n ) where\n\nimport Data.Ratio ( Ratio\n , (%)\n , numerator\n , denominator )\nimport Control.Monad ( liftM\n , liftM4)\n{#import Media.Streaming.GStreamer.Core.Types#}\nimport System.Glib.FFI\nimport System.Glib.Attributes ( Attr\n , newAttr )\nimport System.Glib.Properties\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\n-- | Gets the flags set on the clock.\nclockGetFlags :: ClockClass clockT\n => clockT -- ^ @clock@\n -> IO [ClockFlags] -- ^ the flags currently set on the clock\nclockGetFlags = mkObjectGetFlags\n\n-- | Sets the given flags on the clock.\nclockSetFlags :: ClockClass clockT\n => clockT -- ^ @clock@\n -> [ClockFlags] -- ^ @flags@ - the flags to be set\n -> IO ()\nclockSetFlags = mkObjectSetFlags\n\n-- | Unsets the given flags on the clock.\nclockUnsetFlags :: ClockClass clockT\n => clockT -- ^ @clock@\n -> [ClockFlags] -- ^ @flags@ - the flags to be unset\n -> IO ()\nclockUnsetFlags = mkObjectUnsetFlags\n\n-- | Returns 'True' if the given 'ClockTime' is valid, and 'False'\n-- otherwise.\nclockTimeIsValid :: ClockTime -- ^ @clockTime@\n -> Bool -- ^ 'True' if @clockTime@ is valid, 'False' otherwise\nclockTimeIsValid = (\/= clockTimeNone)\n\n-- | The time master of the master clock and the time slave of the\n-- slave clock are added to the list of observations. If enough\n-- observations are available, a linear regression algorithm is run\n-- on the observations and clock is recalibrated.\n-- \n-- If a calibration is performed, the correlation coefficient of the\n-- interpolation will be returned. A value of 1.0 means the clocks\n-- are in perfect sync. This value can be used to control the\n-- sampling frequency of the master and slave clocks.\nclockAddObservation :: ClockClass clock\n => clock\n -> ClockTime\n -> ClockTime\n -> IO (Maybe Double)\nclockAddObservation clock slave master =\n alloca $ \\rSquaredPtr ->\n do success <- {# call clock_add_observation #} (toClock clock)\n (fromIntegral slave)\n (fromIntegral master)\n rSquaredPtr\n if toBool success\n then liftM (Just . realToFrac) $ peek rSquaredPtr\n else return Nothing\n\n-- | Set @master@ as the master clock for @clock@. The @clock@ will\n-- automatically be calibrated so that 'clockGetTime' reports the\n-- same time as the @master@ clock.\n-- \n-- A clock provider that slaves its clock to a master can get the\n-- current calibration values with 'clockGetCalibration'.\n-- \n-- The @master@ clock can be 'Nothing' in which case @clock@ will\n-- not be slaved any longer. It will, however, continue to report\n-- its time adjusted using the last configured rate and time\n-- offsets.\n-- \n-- Note that if @clock@ does not have the 'ClockFlagCanSetMaster'\n-- flag set, this function will not succeed and return 'False'.\nclockSetMaster :: (ClockClass clock, ClockClass master)\n => clock -- ^ @clock@\n -> Maybe master -- ^ @master@\n -> IO Bool -- ^ 'True' if @clock@ is capable of\n -- being slaved to the @master@ clock, otherwise 'False'\nclockSetMaster clock master =\n withObject (toClock clock) $ \\clockPtr ->\n maybeWith withObject (liftM toClock $ master) $ \\masterPtr ->\n liftM toBool $ gst_clock_set_master clockPtr masterPtr\n where\n _ = {# call clock_set_master #}\n\n-- | Return the master that @clock@ is slaved to, or 'Nothing' if\n-- @clock@ is not slaved.\nclockGetMaster :: ClockClass clock\n => clock -- ^ @clock@\n -> IO (Maybe Clock) -- ^ the master that @clock@ is slaved to, or 'Nothing'\nclockGetMaster clock =\n {# call clock_get_master #} (toClock clock) >>= maybePeek takeObject\n\n-- | Set the resolution of @clock@. Some clocks have the possibility\n-- to operate with different resolution at the expense of more\n-- resource usage. There is normally no need to change the default\n-- resolution of a clock. The resolution of a clock can only be\n-- changed if the clock has the 'ClockFlagCanSetResolution' flag\n-- set.\nclockSetResolution :: ClockClass clock\n => clock\n -> ClockTime\n -> IO ClockTime\nclockSetResolution clock resolution =\n liftM fromIntegral $\n {# call clock_set_resolution #} (toClock clock)\n (fromIntegral resolution)\n\n-- | Get the resolution of the @clock@. The resolution of the clock is\n-- the granularity of the values returned by 'clockGetTime'.\nclockGetResolution :: ClockClass clock\n => clock -- ^ @clock@\n -> IO ClockTime -- ^ the resolution currently set in @clock@\nclockGetResolution clock =\n liftM fromIntegral $\n {# call clock_get_resolution #} (toClock clock)\n\n-- | Gets the current time of @clock@. The time is always\n-- monotonically increasing and adjusted according to the current\n-- offset and rate.\nclockGetTime :: ClockClass clock\n => clock -- ^ @clock@\n -> IO ClockTime -- ^ the current time in @clock@\nclockGetTime clock =\n liftM fromIntegral $\n {# call clock_get_time #} (toClock clock)\n\n-- | Get a 'ClockID' from @clock@ to trigger a single shot\n-- notification at the requested time.\nclockNewSingleShotID :: ClockClass clock\n => clock -- ^ @clock@\n -> ClockTime -- ^ @clockTime@\n -> IO ClockID -- ^ a single shot notification id triggered at @clockTime@\nclockNewSingleShotID clock time =\n {# call clock_new_single_shot_id #} (toClock clock)\n (fromIntegral time) >>=\n takeClockID . castPtr\n\n-- | Get a 'ClockID' from @clock@ to trigger periodic\n-- notifications. The notifications will start at time @startTime@\n-- and then be fired at each @interval@ after.\nclockNewPeriodicID :: ClockClass clock\n => clock -- ^ @clock@\n -> ClockTime -- ^ @startTime@\n -> ClockTime -- ^ @interval@\n -> IO ClockID -- ^ a periodic notification id\nclockNewPeriodicID clock startTime interval =\n {# call clock_new_periodic_id #} (toClock clock)\n (fromIntegral startTime)\n (fromIntegral interval) >>=\n takeClockID . castPtr\n\n-- | Gets the current internal time of @clock@. The time is\n-- returned unadjusted in the offset and rate.\nclockGetInternalTime :: ClockClass clock\n => clock -- ^ @clock@\n -> IO ClockTime -- ^ the clock's internal time value\nclockGetInternalTime clock =\n liftM fromIntegral $\n {# call clock_get_internal_time #} (toClock clock)\n\n-- | Gets the internal rate and reference time of @clock@. See\n-- 'clockSetCalibration' for more information.\nclockGetCalibration :: ClockClass clock\n => clock -- ^ @clock@\n -> IO (ClockTime, ClockTime, Ratio ClockTime)\n -- ^ the clock's internal time, external (adjusted) time, and skew rate\nclockGetCalibration clock =\n alloca $ \\internalPtr ->\n alloca $ \\externalPtr ->\n alloca $ \\rateNumPtr ->\n alloca $ \\rateDenomPtr ->\n do {# call clock_get_calibration #} (toClock clock)\n internalPtr\n externalPtr\n rateNumPtr\n rateDenomPtr\n liftM4 (\\a b c d ->\n (fromIntegral a,\n fromIntegral b,\n fromIntegral c % fromIntegral d))\n (peek internalPtr)\n (peek externalPtr)\n (peek rateNumPtr)\n (peek rateDenomPtr)\n\n-- | Adjusts the rate and time of clock. A rate of @1 % 1@ is the\n-- normal speed of the clock. Larger values make the clock go\n-- faster.\n-- \n-- The parameters @internal@ and @external@ specifying that\n-- 'clockGetTime' should have returned @external@ when the clock had\n-- internal time @internal@. The parameter @internal@ should not be\n-- in the future; that is, it should be less than the value returned\n-- by 'clockGetInternalTime' when this function is called.\n-- \n-- Subsequent calls to 'clockGetTime' will return clock times\n-- computed as follows:\n-- \n-- > (clock_internal - internal) * rate + external\n-- \n-- Note that 'clockGetTime' always returns increasing values, so if\n-- the clock is moved backwards, 'clockGetTime' will report the\n-- previous value until the clock catches up.\nclockSetCalibration :: ClockClass clock\n => clock -- ^ @clock@\n -> ClockTime -- ^ @internal@\n -> ClockTime -- ^ @external@\n -> Ratio ClockTime -- ^ @rate@\n -> IO ()\nclockSetCalibration clock internal external rate =\n {# call clock_set_calibration #} (toClock clock)\n (fromIntegral internal)\n (fromIntegral external)\n (fromIntegral $ numerator rate)\n (fromIntegral $ denominator rate)\n\n-- | Get the time of @clockID@.\nclockIDGetTime :: ClockID -- ^ @clockID@\n -> IO ClockTime\nclockIDGetTime clockID =\n liftM fromIntegral $ withClockID clockID $\n {# call clock_id_get_time #} . castPtr\n\n-- | Perform a blocking wait on @clockID@. The parameter @clockID@\n-- should have been created with 'clockNewSingleShotID' or\n-- 'clockNewPeriodicID', and should not been unscheduled with a call\n-- to 'clockIDUnschedule'.\n-- \n-- If second value in the returned pair is not 'Nothing', it will\n-- contain the difference against the clock and the time of\n-- @clockID@ when this method was called. Positive values indicate\n-- how late @clockID@ was relative to the clock. Negative values\n-- indicate how much time was spend waiting on the clock before the\n-- function returned.\nclockIDWait :: ClockID -- ^ @clockID@\n -> IO (ClockReturn, Maybe ClockTimeDiff)\nclockIDWait clockID =\n alloca $ \\jitterPtr ->\n do result <- liftM cToEnum $ withClockID clockID $ \\clockIDPtr ->\n {# call clock_id_wait #} (castPtr clockIDPtr) jitterPtr\n jitter <- let peekJitter = liftM (Just . fromIntegral) $ peek jitterPtr\n in case result of\n ClockOk -> peekJitter\n ClockEarly -> peekJitter\n _ -> return Nothing\n return (result, jitter)\n\n-- | Cancel an outstanding request with @clockID@. After this call,\n-- @clockID@ cannot be used anymore to recieve notifications; you\n-- must create a new 'ClockID'.\nclockIDUnschedule :: ClockID -- ^ @clockID@\n -> IO ()\nclockIDUnschedule clockID =\n withClockID clockID $ {# call clock_id_unschedule #} . castPtr\n\nclockTimeout :: ClockClass clockT\n => Attr clockT ClockTime\nclockTimeout = newAttr\n (objectGetPropertyUInt64 \"timeout\")\n (objectSetPropertyUInt64 \"timeout\")\n\nclockWindowSize :: ClockClass clockT\n => Attr clockT Int\nclockWindowSize =\n newAttrFromIntProperty \"window-size\"\n\nclockWindowThreshold :: ClockClass clockT\n => Attr clockT Int\nclockWindowThreshold =\n newAttrFromIntProperty \"window-threshold\"\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"f4876f2b46f80c5a9ff4376053158579ca84d438","subject":"Reorder Call.chs","message":"Reorder Call.chs\n","repos":"grpc\/grpc-haskell","old_file":"src\/Network\/Grpc\/Core\/Call.chs","new_file":"src\/Network\/Grpc\/Core\/Call.chs","new_contents":"-- Copyright (c) 2016, Google Inc.\n-- All rights reserved.\n--\n-- Redistribution and use in source and binary forms, with or without\n-- modification, are permitted provided that the following conditions are met:\n-- * Redistributions of source code must retain the above copyright\n-- notice, this list of conditions and the following disclaimer.\n-- * Redistributions in binary form must reproduce the above copyright\n-- notice, this list of conditions and the following disclaimer in the\n-- documentation and\/or other materials provided with the distribution.\n-- * Neither the name of Google Inc. nor the\n-- names of its contributors may be used to endorse or promote products\n-- derived from this software without specific prior written permission.\n--\n-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n-- DISCLAIMED. IN NO EVENT SHALL Google Inc. BE LIABLE FOR ANY\n-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n--\n--------------------------------------------------------------------------------\n{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, ExistentialQuantification, RecordWildCards #-}\nmodule Network.Grpc.Core.Call where\n\n\nimport Control.Concurrent\nimport Control.Exception\nimport Control.Monad\n\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Lazy as L\nimport Data.IORef\n\nimport Foreign.C.Types as C\nimport qualified Foreign.ForeignPtr as C\nimport qualified Foreign.Marshal.Alloc as C\nimport qualified Foreign.Marshal.Utils as C\nimport qualified Foreign.Ptr as C\nimport Foreign.Ptr (Ptr)\nimport qualified Foreign.Storable as C\n\n-- transformers\nimport Control.Monad.IO.Class\nimport Control.Monad.Trans.Class\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Reader\n\nimport qualified Network.Grpc.CompletionQueue as CQ\n{#import Network.Grpc.Lib.ByteBuffer#}\n{#import Network.Grpc.Lib.Metadata#}\n{#import Network.Grpc.Lib.TimeSpec#}\n{#import Network.Grpc.Lib.Types#}\n{#import Network.Grpc.Lib.Grpc#}\n\n\n#include \n#include \"hs_grpc.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\ntype Deadline = TimeSpec\n\ndata ClientContext = ClientContext\n { ccChannel :: Channel\n , ccCQ :: CompletionQueue\n , ccWorker :: CQ.Worker\n , ccDeadline :: Deadline\n }\n\nemptyChannelArgs :: ChannelArgs\nemptyChannelArgs = ChannelArgs C.nullPtr\n\nnewClientContext :: Channel -> IO ClientContext\nnewClientContext chan = do\n cq <- completionQueueCreate reservedPtr\n cqt <- CQ.startCompletionQueueThread cq\n return (ClientContext chan cq cqt gprInfFuture)\n\ndestroyClientContext :: ClientContext -> IO ()\ndestroyClientContext (ClientContext _ cq w _) = do\n completionQueueShutdown cq\n CQ.waitWorkerTermination w\n\nwithTimeout :: Deadline -> ClientContext -> ClientContext\nwithTimeout ts (ClientContext chan cq cqt _) = ClientContext chan cq cqt ts\n\ntype MethodName = B.ByteString\ntype Arg = B.ByteString\n\n-- | Run the IO function once, cache it in the MVar.\nonceMVar :: MVar (Maybe a) -> IO a -> IO a\nonceMVar mvar io = modifyMVar mvar $ \\x ->\n case x of\n Just x' -> return (x, x')\n Nothing -> do\n x' <- io\n return (Just x', x')\n\nreservedPtr :: Ptr ()\nreservedPtr = C.nullPtr\n\ndata UnaryResult a = UnaryResult [Metadata] [Metadata] a deriving Show\n\ncallUnary :: ClientContext -> MethodName -> Arg -> [Metadata] -> IO (RpcReply (UnaryResult L.ByteString))\ncallUnary ctx@(ClientContext chan cq _ deadline) method arg mds =\n C.withForeignPtr chan $ \\chanPtr ->\n bracket (grpcChannelCreateCall chanPtr C.nullPtr defaultPropagationMask cq method \"localhost\" deadline) grpcCallDestroy $ \\call0 -> newMVar call0 >>= \\mcall -> do\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata mds\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n recvStatusOp <- opRecvStatusOnClient crw\n recvMessageOp <- opRecvMessage\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX recvInitialMetadataOp\n , OpX recvMessageOp\n , OpX sendMessageOp\n , OpX recvStatusOp\n ]\n case res of\n RpcOk _ -> do\n (RpcStatus trailMD status statusDetails) <- opRead recvStatusOp\n case status of\n StatusOk -> do\n initMD <- opRead recvInitialMetadataOp\n answ <- opRead recvMessageOp\n let answ' = maybe L.empty id answ\n return (RpcOk (UnaryResult initMD trailMD answ'))\n _ -> return (RpcError (StatusError status statusDetails))\n RpcError err -> return (RpcError err)\n\ncallDownstream :: ClientContext -> MethodName -> Arg -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallDownstream ctx@(ClientContext chan cq _ deadline) method arg =\n C.withForeignPtr chan $ \\chanPtr -> do\n mcall <- grpcChannelCreateCall chanPtr C.nullPtr defaultPropagationMask cq method \"localhost\" deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata []\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX sendMessageOp\n ]\n case res of\n RpcOk _ -> do\n return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n\ncallUpstream :: ClientContext -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallUpstream ctx@(ClientContext chan cq _ deadline) method =\n C.withForeignPtr chan $ \\chanPtr -> do\n mcall <- grpcChannelCreateCall chanPtr C.nullPtr defaultPropagationMask cq method \"localhost\" deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata []\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> do\n return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n\ncallBidi :: ClientContext -> MethodName -> [Metadata] -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallBidi ctx@(ClientContext chan cq _ deadline) method mds = do\n C.withForeignPtr chan $ \\chanPtr -> do\n mcall <- grpcChannelCreateCall chanPtr C.nullPtr defaultPropagationMask cq method \"localhost\" deadline >>= newMVar\n\n crw <- newClientReaderWriter ctx mcall\n sendInitOp <- opSendInitialMetadata mds\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n\ndata Client req resp = Client\n { clientCrw :: ClientReaderWriter\n , clientEncoder :: Encoder req\n , clientDecoder :: Decoder resp\n }\n\ntype Decoder a = L.ByteString -> IO (RpcReply a)\ntype Encoder a = a -> IO (RpcReply B.ByteString)\n\ndefaultDecoder :: L.ByteString -> IO (RpcReply L.ByteString)\ndefaultDecoder bs = return (RpcOk bs)\n\ndefaultEncoder :: B.ByteString -> IO (RpcReply B.ByteString)\ndefaultEncoder bs = return (RpcOk bs)\n\ndata ClientReaderWriter = ClientReaderWriter {\n context :: ClientContext,\n callMVar_ :: MVar Call,\n initialMDRef :: !(IORef (Maybe [Metadata])),\n trailingMDRef :: !(IORef (Maybe [Metadata])),\n statusFromServer :: !(IORef (Maybe RpcStatus))\n}\n\nnewClientReaderWriter :: ClientContext -> MVar Call -> IO ClientReaderWriter\nnewClientReaderWriter ctx mcall = do\n initMD <- newIORef Nothing\n trailMD <- newIORef Nothing\n status <- newIORef Nothing\n return (ClientReaderWriter ctx mcall initMD trailMD status)\n\ndata OpX = forall t. OpX (OpT t)\n\ndata OpArray = OpArray { opArrPtr :: !GrpcOpPtr\n , opArrLen :: !CULong\n , opArrFree :: !(IO ())\n }\n\ntoArray :: [OpX] -> IO OpArray\ntoArray ops = do\n aptr <- C.mallocBytes (length ops * {#sizeof grpc_op#})\n let ptrs = iterate (`C.plusPtr` {#sizeof grpc_op#}) aptr\n ops' = concatMap (\\(OpX op) -> opAdd op) ops\n free = C.free aptr >> sequence_ (map (\\(OpX op) -> opFinish op) ops)\n write op p = do\n {#set grpc_op->flags#} p 0\n {#set grpc_op->reserved#} p C.nullPtr\n op p\n zipWithM_ write ops' ptrs\n return $! OpArray aptr (fromIntegral $ length ops) free\n\ncallBatch :: ClientReaderWriter -> [OpX] -> IO (RpcReply ())\ncallBatch crw ops = do\n let ctx = context crw\n CQ.withEvent (ccWorker ctx) $ \\eDesc -> do\n arr <- toArray ops\n callStatus <- withMVar (callMVar_ crw) $ \\call ->\n grpcCallStartBatch call (opArrPtr arr) (opArrLen arr) (CQ.eventTag eDesc) reservedPtr\n -- print (\"callStatus: \" ++ show callStatus)\n case callStatus of\n CallOk -> do\n e <- CQ.interruptibleWaitEvent eDesc\n -- print (\"event: \" ++ show e)\n opArrFree arr -- TODO: We leak if we're interrupted.\n case e of\n QueueOpComplete OpSuccess _ -> return (RpcOk ())\n QueueOpComplete OpError _ -> return (RpcError (Error \"callBatch: op error\"))\n QueueTimeOut -> return (RpcError DeadlineExceeded)\n QueueShutdown -> return (RpcError (Error \"queue shutdown\"))\n _ -> do\n -- print callStatus\n return (RpcError (CallErrorStatus callStatus))\n\ndata OpT out = Op\n { opAdd :: [Ptr GrpcOp -> IO ()]\n , opValue :: IORef out\n , opFinish :: IO ()\n }\n\nopRead :: OpT a -> IO a\nopRead op = readIORef (opValue op)\n\nopRecvInitialMetadata :: ClientReaderWriter -> IO (OpT [Metadata])\nopRecvInitialMetadata crw = do\n arr <- mallocMetadataArray\n value <- newIORef (error \"opRecvInitialMetadata never finished\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvInitialMetadata))\n {#set grpc_op->data.recv_initial_metadata#} p arr\n ]\n finish = do\n mds <- readMetadataArray arr\n writeIORef (initialMDRef crw) (Just mds)\n writeIORef value mds\n freeMetadataArray arr\n return (Op add value finish)\n\nopSendMessage :: B.ByteString -> IO (OpT ())\nopSendMessage bs = do\n bb <- fromByteString bs\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendMessage))\n {#set grpc_op->data.send_message#} p bb\n ]\n finish =\n byteBufferDestroy bb\n return (Op add value finish)\n\nopRecvMessage :: IO (OpT (Maybe L.ByteString))\nopRecvMessage = do\n bbptr <- C.malloc :: IO (Ptr (Ptr CByteBuffer))\n value <- newIORef Nothing\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvMessage))\n {#set grpc_op->data.recv_message#} p bbptr\n ]\n finish = do\n bb <- C.peek bbptr\n C.free bbptr\n writeIORef value =<< if bb \/= C.nullPtr\n then do\n lbs <- toLazyByteString bb\n byteBufferDestroy bb\n return (Just lbs)\n else return Nothing\n return (Op add value finish)\n\nopSendInitialMetadata :: [Metadata] -> IO (OpT ())\nopSendInitialMetadata elems = do\n (mdArrPtr, free) <- mallocMetadata elems\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendInitialMetadata))\n {#set grpc_op->data.send_initial_metadata.count#} p (fromIntegral (length elems))\n {#set grpc_op->data.send_initial_metadata.metadata#} p (C.castPtr mdArrPtr)\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.is_set#} p 0\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.level#} p 0\n ]\n finish = do\n free\n return (Op add value finish)\n\ndata RpcStatus = RpcStatus [Metadata] StatusCode B.ByteString\n deriving Show\n\nopRecvStatusOnClient :: ClientReaderWriter -> IO (OpT RpcStatus)\nopRecvStatusOnClient (ClientReaderWriter{..}) = do\n trailingMetadataArrPtr <- mallocMetadataArray\n statusCodePtr <- C.malloc :: IO (Ptr StatusCodeT)\n ptrPtrStatusStr <- C.new C.nullPtr :: IO (Ptr (Ptr CChar))\n capacityPtr <- C.new 0 :: IO (Ptr SizeT)\n value <- newIORef (error \"opRecvStatusOnClient never ran\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvStatusOnClient))\n {#set grpc_op->data.recv_status_on_client.trailing_metadata#} p trailingMetadataArrPtr\n {#set grpc_op->data.recv_status_on_client.status#} p statusCodePtr\n {#set grpc_op->data.recv_status_on_client.status_details#} p ptrPtrStatusStr\n {#set grpc_op->data.recv_status_on_client.status_details_capacity#} p capacityPtr\n ]\n finish = do\n trailingMd <- readMetadataArray trailingMetadataArrPtr\n statusCode <- fmap toStatusCode (C.peek statusCodePtr)\n statusDetails <- B.packCString =<< C.peek ptrPtrStatusStr\n let status = RpcStatus trailingMd statusCode statusDetails\n writeIORef value status\n writeIORef statusFromServer (Just status)\n free\n free = do\n freeMetadataArray trailingMetadataArrPtr\n C.free statusCodePtr\n C.free ptrPtrStatusStr\n C.free capacityPtr\n return (Op add value finish)\n\nopSendCloseFromClient :: IO (OpT ())\nopSendCloseFromClient = do\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendCloseFromClient))\n ]\n finish =\n return ()\n return (Op add value finish)\n\nclientWaitForInitialMetadata :: ClientReaderWriter -> IO (RpcReply [Metadata])\nclientWaitForInitialMetadata crw@(ClientReaderWriter { .. }) = do\n initMD <- readIORef initialMDRef\n case initMD of\n Just md -> return (RpcOk md)\n Nothing -> do\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n res <- callBatch crw [ OpX recvInitialMetadataOp ]\n case res of\n RpcOk _ -> do\n md <- opRead recvInitialMetadataOp\n writeIORef initialMDRef (Just md)\n return (RpcOk md)\n RpcError err ->\n return (RpcError err)\n\nclientReadInitialMetadata :: ClientReaderWriter -> IO (RpcReply (Maybe [Metadata]))\nclientReadInitialMetadata (ClientReaderWriter {..}) = do\n md <- readIORef initialMDRef\n return (RpcOk md)\n\nclientRead :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nclientRead crw = do\n _ <- clientWaitForInitialMetadata crw\n recvMessage crw\n\nrecvMessage :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nrecvMessage crw = do\n recvMessageOp <- opRecvMessage\n res <- callBatch crw [ OpX recvMessageOp ]\n case res of\n RpcOk _ -> do\n bs <- opRead recvMessageOp\n return (RpcOk bs)\n RpcError err -> do\n putStrLn \"recvMessage: callBatch failed\"\n return (RpcError err)\n\nclientWaitForStatus :: ClientReaderWriter -> IO (RpcReply RpcStatus)\nclientWaitForStatus crw@(ClientReaderWriter{..}) = do\n status <- readIORef statusFromServer\n case status of\n Nothing -> do\n recvStatusOp <- opRecvStatusOnClient crw\n res <- callBatch crw [ OpX recvStatusOp ]\n case res of\n RpcOk _ -> do\n st <- opRead recvStatusOp\n return (RpcOk st)\n RpcError err -> do\n return (RpcError err)\n Just st -> return (RpcOk st)\n\nclientClose :: ClientReaderWriter -> IO ()\nclientClose (ClientReaderWriter{..}) = do\n withMVar callMVar_ $ \\call ->\n grpcCallDestroy call\n\nclientWrite :: ClientReaderWriter -> B.ByteString -> IO (RpcReply ())\nclientWrite crw@(ClientReaderWriter{..}) arg = do\n sendMessageOp <- opSendMessage arg\n callBatch crw [ OpX sendMessageOp ]\n\nclientSendHalfClose :: ClientReaderWriter -> IO (RpcReply ())\nclientSendHalfClose crw@(ClientReaderWriter{..}) = do\n sendCloseOp <- opSendCloseFromClient\n callBatch crw [ OpX sendCloseOp ]\n\nclientCloseCall :: ClientReaderWriter -> IO ()\nclientCloseCall ClientReaderWriter { callMVar_ = callMVar } =\n withMVar callMVar $ \\call ->\n grpcCallDestroy call\n\ntype Rpc req resp a = ReaderT (Client req resp) (ExceptT RpcError IO) a\n\naskCrw :: Rpc req resp ClientReaderWriter\naskCrw = asks clientCrw\n\naskDecoder :: Rpc req resp (Decoder resp)\naskDecoder = asks clientDecoder\n\naskEncoder :: Rpc req resp (Encoder req)\naskEncoder = asks clientEncoder\n\njoinReply :: RpcReply a -> Rpc req resp a\njoinReply (RpcOk a) = return a\njoinReply (RpcError err) = lift (throwE err)\n\nwithNewClient :: RpcReply (Client req resp) -> Rpc req resp a -> IO (RpcReply a)\nwithNewClient r_client m = do\n case r_client of\n RpcOk client -> withClient client m\n RpcError err -> return (RpcError err)\n\nwithClient :: Client req resp -> Rpc req resp a -> IO (RpcReply a)\nwithClient client m = do\n e <- runExceptT (runReaderT m client)\n case e of\n Left err -> return (RpcError err)\n Right a -> return (RpcOk a)\n\ninitialMetadata :: Rpc req resp [Metadata]\ninitialMetadata = do\n crw <- askCrw\n joinReply =<< liftIO (clientWaitForInitialMetadata crw)\n\nwaitForStatus :: Rpc req resp RpcStatus\nwaitForStatus = do\n crw <- askCrw\n joinReply =<< liftIO (clientWaitForStatus crw)\n\nreceiveMessage :: Rpc req resp (Maybe resp)\nreceiveMessage = do\n crw <- askCrw\n msg <- joinReply =<< liftIO (clientRead crw)\n case msg of\n Nothing -> return Nothing\n Just x -> do\n decoder <- askDecoder\n liftM Just (joinReply =<< liftIO (decoder x))\n\nreceiveAllMessages :: Rpc req resp [resp]\nreceiveAllMessages = do\n crw <- askCrw\n decoder <- askDecoder\n let go acc = do\n value <- joinReply =<< liftIO (clientRead crw)\n case value of\n Just x -> do\n y <- joinReply =<< (liftIO (decoder x))\n go (y:acc)\n Nothing -> return (reverse acc)\n go []\n\nsendMessage :: req -> Rpc req resp ()\nsendMessage o = do\n crw <- askCrw\n encoder <- askEncoder\n x <- joinReply =<< liftIO (encoder o)\n joinReply =<< liftIO (clientWrite crw x)\n\nsendHalfClose :: Rpc req resp ()\nsendHalfClose = do\n crw <- askCrw\n joinReply =<< liftIO (clientSendHalfClose crw)\n\ncloseCall :: Rpc req resp ()\ncloseCall = do\n crw <- askCrw\n liftIO (clientClose crw)\n\ndata RpcReply a\n = RpcOk a\n | RpcError RpcError\n deriving Show\n\ndata RpcError\n = DeadlineExceeded\n | Cancelled\n | Error String\n | CallErrorStatus CallError\n | StatusError StatusCode B.ByteString\n deriving Show\n","old_contents":"-- Copyright (c) 2016, Google Inc.\n-- All rights reserved.\n--\n-- Redistribution and use in source and binary forms, with or without\n-- modification, are permitted provided that the following conditions are met:\n-- * Redistributions of source code must retain the above copyright\n-- notice, this list of conditions and the following disclaimer.\n-- * Redistributions in binary form must reproduce the above copyright\n-- notice, this list of conditions and the following disclaimer in the\n-- documentation and\/or other materials provided with the distribution.\n-- * Neither the name of Google Inc. nor the\n-- names of its contributors may be used to endorse or promote products\n-- derived from this software without specific prior written permission.\n--\n-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n-- DISCLAIMED. IN NO EVENT SHALL Google Inc. BE LIABLE FOR ANY\n-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n--\n--------------------------------------------------------------------------------\n{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, ExistentialQuantification, RecordWildCards #-}\nmodule Network.Grpc.Core.Call where\n\n\nimport Control.Concurrent\nimport Control.Exception\nimport Control.Monad\n\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Lazy as L\nimport Data.IORef\n\nimport Foreign.C.Types as C\nimport qualified Foreign.ForeignPtr as C\nimport qualified Foreign.Marshal.Alloc as C\nimport qualified Foreign.Marshal.Utils as C\nimport qualified Foreign.Ptr as C\nimport Foreign.Ptr (Ptr)\nimport qualified Foreign.Storable as C\n\n-- transformers\nimport Control.Monad.IO.Class\nimport Control.Monad.Trans.Class\nimport Control.Monad.Trans.Except\nimport Control.Monad.Trans.Reader\n\nimport qualified Network.Grpc.CompletionQueue as CQ\n{#import Network.Grpc.Lib.ByteBuffer#}\n{#import Network.Grpc.Lib.Metadata#}\n{#import Network.Grpc.Lib.TimeSpec#}\n{#import Network.Grpc.Lib.Types#}\n{#import Network.Grpc.Lib.Grpc#}\n\n\n#include \n#include \"hs_grpc.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\ntype Deadline = TimeSpec\n\ndata ClientContext = ClientContext\n { ccChannel :: Channel\n , ccCQ :: CompletionQueue\n , ccWorker :: CQ.Worker\n , ccDeadline :: Deadline\n }\n\nemptyChannelArgs :: ChannelArgs\nemptyChannelArgs = ChannelArgs C.nullPtr\n\nnewClientContext :: Channel -> IO ClientContext\nnewClientContext chan = do\n cq <- completionQueueCreate reservedPtr\n cqt <- CQ.startCompletionQueueThread cq\n return (ClientContext chan cq cqt gprInfFuture)\n\ndestroyClientContext :: ClientContext -> IO ()\ndestroyClientContext (ClientContext _ cq w _) = do\n completionQueueShutdown cq\n CQ.waitWorkerTermination w\n\nwithTimeout :: Deadline -> ClientContext -> ClientContext\nwithTimeout ts (ClientContext chan cq cqt _) = ClientContext chan cq cqt ts\n\ntype MethodName = B.ByteString\ntype Arg = B.ByteString\n\n-- | Run the IO function once, cache it in the MVar.\nonceMVar :: MVar (Maybe a) -> IO a -> IO a\nonceMVar mvar io = modifyMVar mvar $ \\x ->\n case x of\n Just x' -> return (x, x')\n Nothing -> do\n x' <- io\n return (Just x', x')\n\nreservedPtr :: Ptr ()\nreservedPtr = C.nullPtr\n\ncallUnary :: ClientContext -> MethodName -> Arg -> [Metadata] -> IO (RpcReply (UnaryResult L.ByteString))\ncallUnary ctx@(ClientContext chan cq _ deadline) method arg mds =\n C.withForeignPtr chan $ \\chanPtr ->\n bracket (grpcChannelCreateCall chanPtr C.nullPtr defaultPropagationMask cq method \"localhost\" deadline) grpcCallDestroy $ \\call0 -> newMVar call0 >>= \\mcall -> do\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata mds\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n recvStatusOp <- opRecvStatusOnClient crw\n recvMessageOp <- opRecvMessage\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX recvInitialMetadataOp\n , OpX recvMessageOp\n , OpX sendMessageOp\n , OpX recvStatusOp\n ]\n case res of\n RpcOk _ -> do\n (RpcStatus trailMD status statusDetails) <- opRead recvStatusOp\n case status of\n StatusOk -> do\n initMD <- opRead recvInitialMetadataOp\n answ <- opRead recvMessageOp\n let answ' = maybe L.empty id answ\n return (RpcOk (UnaryResult initMD trailMD answ'))\n _ -> return (RpcError (StatusError status statusDetails))\n RpcError err -> return (RpcError err)\n\ndata Client req resp = Client\n { clientCrw :: ClientReaderWriter\n , clientEncoder :: Encoder req\n , clientDecoder :: Decoder resp\n }\n\ntype Decoder a = L.ByteString -> IO (RpcReply a)\ntype Encoder a = a -> IO (RpcReply B.ByteString)\n\ndefaultDecoder :: L.ByteString -> IO (RpcReply L.ByteString)\ndefaultDecoder bs = return (RpcOk bs)\n\ndefaultEncoder :: B.ByteString -> IO (RpcReply B.ByteString)\ndefaultEncoder bs = return (RpcOk bs)\n\ncallDownstream :: ClientContext -> MethodName -> Arg -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallDownstream ctx@(ClientContext chan cq _ deadline) method arg =\n C.withForeignPtr chan $ \\chanPtr -> do\n mcall <- grpcChannelCreateCall chanPtr C.nullPtr defaultPropagationMask cq method \"localhost\" deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata []\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX sendMessageOp\n ]\n case res of\n RpcOk _ -> do\n return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n\ncallUpstream :: ClientContext -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallUpstream ctx@(ClientContext chan cq _ deadline) method =\n C.withForeignPtr chan $ \\chanPtr -> do\n mcall <- grpcChannelCreateCall chanPtr C.nullPtr defaultPropagationMask cq method \"localhost\" deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata []\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> do\n return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n\ndata ClientReaderWriter = ClientReaderWriter {\n context :: ClientContext,\n callMVar_ :: MVar Call,\n initialMDRef :: !(IORef (Maybe [Metadata])),\n trailingMDRef :: !(IORef (Maybe [Metadata])),\n statusFromServer :: !(IORef (Maybe RpcStatus))\n}\n\nnewClientReaderWriter :: ClientContext -> MVar Call -> IO ClientReaderWriter\nnewClientReaderWriter ctx mcall = do\n initMD <- newIORef Nothing\n trailMD <- newIORef Nothing\n status <- newIORef Nothing\n return (ClientReaderWriter ctx mcall initMD trailMD status)\n\ndata OpX = forall t. OpX (OpT t)\n\ndata OpArray = OpArray { opArrPtr :: !GrpcOpPtr\n , opArrLen :: !CULong\n , opArrFree :: !(IO ())\n }\n\ntoArray :: [OpX] -> IO OpArray\ntoArray ops = do\n aptr <- C.mallocBytes (length ops * {#sizeof grpc_op#})\n let ptrs = iterate (`C.plusPtr` {#sizeof grpc_op#}) aptr\n ops' = concatMap (\\(OpX op) -> opAdd op) ops\n free = C.free aptr >> sequence_ (map (\\(OpX op) -> opFinish op) ops)\n write op p = do\n {#set grpc_op->flags#} p 0\n {#set grpc_op->reserved#} p C.nullPtr\n op p\n zipWithM_ write ops' ptrs\n return $! OpArray aptr (fromIntegral $ length ops) free\n\ncallBatch :: ClientReaderWriter -> [OpX] -> IO (RpcReply ())\ncallBatch crw ops = do\n let ctx = context crw\n CQ.withEvent (ccWorker ctx) $ \\eDesc -> do\n arr <- toArray ops\n callStatus <- withMVar (callMVar_ crw) $ \\call ->\n grpcCallStartBatch call (opArrPtr arr) (opArrLen arr) (CQ.eventTag eDesc) reservedPtr\n -- print (\"callStatus: \" ++ show callStatus)\n case callStatus of\n CallOk -> do\n e <- CQ.interruptibleWaitEvent eDesc\n -- print (\"event: \" ++ show e)\n opArrFree arr -- TODO: We leak if we're interrupted.\n case e of\n QueueOpComplete OpSuccess _ -> return (RpcOk ())\n QueueOpComplete OpError _ -> return (RpcError (Error \"callBatch: op error\"))\n QueueTimeOut -> return (RpcError DeadlineExceeded)\n QueueShutdown -> return (RpcError (Error \"queue shutdown\"))\n _ -> do\n -- print callStatus\n return (RpcError (CallErrorStatus callStatus))\n\ndata OpT out = Op\n { opAdd :: [Ptr GrpcOp -> IO ()]\n , opValue :: IORef out\n , opFinish :: IO ()\n }\n\nopRead :: OpT a -> IO a\nopRead op = readIORef (opValue op)\n\nopRecvInitialMetadata :: ClientReaderWriter -> IO (OpT [Metadata])\nopRecvInitialMetadata crw = do\n arr <- mallocMetadataArray\n value <- newIORef (error \"opRecvInitialMetadata never finished\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvInitialMetadata))\n {#set grpc_op->data.recv_initial_metadata#} p arr\n ]\n finish = do\n mds <- readMetadataArray arr\n writeIORef (initialMDRef crw) (Just mds)\n writeIORef value mds\n freeMetadataArray arr\n return (Op add value finish)\n\nopSendMessage :: B.ByteString -> IO (OpT ())\nopSendMessage bs = do\n bb <- fromByteString bs\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendMessage))\n {#set grpc_op->data.send_message#} p bb\n ]\n finish =\n byteBufferDestroy bb\n return (Op add value finish)\n\nopRecvMessage :: IO (OpT (Maybe L.ByteString))\nopRecvMessage = do\n bbptr <- C.malloc :: IO (Ptr (Ptr CByteBuffer))\n value <- newIORef Nothing\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvMessage))\n {#set grpc_op->data.recv_message#} p bbptr\n ]\n finish = do\n bb <- C.peek bbptr\n C.free bbptr\n writeIORef value =<< if bb \/= C.nullPtr\n then do\n lbs <- toLazyByteString bb\n byteBufferDestroy bb\n return (Just lbs)\n else return Nothing\n return (Op add value finish)\n\nopSendInitialMetadata :: [Metadata] -> IO (OpT ())\nopSendInitialMetadata elems = do\n (mdArrPtr, free) <- mallocMetadata elems\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendInitialMetadata))\n {#set grpc_op->data.send_initial_metadata.count#} p (fromIntegral (length elems))\n {#set grpc_op->data.send_initial_metadata.metadata#} p (C.castPtr mdArrPtr)\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.is_set#} p 0\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.level#} p 0\n ]\n finish = do\n free\n return (Op add value finish)\n\ndata RpcStatus = RpcStatus [Metadata] StatusCode B.ByteString\n deriving Show\n\nopRecvStatusOnClient :: ClientReaderWriter -> IO (OpT RpcStatus)\nopRecvStatusOnClient (ClientReaderWriter{..}) = do\n trailingMetadataArrPtr <- mallocMetadataArray\n statusCodePtr <- C.malloc :: IO (Ptr StatusCodeT)\n ptrPtrStatusStr <- C.new C.nullPtr :: IO (Ptr (Ptr CChar))\n capacityPtr <- C.new 0 :: IO (Ptr SizeT)\n value <- newIORef (error \"opRecvStatusOnClient never ran\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvStatusOnClient))\n {#set grpc_op->data.recv_status_on_client.trailing_metadata#} p trailingMetadataArrPtr\n {#set grpc_op->data.recv_status_on_client.status#} p statusCodePtr\n {#set grpc_op->data.recv_status_on_client.status_details#} p ptrPtrStatusStr\n {#set grpc_op->data.recv_status_on_client.status_details_capacity#} p capacityPtr\n ]\n finish = do\n trailingMd <- readMetadataArray trailingMetadataArrPtr\n statusCode <- fmap toStatusCode (C.peek statusCodePtr)\n statusDetails <- B.packCString =<< C.peek ptrPtrStatusStr\n let status = RpcStatus trailingMd statusCode statusDetails\n writeIORef value status\n writeIORef statusFromServer (Just status)\n free\n free = do\n freeMetadataArray trailingMetadataArrPtr\n C.free statusCodePtr\n C.free ptrPtrStatusStr\n C.free capacityPtr\n return (Op add value finish)\n\nopSendCloseFromClient :: IO (OpT ())\nopSendCloseFromClient = do\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendCloseFromClient))\n ]\n finish =\n return ()\n return (Op add value finish)\n\nclientWaitForInitialMetadata :: ClientReaderWriter -> IO (RpcReply [Metadata])\nclientWaitForInitialMetadata crw@(ClientReaderWriter { .. }) = do\n initMD <- readIORef initialMDRef\n case initMD of\n Just md -> return (RpcOk md)\n Nothing -> do\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n res <- callBatch crw [ OpX recvInitialMetadataOp ]\n case res of\n RpcOk _ -> do\n md <- opRead recvInitialMetadataOp\n writeIORef initialMDRef (Just md)\n return (RpcOk md)\n RpcError err ->\n return (RpcError err)\n\nclientReadInitialMetadata :: ClientReaderWriter -> IO (RpcReply (Maybe [Metadata]))\nclientReadInitialMetadata (ClientReaderWriter {..}) = do\n md <- readIORef initialMDRef\n return (RpcOk md)\n\nclientRead :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nclientRead crw = do\n _ <- clientWaitForInitialMetadata crw\n recvMessage crw\n\nrecvMessage :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nrecvMessage crw = do\n recvMessageOp <- opRecvMessage\n res <- callBatch crw [ OpX recvMessageOp ]\n case res of\n RpcOk _ -> do\n bs <- opRead recvMessageOp\n return (RpcOk bs)\n RpcError err -> do\n putStrLn \"recvMessage: callBatch failed\"\n return (RpcError err)\n\nclientWaitForStatus :: ClientReaderWriter -> IO (RpcReply RpcStatus)\nclientWaitForStatus crw@(ClientReaderWriter{..}) = do\n status <- readIORef statusFromServer\n case status of\n Nothing -> do\n recvStatusOp <- opRecvStatusOnClient crw\n res <- callBatch crw [ OpX recvStatusOp ]\n case res of\n RpcOk _ -> do\n st <- opRead recvStatusOp\n return (RpcOk st)\n RpcError err -> do\n return (RpcError err)\n Just st -> return (RpcOk st)\n\nclientClose :: ClientReaderWriter -> IO ()\nclientClose (ClientReaderWriter{..}) = do\n withMVar callMVar_ $ \\call ->\n grpcCallDestroy call\n\nclientWrite :: ClientReaderWriter -> B.ByteString -> IO (RpcReply ())\nclientWrite crw@(ClientReaderWriter{..}) arg = do\n sendMessageOp <- opSendMessage arg\n callBatch crw [ OpX sendMessageOp ]\n\nclientSendHalfClose :: ClientReaderWriter -> IO (RpcReply ())\nclientSendHalfClose crw@(ClientReaderWriter{..}) = do\n sendCloseOp <- opSendCloseFromClient\n callBatch crw [ OpX sendCloseOp ]\n\nclientCloseCall :: ClientReaderWriter -> IO ()\nclientCloseCall ClientReaderWriter { callMVar_ = callMVar } =\n withMVar callMVar $ \\call ->\n grpcCallDestroy call\n\ntype Rpc req resp a = ReaderT (Client req resp) (ExceptT RpcError IO) a\n\naskCrw :: Rpc req resp ClientReaderWriter\naskCrw = asks clientCrw\n\naskDecoder :: Rpc req resp (Decoder resp)\naskDecoder = asks clientDecoder\n\naskEncoder :: Rpc req resp (Encoder req)\naskEncoder = asks clientEncoder\n\njoinReply :: RpcReply a -> Rpc req resp a\njoinReply (RpcOk a) = return a\njoinReply (RpcError err) = lift (throwE err)\n\nwithNewClient :: RpcReply (Client req resp) -> Rpc req resp a -> IO (RpcReply a)\nwithNewClient r_client m = do\n case r_client of\n RpcOk client -> withClient client m\n RpcError err -> return (RpcError err)\n\nwithClient :: Client req resp -> Rpc req resp a -> IO (RpcReply a)\nwithClient client m = do\n e <- runExceptT (runReaderT m client)\n case e of\n Left err -> return (RpcError err)\n Right a -> return (RpcOk a)\n\ninitialMetadata :: Rpc req resp [Metadata]\ninitialMetadata = do\n crw <- askCrw\n joinReply =<< liftIO (clientWaitForInitialMetadata crw)\n\nwaitForStatus :: Rpc req resp RpcStatus\nwaitForStatus = do\n crw <- askCrw\n joinReply =<< liftIO (clientWaitForStatus crw)\n\nreceiveMessage :: Rpc req resp (Maybe resp)\nreceiveMessage = do\n crw <- askCrw\n msg <- joinReply =<< liftIO (clientRead crw)\n case msg of\n Nothing -> return Nothing\n Just x -> do\n decoder <- askDecoder\n liftM Just (joinReply =<< liftIO (decoder x))\n\nreceiveAllMessages :: Rpc req resp [resp]\nreceiveAllMessages = do\n crw <- askCrw\n decoder <- askDecoder\n let go acc = do\n value <- joinReply =<< liftIO (clientRead crw)\n case value of\n Just x -> do\n y <- joinReply =<< (liftIO (decoder x))\n go (y:acc)\n Nothing -> return (reverse acc)\n go []\n\nsendMessage :: req -> Rpc req resp ()\nsendMessage o = do\n crw <- askCrw\n encoder <- askEncoder\n x <- joinReply =<< liftIO (encoder o)\n joinReply =<< liftIO (clientWrite crw x)\n\nsendHalfClose :: Rpc req resp ()\nsendHalfClose = do\n crw <- askCrw\n joinReply =<< liftIO (clientSendHalfClose crw)\n\ncloseCall :: Rpc req resp ()\ncloseCall = do\n crw <- askCrw\n liftIO (clientClose crw)\n\ncallBidi :: ClientContext -> MethodName -> [Metadata] -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallBidi ctx@(ClientContext chan cq _ deadline) method mds = do\n C.withForeignPtr chan $ \\chanPtr -> do\n mcall <- grpcChannelCreateCall chanPtr C.nullPtr defaultPropagationMask cq method \"localhost\" deadline >>= newMVar\n\n crw <- newClientReaderWriter ctx mcall\n sendInitOp <- opSendInitialMetadata mds\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n\ndata UnaryResult a = UnaryResult [Metadata] [Metadata] a deriving Show\n\ndata RpcReply a\n = RpcOk a\n | RpcError RpcError\n deriving Show\n\ndata RpcError\n = DeadlineExceeded\n | Cancelled\n | Error String\n | CallErrorStatus CallError\n | StatusError StatusCode B.ByteString\n deriving Show\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"C2hs Haskell"}
{"commit":"d08ace4bcb95be4456e4eb830da9619341cf6705","subject":"haskell-bindings-improve-cmake: fix reference counting issue with keyListMeta","message":"haskell-bindings-improve-cmake: fix reference counting issue with keyListMeta\n","repos":"e1528532\/libelektra,petermax2\/libelektra,BernhardDenner\/libelektra,mpranj\/libelektra,mpranj\/libelektra,petermax2\/libelektra,mpranj\/libelektra,ElektraInitiative\/libelektra,BernhardDenner\/libelektra,mpranj\/libelektra,e1528532\/libelektra,ElektraInitiative\/libelektra,petermax2\/libelektra,ElektraInitiative\/libelektra,BernhardDenner\/libelektra,ElektraInitiative\/libelektra,BernhardDenner\/libelektra,ElektraInitiative\/libelektra,petermax2\/libelektra,ElektraInitiative\/libelektra,BernhardDenner\/libelektra,mpranj\/libelektra,e1528532\/libelektra,ElektraInitiative\/libelektra,petermax2\/libelektra,ElektraInitiative\/libelektra,BernhardDenner\/libelektra,BernhardDenner\/libelektra,ElektraInitiative\/libelektra,mpranj\/libelektra,e1528532\/libelektra,BernhardDenner\/libelektra,BernhardDenner\/libelektra,mpranj\/libelektra,ElektraInitiative\/libelektra,e1528532\/libelektra,petermax2\/libelektra,e1528532\/libelektra,petermax2\/libelektra,petermax2\/libelektra,ElektraInitiative\/libelektra,e1528532\/libelektra,mpranj\/libelektra,e1528532\/libelektra,mpranj\/libelektra,mpranj\/libelektra,petermax2\/libelektra,mpranj\/libelektra","old_file":"src\/bindings\/haskell\/src\/Elektra\/Key.chs","new_file":"src\/bindings\/haskell\/src\/Elektra\/Key.chs","new_contents":"module Elektra.Key (Key (..), Namespace (..), withKey,\n keyNew, keyNewWithValue, keyDup, keyCopy, keyClear, keyIncRef, keyDecRef, keyGetRef,\n keyName, keyGetNameSize, keyUnescapedName, keyGetUnescapedNameSize, keySetName, keyGetFullNameSize, keyGetFullName,\n keyAddName, keyBaseName, keyGetBaseName, keyGetBaseNameSize, keyAddBaseName, keySetBaseName, keyGetNamespace,\n keyString, keyGetValueSize, keySetString, keySet,\n keyRewindMeta, keyNextMeta, keyCurrentMeta, keyCopyMeta, keyCopyAllMeta, keyGetMeta, keySetMeta, keyListMeta,\n keyCmp, keyNeedSync, keyIsBelow, keyIsDirectBelow, keyRel, keyIsInactive, keyIsBinary, keyIsString, keyPtrNull, ifKey) where\n\n#include \nimport Foreign.Marshal.Alloc (allocaBytes)\nimport Foreign.Ptr (castPtr, nullPtr)\nimport Foreign.ForeignPtr (withForeignPtr)\nimport System.IO.Unsafe (unsafePerformIO)\nimport Control.Monad (liftM)\n\n{#context lib=\"libelektra\" #}\n\n-- ***\n-- TYPE DEFINITIONS\n-- ***\n\n{#pointer *Key foreign finalizer keyDel newtype #}\n\n{#typedef size_t Int#}\n{#typedef ssize_t Int #}\n\n{#enum KEY_NS_NONE as Namespace { underscoreToCase } deriving (Show, Eq) #}\n{#enum KEY_NAME as ElektraKeyVarargs { underscoreToCase } deriving (Show, Eq) #}\n\n-- ***\n-- KEY CREATION \/ DELETION \/ COPPY METHODS\n-- ***\n\nkeyPtrNull :: Key -> IO Bool\nkeyPtrNull (Key ptr) = withForeignPtr ptr (return . (== nullPtr))\n\n-- as we use haskell's reference counting here, increase the number by one\n-- so it gets deleted properly when haskell calls the finalizer\nkeyNew :: String -> IO Key\nkeyNew name = do\n key <- keyNewRaw name KeyEnd\n keyIncRef key\n return key\nkeyNewWithValue :: String -> String -> IO Key\nkeyNewWithValue name value = do\n key <- keyNewRawWithValue name KeyValue value KeyEnd\n keyIncRef key\n return key\n{#fun unsafe variadic keyNew[keyswitch_t] as keyNewRaw {`String', `ElektraKeyVarargs'} -> `Key' #}\n{#fun unsafe variadic keyNew[keyswitch_t, const char *, keyswitch_t]\n as keyNewRawWithValue {`String', `ElektraKeyVarargs', `String', `ElektraKeyVarargs'} -> `Key' #}\nkeyDup :: Key -> IO Key\nkeyDup key = do\n dup <- keyDupRaw key\n keyIncRef dup\n return dup\n{#fun unsafe keyDup as keyDupRaw {`Key'} -> `Key' #}\n{#fun unsafe keyCopy {`Key', `Key'} -> `Int' #}\n{#fun unsafe keyClear {`Key'} -> `Int' #}\n{#fun unsafe keyIncRef {`Key'} -> `Int' #}\n{#fun unsafe keyDecRef {`Key'} -> `Int' #}\n{#fun unsafe keyGetRef {`Key'} -> `Int' #}\n\n-- ***\n-- KEY NAME MANIPULATION METHODS\n-- ***\n\n{#fun unsafe keyName {`Key'} -> `String' #}\nkeyGetName = keyName\n{#fun unsafe keyGetNameSize {`Key'} -> `Int' #}\nkeyUnescapedName :: Key -> IO String\nkeyUnescapedName key = do\n size <- keyGetUnescapedNameSize key\n withKey key $ (\\cKey -> do\n result <- {#call unsafe keyUnescapedName as keyUnescapedNameRaw #} cKey\n C2HSImp.peekCStringLen (castPtr result, size))\n{#fun unsafe keyGetUnescapedNameSize {`Key'} -> `Int' #}\n{#fun unsafe keySetName {`Key', `String'} -> `Int' #}\nkeyGetFullName :: (Key) -> IO String\nkeyGetFullName key = do\n size <- keyGetFullNameSize key\n withKey key $ \\cKey -> \n allocaBytes size (\\result -> do\n {#call unsafe keyGetFullName as keyGetFullNameRaw #} cKey result size\n C2HSImp.peekCString result)\n{#fun unsafe keyGetFullNameSize {`Key'} -> `Int' #}\n{#fun unsafe keyBaseName {`Key'} -> `String' #}\nkeyGetBaseName :: Key -> IO String\nkeyGetBaseName = keyBaseName\n{#fun unsafe keyGetBaseNameSize {`Key'} -> `Int' #}\n{#fun unsafe keyAddBaseName {`Key', `String'} -> `Int' #}\n{#fun unsafe keyAddName {`Key', `String'} -> `Int' #}\n{#fun unsafe keySetBaseName {`Key', `String'} -> `Int' #}\n{#fun unsafe keyGetNamespace {`Key'} -> `Namespace' #}\n\n-- ***\n-- KEY VALUE MANIPULATION METHODS\n-- ***\n\n-- we don't handle binary data currently\n-- {#fun unsafe keyValue {`Key'} -> `PPtr' #}\n{#fun unsafe keyString {`Key'} -> `String' #}\n{#fun unsafe keyGetValueSize {`Key'} -> `Int' #}\nkeySet :: Show a => Key -> a -> IO Int\nkeySet key = keySetString key . show\n{#fun unsafe keySetString {`Key', `String'} -> `Int' #}\n\n-- ***\n-- KEY META MANIPULATION METHODS\n-- ***\n\n{#fun unsafe keyRewindMeta {`Key'} -> `Int' #}\n{#fun unsafe keyNextMeta {`Key'} -> `Key' #}\n{#fun unsafe keyCurrentMeta {`Key'} -> `Key' #}\n{#fun unsafe keyCopyMeta {`Key', `Key', `String'} -> `Int' #}\n{#fun unsafe keyCopyAllMeta {`Key', `Key'} -> `Int' #}\n{#fun unsafe keyGetMeta {`Key', `String'} -> `Key' #}\n{#fun unsafe keySetMeta {`Key', `String', `String'} -> `Int' #}\nkeyListMeta :: Key -> IO [Key]\nkeyListMeta key = keyRewindMeta key >> listMeta []\n where\n listMeta res = do\n cur <- keyNextMeta key\n isNull <- keyPtrNull cur\n if isNull then return res else keyIncRef cur >> liftM (cur :) (listMeta res)\n\n-- ***\n-- KEY TESTING METHODS\n-- ***\n\n{#fun unsafe keyCmp {`Key', `Key'} -> `Int' #}\n{#fun unsafe keyNeedSync {`Key'} -> `Int' #}\n{#fun unsafe keyIsBelow {`Key', `Key'} -> `Int' #}\n{#fun unsafe keyIsDirectBelow {`Key', `Key'} -> `Int' #}\n{#fun unsafe keyRel {`Key', `Key'} -> `Int' #}\n{#fun unsafe keyIsInactive {`Key'} -> `Int' #}\n{#fun unsafe keyIsBinary {`Key'} -> `Int' #}\n{#fun unsafe keyIsString {`Key'} -> `Int' #}\n\n-- ***\n-- COMMON HASKELL TYPE CLASSES\n-- unsafePerformIO should be ok here, as those functions don't alter the key's state\n-- ***\n\ninstance Show Key where\n show key = unsafePerformIO $ do\n name <- keyName key\n value <- keyString key\n ref <- keyGetRef key\n return $ name ++ \" \" ++ value ++ \" \" ++ (show ref)\n\ninstance Eq Key where\n key1 == key2 = unsafePerformIO $ fmap (== 0) $ keyCmp key1 key2\n\n-- ***\n-- ADDITIONAL HELPERS USEFUL IN HASKELL\n-- ***\n\nifKey :: IO Key -> (Key -> IO a) -> IO a -> IO a\nifKey k t f = do\n null <- k >>= keyPtrNull\n if null then f else k >>= t\n","old_contents":"module Elektra.Key (Key (..), Namespace (..), withKey,\n keyNew, keyNewWithValue, keyDup, keyCopy, keyClear, keyIncRef, keyDecRef, keyGetRef,\n keyName, keyGetNameSize, keyUnescapedName, keyGetUnescapedNameSize, keySetName, keyGetFullNameSize, keyGetFullName,\n keyAddName, keyBaseName, keyGetBaseName, keyGetBaseNameSize, keyAddBaseName, keySetBaseName, keyGetNamespace,\n keyString, keyGetValueSize, keySetString, keySet,\n keyRewindMeta, keyNextMeta, keyCurrentMeta, keyCopyMeta, keyCopyAllMeta, keyGetMeta, keySetMeta, keyListMeta,\n keyCmp, keyNeedSync, keyIsBelow, keyIsDirectBelow, keyRel, keyIsInactive, keyIsBinary, keyIsString, keyPtrNull, ifKey) where\n\n#include \nimport Foreign.Marshal.Alloc (allocaBytes)\nimport Foreign.Ptr (castPtr, nullPtr)\nimport Foreign.ForeignPtr (withForeignPtr)\nimport System.IO.Unsafe (unsafePerformIO)\nimport Control.Monad (liftM)\n\n{#context lib=\"libelektra\" #}\n\n-- ***\n-- TYPE DEFINITIONS\n-- ***\n\n{#pointer *Key foreign finalizer keyDel newtype #}\n\n{#typedef size_t Int#}\n{#typedef ssize_t Int #}\n\n{#enum KEY_NS_NONE as Namespace { underscoreToCase } deriving (Show, Eq) #}\n{#enum KEY_NAME as ElektraKeyVarargs { underscoreToCase } deriving (Show, Eq) #}\n\n-- ***\n-- KEY CREATION \/ DELETION \/ COPPY METHODS\n-- ***\n\nkeyPtrNull :: Key -> IO Bool\nkeyPtrNull (Key ptr) = withForeignPtr ptr (return . (== nullPtr))\n\n-- as we use haskell's reference counting here, increase the number by one\n-- so it gets deleted properly when haskell calls the finalizer\nkeyNew :: String -> IO Key\nkeyNew name = do\n key <- keyNewRaw name KeyEnd\n keyIncRef key\n return key\nkeyNewWithValue :: String -> String -> IO Key\nkeyNewWithValue name value = do\n key <- keyNewRawWithValue name KeyValue value KeyEnd\n keyIncRef key\n return key\n{#fun unsafe variadic keyNew[keyswitch_t] as keyNewRaw {`String', `ElektraKeyVarargs'} -> `Key' #}\n{#fun unsafe variadic keyNew[keyswitch_t, const char *, keyswitch_t]\n as keyNewRawWithValue {`String', `ElektraKeyVarargs', `String', `ElektraKeyVarargs'} -> `Key' #}\nkeyDup :: Key -> IO Key\nkeyDup key = do\n dup <- keyDupRaw key\n keyIncRef dup\n return dup\n{#fun unsafe keyDup as keyDupRaw {`Key'} -> `Key' #}\n{#fun unsafe keyCopy {`Key', `Key'} -> `Int' #}\n{#fun unsafe keyClear {`Key'} -> `Int' #}\n{#fun unsafe keyIncRef {`Key'} -> `Int' #}\n{#fun unsafe keyDecRef {`Key'} -> `Int' #}\n{#fun unsafe keyGetRef {`Key'} -> `Int' #}\n\n-- ***\n-- KEY NAME MANIPULATION METHODS\n-- ***\n\n{#fun unsafe keyName {`Key'} -> `String' #}\nkeyGetName = keyName\n{#fun unsafe keyGetNameSize {`Key'} -> `Int' #}\nkeyUnescapedName :: Key -> IO String\nkeyUnescapedName key = do\n size <- keyGetUnescapedNameSize key\n withKey key $ (\\cKey -> do\n result <- {#call unsafe keyUnescapedName as keyUnescapedNameRaw #} cKey\n C2HSImp.peekCStringLen (castPtr result, size))\n{#fun unsafe keyGetUnescapedNameSize {`Key'} -> `Int' #}\n{#fun unsafe keySetName {`Key', `String'} -> `Int' #}\nkeyGetFullName :: (Key) -> IO String\nkeyGetFullName key = do\n size <- keyGetFullNameSize key\n withKey key $ \\cKey -> \n allocaBytes size (\\result -> do\n {#call unsafe keyGetFullName as keyGetFullNameRaw #} cKey result size\n C2HSImp.peekCString result)\n{#fun unsafe keyGetFullNameSize {`Key'} -> `Int' #}\n{#fun unsafe keyBaseName {`Key'} -> `String' #}\nkeyGetBaseName :: Key -> IO String\nkeyGetBaseName = keyBaseName\n{#fun unsafe keyGetBaseNameSize {`Key'} -> `Int' #}\n{#fun unsafe keyAddBaseName {`Key', `String'} -> `Int' #}\n{#fun unsafe keyAddName {`Key', `String'} -> `Int' #}\n{#fun unsafe keySetBaseName {`Key', `String'} -> `Int' #}\n{#fun unsafe keyGetNamespace {`Key'} -> `Namespace' #}\n\n-- ***\n-- KEY VALUE MANIPULATION METHODS\n-- ***\n\n-- we don't handle binary data currently\n-- {#fun unsafe keyValue {`Key'} -> `PPtr' #}\n{#fun unsafe keyString {`Key'} -> `String' #}\n{#fun unsafe keyGetValueSize {`Key'} -> `Int' #}\nkeySet :: Show a => Key -> a -> IO Int\nkeySet key = keySetString key . show\n{#fun unsafe keySetString {`Key', `String'} -> `Int' #}\n\n-- ***\n-- KEY META MANIPULATION METHODS\n-- ***\n\n{#fun unsafe keyRewindMeta {`Key'} -> `Int' #}\n{#fun unsafe keyNextMeta {`Key'} -> `Key' #}\n{#fun unsafe keyCurrentMeta {`Key'} -> `Key' #}\n{#fun unsafe keyCopyMeta {`Key', `Key', `String'} -> `Int' #}\n{#fun unsafe keyCopyAllMeta {`Key', `Key'} -> `Int' #}\n{#fun unsafe keyGetMeta {`Key', `String'} -> `Key' #}\n{#fun unsafe keySetMeta {`Key', `String', `String'} -> `Int' #}\nkeyListMeta :: Key -> IO [Key]\nkeyListMeta key = keyRewindMeta key >> listMeta []\n where\n listMeta res = do\n cur <- keyNextMeta key\n isNull <- keyPtrNull cur\n if isNull then return res else liftM (cur :) (listMeta res)\n\n-- ***\n-- KEY TESTING METHODS\n-- ***\n\n{#fun unsafe keyCmp {`Key', `Key'} -> `Int' #}\n{#fun unsafe keyNeedSync {`Key'} -> `Int' #}\n{#fun unsafe keyIsBelow {`Key', `Key'} -> `Int' #}\n{#fun unsafe keyIsDirectBelow {`Key', `Key'} -> `Int' #}\n{#fun unsafe keyRel {`Key', `Key'} -> `Int' #}\n{#fun unsafe keyIsInactive {`Key'} -> `Int' #}\n{#fun unsafe keyIsBinary {`Key'} -> `Int' #}\n{#fun unsafe keyIsString {`Key'} -> `Int' #}\n\n-- ***\n-- COMMON HASKELL TYPE CLASSES\n-- unsafePerformIO should be ok here, as those functions don't alter the key's state\n-- ***\n\ninstance Show Key where\n show key = unsafePerformIO $ do\n name <- keyName key\n value <- keyString key\n ref <- keyGetRef key\n return $ name ++ \" \" ++ value ++ \" \" ++ (show ref)\n\ninstance Eq Key where\n key1 == key2 = unsafePerformIO $ fmap (== 0) $ keyCmp key1 key2\n\n-- ***\n-- ADDITIONAL HELPERS USEFUL IN HASKELL\n-- ***\n\nifKey :: IO Key -> (Key -> IO a) -> IO a -> IO a\nifKey k t f = do\n null <- k >>= keyPtrNull\n if null then f else k >>= t\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"f091764fe9d1a71972e4fb65ab938ce7c99d8d31","subject":"automatically release device memory","message":"automatically release device memory\n\nIgnore-this: 2d19d6510749575a05bfd806bd59e7ac\n\nNot yet convinced this is the right way to do it, but the functionality (when\nimplemented correctly, at least) would be useful.\n\ndarcs-hash:20090916021904-115f9-8ba8dbbd6e152e612e912a8558a96e6f89b24aa7.gz\n","repos":"mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Marshal.chs","new_file":"Foreign\/CUDA\/Marshal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Marshal\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Memory allocation and marshalling support for CUDA devices\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Marshal\n (\n DevicePtr,\n withDevicePtr,\n\n -- ** Dynamic allocation\n --\n -- Basic methods to allocate a block of memory on the device. The memory\n -- should be deallocated using 'free' when no longer necessary. The\n -- advantage is that failed allocations will not raise an exception.\n --\n free,\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Local allocation\n --\n -- Execute a computation, passing as argument a pointer to a newly allocated\n -- block of memory. The memory is freed when the computation terminates.\n --\n alloca,\n allocaBytes,\n allocaBytesMemset,\n\n -- ** Marshalling\n --\n -- Store and retrieve Haskell lists as arrays on the device\n --\n peek,\n poke,\n peekArray,\n pokeArray,\n\n -- ** Combined allocation and marshalling\n --\n -- Write Haskell values (or lists) to newly allocated device memory. This\n -- may be a temporary store.\n --\n new,\n with,\n newArray,\n withArray,\n withArrayLen,\n\n -- ** Copying\n --\n -- Copy data between the host and device\n --\n )\n where\n\nimport Data.Int\nimport Control.Exception\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.Concurrent\nimport Foreign.ForeignPtr hiding (newForeignPtr, addForeignPtrFinalizer)\nimport Foreign.Storable (Storable)\n\nimport qualified Foreign.Storable as F\nimport qualified Foreign.Marshal as F\n\nimport Foreign.CUDA.Utils\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Stream\nimport Foreign.CUDA.Internal.C2HS\n\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A reference to data stored on the device\n--\ntype DevicePtr a = ForeignPtr a\n\n-- |\n-- Unwrap the device pointer, yielding a device memory address that can be\n-- passed to a kernel function callable from the host code. This allows the type\n-- system to strictly separate host and device memory references, a non-obvious\n-- distinction in pure CUDA.\n--\nwithDevicePtr :: DevicePtr a -> (Ptr a -> IO b) -> IO b\nwithDevicePtr = withForeignPtr\n\n--\n-- Internal, unwrap and cast. Required as some functions such as memset work\n-- with untyped `void' data.\n--\nwithDevicePtr' :: DevicePtr a -> (Ptr b -> IO c) -> IO c\nwithDevicePtr' = withForeignPtr . castForeignPtr\n\n--\n-- Wrap a device memory pointer. The memory will be freed once the last\n-- reference to the data is dropped, although there is no guarantee as to\n-- exactly when this will occur.\n--\nnewDevicePtr :: Ptr a -> IO (DevicePtr a)\nnewDevicePtr p = newForeignPtr p (free_ p)\n\n\n--\n-- Memory copy\n--\n{# enum cudaMemcpyKind as CopyDirection {}\n with prefix=\"cudaMemcpy\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Dynamic allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate the specified number of bytes in linear memory on the device. The\n-- memory is suitably aligned for any kind of variable, and is not cleared.\n--\nmalloc :: Int64 -> IO (Either String (DevicePtr a))\nmalloc bytes = do\n (rv,ptr) <- cudaMalloc bytes\n case rv of\n Success -> Right `fmap` newDevicePtr (castPtr ptr)\n _ -> return . Left . describe $ rv\n\n{# fun unsafe cudaMalloc\n { alloca'- `Ptr ()' peek'* ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n where alloca' = F.alloca\n peek' = F.peek\n\n\n-- |\n-- Allocate at least @width * height@ bytes of linear memory on the device. The\n-- function may pad the allocation to ensure corresponding pointers in each row\n-- meet coalescing requirements. The actual allocation width is returned.\n--\nmalloc2D :: (Int64, Int64) -- ^ allocation (width,height) in bytes\n -> IO (Either String (DevicePtr a, Int64))\nmalloc2D (width,height) = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> (\\p -> Right (p,pitch)) `fmap` newDevicePtr (castPtr ptr)\n _ -> return . Left . describe $ rv\n\n{# fun unsafe cudaMallocPitch\n { alloca'- `Ptr ()' peek'* ,\n alloca'- `Int64' peekIntConv* ,\n cIntConv `Int64' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n where\n -- C->Haskell doesn't like qualified imports\n --\n alloca' :: Storable a => (Ptr a -> IO b) -> IO b\n alloca' = F.alloca\n peek' = F.peek\n\n\n-- |\n-- Allocate at least @width * height * depth@ bytes of linear memory on the\n-- device. The function may pad the allocation to ensure hardware alignment\n-- requirements are met. The actual allocation pitch is returned\n--\nmalloc3D :: (Int64,Int64,Int64) -- ^ allocation (width,height,depth) in bytes\n -> IO (Either String (DevicePtr a, Int64))\nmalloc3D = moduleErr \"malloc3D\" \"not implemented yet\"\n\n\n-- |\n-- Free previously allocated memory on the device\n--\n\n--free :: DevicePtr a -> IO (Maybe String)\n--free p = nothingIfOk `fmap` (withDevicePtr p cudaFree)\n\nfree :: DevicePtr a -> IO ()\nfree = finalizeForeignPtr\n\nfree_ :: Ptr a -> IO ()\nfree_ p = cudaFree p >>= \\rv ->\n case rv of\n Success -> return ()\n _ -> moduleErr \"free\" (describe rv)\n\n{# fun unsafe cudaFree\n { castPtr `Ptr a' } -> `Status' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr a -> IO ()) -> IO (FunPtr (Ptr a -> IO ()))\n\n\n-- |\n-- Initialise device memory to a given value\n--\nmemset :: DevicePtr a -- ^ The device memory\n -> Int64 -- ^ Number of bytes\n -> Int -- ^ Value to set for each byte\n -> IO (Maybe String)\nmemset ptr bytes symbol =\n nothingIfOk `fmap` cudaMemset ptr symbol bytes\n\n{# fun unsafe cudaMemset\n { withDevicePtr'* `DevicePtr a' ,\n `Int' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Initialise a matrix to a given value\n--\nmemset2D :: DevicePtr a -- ^ The device memory\n -> (Int64, Int64) -- ^ The (width,height) of the matrix in bytes\n -> Int64 -- ^ The allocation pitch, as returned by 'malloc2D'\n -> Int -- ^ Value to set for each byte\n -> IO (Maybe String)\nmemset2D ptr (width,height) pitch symbol =\n nothingIfOk `fmap` cudaMemset2D ptr pitch symbol width height\n\n{# fun unsafe cudaMemset2D\n { withDevicePtr'* `DevicePtr a' ,\n cIntConv `Int64' ,\n `Int' ,\n cIntConv `Int64' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Initialise the elements of a 3D array to a given value\n--\nmemset3D :: DevicePtr a -- ^ The device memory\n -> (Int64,Int64,Int64) -- ^ The (width,height,depth) of the array in bytes\n -> Int64 -- ^ The allocation pitch, as returned by 'malloc3D'\n -> Int -- ^ Value to set for each byte\n -> IO (Maybe String)\nmemset3D = moduleErr \"memset3D\" \"not implemented yet\"\n\n\n--------------------------------------------------------------------------------\n-- Local allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Execute a computation, passing a pointer to a temporarily allocated block of\n-- memory\n--\nalloca :: Storable a => (DevicePtr a -> IO b) -> IO b\nalloca = doAlloca undefined\n where\n doAlloca :: Storable a' => a' -> (DevicePtr a' -> IO b') -> IO b'\n doAlloca x = allocaBytes (fromIntegral (F.sizeOf x))\n\n\n-- |\n-- Execute a computation, passing a pointer to a block of 'n' bytes of memory\n--\nallocaBytes :: Int64 -> (DevicePtr a -> IO b) -> IO b\nallocaBytes bytes =\n bracket (forceEither `fmap` malloc bytes) free\n\n\n-- |\n-- Execute a computation, passing a pointer to a block of memory initialised to\n-- a given value\n--\nallocaBytesMemset :: Int64 -> Int -> (DevicePtr a -> IO b) -> IO b\nallocaBytesMemset bytes symbol f =\n allocaBytes bytes $ \\dptr ->\n memset dptr bytes symbol >>= \\rv ->\n case rv of\n Nothing -> f dptr\n Just e -> error e\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Retrieve the specified value from device memory\n--\npeek :: Storable a => DevicePtr a -> IO (Either String a)\npeek d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO (Either String a')\n doPeek x = F.alloca $ \\hptr ->\n withDevicePtr' d $ \\dptr ->\n memcpy hptr dptr (fromIntegral (F.sizeOf x)) DeviceToHost >>= \\rv ->\n case rv of\n Nothing -> Right `fmap` F.peek hptr\n Just s -> return (Left s)\n\n\n-- |\n-- Retrieve the specified number of elements from device memory and return as a\n-- Haskell list\n--\npeekArray :: Storable a => Int -> DevicePtr a -> IO (Either String [a])\npeekArray n d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO (Either String [a'])\n doPeek x = let bytes = fromIntegral n * (fromIntegral (F.sizeOf x)) in\n F.allocaArray n $ \\hptr ->\n withDevicePtr' d $ \\dptr ->\n memcpy hptr dptr bytes DeviceToHost >>= \\rv ->\n case rv of\n Nothing -> Right `fmap` F.peekArray n hptr\n Just s -> return (Left s)\n\n\n-- |\n-- Store the given value to device memory\n--\npoke :: Storable a => DevicePtr a -> a -> IO (Maybe String)\npoke d v =\n F.with v $ \\hptr ->\n withDevicePtr d $ \\dptr ->\n memcpy dptr hptr (fromIntegral (F.sizeOf v)) HostToDevice\n\n\n-- |\n-- Store the list elements consecutively in device memory\n--\npokeArray :: Storable a => DevicePtr a -> [a] -> IO (Maybe String)\npokeArray d = doPoke undefined\n where\n doPoke :: Storable a' => a' -> [a'] -> IO (Maybe String)\n doPoke x v = F.withArrayLen v $ \\n hptr ->\n withDevicePtr' d $ \\dptr ->\n let bytes = (fromIntegral n) * (fromIntegral (F.sizeOf x)) in\n memcpy dptr hptr bytes HostToDevice\n\n\n--------------------------------------------------------------------------------\n-- Combined allocation and marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a block of memory on the device and transfer a value into it. The\n-- memory may be deallocated using 'free' when no longer required.\n--\nnew :: Storable a => a -> IO (DevicePtr a)\nnew v =\n let bytes = fromIntegral (F.sizeOf v) in\n forceEither `fmap` malloc bytes >>= \\dptr ->\n poke dptr v >>= \\rv ->\n case rv of\n Nothing -> return dptr\n Just s -> moduleErr \"new\" s\n\n\n-- |\n-- Write the list of storable elements into a newly allocated linear array on\n-- the device. The memory may be deallocated when no longer required.\n--\nnewArray :: Storable a => [a] -> IO (DevicePtr a)\nnewArray v =\n let bytes = fromIntegral (length v) * fromIntegral (F.sizeOf (head v)) in\n forceEither `fmap` malloc bytes >>= \\dptr ->\n pokeArray dptr v >>= \\rv ->\n case rv of\n Nothing -> return dptr\n Just s -> moduleErr \"newArray\" s\n\n\n-- |\n-- Execute a computation passing a pointer to a temporarily allocated block of\n-- device memory containing the value\n--\nwith :: Storable a => a -> (DevicePtr a -> IO b) -> IO b\nwith v f =\n alloca $ \\dptr ->\n poke dptr v >>= \\rv ->\n case rv of\n Nothing -> f dptr\n Just s -> moduleErr \"with\" s\n\n\n-- |\n-- Temporarily store a list of variable in device memory and operate on them\n--\nwithArray :: Storable a => [a] -> (DevicePtr a -> IO b) -> IO b\nwithArray vs f = withArrayLen vs (\\_ -> f)\n\n\n-- |\n-- Like 'withArray', but the action gets the number of values as an additional\n-- parameter\n--\nwithArrayLen :: Storable a => [a] -> (Int -> DevicePtr a -> IO b) -> IO b\nwithArrayLen vs f =\n let l = length vs\n b = fromIntegral l * fromIntegral (F.sizeOf (head vs))\n in\n allocaBytes b $ \\dptr ->\n pokeArray dptr vs >>= \\rv ->\n case rv of\n Nothing -> f l dptr\n Just s -> moduleErr \"withArray\" s\n\n\n--------------------------------------------------------------------------------\n-- Copying\n--------------------------------------------------------------------------------\n\n-- |\n-- Copy data between host and device\n--\nmemcpy :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> IO (Maybe String)\nmemcpy dst src bytes dir =\n nothingIfOk `fmap` cudaMemcpy dst src bytes dir\n\n{# fun unsafe cudaMemcpy\n { castPtr `Ptr a' ,\n castPtr `Ptr a' ,\n cIntConv `Int64' ,\n cFromEnum `CopyDirection' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Stream -- ^ asynchronous stream to operate over\n -> Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> IO (Maybe String)\nmemcpyAsync stream dst src bytes dir =\n nothingIfOk `fmap` cudaMemcpyAsync dst src bytes dir stream\n\n{# fun unsafe cudaMemcpyAsync\n { castPtr `Ptr a' ,\n castPtr `Ptr a' ,\n cIntConv `Int64' ,\n cFromEnum `CopyDirection' ,\n cIntConv `Stream' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal utilities\n--------------------------------------------------------------------------------\n\nmoduleErr :: String -> String -> a\nmoduleErr fun msg = error (\"Foreign.CUDA.\" ++ fun ++ ':':' ':msg)\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Marshal\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Memory allocation and marshalling support for CUDA devices\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Marshal\n (\n DevicePtr,\n withDevicePtr,\n\n -- ** Dynamic allocation\n --\n -- Basic methods to allocate a block of memory on the device. The memory\n -- should be deallocated using 'free' when no longer necessary. The\n -- advantage is that failed allocations will not raise an exception.\n --\n free,\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Local allocation\n --\n -- Execute a computation, passing as argument a pointer to a newly allocated\n -- block of memory. The memory is freed when the computation terminates.\n --\n alloca,\n allocaBytes,\n allocaBytesMemset,\n\n -- ** Marshalling\n --\n -- Store and retrieve Haskell lists as arrays on the device\n --\n peek,\n poke,\n peekArray,\n pokeArray,\n\n -- ** Combined allocation and marshalling\n --\n -- Write Haskell values (or lists) to newly allocated device memory. This\n -- may be a temporary store.\n --\n new,\n with,\n newArray,\n withArray,\n withArrayLen,\n\n -- ** Copying\n --\n -- Copy data between the host and device\n --\n )\n where\n\nimport Data.Int\nimport Control.Exception\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.ForeignPtr\nimport Foreign.Storable (Storable)\n\nimport qualified Foreign.Storable as F\nimport qualified Foreign.Marshal as F\n\nimport Foreign.CUDA.Utils\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Stream\nimport Foreign.CUDA.Internal.C2HS\n\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A reference to data stored on the device\n--\ntype DevicePtr a = ForeignPtr a\n\n-- |\n-- Unwrap the device pointer, yielding a device memory address that can be\n-- passed to a kernel function callable from the host code. This allows the type\n-- system to strictly separate host and device memory references, a non-obvious\n-- distinction in pure CUDA.\n--\nwithDevicePtr :: DevicePtr a -> (Ptr a -> IO b) -> IO b\nwithDevicePtr = withForeignPtr\n\n--\n-- Internal, unwrap and cast. Required as some functions such as memset work\n-- with untyped `void' data.\n--\nwithDevicePtr' :: DevicePtr a -> (Ptr b -> IO c) -> IO c\nwithDevicePtr' = withForeignPtr . castForeignPtr\n\nnewDevicePtr :: Ptr a -> IO (DevicePtr a)\nnewDevicePtr = newForeignPtr_\n\n\n--\n-- Memory copy\n--\n{# enum cudaMemcpyKind as CopyDirection {}\n with prefix=\"cudaMemcpy\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Dynamic allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate the specified number of bytes in linear memory on the device. The\n-- memory is suitably aligned for any kind of variable, and is not cleared.\n--\nmalloc :: Int64 -> IO (Either String (DevicePtr a))\nmalloc bytes = do\n (rv,ptr) <- cudaMalloc bytes\n case rv of\n Success -> Right `fmap` newDevicePtr (castPtr ptr)\n _ -> return . Left . describe $ rv\n\n{# fun unsafe cudaMalloc\n { alloca'- `Ptr ()' peek'* ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n where alloca' = F.alloca\n peek' = F.peek\n\n\n-- |\n-- Allocate at least @width * height@ bytes of linear memory on the device. The\n-- function may pad the allocation to ensure corresponding pointers in each row\n-- meet coalescing requirements. The actual allocation width is returned.\n--\nmalloc2D :: (Int64, Int64) -- ^ allocation (width,height) in bytes\n -> IO (Either String (DevicePtr a, Int64))\nmalloc2D (width,height) = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> (\\p -> Right (p,pitch)) `fmap` newDevicePtr (castPtr ptr)\n _ -> return . Left . describe $ rv\n\n{# fun unsafe cudaMallocPitch\n { alloca'- `Ptr ()' peek'* ,\n alloca'- `Int64' peekIntConv* ,\n cIntConv `Int64' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n where\n -- C->Haskell doesn't like qualified imports\n --\n alloca' :: Storable a => (Ptr a -> IO b) -> IO b\n alloca' = F.alloca\n peek' = F.peek\n\n\n-- |\n-- Allocate at least @width * height * depth@ bytes of linear memory on the\n-- device. The function may pad the allocation to ensure hardware alignment\n-- requirements are met. The actual allocation pitch is returned\n--\nmalloc3D :: (Int64,Int64,Int64) -- ^ allocation (width,height,depth) in bytes\n -> IO (Either String (DevicePtr a, Int64))\nmalloc3D = moduleErr \"malloc3D\" \"not implemented yet\"\n\n\n-- |\n-- Free previously allocated memory on the device\n--\nfree :: DevicePtr a -> IO (Maybe String)\nfree p = nothingIfOk `fmap` (withDevicePtr p cudaFree)\n\nfree_ :: Ptr a -> IO ()\nfree_ p = cudaFree p >>= \\rv ->\n case rv of\n Success -> return ()\n _ -> moduleErr \"free\" (describe rv)\n\n{# fun unsafe cudaFree\n { castPtr `Ptr a' } -> `Status' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr a -> IO ()) -> IO (FunPtr (Ptr a -> IO ()))\n\n\n-- |\n-- Initialise device memory to a given value\n--\nmemset :: DevicePtr a -- ^ The device memory\n -> Int64 -- ^ Number of bytes\n -> Int -- ^ Value to set for each byte\n -> IO (Maybe String)\nmemset ptr bytes symbol =\n nothingIfOk `fmap` cudaMemset ptr symbol bytes\n\n{# fun unsafe cudaMemset\n { withDevicePtr'* `DevicePtr a' ,\n `Int' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Initialise a matrix to a given value\n--\nmemset2D :: DevicePtr a -- ^ The device memory\n -> (Int64, Int64) -- ^ The (width,height) of the matrix in bytes\n -> Int64 -- ^ The allocation pitch, as returned by 'malloc2D'\n -> Int -- ^ Value to set for each byte\n -> IO (Maybe String)\nmemset2D ptr (width,height) pitch symbol =\n nothingIfOk `fmap` cudaMemset2D ptr pitch symbol width height\n\n{# fun unsafe cudaMemset2D\n { withDevicePtr'* `DevicePtr a' ,\n cIntConv `Int64' ,\n `Int' ,\n cIntConv `Int64' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Initialise the elements of a 3D array to a given value\n--\nmemset3D :: DevicePtr a -- ^ The device memory\n -> (Int64,Int64,Int64) -- ^ The (width,height,depth) of the array in bytes\n -> Int64 -- ^ The allocation pitch, as returned by 'malloc3D'\n -> Int -- ^ Value to set for each byte\n -> IO (Maybe String)\nmemset3D = moduleErr \"memset3D\" \"not implemented yet\"\n\n\n--------------------------------------------------------------------------------\n-- Local allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Execute a computation, passing a pointer to a temporarily allocated block of\n-- memory\n--\nalloca :: Storable a => (DevicePtr a -> IO b) -> IO b\nalloca = doAlloca undefined\n where\n doAlloca :: Storable a' => a' -> (DevicePtr a' -> IO b') -> IO b'\n doAlloca x = allocaBytes (fromIntegral (F.sizeOf x))\n\n\n-- |\n-- Execute a computation, passing a pointer to a block of 'n' bytes of memory\n--\nallocaBytes :: Int64 -> (DevicePtr a -> IO b) -> IO b\nallocaBytes bytes =\n bracket (forceEither `fmap` malloc bytes) free\n\n\n-- |\n-- Execute a computation, passing a pointer to a block of memory initialised to\n-- a given value\n--\nallocaBytesMemset :: Int64 -> Int -> (DevicePtr a -> IO b) -> IO b\nallocaBytesMemset bytes symbol f =\n allocaBytes bytes $ \\dptr ->\n memset dptr bytes symbol >>= \\rv ->\n case rv of\n Nothing -> f dptr\n Just e -> error e\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Retrieve the specified value from device memory\n--\npeek :: Storable a => DevicePtr a -> IO (Either String a)\npeek d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO (Either String a')\n doPeek x = F.alloca $ \\hptr ->\n withDevicePtr' d $ \\dptr ->\n memcpy hptr dptr (fromIntegral (F.sizeOf x)) DeviceToHost >>= \\rv ->\n case rv of\n Nothing -> Right `fmap` F.peek hptr\n Just s -> return (Left s)\n\n\n-- |\n-- Retrieve the specified number of elements from device memory and return as a\n-- Haskell list\n--\npeekArray :: Storable a => Int -> DevicePtr a -> IO (Either String [a])\npeekArray n d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO (Either String [a'])\n doPeek x = let bytes = fromIntegral n * (fromIntegral (F.sizeOf x)) in\n F.allocaArray n $ \\hptr ->\n withDevicePtr' d $ \\dptr ->\n memcpy hptr dptr bytes DeviceToHost >>= \\rv ->\n case rv of\n Nothing -> Right `fmap` F.peekArray n hptr\n Just s -> return (Left s)\n\n\n-- |\n-- Store the given value to device memory\n--\npoke :: Storable a => DevicePtr a -> a -> IO (Maybe String)\npoke d v =\n F.with v $ \\hptr ->\n withDevicePtr d $ \\dptr ->\n memcpy dptr hptr (fromIntegral (F.sizeOf v)) HostToDevice\n\n\n-- |\n-- Store the list elements consecutively in device memory\n--\npokeArray :: Storable a => DevicePtr a -> [a] -> IO (Maybe String)\npokeArray d = doPoke undefined\n where\n doPoke :: Storable a' => a' -> [a'] -> IO (Maybe String)\n doPoke x v = F.withArrayLen v $ \\n hptr ->\n withDevicePtr' d $ \\dptr ->\n let bytes = (fromIntegral n) * (fromIntegral (F.sizeOf x)) in\n memcpy dptr hptr bytes HostToDevice\n\n\n--------------------------------------------------------------------------------\n-- Combined allocation and marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a block of memory on the device and transfer a value into it. The\n-- memory may be deallocated using 'free' when no longer required.\n--\nnew :: Storable a => a -> IO (DevicePtr a)\nnew v =\n let bytes = fromIntegral (F.sizeOf v) in\n forceEither `fmap` malloc bytes >>= \\dptr ->\n poke dptr v >>= \\rv ->\n case rv of\n Nothing -> return dptr\n Just s -> moduleErr \"new\" s\n\n\n-- |\n-- Write the list of storable elements into a newly allocated linear array on\n-- the device. The memory may be deallocated when no longer required.\n--\nnewArray :: Storable a => [a] -> IO (DevicePtr a)\nnewArray v =\n let bytes = fromIntegral (length v) * fromIntegral (F.sizeOf (head v)) in\n forceEither `fmap` malloc bytes >>= \\dptr ->\n pokeArray dptr v >>= \\rv ->\n case rv of\n Nothing -> return dptr\n Just s -> moduleErr \"newArray\" s\n\n\n-- |\n-- Execute a computation passing a pointer to a temporarily allocated block of\n-- device memory containing the value\n--\nwith :: Storable a => a -> (DevicePtr a -> IO b) -> IO b\nwith v f =\n alloca $ \\dptr ->\n poke dptr v >>= \\rv ->\n case rv of\n Nothing -> f dptr\n Just s -> moduleErr \"with\" s\n\n\n-- |\n-- Temporarily store a list of variable in device memory and operate on them\n--\nwithArray :: Storable a => [a] -> (DevicePtr a -> IO b) -> IO b\nwithArray vs f = withArrayLen vs (\\_ -> f)\n\n\n-- |\n-- Like 'withArray', but the action gets the number of values as an additional\n-- parameter\n--\nwithArrayLen :: Storable a => [a] -> (Int -> DevicePtr a -> IO b) -> IO b\nwithArrayLen vs f =\n let l = length vs\n b = fromIntegral l * fromIntegral (F.sizeOf (head vs))\n in\n allocaBytes b $ \\dptr ->\n pokeArray dptr vs >>= \\rv ->\n case rv of\n Nothing -> f l dptr\n Just s -> moduleErr \"withArray\" s\n\n\n--------------------------------------------------------------------------------\n-- Copying\n--------------------------------------------------------------------------------\n\n-- |\n-- Copy data between host and device\n--\nmemcpy :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> IO (Maybe String)\nmemcpy dst src bytes dir =\n nothingIfOk `fmap` cudaMemcpy dst src bytes dir\n\n{# fun unsafe cudaMemcpy\n { castPtr `Ptr a' ,\n castPtr `Ptr a' ,\n cIntConv `Int64' ,\n cFromEnum `CopyDirection' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Stream -- ^ asynchronous stream to operate over\n -> Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> IO (Maybe String)\nmemcpyAsync stream dst src bytes dir =\n nothingIfOk `fmap` cudaMemcpyAsync dst src bytes dir stream\n\n{# fun unsafe cudaMemcpyAsync\n { castPtr `Ptr a' ,\n castPtr `Ptr a' ,\n cIntConv `Int64' ,\n cFromEnum `CopyDirection' ,\n cIntConv `Stream' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal utilities\n--------------------------------------------------------------------------------\n\nmoduleErr :: String -> String -> a\nmoduleErr fun msg = error (\"Foreign.CUDA.\" ++ fun ++ ':':' ':msg)\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"591f4e409809bbeab45c7b692097afaec38ebea2","subject":"Removed commented-off line since it interfered with Haddock","message":"Removed commented-off line since it interfered with Haddock\n","repos":"TomMD\/CV,BeautifulDestinations\/CV,aleator\/CV,aleator\/CV","old_file":"CV\/Image.chs","new_file":"CV\/Image.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns,ParallelListComp, FlexibleInstances, FlexibleContexts, TypeFamilies, EmptyDataDecls, ScopedTypeVariables, StandaloneDeriving, DeriveDataTypeable, UndecidableInstances, MultiParamTypeClasses #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, MutableImage(..)\n, Mask\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\n, withMask\n, withMutableClone\n, withCloneValue\n, CreateImage\n, Save(..)\n\n-- * Colour spaces\n, ChannelOf\n, GrayScale\n, Complex\n, BGR\n, RGB\n, RGBA\n, RGB_Channel(..)\n, LAB\n, LAB_Channel(..)\n, D32\n, D64\n, D8\n, Tag\n, lab\n, rgba\n, rgb\n, compose\n, composeMultichannelImage\n\n-- * IO operations\n, Loadable(..)\n, saveImage\n, loadColorImage\n, loadImage\n\n-- * Pixel level access\n, GetPixel(..)\n, SetPixel(..)\n, safeGetPixel\n, getAllPixels\n, getAllPixelsRowMajor\n, mapImageInplace\n\n-- * Image information\n, ImageDepth\n, Sized(..)\n, biggerThan\n, getArea\n, getChannel\n, getImageChannels\n, getImageDepth\n, getImageInfo\n\n-- * ROI's, COI's and subregions\n, setCOI\n, setROI\n, resetROI\n, getRegion\n, withIOROI\n--, withROI\n\n-- * Blitting\n, blendBlit\n, blit\n, blitM\n, subPixelBlit\n, safeBlit\n, montage\n, tileImages\n\n-- * Conversions\n, rgbToGray\n, rgbToGray8\n, grayToRGB\n, rgbToLab\n, bgrToRgb\n, rgbToBgr\n, cloneTo64F\n, unsafeImageTo32F \n, unsafeImageTo64F \n, unsafeImageTo8Bit \n\n-- * Low level access operations\n, BareImage(..)\n, creatingImage\n, unImage\n, unS\n, withGenBareImage\n, withBareImage\n, creatingBareImage\n, withGenImage\n, withImage\n, withMutableImage\n, withRawImageData\n, imageFPTR\n, ensure32F\n\n-- * Extended error handling\n, setCatch\n, CvException\n, CvSizeError(..)\n, CvIOError(..)\n) where\n\nimport System.Mem\nimport System.Directory\nimport System.FilePath\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Utils\nimport Foreign.ForeignPtr hiding (newForeignPtr,unsafeForeignPtrToPtr)\nimport Foreign.Concurrent\nimport Foreign.Ptr\nimport Control.Parallel.Strategies\nimport Control.DeepSeq\nimport Control.Lens\n\nimport CV.Bindings.Error\n\nimport Data.Maybe(catMaybes)\nimport Data.List(genericLength)\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)\nimport Foreign.Storable\nimport System.IO.Unsafe\nimport Data.Word\nimport qualified Data.Complex as C\nimport Control.Monad\nimport Control.Exception\nimport Data.Data\nimport Data.Typeable\n\nimport Utils.GeometryClass\nimport Control.Applicative hiding (empty)\n\n\n\n\n-- Colorspaces\n\n-- | Single channel grayscale image\ndata GrayScale\ndata Complex\ndata RGB\ndata RGB_Channel = Red |\u00a0Green |\u00a0Blue deriving (Eq,Ord,Enum)\n\ndata BGR\n\ndata LAB\ndata RGBA\ndata LAB_Channel = LAB_L |\u00a0LAB_A |\u00a0LAB_B deriving (Eq,Ord,Enum)\n\n-- | Type family for expressing which channels a colorspace contains. This needs to be fixed wrt. the BGR color space.\ntype family ChannelOf a :: *\ntype instance ChannelOf RGB_Channel = RGB\ntype instance ChannelOf LAB_Channel = LAB\n\n-- Bit Depths\ntype D8 = Word8\ntype D32 = Float\ntype D64 = Double\n\n-- | The type for Images\nnewtype Image channels depth = S BareImage\nnewtype MutableImage channels depth = Mutable (Image channels depth)\n\n-- | Alias for images used as masks\ntype Mask = Maybe (Image GrayScale D8)\n\n-- |\u00a0Remove typing info from an image\nunS (S i) = i -- Unsafe and ugly\n\nimageFPTR :: Image c d -> ForeignPtr BareImage\nimageFPTR (S (BareImage fptr)) = fptr\n\nwithImage :: Image c d -> (Ptr BareImage ->IO a) -> IO a\nwithImage (S i) op = withBareImage i op\n--withGenNewImage (S i) op = withGenImage i op\n\nwithRawImageData :: Image c d -> (Int -> Ptr Word8 -> IO a) -> IO a\nwithRawImageData (S i) op = withBareImage i $ \\pp-> do\n d <- {#get IplImage->imageData#} pp \n wd <- {#get IplImage->widthStep#} pp\n op (fromIntegral wd) (castPtr d)\n\n-- Ok. this is just the example why I need image types\nwithUniPtr with x fun = with x $ \\y ->\n fun (castPtr y)\n\nwithGenImage :: Image c d -> (Ptr b -> IO a) -> IO a\nwithGenImage = withUniPtr withImage\n\n-- |\u00a0This function converts masks to pointers. Masks which are nothing are converted\n-- to null pointers.\nwithMask :: Mask -> (Ptr b -> IO a) -> IO a\nwithMask (Just i) op = withUniPtr withImage i op\nwithMask Nothing op = op nullPtr\n\nwithMutableImage :: MutableImage c d -> (Ptr b -> IO a) -> IO a\nwithMutableImage (Mutable i) o = withGenImage i o\n\nwithGenBareImage :: BareImage -> (Ptr b -> IO a) -> IO a\nwithGenBareImage = withUniPtr withBareImage\n\n{#pointer *IplImage as BareImage foreign newtype#}\n\nfreeBareImage ptr = with ptr {#call cvReleaseImage#}\n\n--foreign import ccall \"& wrapReleaseImage\" releaseImage :: FinalizerPtr BareImage\n\ninstance NFData (Image a b) where\n rnf a@(S (BareImage fptr)) = (unsafeForeignPtrToPtr) fptr `seq` a `seq` ()-- This might also need peek?\n\n\ncreatingImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . S . BareImage $ fptr\n\ncreatingBareImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . BareImage $ fptr\n\nunImage (S (BareImage fptr)) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\nrgba = undefined :: Tag RGBA\nlab = undefined :: Tag LAB\n\n-- | Typeclass for elements that are build from component elements. For example,\n-- RGB images can be constructed from three grayscale images.\nclass Composes a where\n type Source a :: *\n compose :: Source a -> a\n\ninstance (CreateImage (Image RGBA a)) => Composes (Image RGBA a) where\n type Source (Image RGBA a) = (Image GrayScale a, Image GrayScale a\n ,Image GrayScale a, Image GrayScale a)\n compose (r,g,b,a) = composeMultichannelImage (Just b) (Just g) (Just r) (Just a) rgba\n\ninstance (CreateImage (Image RGB a)) => Composes (Image RGB a) where\n type Source (Image RGB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (r,g,b) = composeMultichannelImage (Just b) (Just g) (Just r) Nothing rgb\n\ninstance (CreateImage (Image LAB a)) => Composes (Image LAB a) where\n type Source (Image LAB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (l,a,b) = composeMultichannelImage (Just l) (Just a) (Just b) Nothing lab\n\n{-# DEPRECATED composeMultichannelImage \"This is unsafe. Use compose instead\" #-}\ncomposeMultichannelImage :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannelImage = composeMultichannel\n\ncomposeMultichannel :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannel (c2)\n (c1)\n (c3)\n (c4)\n totag\n = unsafePerformIO $\u00a0do\n res <- create (size) -- TODO: Check channel count -- This is NOT correct\n withMaybe c1 $ \\cc1 ->\n withMaybe c2 $ \\cc2 ->\n withMaybe c3 $ \\cc3 ->\n withMaybe c4 $ \\cc4 ->\n withGenImage res $ \\cres -> {#call cvMerge#} cc1 cc2 cc3 cc4 cres\n return res\n where\n withMaybe (Just i) op = withGenImage i op\n withMaybe (Nothing) op = op nullPtr\n size = getSize . head . catMaybes $ [c1,c2,c3,c4]\n\n\n-- | Typeclass for CV items that can be read from file. Mainly images at this point.\nclass Loadable a where\n readFromFile :: FilePath -> IO a\n\n\ninstance Loadable ((Image GrayScale D32)) where\n readFromFile fp = do\n e <- loadImage fp\n case e of\n Just i -> return i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D32)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ unsafeImageTo32F $ bgrToRgb i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D8)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ bgrToRgb i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image GrayScale D8)) where\n readFromFile fp = do\n e <- loadImage8 fp\n case e of\n Just i -> return i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\n\n-- | This function loads and converts image to an arbitrary format. Notice that it is\n-- polymorphic enough to cause run time errors if the declared and actual types of the\n-- images do not match. Use with care.\nunsafeloadUsing x p n = do\n exists <- doesFileExist n\n if not exists then return Nothing\n else do\n i <- withCString n $ \\name ->\n creatingBareImage ({#call cvLoadImage #} name p)\n bw <- x i\n return . Just .\u00a0S $ bw\n\nloadImage :: FilePath -> IO (Maybe (Image GrayScale D32))\nloadImage = unsafeloadUsing imageTo32F 0\nloadImage8 :: FilePath -> IO (Maybe (Image GrayScale D8))\nloadImage8 = unsafeloadUsing imageTo8Bit 0\nloadColorImage :: FilePath -> IO (Maybe (Image BGR D32))\nloadColorImage = unsafeloadUsing imageTo32F 1\nloadColorImage8 :: FilePath -> IO (Maybe (Image BGR D8))\nloadColorImage8 = unsafeloadUsing imageTo8Bit 1\n\n\ninstance Sized (MutableImage a b) where\n type Size (MutableImage a b) = IO (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize (Mutable i) = evaluate (deep (getSize i))\n\ndeep a = a `deepseq` a\n\ninstance Sized BareImage where\n type Size BareImage = (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize image = unsafePerformIO $ withBareImage image $ \\i -> do\n w <- {#call getImageWidth#} i\n h <- {#call getImageHeight#} i\n return (fromIntegral w,fromIntegral h)\n\ninstance Sized (Image c d) where\n type Size (Image c d) = (Int,Int)\n getSize = getSize . unS\n\n\ncvRGBtoGRAY = 7 :: CInt-- NOTE: This will break.\ncvRGBtoLAB = 45 :: CInt-- NOTE: This will break.\n\n\n#c\nenum CvtFlags {\n CvtFlip = CV_CVTIMG_FLIP,\n CvtSwapRB = CV_CVTIMG_SWAP_RB\n };\n#endc\n\n#c\nenum CvtCodes {\n CV_BGR2BGRA =0,\n CV_RGB2RGBA =CV_BGR2BGRA,\n\n CV_BGRA2BGR =1,\n CV_RGBA2RGB =CV_BGRA2BGR,\n\n CV_BGR2RGBA =2,\n CV_RGB2BGRA =CV_BGR2RGBA,\n\n CV_RGBA2BGR =3,\n CV_BGRA2RGB =CV_RGBA2BGR,\n\n CV_BGR2RGB =4,\n CV_RGB2BGR =CV_BGR2RGB,\n\n CV_BGRA2RGBA =5,\n CV_RGBA2BGRA =CV_BGRA2RGBA,\n\n CV_BGR2GRAY =6,\n CV_RGB2GRAY =7,\n CV_GRAY2BGR =8,\n CV_GRAY2RGB =CV_GRAY2BGR,\n CV_GRAY2BGRA =9,\n CV_GRAY2RGBA =CV_GRAY2BGRA,\n CV_BGRA2GRAY =10,\n CV_RGBA2GRAY =11,\n\n CV_BGR2BGR565 =12,\n CV_RGB2BGR565 =13,\n CV_BGR5652BGR =14,\n CV_BGR5652RGB =15,\n CV_BGRA2BGR565 =16,\n CV_RGBA2BGR565 =17,\n CV_BGR5652BGRA =18,\n CV_BGR5652RGBA =19,\n\n CV_GRAY2BGR565 =20,\n CV_BGR5652GRAY =21,\n\n CV_BGR2BGR555 =22,\n CV_RGB2BGR555 =23,\n CV_BGR5552BGR =24,\n CV_BGR5552RGB =25,\n CV_BGRA2BGR555 =26,\n CV_RGBA2BGR555 =27,\n CV_BGR5552BGRA =28,\n CV_BGR5552RGBA =29,\n\n CV_GRAY2BGR555 =30,\n CV_BGR5552GRAY =31,\n\n CV_BGR2XYZ =32,\n CV_RGB2XYZ =33,\n CV_XYZ2BGR =34,\n CV_XYZ2RGB =35,\n\n CV_BGR2YCrCb =36,\n CV_RGB2YCrCb =37,\n CV_YCrCb2BGR =38,\n CV_YCrCb2RGB =39,\n\n CV_BGR2HSV =40,\n CV_RGB2HSV =41,\n\n CV_BGR2Lab =44,\n CV_RGB2Lab =45,\n\n CV_BayerBG2BGR =46,\n CV_BayerGB2BGR =47,\n CV_BayerRG2BGR =48,\n CV_BayerGR2BGR =49,\n\n CV_BayerBG2RGB =CV_BayerRG2BGR,\n CV_BayerGB2RGB =CV_BayerGR2BGR,\n CV_BayerRG2RGB =CV_BayerBG2BGR,\n CV_BayerGR2RGB =CV_BayerGB2BGR,\n\n CV_BGR2Luv =50,\n CV_RGB2Luv =51,\n CV_BGR2HLS =52,\n CV_RGB2HLS =53,\n\n CV_HSV2BGR =54,\n CV_HSV2RGB =55,\n\n CV_Lab2BGR =56,\n CV_Lab2RGB =57,\n CV_Luv2BGR =58,\n CV_Luv2RGB =59,\n CV_HLS2BGR =60,\n CV_HLS2RGB =61,\n\n CV_BayerBG2BGR_VNG =62,\n CV_BayerGB2BGR_VNG =63,\n CV_BayerRG2BGR_VNG =64,\n CV_BayerGR2BGR_VNG =65,\n\n CV_BayerBG2RGB_VNG =CV_BayerRG2BGR_VNG,\n CV_BayerGB2RGB_VNG =CV_BayerGR2BGR_VNG,\n CV_BayerRG2RGB_VNG =CV_BayerBG2BGR_VNG,\n CV_BayerGR2RGB_VNG =CV_BayerGB2BGR_VNG,\n\n CV_BGR2HSV_FULL = 66,\n CV_RGB2HSV_FULL = 67,\n CV_BGR2HLS_FULL = 68,\n CV_RGB2HLS_FULL = 69,\n\n CV_HSV2BGR_FULL = 70,\n CV_HSV2RGB_FULL = 71,\n CV_HLS2BGR_FULL = 72,\n CV_HLS2RGB_FULL = 73,\n\n CV_LBGR2Lab = 74,\n CV_LRGB2Lab = 75,\n CV_LBGR2Luv = 76,\n CV_LRGB2Luv = 77,\n\n CV_Lab2LBGR = 78,\n CV_Lab2LRGB = 79,\n CV_Luv2LBGR = 80,\n CV_Luv2LRGB = 81,\n\n CV_BGR2YUV = 82,\n CV_RGB2YUV = 83,\n CV_YUV2BGR = 84,\n CV_YUV2RGB = 85,\n\n CV_COLORCVT_MAX =100\n};\n#endc\n\n{#enum CvtCodes {}#}\n\n{#enum CvtFlags {}#}\n\n\nrgbToLab :: Image RGB D32 -> Image LAB D32\nrgbToLab = S . convertTo cvRGBtoLAB 3 . unS\n\nrgbToGray :: Image RGB D32 -> Image GrayScale D32\nrgbToGray = S . convertTo cvRGBtoGRAY 1 . unS\n\nrgbToGray8 :: Image RGB D8 -> Image GrayScale D8\nrgbToGray8 = S . convert8UTo cvRGBtoGRAY 1 . unS\n\ngrayToRGB :: Image GrayScale D32 -> Image RGB D32\ngrayToRGB = S . convertTo (fromIntegral . fromEnum $ CV_GRAY2BGR) 3 . unS\n\n\nbgrToRgb :: Image BGR D8 -> Image RGB D8\nbgrToRgb = S . swapRB . unS\n\nrgbToBgr :: Image RGB D8 -> Image BGR D8\nrgbToBgr = S . swapRB . unS\n\nswapRB :: BareImage -> BareImage\nswapRB img = unsafePerformIO $ do\n res <- cloneBareImage img\n withBareImage img $ \\cimg ->\n withBareImage res $ \\cres ->\n {#call cvConvertImage#} (castPtr cimg) (castPtr cres) (fromIntegral . fromEnum $ CvtSwapRB)\n return res\n\n\nsafeGetPixel :: (Sized image, Size image ~ (Int,Int), GetPixel image) => (P image) -> (Int,Int) -> image -> P image\nsafeGetPixel def (x,y) i |\u00a0x<0 || x>= w || y<0 || y>=h = def\n | otherwise = getPixel (x,y) i\n where\n (w,h) = getSize i\n -- (x',y') = (clamp (0,w-1) x, clamp (0,h-1) y)\n\nclamp :: Ord a => (a, a) -> a -> a\nclamp (a,b) x = max a (min b x)\n\ninstance (NFData (P (Image a b)), GetPixel (Image a b)) => GetPixel (MutableImage a b) where\n type P (MutableImage a b) = IO (P (Image a b))\n getPixel xy (Mutable i) = let p = getPixel xy i\n in p `deepseq` return p\n\nclass GetPixel a where\n type P a :: *\n getPixel :: (Int,Int) -> a -> P a\n\n-- #define FGET(img,x,y) (((float *)((img)->imageData + (y)*(img)->widthStep))[(x)])\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Float))):: Ptr Float)\n\ninstance GetPixel (Image GrayScale D8) where\n type P (Image GrayScale D8) = D8\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Word8))):: Ptr Word8)\n\ninstance GetPixel (Image Complex D32) where\n type P (Image Complex D32) = C.Complex D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n re <- peek (castPtr (d`plusPtr` (y*cs + x*2*fs)))\n im <- peek (castPtr (d`plusPtr` (y*cs +(x*2+1)*fs)))\n return (re C.:+ im)\n\n-- #define UGETC(img,color,x,y) (((uint8_t *)((img)->imageData + (y)*(img)->widthStep))[(x)*3+(color)])\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\ninstance GetPixel (Image BGR D32) where\n type P (Image BGR D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\ninstance GetPixel (Image BGR D8) where\n type P (Image BGR D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image RGB D8) where\n type P (Image RGB D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image LAB D32) where\n type P (Image LAB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n l <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n a <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n b <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (l,a,b)\n\n-- | Perform (a destructive) inplace map of the image. This should be wrapped inside\n-- withClone or an image operation\nmapImageInplace :: (P (Image GrayScale D32) -> P (Image GrayScale D32))\n -> MutableImage GrayScale D32\n -> IO ()\nmapImageInplace f image = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n (w,h) <- getSize image\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n forM_ [(x,y) | x<-[0..w-1], y <- [0..h-1]] $ \\(x,y) ->\u00a0do\n v <- peek (castPtr (d `plusPtr` (y*cs+x*fs)))\n poke (castPtr (d `plusPtr` (y*cs+x*fs))) (f v)\n\n\n\nconvert8UTo :: CInt -> CInt -> BareImage -> BareImage\nconvert8UTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage8U#} w h channels\n withBareImage img $ \\cimg ->\n {#call cvCvtColor#} (castPtr cimg) (castPtr res) code\n return res\n where\n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\nconvertTo :: CInt -> CInt -> BareImage -> BareImage\nconvertTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage32F#} w h channels\n withBareImage img $ \\cimg ->\n {#call cvCvtColor#} (castPtr cimg) (castPtr res) code\n return res\n where\n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\n-- |\u00a0Class for images that exist.\nclass CreateImage a where\n -- | Create an image from size\n create :: (Int,Int) -> IO a\n\ncreateWith :: CreateImage (Image c d) => (Int,Int) -> (MutableImage c d -> IO (MutableImage c d)) -> IO (Image c d)\ncreateWith s f = do\n c <- create s\n Mutable r <- f (Mutable c)\n return r\n\n\n\n\ninstance CreateImage (Image GrayScale D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image Complex D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 2\ninstance CreateImage (Image LAB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image c d) => CreateImage (MutableImage c d) where\n create s = Mutable <$> create s\n\n\n-- | Allocate a new empty image\nempty :: (CreateImage (Image a b)) => (Int,Int) -> (Image a b)\nempty size = unsafePerformIO $ create size\n\n-- |\u00a0Allocate a new image that of the same size and type as the exemplar image given.\nemptyCopy :: (CreateImage (Image a b)) => Image a b -> (Image a b)\nemptyCopy img = unsafePerformIO $ create (getSize img)\n\nemptyCopy' :: (CreateImage (Image a b)) => Image a b -> IO (Image a b)\nemptyCopy' img = create (getSize img)\n\n-- | Save image. This will convert the image to 8 bit one before saving\nclass Save a where\n save :: FilePath -> a -> IO ()\n\ninstance Save (Image BGR D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image)\n\ninstance Save (Image RGB D32) where\n save filename image = primitiveSave filename (swapRB . unS . unsafeImageTo8Bit $ image)\n\ninstance Save (Image RGB D8) where\n save filename image = primitiveSave filename (swapRB . unS $ image)\n\ninstance Save (Image GrayScale D8) where\n save filename image = primitiveSave filename (unS $ image)\n\ninstance Save (Image GrayScale D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image)\n\nprimitiveSave :: FilePath -> BareImage -> IO ()\nprimitiveSave filename fpi = do\n exists <- doesDirectoryExist (takeDirectory filename)\n when (not exists) $\u00a0throw (CvIOError $ \"Directory does not exist: \" ++ (takeDirectory filename))\n withCString filename $ \\name ->\n withGenBareImage fpi $ \\cvArr ->\n alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\n-- |Save an image as 8 bit gray scale\nsaveImage :: (Save (Image c d)) => FilePath -> Image c d -> IO ()\nsaveImage = save\n\ngetArea :: (Sized a,Num b, Size a ~ (b,b)) => a -> b\ngetArea = uncurry (*).getSize\n\ngetRegion :: (Int,Int) -> (Int,Int) -> Image c d -> Image c d\ngetRegion (fromIntegral -> x,fromIntegral -> y) (fromIntegral -> w,fromIntegral -> h) image\n | x+w <= width && y+h <= height = S . getRegion' (x,y) (w,h) $ unS image\n | otherwise = error $ \"Region outside image:\"\n ++ show (getSize image) ++\n \"\/\"++show (x+w,y+h)\n where\n (fromIntegral -> width,fromIntegral -> height) = getSize image\n\ngetRegion' (x,y) (w,h) image = unsafePerformIO $\n withBareImage image $ \\i ->\n creatingBareImage ({#call getSubImage#}\n i x y w h)\n\n\n-- | Tile images by overlapping them on a black canvas.\ntileImages image1 image2 (x,y) = unsafePerformIO $\n withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n creatingImage ({#call simpleMergeImages#}\n i1 i2 x y)\n-- | Blit image2 onto image1.\nclass Blittable channels depth \ninstance Blittable GrayScale D32\ninstance Blittable RGB D32\n\nblit :: Blittable c d => MutableImage c d -> Image c d -> (Int,Int) -> IO ()\nblit image1 image2 (x,y) = do\n (w1,h1) <- getSize image1\n let ((w2,h2)) = getSize image2\n if x+w2>w1 || y+h2>h1 || x<0 || y<0\n then error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n else withMutableImage image1 $ \\i1 ->\n withImage image2 $ \\i2 -> \n ({#call plainBlit#} i1 i2 (fromIntegral y) (fromIntegral x))\n\n-- | Create an image by blitting multiple images onto an empty image.\nblitM :: (CreateImage (MutableImage GrayScale D32)) => \n (Int,Int) -> [((Int,Int),Image GrayScale D32)] -> Image GrayScale D32\nblitM (rw,rh) imgs = unsafePerformIO $ resultPic >>= fromMutable \n where\n resultPic = do\n r <- create (fromIntegral rw,fromIntegral rh)\n sequence_ [blit r i (fromIntegral x, fromIntegral y)\n | ((x,y),i) <- imgs ]\n return r\n\n\nsubPixelBlit :: MutableImage c d -> Image c d -> (CDouble, CDouble) -> IO ()\nsubPixelBlit (image1) (image2) (x,y) = do\n (w1,h1) <- getSize image1\n let ((w2,h2)) = getSize image2\n if ceiling x+w2>w1 || ceiling y+h2>h1 ||\u00a0x<0 || y<0\n then error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n else withMutableImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call subpixel_blit#} i1 i2 y x)\n\nsafeBlit i1 i2 (x,y) = unsafePerformIO $ do\n res <- toMutable i1-- createImage32F (getSize i1) 1\n blit res i2 (x,y)\n return res\n\n-- | Blit image2 onto image1.\n-- This uses an alpha channel bitmap for determining the regions where the image should be \"blended\" with\n-- the base image.\nblendBlit :: MutableImage c d -> Image c1 d1 -> Image c3 d3 -> Image c2 d2\n -> (CInt, CInt) -> IO ()\nblendBlit image1 image1Alpha image2 image2Alpha (x,y) =\n withMutableImage image1 $ \\i1 ->\n withImage image1Alpha $ \\i1a ->\n withImage image2Alpha $ \\i2a ->\n withImage image2 $ \\i2 ->\n ({#call alphaBlit#} i1 i1a i2 i2a y x)\n\n\n-- | Create a copy of an image\ncloneImage :: Image a b -> IO (Image a b)\ncloneImage img = withGenImage img $ \\image ->\n creatingImage ({#call cvCloneImage #} image)\n\ntoMutable :: Image a b -> IO (MutableImage a b)\ntoMutable img = withGenImage img $ \\image ->\n Mutable <$>\u00a0creatingImage ({#call cvCloneImage #} image)\n\nfromMutable :: MutableImage a b -> IO (Image a b)\nfromMutable (Mutable img) = cloneImage img \n\n-- | Create a copy of a non-types image\ncloneBareImage :: BareImage -> IO BareImage\ncloneBareImage img = withGenBareImage img $ \\image ->\n creatingBareImage ({#call cvCloneImage #} image)\n\nwithMutableClone\n :: Image channels depth\n -> (MutableImage channels depth -> IO a)\n -> IO a\nwithMutableClone img fun = do\n result <- toMutable img\n fun result\n\nwithClone\n :: Image channels depth\n -> (Image channels depth -> IO ())\n -> IO (Image channels depth)\nwithClone img fun = do\n result <- cloneImage img\n fun result\n return result\n\nwithCloneValue\n :: Image channels depth\n -> (Image channels depth -> IO a)\n -> IO a\nwithCloneValue img fun = do\n result <- cloneImage img\n r <- fun result\n return r\n\ncloneTo64F :: Image c d -> IO (Image c D64)\ncloneTo64F img = withGenImage img $ \\image ->\n creatingImage\n ({#call ensure64F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 64 bit, floating point, image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image. \nunsafeImageTo64F :: Image c d -> Image c D64\nunsafeImageTo64F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure64F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 32 bit, floating point, image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image. \nunsafeImageTo32F :: Image c d -> Image c D32\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure32F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 8 bit image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image. \nunsafeImageTo8Bit :: Image cspace a -> Image cspace D8\nunsafeImageTo8Bit img =\n unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage ({#call ensure8U #} image)\n\n--toD32 :: Image c d -> Image c D32\n--toD32 i =\n-- unsafePerformIO $\n-- withImage i $ \\i_ptr ->\n-- creatingImage\n\n\nimageTo32F img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure32F #} image)\n\nimageTo8Bit img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure8U #} image)\n#c\nenum ImageDepth {\n Depth32F = IPL_DEPTH_32F,\n Depth64F = IPL_DEPTH_64F,\n Depth8U = IPL_DEPTH_8U,\n Depth8S = IPL_DEPTH_8S,\n Depth16U = IPL_DEPTH_16U,\n Depth16S = IPL_DEPTH_16S,\n Depth32S = IPL_DEPTH_32S\n };\n#endc\n\n{#enum ImageDepth {}#}\n\nderiving instance Show ImageDepth\n\ngetImageDepth :: Image c d -> IO ImageDepth\ngetImageDepth i = withImage i $ \\c_img -> {#get IplImage->depth #} c_img >>= return.toEnum.fromIntegral\ngetImageChannels i = withImage i $ \\c_img -> {#get IplImage->nChannels #} c_img\n\ngetImageInfo x = do\n let s = getSize x\n d <- getImageDepth x\n c <- getImageChannels x\n return (s,d,c)\n\n\n-- | Set the region of interest for a mutable image\nsetROI :: (Integral a) => (a,a) -> (a,a) -> MutableImage c d -> IO ()\nsetROI (fromIntegral -> x,fromIntegral -> y)\n (fromIntegral -> w,fromIntegral -> h)\n image = withMutableImage image $ \\i ->\n {#call wrapSetImageROI#} i x y w h\n\n-- | Set the region of interest to cover the entire image.\nresetROI :: MutableImage c d -> IO ()\nresetROI image = withMutableImage image $ \\i ->\n {#call cvResetImageROI#} i\n\nsetCOI :: (Enum a) => a -> MutableImage (ChannelOf a) d -> IO ()\nsetCOI chnl image = withMutableImage image $ \\i ->\n {#call cvSetImageCOI#} i (fromIntegral . (+1) . fromEnum $ chnl) \n -- CV numbers channels starting from 1. 0 means all channels\n\nresetCOI :: MutableImage a d -> IO ()\nresetCOI image = withMutableImage image $ \\i ->\n {#call cvSetImageCOI#} i 0\n\n\ngetChannel :: (Enum a) => a -> Image (ChannelOf a) d -> Image GrayScale d\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n mut <- toMutable image\n setCOI no mut\n cres <- {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\n withGenImage image $ \\cimage ->\n {#call cvCopy#} cimage (castPtr cres) (nullPtr)\n resetCOI mut\n return cres\n\nwithIOROI :: (Int,Int) -> (Int,Int) -> MutableImage c d -> IO a -> IO a\nwithIOROI pos size image op = do\n setROI pos size image\n x <- op\n resetROI image\n return x\n\n--withROI :: (Int, Int) -> (Int, Int) -> Image c d -> (MutableImage c d -> a) -> a\n--withROI pos size image op = unsafePerformIO $ do\n-- setROI pos size image\n-- let x = op image -- BUG\n-- resetROI image\n-- return x\n\nclass SetPixel a where\n type SP a :: *\n setPixel :: (Int,Int) -> SP a -> a -> IO ()\n\ninstance SetPixel (MutableImage GrayScale D32) where\n type SP (MutableImage GrayScale D32) = D32\n {-#INLINE setPixel#-}\n setPixel (x,y) v (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Float))):: Ptr Float)\n v\n\ninstance SetPixel (MutableImage GrayScale D8) where\n type SP (MutableImage GrayScale D8) = D8\n {-#INLINE setPixel#-}\n setPixel (x,y) v (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Word8))):: Ptr Word8)\n v\n\ninstance SetPixel (MutableImage RGB D8) where\n type SP (MutableImage RGB D8) = (D8,D8,D8)\n {-#INLINE setPixel#-}\n setPixel (x,y) (r,g,b) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n poke (castPtr (d`plusPtr` (y*cs +x*3*fs))) b\n poke (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs))) g\n poke (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs))) r\n\ninstance SetPixel (MutableImage RGB D32) where\n type SP (MutableImage RGB D32) = (D32,D32,D32)\n {-#INLINE setPixel#-}\n setPixel (x,y) (r,g,b) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs +x*3*fs))) b\n poke (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs))) g\n poke (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs))) r\n\ninstance SetPixel (MutableImage Complex D32) where\n type SP (MutableImage Complex D32) = C.Complex D32\n {-#INLINE setPixel#-}\n setPixel (x,y) (re C.:+ im) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs + x*2*fs))) re\n poke (castPtr (d`plusPtr` (y*cs + (x*2+1)*fs))) im\n\n\n\ngetAllPixels image = [getPixel (i,j) image\n | i <- [0..width-1 ]\n , j <- [0..height-1]]\n where\n (width,height) = getSize image\n\ngetAllPixelsRowMajor image = [getPixel (i,j) image\n | j <- [0..height-1]\n , i <- [0..width-1]\n ]\n where\n (width,height) = getSize image\n\n-- |Create a montage form given images (u,v) determines the layout and space the spacing\n-- between images. Images are assumed to be the same size (determined by the first image)\nmontage :: (Blittable c d) => (CreateImage (MutableImage c d)) => (Int,Int) -> Int -> [Image c d] -> Image c d\nmontage (u',v') space' imgs\n | u'*v' < (length imgs) = error (\"Montage mismatch: \"++show (u,v, length imgs))\n | otherwise = resultPic\n where\n space = fromIntegral space'\n (u,v) = (fromIntegral u', fromIntegral v')\n (rw,rh) = (u*xstep,v*ystep)\n (w,h) = foldl (\\(mx,my) (x,y) -> (max mx x, max my y)) (0,0) $ map getSize imgs\n (xstep,ystep) = (fromIntegral space + w,fromIntegral space + h)\n edge = space`div`2\n resultPic = unsafePerformIO $ do\n r <- create (rw,rh)\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep)\n | y <- [0..v-1] , x <- [0..u-1]\n | i <- imgs ]\n let (Mutable i) = r \n i `seq` return i\n\ndata CvException = CvException Int String String String Int\n deriving (Show, Typeable)\n\ndata CvIOError = CvIOError String deriving (Show,Typeable)\ndata CvSizeError = CvSizeError String deriving (Show,Typeable)\n\ninstance Exception CvException\ninstance Exception CvIOError\ninstance Exception CvSizeError\n\nsetCatch = do\n let catch i cstr1 cstr2 cstr3 j = do\n func <- peekCString cstr1\n msg <- peekCString cstr2\n file <- peekCString cstr3\n throw (CvException (fromIntegral i) func msg file (fromIntegral j))\n return 0\n cb <- mk'CvErrorCallback catch\n c'cvRedirectError cb nullPtr nullPtr\n c'cvSetErrMode c'CV_ErrModeSilent\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns,ParallelListComp, FlexibleInstances, FlexibleContexts, TypeFamilies, EmptyDataDecls, ScopedTypeVariables, StandaloneDeriving, DeriveDataTypeable, UndecidableInstances, MultiParamTypeClasses #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, MutableImage(..)\n, Mask\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\n, withMask\n, withMutableClone\n, withCloneValue\n, CreateImage\n, Save(..)\n\n-- * Colour spaces\n, ChannelOf\n, GrayScale\n, Complex\n, BGR\n, RGB\n, RGBA\n, RGB_Channel(..)\n, LAB\n, LAB_Channel(..)\n, D32\n, D64\n, D8\n, Tag\n, lab\n, rgba\n, rgb\n, compose\n, composeMultichannelImage\n\n-- * IO operations\n, Loadable(..)\n, saveImage\n, loadColorImage\n, loadImage\n\n-- * Pixel level access\n, GetPixel(..)\n, SetPixel(..)\n, safeGetPixel\n, getAllPixels\n, getAllPixelsRowMajor\n, mapImageInplace\n\n-- * Image information\n, ImageDepth\n, Sized(..)\n, biggerThan\n, getArea\n, getChannel\n, getImageChannels\n, getImageDepth\n, getImageInfo\n\n-- * ROI's, COI's and subregions\n, setCOI\n, setROI\n, resetROI\n, getRegion\n, withIOROI\n--, withROI\n\n-- * Blitting\n, blendBlit\n, blit\n, blitM\n, subPixelBlit\n, safeBlit\n, montage\n, tileImages\n\n-- * Conversions\n, rgbToGray\n, rgbToGray8\n, grayToRGB\n, rgbToLab\n, bgrToRgb\n, rgbToBgr\n, cloneTo64F\n, unsafeImageTo32F \n, unsafeImageTo64F \n, unsafeImageTo8Bit \n\n-- * Low level access operations\n, BareImage(..)\n, creatingImage\n, unImage\n, unS\n, withGenBareImage\n, withBareImage\n, creatingBareImage\n, withGenImage\n, withImage\n, withMutableImage\n, withRawImageData\n, imageFPTR\n, ensure32F\n\n-- * Extended error handling\n, setCatch\n, CvException\n, CvSizeError(..)\n, CvIOError(..)\n) where\n\nimport System.Mem\nimport System.Directory\nimport System.FilePath\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Utils\nimport Foreign.ForeignPtr hiding (newForeignPtr,unsafeForeignPtrToPtr)\nimport Foreign.Concurrent\nimport Foreign.Ptr\nimport Control.Parallel.Strategies\nimport Control.DeepSeq\nimport Control.Lens\n\nimport CV.Bindings.Error\n\nimport Data.Maybe(catMaybes)\nimport Data.List(genericLength)\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)\nimport Foreign.Storable\nimport System.IO.Unsafe\nimport Data.Word\nimport qualified Data.Complex as C\nimport Control.Monad\nimport Control.Exception\nimport Data.Data\nimport Data.Typeable\n\nimport Utils.GeometryClass\nimport Control.Applicative hiding (empty)\n\n\n\n\n-- Colorspaces\n\n-- | Single channel grayscale image\ndata GrayScale\ndata Complex\ndata RGB\ndata RGB_Channel = Red |\u00a0Green |\u00a0Blue deriving (Eq,Ord,Enum)\n\ndata BGR\n\ndata LAB\ndata RGBA\ndata LAB_Channel = LAB_L |\u00a0LAB_A |\u00a0LAB_B deriving (Eq,Ord,Enum)\n\n-- | Type family for expressing which channels a colorspace contains. This needs to be fixed wrt. the BGR color space.\ntype family ChannelOf a :: *\ntype instance ChannelOf RGB_Channel = RGB\ntype instance ChannelOf LAB_Channel = LAB\n\n-- Bit Depths\ntype D8 = Word8\ntype D32 = Float\ntype D64 = Double\n\n-- | The type for Images\nnewtype Image channels depth = S BareImage\nnewtype MutableImage channels depth = Mutable (Image channels depth)\n\n-- | Alias for images used as masks\ntype Mask = Maybe (Image GrayScale D8)\n\n-- |\u00a0Remove typing info from an image\nunS (S i) = i -- Unsafe and ugly\n\nimageFPTR :: Image c d -> ForeignPtr BareImage\nimageFPTR (S (BareImage fptr)) = fptr\n\nwithImage :: Image c d -> (Ptr BareImage ->IO a) -> IO a\nwithImage (S i) op = withBareImage i op\n--withGenNewImage (S i) op = withGenImage i op\n\nwithRawImageData :: Image c d -> (Int -> Ptr Word8 -> IO a) -> IO a\nwithRawImageData (S i) op = withBareImage i $ \\pp-> do\n d <- {#get IplImage->imageData#} pp \n wd <- {#get IplImage->widthStep#} pp\n op (fromIntegral wd) (castPtr d)\n\n-- Ok. this is just the example why I need image types\nwithUniPtr with x fun = with x $ \\y ->\n fun (castPtr y)\n\nwithGenImage :: Image c d -> (Ptr b -> IO a) -> IO a\nwithGenImage = withUniPtr withImage\n\n-- |\u00a0This function converts masks to pointers. Masks which are nothing are converted\n-- to null pointers.\nwithMask :: Mask -> (Ptr b -> IO a) -> IO a\nwithMask (Just i) op = withUniPtr withImage i op\nwithMask Nothing op = op nullPtr\n\nwithMutableImage :: MutableImage c d -> (Ptr b -> IO a) -> IO a\nwithMutableImage (Mutable i) o = withGenImage i o\n\nwithGenBareImage :: BareImage -> (Ptr b -> IO a) -> IO a\nwithGenBareImage = withUniPtr withBareImage\n\n{#pointer *IplImage as BareImage foreign newtype#}\n\nfreeBareImage ptr = with ptr {#call cvReleaseImage#}\n\n--foreign import ccall \"& wrapReleaseImage\" releaseImage :: FinalizerPtr BareImage\n\ninstance NFData (Image a b) where\n rnf a@(S (BareImage fptr)) = (unsafeForeignPtrToPtr) fptr `seq` a `seq` ()-- This might also need peek?\n\n\ncreatingImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . S . BareImage $ fptr\n\ncreatingBareImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . BareImage $ fptr\n\nunImage (S (BareImage fptr)) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\nrgba = undefined :: Tag RGBA\nlab = undefined :: Tag LAB\n\n-- | Typeclass for elements that are build from component elements. For example,\n-- RGB images can be constructed from three grayscale images.\nclass Composes a where\n type Source a :: *\n compose :: Source a -> a\n\ninstance (CreateImage (Image RGBA a)) => Composes (Image RGBA a) where\n type Source (Image RGBA a) = (Image GrayScale a, Image GrayScale a\n ,Image GrayScale a, Image GrayScale a)\n compose (r,g,b,a) = composeMultichannelImage (Just b) (Just g) (Just r) (Just a) rgba\n\ninstance (CreateImage (Image RGB a)) => Composes (Image RGB a) where\n type Source (Image RGB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (r,g,b) = composeMultichannelImage (Just b) (Just g) (Just r) Nothing rgb\n\ninstance (CreateImage (Image LAB a)) => Composes (Image LAB a) where\n type Source (Image LAB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (l,a,b) = composeMultichannelImage (Just l) (Just a) (Just b) Nothing lab\n\n{-# DEPRECATED composeMultichannelImage \"This is unsafe. Use compose instead\" #-}\ncomposeMultichannelImage :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannelImage = composeMultichannel\n\ncomposeMultichannel :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannel (c2)\n (c1)\n (c3)\n (c4)\n totag\n = unsafePerformIO $\u00a0do\n res <- create (size) -- TODO: Check channel count -- This is NOT correct\n withMaybe c1 $ \\cc1 ->\n withMaybe c2 $ \\cc2 ->\n withMaybe c3 $ \\cc3 ->\n withMaybe c4 $ \\cc4 ->\n withGenImage res $ \\cres -> {#call cvMerge#} cc1 cc2 cc3 cc4 cres\n return res\n where\n withMaybe (Just i) op = withGenImage i op\n withMaybe (Nothing) op = op nullPtr\n size = getSize . head . catMaybes $ [c1,c2,c3,c4]\n\n\n-- | Typeclass for CV items that can be read from file. Mainly images at this point.\nclass Loadable a where\n readFromFile :: FilePath -> IO a\n\n\ninstance Loadable ((Image GrayScale D32)) where\n readFromFile fp = do\n e <- loadImage fp\n case e of\n Just i -> return i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D32)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ unsafeImageTo32F $ bgrToRgb i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D8)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ bgrToRgb i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image GrayScale D8)) where\n readFromFile fp = do\n e <- loadImage8 fp\n case e of\n Just i -> return i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\n\n-- | This function loads and converts image to an arbitrary format. Notice that it is\n-- polymorphic enough to cause run time errors if the declared and actual types of the\n-- images do not match. Use with care.\nunsafeloadUsing x p n = do\n exists <- doesFileExist n\n if not exists then return Nothing\n else do\n i <- withCString n $ \\name ->\n creatingBareImage ({#call cvLoadImage #} name p)\n bw <- x i\n return . Just .\u00a0S $ bw\n\nloadImage :: FilePath -> IO (Maybe (Image GrayScale D32))\nloadImage = unsafeloadUsing imageTo32F 0\nloadImage8 :: FilePath -> IO (Maybe (Image GrayScale D8))\nloadImage8 = unsafeloadUsing imageTo8Bit 0\nloadColorImage :: FilePath -> IO (Maybe (Image BGR D32))\nloadColorImage = unsafeloadUsing imageTo32F 1\nloadColorImage8 :: FilePath -> IO (Maybe (Image BGR D8))\nloadColorImage8 = unsafeloadUsing imageTo8Bit 1\n\n\ninstance Sized (MutableImage a b) where\n type Size (MutableImage a b) = IO (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize (Mutable i) = evaluate (deep (getSize i))\n\ndeep a = a `deepseq` a\n\ninstance Sized BareImage where\n type Size BareImage = (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize image = unsafePerformIO $ withBareImage image $ \\i -> do\n w <- {#call getImageWidth#} i\n h <- {#call getImageHeight#} i\n return (fromIntegral w,fromIntegral h)\n\ninstance Sized (Image c d) where\n type Size (Image c d) = (Int,Int)\n getSize = getSize . unS\n\n\ncvRGBtoGRAY = 7 :: CInt-- NOTE: This will break.\ncvRGBtoLAB = 45 :: CInt-- NOTE: This will break.\n\n\n#c\nenum CvtFlags {\n CvtFlip = CV_CVTIMG_FLIP,\n CvtSwapRB = CV_CVTIMG_SWAP_RB\n };\n#endc\n\n#c\nenum CvtCodes {\n CV_BGR2BGRA =0,\n CV_RGB2RGBA =CV_BGR2BGRA,\n\n CV_BGRA2BGR =1,\n CV_RGBA2RGB =CV_BGRA2BGR,\n\n CV_BGR2RGBA =2,\n CV_RGB2BGRA =CV_BGR2RGBA,\n\n CV_RGBA2BGR =3,\n CV_BGRA2RGB =CV_RGBA2BGR,\n\n CV_BGR2RGB =4,\n CV_RGB2BGR =CV_BGR2RGB,\n\n CV_BGRA2RGBA =5,\n CV_RGBA2BGRA =CV_BGRA2RGBA,\n\n CV_BGR2GRAY =6,\n CV_RGB2GRAY =7,\n CV_GRAY2BGR =8,\n CV_GRAY2RGB =CV_GRAY2BGR,\n CV_GRAY2BGRA =9,\n CV_GRAY2RGBA =CV_GRAY2BGRA,\n CV_BGRA2GRAY =10,\n CV_RGBA2GRAY =11,\n\n CV_BGR2BGR565 =12,\n CV_RGB2BGR565 =13,\n CV_BGR5652BGR =14,\n CV_BGR5652RGB =15,\n CV_BGRA2BGR565 =16,\n CV_RGBA2BGR565 =17,\n CV_BGR5652BGRA =18,\n CV_BGR5652RGBA =19,\n\n CV_GRAY2BGR565 =20,\n CV_BGR5652GRAY =21,\n\n CV_BGR2BGR555 =22,\n CV_RGB2BGR555 =23,\n CV_BGR5552BGR =24,\n CV_BGR5552RGB =25,\n CV_BGRA2BGR555 =26,\n CV_RGBA2BGR555 =27,\n CV_BGR5552BGRA =28,\n CV_BGR5552RGBA =29,\n\n CV_GRAY2BGR555 =30,\n CV_BGR5552GRAY =31,\n\n CV_BGR2XYZ =32,\n CV_RGB2XYZ =33,\n CV_XYZ2BGR =34,\n CV_XYZ2RGB =35,\n\n CV_BGR2YCrCb =36,\n CV_RGB2YCrCb =37,\n CV_YCrCb2BGR =38,\n CV_YCrCb2RGB =39,\n\n CV_BGR2HSV =40,\n CV_RGB2HSV =41,\n\n CV_BGR2Lab =44,\n CV_RGB2Lab =45,\n\n CV_BayerBG2BGR =46,\n CV_BayerGB2BGR =47,\n CV_BayerRG2BGR =48,\n CV_BayerGR2BGR =49,\n\n CV_BayerBG2RGB =CV_BayerRG2BGR,\n CV_BayerGB2RGB =CV_BayerGR2BGR,\n CV_BayerRG2RGB =CV_BayerBG2BGR,\n CV_BayerGR2RGB =CV_BayerGB2BGR,\n\n CV_BGR2Luv =50,\n CV_RGB2Luv =51,\n CV_BGR2HLS =52,\n CV_RGB2HLS =53,\n\n CV_HSV2BGR =54,\n CV_HSV2RGB =55,\n\n CV_Lab2BGR =56,\n CV_Lab2RGB =57,\n CV_Luv2BGR =58,\n CV_Luv2RGB =59,\n CV_HLS2BGR =60,\n CV_HLS2RGB =61,\n\n CV_BayerBG2BGR_VNG =62,\n CV_BayerGB2BGR_VNG =63,\n CV_BayerRG2BGR_VNG =64,\n CV_BayerGR2BGR_VNG =65,\n\n CV_BayerBG2RGB_VNG =CV_BayerRG2BGR_VNG,\n CV_BayerGB2RGB_VNG =CV_BayerGR2BGR_VNG,\n CV_BayerRG2RGB_VNG =CV_BayerBG2BGR_VNG,\n CV_BayerGR2RGB_VNG =CV_BayerGB2BGR_VNG,\n\n CV_BGR2HSV_FULL = 66,\n CV_RGB2HSV_FULL = 67,\n CV_BGR2HLS_FULL = 68,\n CV_RGB2HLS_FULL = 69,\n\n CV_HSV2BGR_FULL = 70,\n CV_HSV2RGB_FULL = 71,\n CV_HLS2BGR_FULL = 72,\n CV_HLS2RGB_FULL = 73,\n\n CV_LBGR2Lab = 74,\n CV_LRGB2Lab = 75,\n CV_LBGR2Luv = 76,\n CV_LRGB2Luv = 77,\n\n CV_Lab2LBGR = 78,\n CV_Lab2LRGB = 79,\n CV_Luv2LBGR = 80,\n CV_Luv2LRGB = 81,\n\n CV_BGR2YUV = 82,\n CV_RGB2YUV = 83,\n CV_YUV2BGR = 84,\n CV_YUV2RGB = 85,\n\n CV_COLORCVT_MAX =100\n};\n#endc\n\n{#enum CvtCodes {}#}\n\n{#enum CvtFlags {}#}\n\n\nrgbToLab :: Image RGB D32 -> Image LAB D32\nrgbToLab = S . convertTo cvRGBtoLAB 3 . unS\n\nrgbToGray :: Image RGB D32 -> Image GrayScale D32\nrgbToGray = S . convertTo cvRGBtoGRAY 1 . unS\n\nrgbToGray8 :: Image RGB D8 -> Image GrayScale D8\nrgbToGray8 = S . convert8UTo cvRGBtoGRAY 1 . unS\n\ngrayToRGB :: Image GrayScale D32 -> Image RGB D32\ngrayToRGB = S . convertTo (fromIntegral . fromEnum $ CV_GRAY2BGR) 3 . unS\n\n\nbgrToRgb :: Image BGR D8 -> Image RGB D8\nbgrToRgb = S . swapRB . unS\n\nrgbToBgr :: Image RGB D8 -> Image BGR D8\nrgbToBgr = S . swapRB . unS\n\nswapRB :: BareImage -> BareImage\nswapRB img = unsafePerformIO $ do\n res <- cloneBareImage img\n withBareImage img $ \\cimg ->\n withBareImage res $ \\cres ->\n {#call cvConvertImage#} (castPtr cimg) (castPtr cres) (fromIntegral . fromEnum $ CvtSwapRB)\n return res\n\n\nsafeGetPixel :: (Sized image, Size image ~ (Int,Int), GetPixel image) => (P image) -> (Int,Int) -> image -> P image\nsafeGetPixel def (x,y) i |\u00a0x<0 || x>= w || y<0 || y>=h = def\n | otherwise = getPixel (x,y) i\n -- | otherwise = def\n where\n (w,h) = getSize i\n -- (x',y') = (clamp (0,w-1) x, clamp (0,h-1) y)\n\nclamp :: Ord a => (a, a) -> a -> a\nclamp (a,b) x = max a (min b x)\n\ninstance (NFData (P (Image a b)), GetPixel (Image a b)) => GetPixel (MutableImage a b) where\n type P (MutableImage a b) = IO (P (Image a b))\n getPixel xy (Mutable i) = let p = getPixel xy i\n in p `deepseq` return p\n\nclass GetPixel a where\n type P a :: *\n getPixel :: (Int,Int) -> a -> P a\n\n-- #define FGET(img,x,y) (((float *)((img)->imageData + (y)*(img)->widthStep))[(x)])\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Float))):: Ptr Float)\n\ninstance GetPixel (Image GrayScale D8) where\n type P (Image GrayScale D8) = D8\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Word8))):: Ptr Word8)\n\ninstance GetPixel (Image Complex D32) where\n type P (Image Complex D32) = C.Complex D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n re <- peek (castPtr (d`plusPtr` (y*cs + x*2*fs)))\n im <- peek (castPtr (d`plusPtr` (y*cs +(x*2+1)*fs)))\n return (re C.:+ im)\n\n-- #define UGETC(img,color,x,y) (((uint8_t *)((img)->imageData + (y)*(img)->widthStep))[(x)*3+(color)])\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\ninstance GetPixel (Image BGR D32) where\n type P (Image BGR D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\ninstance GetPixel (Image BGR D8) where\n type P (Image BGR D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image RGB D8) where\n type P (Image RGB D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image LAB D32) where\n type P (Image LAB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n l <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n a <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n b <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (l,a,b)\n\n-- | Perform (a destructive) inplace map of the image. This should be wrapped inside\n-- withClone or an image operation\nmapImageInplace :: (P (Image GrayScale D32) -> P (Image GrayScale D32))\n -> MutableImage GrayScale D32\n -> IO ()\nmapImageInplace f image = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n (w,h) <- getSize image\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n forM_ [(x,y) | x<-[0..w-1], y <- [0..h-1]] $ \\(x,y) ->\u00a0do\n v <- peek (castPtr (d `plusPtr` (y*cs+x*fs)))\n poke (castPtr (d `plusPtr` (y*cs+x*fs))) (f v)\n\n\n\nconvert8UTo :: CInt -> CInt -> BareImage -> BareImage\nconvert8UTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage8U#} w h channels\n withBareImage img $ \\cimg ->\n {#call cvCvtColor#} (castPtr cimg) (castPtr res) code\n return res\n where\n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\nconvertTo :: CInt -> CInt -> BareImage -> BareImage\nconvertTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage32F#} w h channels\n withBareImage img $ \\cimg ->\n {#call cvCvtColor#} (castPtr cimg) (castPtr res) code\n return res\n where\n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\n-- |\u00a0Class for images that exist.\nclass CreateImage a where\n -- | Create an image from size\n create :: (Int,Int) -> IO a\n\ncreateWith :: CreateImage (Image c d) => (Int,Int) -> (MutableImage c d -> IO (MutableImage c d)) -> IO (Image c d)\ncreateWith s f = do\n c <- create s\n Mutable r <- f (Mutable c)\n return r\n\n\n\n\ninstance CreateImage (Image GrayScale D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image Complex D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 2\ninstance CreateImage (Image LAB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image c d) => CreateImage (MutableImage c d) where\n create s = Mutable <$> create s\n\n\n-- | Allocate a new empty image\nempty :: (CreateImage (Image a b)) => (Int,Int) -> (Image a b)\nempty size = unsafePerformIO $ create size\n\n-- |\u00a0Allocate a new image that of the same size and type as the exemplar image given.\nemptyCopy :: (CreateImage (Image a b)) => Image a b -> (Image a b)\nemptyCopy img = unsafePerformIO $ create (getSize img)\n\nemptyCopy' :: (CreateImage (Image a b)) => Image a b -> IO (Image a b)\nemptyCopy' img = create (getSize img)\n\n-- | Save image. This will convert the image to 8 bit one before saving\nclass Save a where\n save :: FilePath -> a -> IO ()\n\ninstance Save (Image BGR D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image)\n\ninstance Save (Image RGB D32) where\n save filename image = primitiveSave filename (swapRB . unS . unsafeImageTo8Bit $ image)\n\ninstance Save (Image RGB D8) where\n save filename image = primitiveSave filename (swapRB . unS $ image)\n\ninstance Save (Image GrayScale D8) where\n save filename image = primitiveSave filename (unS $ image)\n\ninstance Save (Image GrayScale D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image)\n\nprimitiveSave :: FilePath -> BareImage -> IO ()\nprimitiveSave filename fpi = do\n exists <- doesDirectoryExist (takeDirectory filename)\n when (not exists) $\u00a0throw (CvIOError $ \"Directory does not exist: \" ++ (takeDirectory filename))\n withCString filename $ \\name ->\n withGenBareImage fpi $ \\cvArr ->\n alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\n-- |Save an image as 8 bit gray scale\nsaveImage :: (Save (Image c d)) => FilePath -> Image c d -> IO ()\nsaveImage = save\n\ngetArea :: (Sized a,Num b, Size a ~ (b,b)) => a -> b\ngetArea = uncurry (*).getSize\n\ngetRegion :: (Int,Int) -> (Int,Int) -> Image c d -> Image c d\ngetRegion (fromIntegral -> x,fromIntegral -> y) (fromIntegral -> w,fromIntegral -> h) image\n | x+w <= width && y+h <= height = S . getRegion' (x,y) (w,h) $ unS image\n | otherwise = error $ \"Region outside image:\"\n ++ show (getSize image) ++\n \"\/\"++show (x+w,y+h)\n where\n (fromIntegral -> width,fromIntegral -> height) = getSize image\n\ngetRegion' (x,y) (w,h) image = unsafePerformIO $\n withBareImage image $ \\i ->\n creatingBareImage ({#call getSubImage#}\n i x y w h)\n\n\n-- | Tile images by overlapping them on a black canvas.\ntileImages image1 image2 (x,y) = unsafePerformIO $\n withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n creatingImage ({#call simpleMergeImages#}\n i1 i2 x y)\n-- | Blit image2 onto image1.\nclass Blittable channels depth \ninstance Blittable GrayScale D32\ninstance Blittable RGB D32\n\nblit :: Blittable c d => MutableImage c d -> Image c d -> (Int,Int) -> IO ()\nblit image1 image2 (x,y) = do\n (w1,h1) <- getSize image1\n let ((w2,h2)) = getSize image2\n if x+w2>w1 || y+h2>h1 || x<0 || y<0\n then error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n else withMutableImage image1 $ \\i1 ->\n withImage image2 $ \\i2 -> \n ({#call plainBlit#} i1 i2 (fromIntegral y) (fromIntegral x))\n\n-- | Create an image by blitting multiple images onto an empty image.\nblitM :: (CreateImage (MutableImage GrayScale D32)) => \n (Int,Int) -> [((Int,Int),Image GrayScale D32)] -> Image GrayScale D32\nblitM (rw,rh) imgs = unsafePerformIO $ resultPic >>= fromMutable \n where\n resultPic = do\n r <- create (fromIntegral rw,fromIntegral rh)\n sequence_ [blit r i (fromIntegral x, fromIntegral y)\n | ((x,y),i) <- imgs ]\n return r\n\n\nsubPixelBlit :: MutableImage c d -> Image c d -> (CDouble, CDouble) -> IO ()\nsubPixelBlit (image1) (image2) (x,y) = do\n (w1,h1) <- getSize image1\n let ((w2,h2)) = getSize image2\n if ceiling x+w2>w1 || ceiling y+h2>h1 ||\u00a0x<0 || y<0\n then error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n else withMutableImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call subpixel_blit#} i1 i2 y x)\n\nsafeBlit i1 i2 (x,y) = unsafePerformIO $ do\n res <- toMutable i1-- createImage32F (getSize i1) 1\n blit res i2 (x,y)\n return res\n\n-- | Blit image2 onto image1.\n-- This uses an alpha channel bitmap for determining the regions where the image should be \"blended\" with\n-- the base image.\nblendBlit :: MutableImage c d -> Image c1 d1 -> Image c3 d3 -> Image c2 d2\n -> (CInt, CInt) -> IO ()\nblendBlit image1 image1Alpha image2 image2Alpha (x,y) =\n withMutableImage image1 $ \\i1 ->\n withImage image1Alpha $ \\i1a ->\n withImage image2Alpha $ \\i2a ->\n withImage image2 $ \\i2 ->\n ({#call alphaBlit#} i1 i1a i2 i2a y x)\n\n\n-- | Create a copy of an image\ncloneImage :: Image a b -> IO (Image a b)\ncloneImage img = withGenImage img $ \\image ->\n creatingImage ({#call cvCloneImage #} image)\n\ntoMutable :: Image a b -> IO (MutableImage a b)\ntoMutable img = withGenImage img $ \\image ->\n Mutable <$>\u00a0creatingImage ({#call cvCloneImage #} image)\n\nfromMutable :: MutableImage a b -> IO (Image a b)\nfromMutable (Mutable img) = cloneImage img \n\n-- | Create a copy of a non-types image\ncloneBareImage :: BareImage -> IO BareImage\ncloneBareImage img = withGenBareImage img $ \\image ->\n creatingBareImage ({#call cvCloneImage #} image)\n\nwithMutableClone\n :: Image channels depth\n -> (MutableImage channels depth -> IO a)\n -> IO a\nwithMutableClone img fun = do\n result <- toMutable img\n fun result\n\nwithClone\n :: Image channels depth\n -> (Image channels depth -> IO ())\n -> IO (Image channels depth)\nwithClone img fun = do\n result <- cloneImage img\n fun result\n return result\n\nwithCloneValue\n :: Image channels depth\n -> (Image channels depth -> IO a)\n -> IO a\nwithCloneValue img fun = do\n result <- cloneImage img\n r <- fun result\n return r\n\ncloneTo64F :: Image c d -> IO (Image c D64)\ncloneTo64F img = withGenImage img $ \\image ->\n creatingImage\n ({#call ensure64F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 64 bit, floating point, image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image. \nunsafeImageTo64F :: Image c d -> Image c D64\nunsafeImageTo64F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure64F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 32 bit, floating point, image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image. \nunsafeImageTo32F :: Image c d -> Image c D32\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure32F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 8 bit image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image. \nunsafeImageTo8Bit :: Image cspace a -> Image cspace D8\nunsafeImageTo8Bit img =\n unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage ({#call ensure8U #} image)\n\n--toD32 :: Image c d -> Image c D32\n--toD32 i =\n-- unsafePerformIO $\n-- withImage i $ \\i_ptr ->\n-- creatingImage\n\n\nimageTo32F img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure32F #} image)\n\nimageTo8Bit img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure8U #} image)\n#c\nenum ImageDepth {\n Depth32F = IPL_DEPTH_32F,\n Depth64F = IPL_DEPTH_64F,\n Depth8U = IPL_DEPTH_8U,\n Depth8S = IPL_DEPTH_8S,\n Depth16U = IPL_DEPTH_16U,\n Depth16S = IPL_DEPTH_16S,\n Depth32S = IPL_DEPTH_32S\n };\n#endc\n\n{#enum ImageDepth {}#}\n\nderiving instance Show ImageDepth\n\ngetImageDepth :: Image c d -> IO ImageDepth\ngetImageDepth i = withImage i $ \\c_img -> {#get IplImage->depth #} c_img >>= return.toEnum.fromIntegral\ngetImageChannels i = withImage i $ \\c_img -> {#get IplImage->nChannels #} c_img\n\ngetImageInfo x = do\n let s = getSize x\n d <- getImageDepth x\n c <- getImageChannels x\n return (s,d,c)\n\n\n-- | Set the region of interest for a mutable image\nsetROI :: (Integral a) => (a,a) -> (a,a) -> MutableImage c d -> IO ()\nsetROI (fromIntegral -> x,fromIntegral -> y)\n (fromIntegral -> w,fromIntegral -> h)\n image = withMutableImage image $ \\i ->\n {#call wrapSetImageROI#} i x y w h\n\n-- | Set the region of interest to cover the entire image.\nresetROI :: MutableImage c d -> IO ()\nresetROI image = withMutableImage image $ \\i ->\n {#call cvResetImageROI#} i\n\nsetCOI :: (Enum a) => a -> MutableImage (ChannelOf a) d -> IO ()\nsetCOI chnl image = withMutableImage image $ \\i ->\n {#call cvSetImageCOI#} i (fromIntegral . (+1) . fromEnum $ chnl) \n -- CV numbers channels starting from 1. 0 means all channels\n\nresetCOI :: MutableImage a d -> IO ()\nresetCOI image = withMutableImage image $ \\i ->\n {#call cvSetImageCOI#} i 0\n\n\ngetChannel :: (Enum a) => a -> Image (ChannelOf a) d -> Image GrayScale d\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n mut <- toMutable image\n setCOI no mut\n cres <- {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\n withGenImage image $ \\cimage ->\n {#call cvCopy#} cimage (castPtr cres) (nullPtr)\n resetCOI mut\n return cres\n\nwithIOROI :: (Int,Int) -> (Int,Int) -> MutableImage c d -> IO a -> IO a\nwithIOROI pos size image op = do\n setROI pos size image\n x <- op\n resetROI image\n return x\n\n--withROI :: (Int, Int) -> (Int, Int) -> Image c d -> (MutableImage c d -> a) -> a\n--withROI pos size image op = unsafePerformIO $ do\n-- setROI pos size image\n-- let x = op image -- BUG\n-- resetROI image\n-- return x\n\nclass SetPixel a where\n type SP a :: *\n setPixel :: (Int,Int) -> SP a -> a -> IO ()\n\ninstance SetPixel (MutableImage GrayScale D32) where\n type SP (MutableImage GrayScale D32) = D32\n {-#INLINE setPixel#-}\n setPixel (x,y) v (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Float))):: Ptr Float)\n v\n\ninstance SetPixel (MutableImage GrayScale D8) where\n type SP (MutableImage GrayScale D8) = D8\n {-#INLINE setPixel#-}\n setPixel (x,y) v (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Word8))):: Ptr Word8)\n v\n\ninstance SetPixel (MutableImage RGB D8) where\n type SP (MutableImage RGB D8) = (D8,D8,D8)\n {-#INLINE setPixel#-}\n setPixel (x,y) (r,g,b) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n poke (castPtr (d`plusPtr` (y*cs +x*3*fs))) b\n poke (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs))) g\n poke (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs))) r\n\ninstance SetPixel (MutableImage RGB D32) where\n type SP (MutableImage RGB D32) = (D32,D32,D32)\n {-#INLINE setPixel#-}\n setPixel (x,y) (r,g,b) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs +x*3*fs))) b\n poke (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs))) g\n poke (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs))) r\n\ninstance SetPixel (MutableImage Complex D32) where\n type SP (MutableImage Complex D32) = C.Complex D32\n {-#INLINE setPixel#-}\n setPixel (x,y) (re C.:+ im) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs + x*2*fs))) re\n poke (castPtr (d`plusPtr` (y*cs + (x*2+1)*fs))) im\n\n\n\ngetAllPixels image = [getPixel (i,j) image\n | i <- [0..width-1 ]\n , j <- [0..height-1]]\n where\n (width,height) = getSize image\n\ngetAllPixelsRowMajor image = [getPixel (i,j) image\n | j <- [0..height-1]\n , i <- [0..width-1]\n ]\n where\n (width,height) = getSize image\n\n-- |Create a montage form given images (u,v) determines the layout and space the spacing\n-- between images. Images are assumed to be the same size (determined by the first image)\nmontage :: (Blittable c d) => (CreateImage (MutableImage c d)) => (Int,Int) -> Int -> [Image c d] -> Image c d\nmontage (u',v') space' imgs\n | u'*v' < (length imgs) = error (\"Montage mismatch: \"++show (u,v, length imgs))\n | otherwise = resultPic\n where\n space = fromIntegral space'\n (u,v) = (fromIntegral u', fromIntegral v')\n (rw,rh) = (u*xstep,v*ystep)\n (w,h) = foldl (\\(mx,my) (x,y) -> (max mx x, max my y)) (0,0) $ map getSize imgs\n (xstep,ystep) = (fromIntegral space + w,fromIntegral space + h)\n edge = space`div`2\n resultPic = unsafePerformIO $ do\n r <- create (rw,rh)\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep)\n | y <- [0..v-1] , x <- [0..u-1]\n | i <- imgs ]\n let (Mutable i) = r \n i `seq` return i\n\ndata CvException = CvException Int String String String Int\n deriving (Show, Typeable)\n\ndata CvIOError = CvIOError String deriving (Show,Typeable)\ndata CvSizeError = CvSizeError String deriving (Show,Typeable)\n\ninstance Exception CvException\ninstance Exception CvIOError\ninstance Exception CvSizeError\n\nsetCatch = do\n let catch i cstr1 cstr2 cstr3 j = do\n func <- peekCString cstr1\n msg <- peekCString cstr2\n file <- peekCString cstr3\n throw (CvException (fromIntegral i) func msg file (fromIntegral j))\n return 0\n cb <- mk'CvErrorCallback catch\n c'cvRedirectError cb nullPtr nullPtr\n c'cvSetErrMode c'CV_ErrModeSilent\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"c6b28841a5f39c7c65cfbf7d4ebd72a3c128fe0d","subject":"Check if the prog was linked with -threaded and if so fail on initialisation","message":"Check if the prog was linked with -threaded and if so fail on initialisation\n","repos":"gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/gstreamer,gtk2hs\/gtksourceview,gtk2hs\/vte","old_file":"gtk\/Graphics\/UI\/Gtk\/General\/General.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/General\/General.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) General\n--\n-- Author : Axel Simon, Manuel M. T. Chakravarty\n--\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.13 $ from $Date: 2005\/11\/06 19:10:16 $\n--\n-- Copyright (C) 2000..2005 Axel Simon, Manuel M. T. Chakravarty\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- TODO\n--\n-- quitAddDestroy, quitAdd, quitRemove\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- library initialization, main event loop, and events\n--\nmodule Graphics.UI.Gtk.General.General (\n-- getDefaultLanguage,\n initGUI,\n eventsPending,\n mainGUI,\n mainLevel,\n mainQuit,\n mainIteration,\n mainIterationDo,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n Priority,\n priorityLow,\n priorityDefaultIdle,\n priorityHighIdle,\n priorityDefault,\n priorityHigh,\n timeoutAdd,\n timeoutAddFull,\n timeoutRemove,\n idleAdd,\n idleRemove,\n inputAdd,\n inputRemove,\n IOCondition,\n HandlerId\n ) where\n\nimport System.Environment (getProgName, getArgs)\nimport Control.Monad (liftM, mapM, when)\nimport Control.Exception (ioError, Exception(ErrorCall))\nimport Control.Concurrent (rtsSupportsBoundThreads)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t\t(DestroyNotify, mkFunPtrDestroyNotify)\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n{-\n-- | Retreive the current language.\n-- * This function returns a String which's pointer can be used later on for\n-- comarisions.\n--\n--getDefaultLanguage :: IO String\n--getDefaultLanguage = do\n-- strPtr <- {#call unsafe get_default_language#}\n-- str <- peekUTFString strPtr\n-- destruct strPtr\n-- return str\n-}\n\n-- We compile this module using -#includ\"gtk\/wingtk.h\" to bypass the win32 abi\n-- check however we do not compile users programs with this headder so if\n-- initGUI was ever inlined in a users program, then that program would not\n-- bypass the abi check and would fail on startup. So to stop that we must\n-- prevent initGUI from being inlined.\n{-# NOINLINE initGUI #-}\n-- | Initialize the GUI binding.\n--\n-- * This function initialized the GUI toolkit and parses all Gtk\n-- specific arguments. The remaining arguments are returned. If the\n-- initialization of the toolkit fails for whatever reason, an exception\n-- is thrown.\n--\n-- * Throws: @ErrorCall \\\"Cannot initialize GUI.\\\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n when rtsSupportsBoundThreads\n (fail $ \"initGUI: Gtk2Hs does not currently support the threaded RTS\\n\"\n ++ \"see http:\/\/haskell.org\/gtk2hs\/archives\/2005\/07\/24\/writing-multi-threaded-guis\/2\/\\n\"\n\t ++ \"Please relink your program without using the '-threaded' flag.\")\n prog <- getProgName\n args <- getArgs\n let allArgs = (prog:args)\n withMany withUTFString allArgs $ \\addrs ->\n withArrayLen addrs $ \\argc argv ->\n with\t argv $ \\argvp ->\n with\t argc $ \\argcp -> do \n res <- {#call unsafe init_check#} (castPtr argcp) (castPtr argvp)\n if (toBool res) then do\n argc' <- peek argcp\n argv' <- peek argvp\n _:addrs' <- peekArray argc' argv' -- drop the program name\n mapM peekUTFString addrs'\n else error \"Cannot initialize GUI.\"\n\n-- | Inquire the number of events pending on the event queue\n--\neventsPending :: IO Int\neventsPending = liftM fromIntegral {#call unsafe events_pending#}\n\n-- | Run the Gtk+ main event loop.\n--\nmainGUI :: IO ()\nmainGUI = {#call main#}\n\n-- | Inquire the main loop level.\n--\n-- * Callbacks that take more time to process can call 'mainIteration' to keep\n-- the GUI responsive. Each time the main loop is restarted this way, the main\n-- loop counter is increased. This function returns this counter.\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- | Exit the main event loop.\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- | Process an event, block if necessary.\n--\n-- * Returns @True@ if 'mainQuit' was called while processing the event.\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- | Process a single event.\n--\n-- * Called with @True@, this function behaves as 'mainIteration' in that it\n-- waits until an event is available for processing. It will return\n-- immediately, if passed @False@.\n--\n-- * Returns @True@ if the 'mainQuit' was called while processing the event.\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- | add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- | inquire current grab widget\n--\ngrabGetCurrent :: IO (Maybe Widget)\ngrabGetCurrent = do\n wPtr <- {#call grab_get_current#}\n if (wPtr==nullPtr) then return Nothing else \n liftM Just $ makeNewObject mkWidget (return wPtr)\n\n-- | remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) General\n--\n-- Author : Axel Simon, Manuel M. T. Chakravarty\n--\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.13 $ from $Date: 2005\/11\/06 19:10:16 $\n--\n-- Copyright (C) 2000..2005 Axel Simon, Manuel M. T. Chakravarty\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- TODO\n--\n-- quitAddDestroy, quitAdd, quitRemove\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- library initialization, main event loop, and events\n--\nmodule Graphics.UI.Gtk.General.General (\n-- getDefaultLanguage,\n initGUI,\n eventsPending,\n mainGUI,\n mainLevel,\n mainQuit,\n mainIteration,\n mainIterationDo,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n Priority,\n priorityLow,\n priorityDefaultIdle,\n priorityHighIdle,\n priorityDefault,\n priorityHigh,\n timeoutAdd,\n timeoutAddFull,\n timeoutRemove,\n idleAdd,\n idleRemove,\n inputAdd,\n inputRemove,\n IOCondition,\n HandlerId\n ) where\n\nimport System (getProgName, getArgs)\nimport Monad\t(liftM, mapM)\nimport Control.Exception (ioError, Exception(ErrorCall))\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t\t(DestroyNotify, mkFunPtrDestroyNotify)\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n{-\n-- | Retreive the current language.\n-- * This function returns a String which's pointer can be used later on for\n-- comarisions.\n--\n--getDefaultLanguage :: IO String\n--getDefaultLanguage = do\n-- strPtr <- {#call unsafe get_default_language#}\n-- str <- peekUTFString strPtr\n-- destruct strPtr\n-- return str\n-}\n\n-- We compile this module using -#includ\"gtk\/wingtk.h\" to bypass the win32 abi\n-- check however we do not compile users programs with this headder so if\n-- initGUI was ever inlined in a users program, then that program would not\n-- bypass the abi check and would fail on startup. So to stop that we must\n-- prevent initGUI from being inlined.\n{-# NOINLINE initGUI #-}\n-- | Initialize the GUI binding.\n--\n-- * This function initialized the GUI toolkit and parses all Gtk\n-- specific arguments. The remaining arguments are returned. If the\n-- initialization of the toolkit fails for whatever reason, an exception\n-- is thrown.\n--\n-- * Throws: @ErrorCall \\\"Cannot initialize GUI.\\\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n prog <- getProgName\n args <- getArgs\n let allArgs = (prog:args)\n withMany withUTFString allArgs $ \\addrs ->\n withArrayLen addrs $ \\argc argv ->\n with\t argv $ \\argvp ->\n with\t argc $ \\argcp -> do \n res <- {#call unsafe init_check#} (castPtr argcp) (castPtr argvp)\n if (toBool res) then do\n argc' <- peek argcp\n argv' <- peek argvp\n _:addrs' <- peekArray argc' argv' -- drop the program name\n mapM peekUTFString addrs'\n else error \"Cannot initialize GUI.\"\n\n-- | Inquire the number of events pending on the event queue\n--\neventsPending :: IO Int\neventsPending = liftM fromIntegral {#call unsafe events_pending#}\n\n-- | Run the Gtk+ main event loop.\n--\nmainGUI :: IO ()\nmainGUI = {#call main#}\n\n-- | Inquire the main loop level.\n--\n-- * Callbacks that take more time to process can call 'mainIteration' to keep\n-- the GUI responsive. Each time the main loop is restarted this way, the main\n-- loop counter is increased. This function returns this counter.\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- | Exit the main event loop.\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- | Process an event, block if necessary.\n--\n-- * Returns @True@ if 'mainQuit' was called while processing the event.\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- | Process a single event.\n--\n-- * Called with @True@, this function behaves as 'mainIteration' in that it\n-- waits until an event is available for processing. It will return\n-- immediately, if passed @False@.\n--\n-- * Returns @True@ if the 'mainQuit' was called while processing the event.\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- | add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- | inquire current grab widget\n--\ngrabGetCurrent :: IO (Maybe Widget)\ngrabGetCurrent = do\n wPtr <- {#call grab_get_current#}\n if (wPtr==nullPtr) then return Nothing else \n liftM Just $ makeNewObject mkWidget (return wPtr)\n\n-- | remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"180efd4e4bbb09b7a6677cf8ce78be191a1196ec","subject":"Simplified #funs in Internals to make haddock work properly","message":"Simplified #funs in Internals to make haddock work properly\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Control\/Parallel\/MPI\/Internal.chs","new_file":"src\/Control\/Parallel\/MPI\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n#include \n#include \"init_wrapper.h\"\n#include \"comparison_result.h\"\n#include \"error_classes.h\"\n#include \"thread_support.h\"\n-----------------------------------------------------------------------------\n{- |\nModule : Control.Parallel.MPI.Internal\nCopyright : (c) 2010 Bernie Pope, Dmitry Astapov\nLicense : BSD-style\nMaintainer : florbitous@gmail.com\nStability : experimental\nPortability : ghc\n\nThis module contains low-level Haskell bindings to core MPI functions.\nAll Haskell functions correspond to MPI functions with the similar\nname (i.e. @commRank@ is the binding for @MPI_Comm_rank@)\n\nActual types of all functions defined here depend on the MPI\nimplementation.\n\nSince \"Control.Parallel.MPI.Storable\" and\n\"Control.Parallel.MPI.Serializable\" contains many functions of the\nsame name as defined here, users would want to import this module\nqualified.\n-}\n-----------------------------------------------------------------------------\nmodule Control.Parallel.MPI.Internal\n ( maxProcessorName,\n maxErrorString,\n init, initThread, queryThread, isThreadMain, initialized, finalized,\n finalize, getProcessorName, getVersion, Version(..),\n send, bsend, ssend, rsend, recv,\n commRank, probe, commSize, commTestInter, commRemoteSize,\n commCompare, commGetAttr,\n isend, ibsend, issend, isendPtr, ibsendPtr, issendPtr, irecv, irecvPtr, bcast, barrier, wait, waitall, test,\n cancel, scatter, gather,\n scatterv, gatherv,\n allgather, allgatherv,\n alltoall, alltoallv,\n reduce, allreduce, reduceScatter,\n opCreate, opFree,\n wtime, wtick,\n commGroup, groupRank, groupSize, groupUnion, groupIntersection, groupDifference,\n groupCompare, groupExcl, groupIncl, groupTranslateRanks,\n typeSize,\n errorClass, errorString, commSetErrhandler, commGetErrhandler,\n abort,\n Comm(), commWorld, commSelf,\n ComparisonResult (..),\n Datatype(), char, wchar, short, int, long, longLong, unsignedChar,\n unsignedShort, unsigned, unsignedLong, unsignedLongLong, float, double,\n longDouble, byte, packed,\n Errhandler, errorsAreFatal, errorsReturn,\n ErrorClass (..), MPIError(..),\n Group(), groupEmpty,\n Operation(), maxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp,\n borOp, lxorOp, bxorOp,\n Rank(), rankId, toRank, fromRank, anySource, theRoot, procNull,\n Request(),\n Status (..),\n Tag(), toTag, fromTag, tagVal, anyTag, tagUpperBound,\n ThreadSupport (..)\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Data.Maybe (fromMaybe)\nimport Control.Monad (liftM, unless)\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception\n\n{# context prefix = \"MPI\" #}\n\ntype BufferPtr = Ptr ()\ntype Count = CInt\n\n{-\nThis module provides Haskell enum that comprises of MPI constants\n@MPI_IDENT@, @MPI_CONGRUENT@, @MPI_SIMILAR@ and @MPI_UNEQUAL@.\n\nThose are used to compare communicators (f.e. 'commCompare') and\nprocess groups (f.e. 'groupCompare').\n-}\n{# enum ComparisonResult {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- | Which Haskell type will be used as @Comm@ depends on the MPI\n-- implementation that was selected during compilation. It could be\n-- @CInt@, @Ptr ()@, @Ptr CInt@ or something else.\ntype MPIComm = {# type MPI_Comm #}\nnewtype Comm = MkComm { fromComm :: MPIComm }\nforeign import ccall \"&mpi_comm_world\" commWorld_ :: Ptr MPIComm\nforeign import ccall \"&mpi_comm_self\" commSelf_ :: Ptr MPIComm\n\n-- | Predefined handle for communicator that includes all running\n-- processes. Similar to @MPI_Comm_world@\ncommWorld :: Comm\ncommWorld = MkComm <$> unsafePerformIO $ peek commWorld_\n\n-- | Predefined handle for communicator that includes only current\n-- process. Similar to @MPI_Comm_self@\ncommSelf :: Comm\ncommSelf = MkComm <$> unsafePerformIO $ peek commSelf_\n\nforeign import ccall \"&mpi_max_processor_name\" max_processor_name_ :: Ptr CInt\nforeign import ccall \"&mpi_max_error_string\" max_error_string_ :: Ptr CInt\nmaxProcessorName :: CInt\nmaxProcessorName = unsafePerformIO $ peek max_processor_name_\nmaxErrorString :: CInt\nmaxErrorString = unsafePerformIO $ peek max_error_string_\n\n-- | Initialize the MPI environment. The MPI environment must be intialized by each\n-- MPI process before any other MPI function is called. Note that\n-- the environment may also be initialized by the functions 'initThread', 'mpi',\n-- and 'mpiWorld'. It is an error to attempt to initialize the environment more\n-- than once for a given MPI program execution. The only MPI functions that may\n-- be called before the MPI environment is initialized are 'getVersion',\n-- 'initialized' and 'finalized'. This function corresponds to @MPI_Init@.\n{# fun unsafe init_wrapper as init {} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been initialized. Returns @True@ if the\n-- environment has been initialized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Initialized@.\n{# fun unsafe Initialized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been finalized. Returns @True@ if the\n-- environment has been finalized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Finalized@.\n{# fun unsafe Finalized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Initialize the MPI environment with a \/required\/ level of thread support.\n-- See the documentation for 'init' for more information about MPI initialization.\n-- The \/provided\/ level of thread support is returned in the result.\n-- There is no guarantee that provided will be greater than or equal to required.\n-- The level of provided thread support depends on the underlying MPI implementation,\n-- and may also depend on information provided when the program is executed\n-- (for example, by supplying appropriate arguments to @mpiexec@).\n-- If the required level of support cannot be provided then it will try to\n-- return the least supported level greater than what was required.\n-- If that cannot be satisfied then it will return the highest supported level\n-- provided by the MPI implementation. See the documentation for 'ThreadSupport'\n-- for information about what levels are available and their relative ordering.\n-- This function corresponds to @MPI_Init_thread@.\n{# fun unsafe init_wrapper_thread as initThread\n {cFromEnum `ThreadSupport', alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\n{# fun unsafe Query_thread as ^ {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n{# fun unsafe Is_thread_main as ^\n {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Terminate the MPI execution environment.\n-- Once 'finalize' is called no other MPI functions may be called except\n-- 'getVersion', 'initialized' and 'finalized'. Each process must complete\n-- any pending communication that it initiated before calling 'finalize'.\n-- If 'finalize' returns then regular (non-MPI) computations may continue,\n-- but no further MPI computation is possible. Note: the error code returned\n-- by 'finalize' is not checked. This function corresponds to @MPI_Finalize@.\n{# fun unsafe Finalize as ^ {} -> `()' discard*- #}\ndiscard _ = return ()\n-- XXX can't call checkError on finalize, because\n-- checkError calls Internal.errorClass and Internal.errorString.\n-- These cannot be called after finalize (at least on OpenMPI).\n\ngetProcessorName :: IO String\ngetProcessorName = do\n allocaBytes (fromIntegral maxProcessorName) $ \\ptr -> do\n len <- getProcessorName' ptr\n peekCStringLen (ptr, cIntConv len)\n where\n getProcessorName' = {# fun unsafe Get_processor_name as getProcessorName_\n {id `Ptr CChar', alloca- `CInt' peekIntConv*} -> `()' checkError*- #}\n\ndata Version =\n Version { version :: Int, subversion :: Int }\n deriving (Eq, Ord)\n\ninstance Show Version where\n show v = show (version v) ++ \".\" ++ show (subversion v)\n\ngetVersion :: IO Version\ngetVersion = do\n (version, subversion) <- getVersion'\n return $ Version version subversion\n where\n getVersion' = {# fun unsafe Get_version as getVersion_\n {alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Return the number of processes involved in a communicator. For 'commWorld'\n-- it returns the total number of processes available. If the communicator is\n-- and intra-communicator it returns the number of processes in the local group.\n-- This function corresponds to @MPI_Comm_size@.\n{# fun unsafe Comm_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n{# fun unsafe Comm_remote_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n{# fun unsafe Comm_test_inter as ^\n {fromComm `Comm', alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\ncommGetAttr :: Storable e => Comm -> Int -> IO (Maybe e)\ncommGetAttr comm key = do\n isInitialized <- initialized\n if isInitialized then do \n alloca $ \\ptr -> do\n found <- commGetAttr' comm key (castPtr ptr)\n if found then do ptr2 <- peek ptr\n Just <$> peek ptr2\n else return Nothing\n else return Nothing\n where\n commGetAttr' = {# fun unsafe Comm_get_attr as commGetAttr_\n {fromComm `Comm', cIntConv `Int', id `Ptr ()', alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\nforeign import ccall unsafe \"&mpi_tag_ub\" tagUB_ :: Ptr Int\n\n-- | Predefined tag value that allows reception of the messages with\n-- arbitrary tag values. Corresponds to @MPI_ANY_TAG@.\ntagUpperBound :: Int\ntagUpperBound =\n let key = unsafePerformIO (peek tagUB_) \n in fromMaybe 0 $ unsafePerformIO (commGetAttr commWorld key)\n\n-- | Return the rank of the calling process for the given communicator.\n-- This function corresponds to @MPI_Comm_rank@.\n{# fun unsafe Comm_rank as ^\n {fromComm `Comm', alloca- `Rank' peekIntConv* } -> `()' checkError*- #}\n\n{# fun unsafe Comm_compare as ^\n {fromComm `Comm', fromComm `Comm', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- | Test for an incomming message, without actually receiving it.\n-- If a message has been sent from @Rank@ to the current process with @Tag@ on the\n-- communicator @Comm@ then 'probe' will return the 'Status' of the message. Otherwise\n-- it will block the current process until such a matching message is sent.\n-- This allows the current process to check for an incoming message and decide\n-- how to receive it, based on the information in the 'Status'.\n-- This function corresponds to @MPI_Probe@.\n{# fun Probe as ^\n {fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n{- probe :: Rank -- ^ Rank of the sender.\n -> Tag -- ^ Tag of the sent message.\n -> Comm -- ^ Communicator.\n -> IO Status -- ^ Information about the incoming message (but not the content of the message). -}\n\n{# fun unsafe Send as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Bsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Ssend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Rsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Recv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast* } -> `()' checkError*- #}\n{# fun unsafe Isend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n{# fun unsafe Ibsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n{# fun unsafe Issend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n{# fun unsafe Isend as isendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n{# fun unsafe Ibsend as ibsendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n{# fun unsafe Issend as issendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n{# fun Irecv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n{# fun Irecv as irecvPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n{# fun unsafe Bcast as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocks until all processes on the communicator call this function.\n-- This function corresponds to @MPI_Barrier@.\n{# fun unsafe Barrier as ^ {fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocking test for the completion of a send of receive.\n-- See 'test' for a non-blocking variant.\n-- This function corresponds to @MPI_Wait@.\n{# fun unsafe Wait as ^\n {withRequest* `Request', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- TODO: Make this Storable Array instead of Ptr ?\n{# fun unsafe Waitall as ^\n { id `Count', castPtr `Ptr Request', castPtr `Ptr Status'} -> `()' checkError*- #}\n\n-- | Non-blocking test for the completion of a send or receive.\n-- Returns @Nothing@ if the request is not complete, otherwise\n-- it returns @Just status@. See 'wait' for a blocking variant.\n-- This function corresponds to @MPI_Test@.\ntest :: Request -> IO (Maybe Status)\ntest request = do\n (flag, status) <- test' request\n if flag\n then return $ Just status\n else return Nothing\n where\n test' = {# fun unsafe Test as test_\n {withRequest* `Request', alloca- `Bool' peekBool*, allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Cancel a pending communication request.\n-- This function corresponds to @MPI_Cancel@.\n{# fun unsafe Cancel as ^\n {withRequest* `Request'} -> `()' checkError*- #}\nwithRequest req f = do alloca $ \\ptr -> do poke ptr req\n f (castPtr ptr)\n{# fun unsafe Scatter as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n{# fun unsafe Gather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- We pass counts\/displs as Ptr CInt so that caller could supply nullPtr here\n-- which would be impossible if we marshal arrays ourselves here.\n{# fun unsafe Scatterv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Gatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Allgather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Allgatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Alltoall as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Alltoallv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\n{# fun Reduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n{# fun Allreduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n{# fun Reduce_scatter as ^\n { id `BufferPtr', id `BufferPtr', id `Ptr CInt', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Op_create as ^\n {castFunPtr `FunPtr (Ptr t -> Ptr t -> Ptr CInt -> Ptr Datatype -> IO ())', cFromEnum `Bool', alloca- `Operation' peekOperation*} -> `()' checkError*- #}\nopFree = {# call unsafe Op_free as opFree_ #}\n{# fun unsafe Wtime as ^ {} -> `Double' realToFrac #}\n{# fun unsafe Wtick as ^ {} -> `Double' realToFrac #}\n\n-- | Return the process group from a communicator.\n{# fun unsafe Comm_group as ^\n {fromComm `Comm', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupRank = unsafePerformIO <$> groupRank'\n where groupRank' = {# fun unsafe Group_rank as groupRank_\n {fromGroup `Group', alloca- `Rank' peekIntConv*} -> `()' checkError*- #}\n\ngroupSize = unsafePerformIO <$> groupSize'\n where groupSize' = {# fun unsafe Group_size as groupSize_\n {fromGroup `Group', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\ngroupUnion g1 g2 = unsafePerformIO $ groupUnion' g1 g2\n where groupUnion' = {# fun unsafe Group_union as groupUnion_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupIntersection g1 g2 = unsafePerformIO $ groupIntersection' g1 g2\n where groupIntersection' = {# fun unsafe Group_intersection as groupIntersection_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupDifference g1 g2 = unsafePerformIO $ groupDifference' g1 g2\n where groupDifference' = {# fun unsafe Group_difference as groupDifference_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupCompare g1 g2 = unsafePerformIO $ groupCompare' g1 g2\n where\n groupCompare' = {# fun unsafe Group_compare as groupCompare_\n {fromGroup `Group', fromGroup `Group', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- Technically it might make better sense to make the second argument a Set rather than a list\n-- but the order is significant in the groupIncl function (the other function, not this one).\n-- For the sake of keeping their types in sync, a list is used instead.\n{# fun unsafe Group_excl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n{# fun unsafe Group_incl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupTranslateRanks :: Group -> [Rank] -> Group -> [Rank]\ngroupTranslateRanks group1 ranks group2 =\n unsafePerformIO $ do\n let (rankIntList :: [Int]) = map fromEnum ranks\n withArrayLen rankIntList $ \\size ranksPtr ->\n allocaArray size $ \\resultPtr -> do\n groupTranslateRanks' group1 (cFromEnum size) (castPtr ranksPtr) group2 resultPtr\n map toRank <$> peekArray size resultPtr\n where\n groupTranslateRanks' = {# fun unsafe Group_translate_ranks as groupTranslateRanks_\n {fromGroup `Group', id `CInt', id `Ptr CInt', fromGroup `Group', id `Ptr CInt'} -> `()' checkError*- #}\n\nwithRanksAsInts ranks f = withArrayLen (map fromEnum ranks) $ \\size ptr -> f (cIntConv size, castPtr ptr)\n\n-- | Return the number of bytes used to store an MPI 'Datatype'.\ntypeSize = unsafePerformIO . typeSize'\n where\n typeSize' =\n {# fun unsafe Type_size as typeSize_\n {fromDatatype `Datatype', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n{# fun unsafe Error_class as ^\n { id `CInt', alloca- `CInt' peek*} -> `CInt' id #}\nerrorString = {# call unsafe Error_string as errorString_ #}\n\n-- | Set the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_set_errhandler@.\n{# fun unsafe Comm_set_errhandler as ^\n {fromComm `Comm', fromErrhandler `Errhandler'} -> `()' checkError*- #}\n\n-- | Get the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_get_errhandler@.\n{# fun unsafe Comm_get_errhandler as ^\n {fromComm `Comm', alloca- `Errhandler' peekErrhandler*} -> `()' checkError*- #}\n\n-- | Tries to terminate all MPI processes in its communicator argument.\n-- The second argument is an error code which \/may\/ be used as the return status\n-- of the MPI process, but this is not guaranteed. On systems where 'Int' has a larger\n-- range than 'CInt', the error code will be clipped to fit into the range of 'CInt'.\n-- This function corresponds to @MPI_Abort@.\nabort :: Comm -> Int -> IO ()\nabort comm code =\n abort' comm (toErrorCode code)\n where\n toErrorCode :: Int -> CInt\n toErrorCode i\n -- Assumes Int always has range at least as big as CInt.\n | i < (fromIntegral (minBound :: CInt)) = minBound\n | i > (fromIntegral (maxBound :: CInt)) = maxBound\n | otherwise = cIntConv i\n\n abort' = {# fun unsafe Abort as abort_ {fromComm `Comm', id `CInt'} -> `()' checkError*- #}\n\n\ntype MPIDatatype = {# type MPI_Datatype #}\n\nnewtype Datatype = MkDatatype { fromDatatype :: MPIDatatype }\n\nforeign import ccall unsafe \"&mpi_char\" char_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_wchar\" wchar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_short\" short_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_int\" int_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long\" long_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_long\" longLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_char\" unsignedChar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_short\" unsignedShort_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned\" unsigned_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long\" unsignedLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long_long\" unsignedLongLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_float\" float_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_double\" double_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_double\" longDouble_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_byte\" byte_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_packed\" packed_ :: Ptr MPIDatatype\n\nchar, wchar, short, int, long, longLong, unsignedChar, unsignedShort :: Datatype\nunsigned, unsignedLong, unsignedLongLong, float, double, longDouble :: Datatype\nbyte, packed :: Datatype\n\nchar = MkDatatype <$> unsafePerformIO $ peek char_\nwchar = MkDatatype <$> unsafePerformIO $ peek wchar_\nshort = MkDatatype <$> unsafePerformIO $ peek short_\nint = MkDatatype <$> unsafePerformIO $ peek int_\nlong = MkDatatype <$> unsafePerformIO $ peek long_\nlongLong = MkDatatype <$> unsafePerformIO $ peek longLong_\nunsignedChar = MkDatatype <$> unsafePerformIO $ peek unsignedChar_\nunsignedShort = MkDatatype <$> unsafePerformIO $ peek unsignedShort_\nunsigned = MkDatatype <$> unsafePerformIO $ peek unsigned_\nunsignedLong = MkDatatype <$> unsafePerformIO $ peek unsignedLong_\nunsignedLongLong = MkDatatype <$> unsafePerformIO $ peek unsignedLongLong_\nfloat = MkDatatype <$> unsafePerformIO $ peek float_\ndouble = MkDatatype <$> unsafePerformIO $ peek double_\nlongDouble = MkDatatype <$> unsafePerformIO $ peek longDouble_\nbyte = MkDatatype <$> unsafePerformIO $ peek byte_\npacked = MkDatatype <$> unsafePerformIO $ peek packed_\n\n\ntype MPIErrhandler = {# type MPI_Errhandler #}\nnewtype Errhandler = MkErrhandler { fromErrhandler :: MPIErrhandler } deriving Storable\npeekErrhandler ptr = MkErrhandler <$> peek ptr\n\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr MPIErrhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr MPIErrhandler\nerrorsAreFatal, errorsReturn :: Errhandler\nerrorsAreFatal = MkErrhandler <$> unsafePerformIO $ peek errorsAreFatal_\nerrorsReturn = MkErrhandler <$> unsafePerformIO $ peek errorsReturn_\n\n{# enum ErrorClass {underscoreToCase} deriving (Eq,Ord,Show,Typeable) #}\n\n-- XXX Should this be a ForeinPtr?\n-- there is a MPI_Group_free function, which we should probably\n-- call when the group is no longer referenced.\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIGroup = {# type MPI_Group #}\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\npeekGroup ptr = MkGroup <$> peek ptr\n\nforeign import ccall \"&mpi_group_empty\" groupEmpty_ :: Ptr MPIGroup\n-- | Predefined handle for group without any members. Corresponds to @MPI_GROUP_EMPTY@\ngroupEmpty :: Group\ngroupEmpty = MkGroup <$> unsafePerformIO $ peek groupEmpty_\n\n\n{-\nThis module provides Haskell type that represents values of @MPI_Op@\ntype (reduction operations), and predefined reduction operations\ndefined in the MPI Report.\n-}\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIOperation = {# type MPI_Op #}\nnewtype Operation = MkOperation { fromOperation :: MPIOperation } deriving Storable\npeekOperation ptr = MkOperation <$> peek ptr\n\nforeign import ccall unsafe \"&mpi_max\" maxOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_min\" minOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_sum\" sumOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_prod\" prodOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_land\" landOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_band\" bandOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lor\" lorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bor\" borOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lxor\" lxorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bxor\" bxorOp_ :: Ptr MPIOperation\n-- foreign import ccall \"mpi_maxloc\" maxlocOp :: MPIOperation\n-- foreign import ccall \"mpi_minloc\" minlocOp :: MPIOperation\n-- foreign import ccall \"mpi_replace\" replaceOp :: MPIOperation\n-- TODO: support for those requires better support for pair datatypes\n\nmaxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp :: Operation\nmaxOp = MkOperation <$> unsafePerformIO $ peek maxOp_\nminOp = MkOperation <$> unsafePerformIO $ peek minOp_\nsumOp = MkOperation <$> unsafePerformIO $ peek sumOp_\nprodOp = MkOperation <$> unsafePerformIO $ peek prodOp_\nlandOp = MkOperation <$> unsafePerformIO $ peek landOp_\nbandOp = MkOperation <$> unsafePerformIO $ peek bandOp_\nlorOp = MkOperation <$> unsafePerformIO $ peek lorOp_\nborOp = MkOperation <$> unsafePerformIO $ peek borOp_\nlxorOp = MkOperation <$> unsafePerformIO $ peek lxorOp_\nbxorOp = MkOperation <$> unsafePerformIO $ peek bxorOp_\n\n\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI rank designations.\n-}\n\nnewtype Rank = MkRank { rankId :: Int }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Rank where\n (MkRank x) + (MkRank y) = MkRank (x+y)\n (MkRank x) * (MkRank y) = MkRank (x*y)\n abs (MkRank x) = MkRank (abs x)\n signum (MkRank x) = MkRank (signum x)\n fromInteger x \n | x > ( fromIntegral (maxBound :: CInt)) = error \"Rank value does not fit into 32 bits\" \n | x < 0 = error \"Negative Rank value\"\n | otherwise = MkRank (fromIntegral x)\n\nforeign import ccall \"mpi_any_source\" anySource_ :: Ptr Int\nforeign import ccall \"mpi_root\" theRoot_ :: Ptr Int\nforeign import ccall \"mpi_proc_null\" procNull_ :: Ptr Int\n\n-- | Predefined rank number that allows reception of point-to-point messages\n-- regardless of their source. Corresponds to @MPI_ANY_SOURCE@\nanySource :: Rank\nanySource = toRank $ unsafePerformIO $ peek anySource_\n\n-- | Predefined rank number that specifies root process during\n-- operations involving intercommunicators. Corresponds to @MPI_ROOT@\ntheRoot :: Rank\ntheRoot = toRank $ unsafePerformIO $ peek theRoot_\n\n-- | Predefined rank number that specifies non-root processes during\n-- operations involving intercommunicators. Corresponds to @MPI_PROC_NULL@\nprocNull :: Rank\nprocNull = toRank $ unsafePerformIO $ peek procNull_\n\ninstance Show Rank where\n show = show . rankId\n\ntoRank :: Enum a => a -> Rank\ntoRank x = MkRank { rankId = fromEnum x }\n\nfromRank :: Enum a => Rank -> a\nfromRank = toEnum . rankId\n\n{- This module provides Haskell representation of the @MPI_Request@ type. -}\ntype MPIRequest = {# type MPI_Request #}\nnewtype Request = MkRequest MPIRequest deriving Storable\npeekRequest ptr = MkRequest <$> peek ptr\n\n{-\nThis module provides Haskell representation of the @MPI_Status@ type\n(request status).\n\nField `status_error' should be used with care:\n\\\"The error field in status is not needed for calls that return only\none status, such as @MPI_WAIT@, since that would only duplicate the\ninformation returned by the function itself. The current design avoids\nthe additional overhead of setting it, in such cases. The field is\nneeded for calls that return multiple statuses, since each request may\nhave had a different failure.\\\"\n(this is a quote from )\n\nThis means that, for example, during the call to @MPI_Wait@\nimplementation is free to leave this field filled with whatever\ngarbage got there during memory allocation. Haskell FFI is not\nblanking out freshly allocated memory, so beware!\n-}\n\n-- | Haskell structure that holds fields of @MPI_Status@.\n--\n-- Please note that MPI report lists only three fields as mandatory:\n-- @status_source@, @status_tag@ and @status_error@. However, all\n-- MPI implementations that were used to test those bindings supported\n-- extended set of fields represented here.\ndata Status =\n Status\n { status_source :: CInt -- ^ rank of the source process\n , status_tag :: CInt -- ^ tag assigned at source\n , status_error :: CInt -- ^ error code, if any\n , status_count :: CInt -- ^ number of received elements, if applicable\n , status_cancelled :: CInt -- ^ whether the request was cancelled\n }\n deriving (Eq, Ord, Show)\n\ninstance Storable Status where\n sizeOf _ = {#sizeof MPI_Status #}\n alignment _ = 4\n peek p = Status\n <$> liftM cIntConv ({#get MPI_Status->MPI_SOURCE #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_TAG #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_ERROR #} p)\n#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields-\n <*> liftM cIntConv ({#get MPI_Status->count #} p)\n <*> liftM cIntConv ({#get MPI_Status->cancelled #} p)\n#else\n <*> liftM cIntConv ({#get MPI_Status->_count #} p)\n <*> liftM cIntConv ({#get MPI_Status->_cancelled #} p)\n#endif\n poke p x = do\n {#set MPI_Status.MPI_SOURCE #} p (cIntConv $ status_source x)\n {#set MPI_Status.MPI_TAG #} p (cIntConv $ status_tag x)\n {#set MPI_Status.MPI_ERROR #} p (cIntConv $ status_error x)\n#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields AND different order of fields\n {#set MPI_Status.count #} p (cIntConv $ status_count x)\n {#set MPI_Status.cancelled #} p (cIntConv $ status_cancelled x)\n#else\n {#set MPI_Status._count #} p (cIntConv $ status_count x)\n {#set MPI_Status._cancelled #} p (cIntConv $ status_cancelled x)\n#endif\n\n-- NOTE: Int here is picked arbitrary\nallocaCast f =\n alloca $ \\(ptr :: Ptr Int) -> f (castPtr ptr :: Ptr ())\npeekCast = peek . castPtr\n\n\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI tags.\n-}\n\nnewtype Tag = MkTag { tagVal :: Int }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Tag where\n (MkTag x) + (MkTag y) = MkTag (x+y)\n (MkTag x) * (MkTag y) = MkTag (x*y)\n abs (MkTag x) = MkTag (abs x)\n signum (MkTag x) = MkTag (signum x)\n fromInteger x \n | fromIntegral x > tagUpperBound = error \"Tag value is over the MPI_TAG_UB\" \n | x < 0 = error \"Negative Tag value\"\n | otherwise = MkTag (fromIntegral x)\n\ninstance Show Tag where\n show = show . tagVal\n\ntoTag :: Enum a => a -> Tag\ntoTag x = MkTag { tagVal = fromEnum x }\n\nfromTag :: Enum a => Tag -> a\nfromTag = toEnum . tagVal\n\nforeign import ccall unsafe \"&mpi_any_tag\" anyTag_ :: Ptr Int\n\n-- | Predefined tag value that allows reception of the messages with\n-- arbitrary tag values. Corresponds to @MPI_ANY_TAG@.\nanyTag :: Tag\nanyTag = toTag $ unsafePerformIO $ peek anyTag_\n\n{-\nThis module provides Haskell datatypes that comprises of values of\npredefined MPI constants @MPI_THREAD_SINGLE@, @MPI_THREAD_FUNNELED@,\n@MPI_THREAD_SERIALIZED@, @MPI_THREAD_MULTIPLE@.\n-}\n\n{# enum ThreadSupport {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n{- From MPI 2.2 report:\n \"To make it possible for an application to interpret an error code, the routine\n MPI_ERROR_CLASS converts any error code into one of a small set of standard\n error codes\"\n-}\n\ndata MPIError\n = MPIError\n { mpiErrorClass :: ErrorClass\n , mpiErrorString :: String\n }\n deriving (Eq, Show, Typeable)\n\ninstance Exception MPIError\n\ncheckError :: CInt -> IO ()\ncheckError code = do\n -- We ignore the error code from the call to Internal.errorClass\n -- because we call errorClass from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n (_, errClassRaw) <- errorClass code\n let errClass = cToEnum errClassRaw\n unless (errClass == Success) $ do\n errStr <- errorStringWrapper code\n throwIO $ MPIError errClass errStr\n\nerrorStringWrapper :: CInt -> IO String\nerrorStringWrapper code =\n allocaBytes (fromIntegral maxErrorString) $ \\ptr ->\n alloca $ \\lenPtr -> do\n -- We ignore the error code from the call to Internal.errorString\n -- because we call errorString from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n _ <- errorString code ptr lenPtr\n len <- peek lenPtr\n peekCStringLen (ptr, cIntConv len)\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n#include \n#include \"init_wrapper.h\"\n#include \"comparison_result.h\"\n#include \"error_classes.h\"\n#include \"thread_support.h\"\n-----------------------------------------------------------------------------\n{- |\nModule : Control.Parallel.MPI.Internal\nCopyright : (c) 2010 Bernie Pope, Dmitry Astapov\nLicense : BSD-style\nMaintainer : florbitous@gmail.com\nStability : experimental\nPortability : ghc\n\nThis module contains low-level Haskell bindings to core MPI functions.\nAll Haskell functions correspond to MPI functions with the similar\nname (i.e. @commRank@ is the binding for @MPI_Comm_rank@)\n\nActual types of all functions defined here depend on the MPI\nimplementation.\n\nSince \"Control.Parallel.MPI.Storable\" and\n\"Control.Parallel.MPI.Serializable\" contains many functions of the\nsame name as defined here, users would want to import this module\nqualified.\n-}\n-----------------------------------------------------------------------------\nmodule Control.Parallel.MPI.Internal\n ( maxProcessorName,\n maxErrorString,\n init, initThread, queryThread, isThreadMain, initialized, finalized,\n finalize, getProcessorName, getVersion, Version(..),\n send, bsend, ssend, rsend, recv,\n commRank, probe, commSize, commTestInter, commRemoteSize,\n commCompare, commGetAttr,\n isend, ibsend, issend, isendPtr, ibsendPtr, issendPtr, irecv, irecvPtr, bcast, barrier, wait, waitall, test,\n cancel, scatter, gather,\n scatterv, gatherv,\n allgather, allgatherv,\n alltoall, alltoallv,\n reduce, allreduce, reduceScatter,\n opCreate, opFree,\n wtime, wtick,\n commGroup, groupRank, groupSize, groupUnion, groupIntersection, groupDifference,\n groupCompare, groupExcl, groupIncl, groupTranslateRanks,\n typeSize,\n errorClass, errorString, commSetErrhandler, commGetErrhandler,\n abort,\n Comm(), commWorld, commSelf,\n ComparisonResult (..),\n Datatype(), char, wchar, short, int, long, longLong, unsignedChar,\n unsignedShort, unsigned, unsignedLong, unsignedLongLong, float, double,\n longDouble, byte, packed,\n Errhandler, errorsAreFatal, errorsReturn,\n ErrorClass (..), MPIError(..),\n Group(), groupEmpty,\n Operation(), maxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp,\n borOp, lxorOp, bxorOp,\n Rank(), rankId, toRank, fromRank, anySource, theRoot, procNull,\n Request(),\n Status (..),\n Tag(), toTag, fromTag, tagVal, anyTag, tagUpperBound,\n ThreadSupport (..)\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Data.Maybe (fromMaybe)\nimport Control.Monad (liftM, unless)\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception\n\n{# context prefix = \"MPI\" #}\n\ntype BufferPtr = Ptr ()\ntype Count = CInt\n\n{-\nThis module provides Haskell enum that comprises of MPI constants\n@MPI_IDENT@, @MPI_CONGRUENT@, @MPI_SIMILAR@ and @MPI_UNEQUAL@.\n\nThose are used to compare communicators (f.e. 'commCompare') and\nprocess groups (f.e. 'groupCompare').\n-}\n{# enum ComparisonResult {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- | Which Haskell type will be used as @Comm@ depends on the MPI\n-- implementation that was selected during compilation. It could be\n-- @CInt@, @Ptr ()@, @Ptr CInt@ or something else.\ntype MPIComm = {# type MPI_Comm #}\nnewtype Comm = MkComm { fromComm :: MPIComm }\nforeign import ccall \"&mpi_comm_world\" commWorld_ :: Ptr MPIComm\nforeign import ccall \"&mpi_comm_self\" commSelf_ :: Ptr MPIComm\n\n-- | Predefined handle for communicator that includes all running\n-- processes. Similar to @MPI_Comm_world@\ncommWorld :: Comm\ncommWorld = MkComm <$> unsafePerformIO $ peek commWorld_\n\n-- | Predefined handle for communicator that includes only current\n-- process. Similar to @MPI_Comm_self@\ncommSelf :: Comm\ncommSelf = MkComm <$> unsafePerformIO $ peek commSelf_\n\nforeign import ccall \"&mpi_max_processor_name\" max_processor_name_ :: Ptr CInt\nforeign import ccall \"&mpi_max_error_string\" max_error_string_ :: Ptr CInt\nmaxProcessorName :: CInt\nmaxProcessorName = unsafePerformIO $ peek max_processor_name_\nmaxErrorString :: CInt\nmaxErrorString = unsafePerformIO $ peek max_error_string_\n\n-- | Initialize the MPI environment. The MPI environment must be intialized by each\n-- MPI process before any other MPI function is called. Note that\n-- the environment may also be initialized by the functions 'initThread', 'mpi',\n-- and 'mpiWorld'. It is an error to attempt to initialize the environment more\n-- than once for a given MPI program execution. The only MPI functions that may\n-- be called before the MPI environment is initialized are 'getVersion',\n-- 'initialized' and 'finalized'. This function corresponds to @MPI_Init@.\ninit = {# fun unsafe init_wrapper as init_wrapper_ {} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been initialized. Returns @True@ if the\n-- environment has been initialized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Initialized@.\ninitialized = {# fun unsafe Initialized as initialized_ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been finalized. Returns @True@ if the\n-- environment has been finalized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Finalized@.\nfinalized = {# fun unsafe Finalized as finalized_ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Initialize the MPI environment with a \/required\/ level of thread support.\n-- See the documentation for 'init' for more information about MPI initialization.\n-- The \/provided\/ level of thread support is returned in the result.\n-- There is no guarantee that provided will be greater than or equal to required.\n-- The level of provided thread support depends on the underlying MPI implementation,\n-- and may also depend on information provided when the program is executed\n-- (for example, by supplying appropriate arguments to @mpiexec@).\n-- If the required level of support cannot be provided then it will try to\n-- return the least supported level greater than what was required.\n-- If that cannot be satisfied then it will return the highest supported level\n-- provided by the MPI implementation. See the documentation for 'ThreadSupport'\n-- for information about what levels are available and their relative ordering.\n-- This function corresponds to @MPI_Init_thread@.\ninitThread = {# fun unsafe init_wrapper_thread as init_wrapper_thread_\n {cFromEnum `ThreadSupport', alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\nqueryThread = {# fun unsafe Query_thread as queryThread_\n {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\nisThreadMain = {# fun unsafe Is_thread_main as isThreadMain_\n {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Terminate the MPI execution environment.\n-- Once 'finalize' is called no other MPI functions may be called except\n-- 'getVersion', 'initialized' and 'finalized'. Each process must complete\n-- any pending communication that it initiated before calling 'finalize'.\n-- If 'finalize' returns then regular (non-MPI) computations may continue,\n-- but no further MPI computation is possible. Note: the error code returned\n-- by 'finalize' is not checked. This function corresponds to @MPI_Finalize@.\nfinalize = {# fun unsafe Finalize as finalize_ {} -> `()' discard*- #}\n where discard _ = return ()\n-- XXX can't call checkError on finalize, because\n-- checkError calls Internal.errorClass and Internal.errorString.\n-- These cannot be called after finalize (at least on OpenMPI).\n\ngetProcessorName :: IO String\ngetProcessorName = do\n allocaBytes (fromIntegral maxProcessorName) $ \\ptr -> do\n len <- getProcessorName' ptr\n peekCStringLen (ptr, cIntConv len)\n where\n getProcessorName' = {# fun unsafe Get_processor_name as getProcessorName_\n {id `Ptr CChar', alloca- `CInt' peekIntConv*} -> `()' checkError*- #}\n\ndata Version =\n Version { version :: Int, subversion :: Int }\n deriving (Eq, Ord)\n\ninstance Show Version where\n show v = show (version v) ++ \".\" ++ show (subversion v)\n\ngetVersion :: IO Version\ngetVersion = do\n (version, subversion) <- getVersion'\n return $ Version version subversion\n where\n getVersion' = {# fun unsafe Get_version as getVersion_\n {alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Return the number of processes involved in a communicator. For 'commWorld'\n-- it returns the total number of processes available. If the communicator is\n-- and intra-communicator it returns the number of processes in the local group.\n-- This function corresponds to @MPI_Comm_size@.\ncommSize = {# fun unsafe Comm_size as commSize_\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\ncommRemoteSize = {# fun unsafe Comm_remote_size as commRemoteSize_\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\ncommTestInter = {# fun unsafe Comm_test_inter as commTestInter_\n {fromComm `Comm', alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\ncommGetAttr :: Storable e => Comm -> Int -> IO (Maybe e)\ncommGetAttr comm key = do\n isInitialized <- initialized\n if isInitialized then do \n alloca $ \\ptr -> do\n found <- commGetAttr' comm key (castPtr ptr)\n if found then do ptr2 <- peek ptr\n Just <$> peek ptr2\n else return Nothing\n else return Nothing\n where\n commGetAttr' = {# fun unsafe Comm_get_attr as commGetAttr_\n {fromComm `Comm', cIntConv `Int', id `Ptr ()', alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\nforeign import ccall unsafe \"&mpi_tag_ub\" tagUB_ :: Ptr Int\n\n-- | Predefined tag value that allows reception of the messages with\n-- arbitrary tag values. Corresponds to @MPI_ANY_TAG@.\ntagUpperBound :: Int\ntagUpperBound = \n let key = unsafePerformIO (peek tagUB_) \n in fromMaybe 0 $ unsafePerformIO (commGetAttr commWorld key)\n\n-- | Return the rank of the calling process for the given communicator.\n-- This function corresponds to @MPI_Comm_rank@.\ncommRank = {# fun unsafe Comm_rank as commRank_\n {fromComm `Comm', alloca- `Rank' peekIntConv* } -> `()' checkError*- #}\n\ncommCompare = {# fun unsafe Comm_compare as commCompare_\n {fromComm `Comm', fromComm `Comm', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- | Test for an incomming message, without actually receiving it.\n-- If a message has been sent from @Rank@ to the current process with @Tag@ on the\n-- communicator @Comm@ then 'probe' will return the 'Status' of the message. Otherwise\n-- it will block the current process until such a matching message is sent.\n-- This allows the current process to check for an incoming message and decide\n-- how to receive it, based on the information in the 'Status'.\n-- This function corresponds to @MPI_Probe@.\nprobe = {# fun Probe as probe_\n {fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n{- probe :: Rank -- ^ Rank of the sender.\n -> Tag -- ^ Tag of the sent message.\n -> Comm -- ^ Communicator.\n -> IO Status -- ^ Information about the incoming message (but not the content of the message). -}\n\nsend = {# fun unsafe Send as send_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\nbsend = {# fun unsafe Bsend as bsend_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\nssend = {# fun unsafe Ssend as ssend_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\nrsend = {# fun unsafe Rsend as rsend_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\nrecv = {# fun unsafe Recv as recv_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast* } -> `()' checkError*- #}\nisend = {# fun unsafe Isend as isend_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\nibsend = {# fun unsafe Ibsend as ibsend_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\nissend = {# fun unsafe Issend as issend_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\nisendPtr = {# fun unsafe Isend as isendPtr_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\nibsendPtr = {# fun unsafe Ibsend as ibsendPtr_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\nissendPtr = {# fun unsafe Issend as issendPtr_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\nirecv = {# fun Irecv as irecv_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\nirecvPtr = {# fun Irecv as irecvPtr_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\nbcast = {# fun unsafe Bcast as bcast_\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocks until all processes on the communicator call this function.\n-- This function corresponds to @MPI_Barrier@.\nbarrier = {# fun unsafe Barrier as barrier_ {fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocking test for the completion of a send of receive.\n-- See 'test' for a non-blocking variant.\n-- This function corresponds to @MPI_Wait@.\nwait = {# fun unsafe Wait as wait_\n {withRequest* `Request', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- TODO: Make this Storable Array instead of Ptr ?\nwaitall = {# fun unsafe Waitall as waitall_\n { id `Count', castPtr `Ptr Request', castPtr `Ptr Status'} -> `()' checkError*- #}\n\n-- | Non-blocking test for the completion of a send or receive.\n-- Returns @Nothing@ if the request is not complete, otherwise\n-- it returns @Just status@. See 'wait' for a blocking variant.\n-- This function corresponds to @MPI_Test@.\n-- | Non-blocking test for the completion of a send or receive.\n-- Returns @Nothing@ if the request is not complete, otherwise\n-- it returns @Just status@. See 'wait' for a blocking variant.\n-- This function corresponds to @MPI_Test@.\ntest :: Request -> IO (Maybe Status)\ntest request = do\n (flag, status) <- test' request\n if flag\n then return $ Just status\n else return Nothing\n where\n test' = {# fun unsafe Test as test_\n {withRequest* `Request', alloca- `Bool' peekBool*, allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Cancel a pending communication request.\n-- This function corresponds to @MPI_Cancel@.\ncancel = {# fun unsafe Cancel as cancel_\n {withRequest* `Request'} -> `()' checkError*- #}\nwithRequest req f = do alloca $ \\ptr -> do poke ptr req\n f (castPtr ptr)\nscatter = {# fun unsafe Scatter as scatter_\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\ngather = {# fun unsafe Gather as gather_\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n-- We pass counts\/displs as Ptr CInt so that caller could supply nullPtr here\n-- which would be impossible if we marshal arrays ourselves here.\nscatterv = {# fun unsafe Scatterv as scatterv_\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\ngatherv = {# fun unsafe Gatherv as gatherv_\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\nallgather = {# fun unsafe Allgather as allgather_\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\nallgatherv = {# fun unsafe Allgatherv as allgatherv_\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\nalltoall = {# fun unsafe Alltoall as alltoall_\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\nalltoallv = {# fun unsafe Alltoallv as alltoallv_\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\nreduce = {# fun Reduce as reduce_ \n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\nallreduce = {# fun Allreduce as allreduce_\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\nreduceScatter = {# fun Reduce_scatter as reduceScatter_\n { id `BufferPtr', id `BufferPtr', id `Ptr CInt', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\nopCreate = {# fun unsafe Op_create as opCreate_\n {castFunPtr `FunPtr (Ptr t -> Ptr t -> Ptr CInt -> Ptr Datatype -> IO ())', cFromEnum `Bool', alloca- `Operation' peekOperation*} -> `()' checkError*- #}\nopFree = {# call unsafe Op_free as opFree_ #}\nwtime = {# fun unsafe Wtime as wtime_ {} -> `Double' realToFrac #}\nwtick = {# fun unsafe Wtick as wtick_ {} -> `Double' realToFrac #}\n\n-- | Return the process group from a communicator.\ncommGroup = {# fun unsafe Comm_group as commGroup_\n {fromComm `Comm', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupRank = unsafePerformIO <$> groupRank'\n where groupRank' = {# fun unsafe Group_rank as groupRank_\n {fromGroup `Group', alloca- `Rank' peekIntConv*} -> `()' checkError*- #}\n\ngroupSize = unsafePerformIO <$> groupSize'\n where groupSize' = {# fun unsafe Group_size as groupSize_\n {fromGroup `Group', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\ngroupUnion g1 g2 = unsafePerformIO $ groupUnion' g1 g2\n where groupUnion' = {# fun unsafe Group_union as groupUnion_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupIntersection g1 g2 = unsafePerformIO $ groupIntersection' g1 g2\n where groupIntersection' = {# fun unsafe Group_intersection as groupIntersection_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupDifference g1 g2 = unsafePerformIO $ groupDifference' g1 g2\n where groupDifference' = {# fun unsafe Group_difference as groupDifference_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupCompare g1 g2 = unsafePerformIO $ groupCompare' g1 g2\n where\n groupCompare' = {# fun unsafe Group_compare as groupCompare_\n {fromGroup `Group', fromGroup `Group', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- Technically it might make better sense to make the second argument a Set rather than a list\n-- but the order is significant in the groupIncl function (the other function, not this one).\n-- For the sake of keeping their types in sync, a list is used instead.\ngroupExcl = {# fun unsafe Group_excl as groupExcl_\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\ngroupIncl = {# fun unsafe Group_incl as groupIncl_\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupTranslateRanks :: Group -> [Rank] -> Group -> [Rank]\ngroupTranslateRanks group1 ranks group2 =\n unsafePerformIO $ do\n let (rankIntList :: [Int]) = map fromEnum ranks\n withArrayLen rankIntList $ \\size ranksPtr ->\n allocaArray size $ \\resultPtr -> do\n groupTranslateRanks' group1 (cFromEnum size) (castPtr ranksPtr) group2 resultPtr\n map toRank <$> peekArray size resultPtr\n where\n groupTranslateRanks' = {# fun unsafe Group_translate_ranks as groupTranslateRanks_\n {fromGroup `Group', id `CInt', id `Ptr CInt', fromGroup `Group', id `Ptr CInt'} -> `()' checkError*- #}\n\nwithRanksAsInts ranks f = withArrayLen (map fromEnum ranks) $ \\size ptr -> f (cIntConv size, castPtr ptr)\n\n-- | Return the number of bytes used to store an MPI 'Datatype'.\ntypeSize = unsafePerformIO . typeSize'\n where\n typeSize' =\n {# fun unsafe Type_size as typeSize_\n {fromDatatype `Datatype', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n\nerrorClass = {# fun unsafe Error_class as errorClass_\n { id `CInt', alloca- `CInt' peek*} -> `CInt' id #}\nerrorString = {# call unsafe Error_string as errorString_ #}\n\n-- | Set the error handler for a communicator.\n-- This function corresponds to MPI_Comm_set_errhandler.\ncommSetErrhandler = {# fun unsafe Comm_set_errhandler as commSetErrhandler_\n {fromComm `Comm', fromErrhandler `Errhandler'} -> `()' checkError*- #}\n\n-- | Get the error handler for a communicator.\n-- This function corresponds to MPI_Comm_get_errhandler.\ncommGetErrhandler = {# fun unsafe Comm_get_errhandler as commGetErrhandler_\n {fromComm `Comm', alloca- `Errhandler' peekErrhandler*} -> `()' checkError*- #}\n\n-- | Tries to terminate all MPI processes in its communicator argument.\n-- The second argument is an error code which \/may\/ be used as the return status\n-- of the MPI process, but this is not guaranteed. On systems where 'Int' has a larger\n-- range than 'CInt', the error code will be clipped to fit into the range of 'CInt'.\n-- This function corresponds to @MPI_Abort@.\nabort :: Comm -> Int -> IO ()\nabort comm code =\n abort' comm (toErrorCode code)\n where\n toErrorCode :: Int -> CInt\n toErrorCode i\n -- Assumes Int always has range at least as big as CInt.\n | i < (fromIntegral (minBound :: CInt)) = minBound\n | i > (fromIntegral (maxBound :: CInt)) = maxBound\n | otherwise = cIntConv i\n\n abort' = {# fun unsafe Abort as abort_ {fromComm `Comm', id `CInt'} -> `()' checkError*- #}\n\n\ntype MPIDatatype = {# type MPI_Datatype #}\n\nnewtype Datatype = MkDatatype { fromDatatype :: MPIDatatype }\n\nforeign import ccall unsafe \"&mpi_char\" char_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_wchar\" wchar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_short\" short_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_int\" int_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long\" long_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_long\" longLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_char\" unsignedChar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_short\" unsignedShort_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned\" unsigned_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long\" unsignedLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long_long\" unsignedLongLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_float\" float_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_double\" double_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_double\" longDouble_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_byte\" byte_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_packed\" packed_ :: Ptr MPIDatatype\n\nchar, wchar, short, int, long, longLong, unsignedChar, unsignedShort :: Datatype\nunsigned, unsignedLong, unsignedLongLong, float, double, longDouble :: Datatype\nbyte, packed :: Datatype\n\nchar = MkDatatype <$> unsafePerformIO $ peek char_\nwchar = MkDatatype <$> unsafePerformIO $ peek wchar_\nshort = MkDatatype <$> unsafePerformIO $ peek short_\nint = MkDatatype <$> unsafePerformIO $ peek int_\nlong = MkDatatype <$> unsafePerformIO $ peek long_\nlongLong = MkDatatype <$> unsafePerformIO $ peek longLong_\nunsignedChar = MkDatatype <$> unsafePerformIO $ peek unsignedChar_\nunsignedShort = MkDatatype <$> unsafePerformIO $ peek unsignedShort_\nunsigned = MkDatatype <$> unsafePerformIO $ peek unsigned_\nunsignedLong = MkDatatype <$> unsafePerformIO $ peek unsignedLong_\nunsignedLongLong = MkDatatype <$> unsafePerformIO $ peek unsignedLongLong_\nfloat = MkDatatype <$> unsafePerformIO $ peek float_\ndouble = MkDatatype <$> unsafePerformIO $ peek double_\nlongDouble = MkDatatype <$> unsafePerformIO $ peek longDouble_\nbyte = MkDatatype <$> unsafePerformIO $ peek byte_\npacked = MkDatatype <$> unsafePerformIO $ peek packed_\n\n\ntype MPIErrhandler = {# type MPI_Errhandler #}\nnewtype Errhandler = MkErrhandler { fromErrhandler :: MPIErrhandler } deriving Storable\npeekErrhandler ptr = MkErrhandler <$> peek ptr\n\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr MPIErrhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr MPIErrhandler\nerrorsAreFatal, errorsReturn :: Errhandler\nerrorsAreFatal = MkErrhandler <$> unsafePerformIO $ peek errorsAreFatal_\nerrorsReturn = MkErrhandler <$> unsafePerformIO $ peek errorsReturn_\n\n{# enum ErrorClass {underscoreToCase} deriving (Eq,Ord,Show,Typeable) #}\n\n-- XXX Should this be a ForeinPtr?\n-- there is a MPI_Group_free function, which we should probably\n-- call when the group is no longer referenced.\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIGroup = {# type MPI_Group #}\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\npeekGroup ptr = MkGroup <$> peek ptr\n\nforeign import ccall \"&mpi_group_empty\" groupEmpty_ :: Ptr MPIGroup\n-- | Predefined handle for group without any members. Corresponds to @MPI_GROUP_EMPTY@\ngroupEmpty :: Group\ngroupEmpty = MkGroup <$> unsafePerformIO $ peek groupEmpty_\n\n\n{-\nThis module provides Haskell type that represents values of @MPI_Op@\ntype (reduction operations), and predefined reduction operations\ndefined in the MPI Report.\n-}\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIOperation = {# type MPI_Op #}\nnewtype Operation = MkOperation { fromOperation :: MPIOperation } deriving Storable\npeekOperation ptr = MkOperation <$> peek ptr\n\nforeign import ccall unsafe \"&mpi_max\" maxOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_min\" minOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_sum\" sumOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_prod\" prodOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_land\" landOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_band\" bandOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lor\" lorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bor\" borOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lxor\" lxorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bxor\" bxorOp_ :: Ptr MPIOperation\n-- foreign import ccall \"mpi_maxloc\" maxlocOp :: MPIOperation\n-- foreign import ccall \"mpi_minloc\" minlocOp :: MPIOperation\n-- foreign import ccall \"mpi_replace\" replaceOp :: MPIOperation\n-- TODO: support for those requires better support for pair datatypes\n\nmaxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp :: Operation\nmaxOp = MkOperation <$> unsafePerformIO $ peek maxOp_\nminOp = MkOperation <$> unsafePerformIO $ peek minOp_\nsumOp = MkOperation <$> unsafePerformIO $ peek sumOp_\nprodOp = MkOperation <$> unsafePerformIO $ peek prodOp_\nlandOp = MkOperation <$> unsafePerformIO $ peek landOp_\nbandOp = MkOperation <$> unsafePerformIO $ peek bandOp_\nlorOp = MkOperation <$> unsafePerformIO $ peek lorOp_\nborOp = MkOperation <$> unsafePerformIO $ peek borOp_\nlxorOp = MkOperation <$> unsafePerformIO $ peek lxorOp_\nbxorOp = MkOperation <$> unsafePerformIO $ peek bxorOp_\n\n\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI rank designations.\n-}\n\nnewtype Rank = MkRank { rankId :: Int }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Rank where\n (MkRank x) + (MkRank y) = MkRank (x+y)\n (MkRank x) * (MkRank y) = MkRank (x*y)\n abs (MkRank x) = MkRank (abs x)\n signum (MkRank x) = MkRank (signum x)\n fromInteger x \n | x > ( fromIntegral (maxBound :: CInt)) = error \"Rank value does not fit into 32 bits\" \n | x < 0 = error \"Negative Rank value\"\n | otherwise = MkRank (fromIntegral x)\n\nforeign import ccall \"mpi_any_source\" anySource_ :: Ptr Int\nforeign import ccall \"mpi_root\" theRoot_ :: Ptr Int\nforeign import ccall \"mpi_proc_null\" procNull_ :: Ptr Int\n\n-- | Predefined rank number that allows reception of point-to-point messages\n-- regardless of their source. Corresponds to @MPI_ANY_SOURCE@\nanySource :: Rank\nanySource = toRank $ unsafePerformIO $ peek anySource_\n\n-- | Predefined rank number that specifies root process during\n-- operations involving intercommunicators. Corresponds to @MPI_ROOT@\ntheRoot :: Rank\ntheRoot = toRank $ unsafePerformIO $ peek theRoot_\n\n-- | Predefined rank number that specifies non-root processes during\n-- operations involving intercommunicators. Corresponds to @MPI_PROC_NULL@\nprocNull :: Rank\nprocNull = toRank $ unsafePerformIO $ peek procNull_\n\ninstance Show Rank where\n show = show . rankId\n\ntoRank :: Enum a => a -> Rank\ntoRank x = MkRank { rankId = fromEnum x }\n\nfromRank :: Enum a => Rank -> a\nfromRank = toEnum . rankId\n\n{- This module provides Haskell representation of the @MPI_Request@ type. -}\ntype MPIRequest = {# type MPI_Request #}\nnewtype Request = MkRequest MPIRequest deriving Storable\npeekRequest ptr = MkRequest <$> peek ptr\n\n{-\nThis module provides Haskell representation of the @MPI_Status@ type\n(request status).\n\nField `status_error' should be used with care:\n\\\"The error field in status is not needed for calls that return only\none status, such as @MPI_WAIT@, since that would only duplicate the\ninformation returned by the function itself. The current design avoids\nthe additional overhead of setting it, in such cases. The field is\nneeded for calls that return multiple statuses, since each request may\nhave had a different failure.\\\"\n(this is a quote from )\n\nThis means that, for example, during the call to @MPI_Wait@\nimplementation is free to leave this field filled with whatever\ngarbage got there during memory allocation. Haskell FFI is not\nblanking out freshly allocated memory, so beware!\n-}\n\n-- | Haskell structure that holds fields of @MPI_Status@.\n--\n-- Please note that MPI report lists only three fields as mandatory:\n-- @status_source@, @status_tag@ and @status_error@. However, all\n-- MPI implementations that were used to test those bindings supported\n-- extended set of fields represented here.\ndata Status =\n Status\n { status_source :: CInt -- ^ rank of the source process\n , status_tag :: CInt -- ^ tag assigned at source\n , status_error :: CInt -- ^ error code, if any\n , status_count :: CInt -- ^ number of received elements, if applicable\n , status_cancelled :: CInt -- ^ whether the request was cancelled\n }\n deriving (Eq, Ord, Show)\n\ninstance Storable Status where\n sizeOf _ = {#sizeof MPI_Status #}\n alignment _ = 4\n peek p = Status\n <$> liftM cIntConv ({#get MPI_Status->MPI_SOURCE #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_TAG #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_ERROR #} p)\n#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields-\n <*> liftM cIntConv ({#get MPI_Status->count #} p)\n <*> liftM cIntConv ({#get MPI_Status->cancelled #} p)\n#else\n <*> liftM cIntConv ({#get MPI_Status->_count #} p)\n <*> liftM cIntConv ({#get MPI_Status->_cancelled #} p)\n#endif\n poke p x = do\n {#set MPI_Status.MPI_SOURCE #} p (cIntConv $ status_source x)\n {#set MPI_Status.MPI_TAG #} p (cIntConv $ status_tag x)\n {#set MPI_Status.MPI_ERROR #} p (cIntConv $ status_error x)\n#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields AND different order of fields\n {#set MPI_Status.count #} p (cIntConv $ status_count x)\n {#set MPI_Status.cancelled #} p (cIntConv $ status_cancelled x)\n#else\n {#set MPI_Status._count #} p (cIntConv $ status_count x)\n {#set MPI_Status._cancelled #} p (cIntConv $ status_cancelled x)\n#endif\n\n-- NOTE: Int here is picked arbitrary\nallocaCast f =\n alloca $ \\(ptr :: Ptr Int) -> f (castPtr ptr :: Ptr ())\npeekCast = peek . castPtr\n\n\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI tags.\n-}\n\nnewtype Tag = MkTag { tagVal :: Int }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Tag where\n (MkTag x) + (MkTag y) = MkTag (x+y)\n (MkTag x) * (MkTag y) = MkTag (x*y)\n abs (MkTag x) = MkTag (abs x)\n signum (MkTag x) = MkTag (signum x)\n fromInteger x \n | fromIntegral x > tagUpperBound = error \"Tag value is over the MPI_TAG_UB\" \n | x < 0 = error \"Negative Tag value\"\n | otherwise = MkTag (fromIntegral x)\n\ninstance Show Tag where\n show = show . tagVal\n\ntoTag :: Enum a => a -> Tag\ntoTag x = MkTag { tagVal = fromEnum x }\n\nfromTag :: Enum a => Tag -> a\nfromTag = toEnum . tagVal\n\nforeign import ccall unsafe \"&mpi_any_tag\" anyTag_ :: Ptr Int\n\n-- | Predefined tag value that allows reception of the messages with\n-- arbitrary tag values. Corresponds to @MPI_ANY_TAG@.\nanyTag :: Tag\nanyTag = toTag $ unsafePerformIO $ peek anyTag_\n\n{-\nThis module provides Haskell datatypes that comprises of values of\npredefined MPI constants @MPI_THREAD_SINGLE@, @MPI_THREAD_FUNNELED@,\n@MPI_THREAD_SERIALIZED@, @MPI_THREAD_MULTIPLE@.\n-}\n\n{# enum ThreadSupport {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n{- From MPI 2.2 report:\n \"To make it possible for an application to interpret an error code, the routine\n MPI_ERROR_CLASS converts any error code into one of a small set of standard\n error codes\"\n-}\n\ndata MPIError\n = MPIError\n { mpiErrorClass :: ErrorClass\n , mpiErrorString :: String\n }\n deriving (Eq, Show, Typeable)\n\ninstance Exception MPIError\n\ncheckError :: CInt -> IO ()\ncheckError code = do\n -- We ignore the error code from the call to Internal.errorClass\n -- because we call errorClass from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n (_, errClassRaw) <- errorClass code\n let errClass = cToEnum errClassRaw\n unless (errClass == Success) $ do\n errStr <- errorStringWrapper code\n throwIO $ MPIError errClass errStr\n\nerrorStringWrapper :: CInt -> IO String\nerrorStringWrapper code =\n allocaBytes (fromIntegral maxErrorString) $ \\ptr ->\n alloca $ \\lenPtr -> do\n -- We ignore the error code from the call to Internal.errorString\n -- because we call errorString from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n _ <- errorString code ptr lenPtr\n len <- peek lenPtr\n peekCStringLen (ptr, cIntConv len)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"4d198e10204ead4943e54657a264307efc34151d","subject":"peek and poke device arrays with offset","message":"peek and poke device arrays with offset\n\nIgnore-this: 464a42685e89a77b36d5182c8584aa60\n\ndarcs-hash:20090923004254-115f9-165279e591cea1a18e502b5c27b3eefad3ceab9b.gz\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Marshal.chs","new_file":"Foreign\/CUDA\/Marshal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Marshal\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Memory allocation and marshalling support for CUDA devices\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Marshal\n (\n DevicePtr,\n withDevicePtr,\n\n -- ** Dynamic allocation\n --\n -- Basic methods to allocate a block of memory on the device. The memory\n -- should be deallocated using 'free' when no longer necessary. The\n -- advantage is that failed allocations will not raise an exception.\n --\n free,\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Local allocation\n --\n -- Execute a computation, passing as argument a pointer to a newly allocated\n -- block of memory. The memory is freed when the computation terminates.\n --\n alloca,\n allocaBytes,\n allocaBytesMemset,\n\n -- ** Marshalling\n --\n -- Store and retrieve Haskell lists as arrays on the device\n --\n peek,\n poke,\n peekArray,\n peekArrayAt,\n pokeArray,\n pokeArrayAt,\n\n -- ** Combined allocation and marshalling\n --\n -- Write Haskell values (or lists) to newly allocated device memory. This\n -- may be a temporary store.\n --\n new,\n with,\n newArray,\n withArray,\n withArrayLen,\n\n -- ** Copying\n --\n -- Copy data between the host and device\n --\n )\n where\n\nimport Data.Int\nimport Control.Exception\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.Concurrent\nimport Foreign.ForeignPtr hiding (newForeignPtr, addForeignPtrFinalizer)\nimport Foreign.Storable (Storable)\n\nimport qualified Foreign.Storable as F\nimport qualified Foreign.Marshal as F\n\nimport Foreign.CUDA.Utils\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Stream\nimport Foreign.CUDA.Internal.C2HS\n\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A reference to data stored on the device\n--\ntype DevicePtr a = ForeignPtr a\n\n-- |\n-- Unwrap the device pointer, yielding a device memory address that can be\n-- passed to a kernel function callable from the host code. This allows the type\n-- system to strictly separate host and device memory references, a non-obvious\n-- distinction in pure CUDA.\n--\nwithDevicePtr :: DevicePtr a -> (Ptr a -> IO b) -> IO b\nwithDevicePtr = withForeignPtr\n\n--\n-- Internal, unwrap and cast. Required as some functions such as memset work\n-- with untyped `void' data.\n--\nwithDevicePtr' :: DevicePtr a -> (Ptr b -> IO c) -> IO c\nwithDevicePtr' = withForeignPtr . castForeignPtr\n\n--\n-- Wrap a device memory pointer. The memory will be freed once the last\n-- reference to the data is dropped, although there is no guarantee as to\n-- exactly when this will occur.\n--\nnewDevicePtr :: Ptr a -> IO (DevicePtr a)\nnewDevicePtr p = newForeignPtr p (free_ p)\n\n\n--\n-- Memory copy\n--\n{# enum cudaMemcpyKind as CopyDirection {}\n with prefix=\"cudaMemcpy\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Dynamic allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate the specified number of bytes in linear memory on the device. The\n-- memory is suitably aligned for any kind of variable, and is not cleared.\n--\nmalloc :: Int64 -> IO (Either String (DevicePtr a))\nmalloc bytes = do\n (rv,ptr) <- cudaMalloc bytes\n case rv of\n Success -> Right `fmap` newDevicePtr (castPtr ptr)\n _ -> return . Left . describe $ rv\n\n{# fun unsafe cudaMalloc\n { alloca'- `Ptr ()' peek'* ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n where alloca' = F.alloca\n peek' = F.peek\n\n\n-- |\n-- Allocate at least @width * height@ bytes of linear memory on the device. The\n-- function may pad the allocation to ensure corresponding pointers in each row\n-- meet coalescing requirements. The actual allocation width is returned.\n--\nmalloc2D :: (Int64, Int64) -- ^ allocation (width,height) in bytes\n -> IO (Either String (DevicePtr a, Int64))\nmalloc2D (width,height) = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> (\\p -> Right (p,pitch)) `fmap` newDevicePtr (castPtr ptr)\n _ -> return . Left . describe $ rv\n\n{# fun unsafe cudaMallocPitch\n { alloca'- `Ptr ()' peek'* ,\n alloca'- `Int64' peekIntConv* ,\n cIntConv `Int64' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n where\n -- C->Haskell doesn't like qualified imports\n --\n alloca' :: Storable a => (Ptr a -> IO b) -> IO b\n alloca' = F.alloca\n peek' = F.peek\n\n\n-- |\n-- Allocate at least @width * height * depth@ bytes of linear memory on the\n-- device. The function may pad the allocation to ensure hardware alignment\n-- requirements are met. The actual allocation pitch is returned\n--\nmalloc3D :: (Int64,Int64,Int64) -- ^ allocation (width,height,depth) in bytes\n -> IO (Either String (DevicePtr a, Int64))\nmalloc3D = moduleErr \"malloc3D\" \"not implemented yet\"\n\n\n-- |\n-- Free previously allocated memory on the device\n--\n\n--free :: DevicePtr a -> IO (Maybe String)\n--free p = nothingIfOk `fmap` (withDevicePtr p cudaFree)\n\nfree :: DevicePtr a -> IO ()\nfree = finalizeForeignPtr\n\nfree_ :: Ptr a -> IO ()\nfree_ p = cudaFree p >>= \\rv ->\n case rv of\n Success -> return ()\n _ -> moduleErr \"free\" (describe rv)\n\n{# fun unsafe cudaFree\n { castPtr `Ptr a' } -> `Status' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr a -> IO ()) -> IO (FunPtr (Ptr a -> IO ()))\n\n\n-- |\n-- Initialise device memory to a given value\n--\nmemset :: DevicePtr a -- ^ The device memory\n -> Int64 -- ^ Number of bytes\n -> Int -- ^ Value to set for each byte\n -> IO (Maybe String)\nmemset ptr bytes symbol =\n nothingIfOk `fmap` cudaMemset ptr symbol bytes\n\n{# fun unsafe cudaMemset\n { withDevicePtr'* `DevicePtr a' ,\n `Int' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Initialise a matrix to a given value\n--\nmemset2D :: DevicePtr a -- ^ The device memory\n -> (Int64, Int64) -- ^ The (width,height) of the matrix in bytes\n -> Int64 -- ^ The allocation pitch, as returned by 'malloc2D'\n -> Int -- ^ Value to set for each byte\n -> IO (Maybe String)\nmemset2D ptr (width,height) pitch symbol =\n nothingIfOk `fmap` cudaMemset2D ptr pitch symbol width height\n\n{# fun unsafe cudaMemset2D\n { withDevicePtr'* `DevicePtr a' ,\n cIntConv `Int64' ,\n `Int' ,\n cIntConv `Int64' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Initialise the elements of a 3D array to a given value\n--\nmemset3D :: DevicePtr a -- ^ The device memory\n -> (Int64,Int64,Int64) -- ^ The (width,height,depth) of the array in bytes\n -> Int64 -- ^ The allocation pitch, as returned by 'malloc3D'\n -> Int -- ^ Value to set for each byte\n -> IO (Maybe String)\nmemset3D = moduleErr \"memset3D\" \"not implemented yet\"\n\n\n--------------------------------------------------------------------------------\n-- Local allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Execute a computation, passing a pointer to a temporarily allocated block of\n-- memory\n--\nalloca :: Storable a => (DevicePtr a -> IO b) -> IO b\nalloca = doAlloca undefined\n where\n doAlloca :: Storable a' => a' -> (DevicePtr a' -> IO b') -> IO b'\n doAlloca x = allocaBytes (fromIntegral (F.sizeOf x))\n\n\n-- |\n-- Execute a computation, passing a pointer to a block of 'n' bytes of memory\n--\nallocaBytes :: Int64 -> (DevicePtr a -> IO b) -> IO b\nallocaBytes bytes =\n bracket (forceEither `fmap` malloc bytes) free\n\n\n-- |\n-- Execute a computation, passing a pointer to a block of memory initialised to\n-- a given value\n--\nallocaBytesMemset :: Int64 -> Int -> (DevicePtr a -> IO b) -> IO b\nallocaBytesMemset bytes symbol f =\n allocaBytes bytes $ \\dptr ->\n memset dptr bytes symbol >>= \\rv ->\n case rv of\n Nothing -> f dptr\n Just e -> error e\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Retrieve the specified value from device memory\n--\npeek :: Storable a => DevicePtr a -> IO (Either String a)\npeek d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO (Either String a')\n doPeek x = F.alloca $ \\hptr ->\n withDevicePtr' d $ \\dptr ->\n memcpy hptr dptr (fromIntegral (F.sizeOf x)) DeviceToHost >>= \\rv ->\n case rv of\n Nothing -> Right `fmap` F.peek hptr\n Just s -> return (Left s)\n\n\n-- |\n-- Retrieve the specified number of elements from device memory and return as a\n-- Haskell list\n--\npeekArray :: Storable a => Int -> DevicePtr a -> IO (Either String [a])\npeekArray = peekArrayAt 0\n\n\n-- |\n-- Retrieve the specified number of elements from device memory, beginning at\n-- the specified index (from zero), and return as a Haskell list.\n--\npeekArrayAt :: Storable a => Int -> Int -> DevicePtr a -> IO (Either String [a])\npeekArrayAt o n d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO (Either String [a'])\n doPeek x = let bytes = fromIntegral n * (fromIntegral (F.sizeOf x)) in\n F.allocaArray n $ \\hptr ->\n withDevicePtr' d $ \\dptr ->\n memcpy hptr (dptr `plusPtr` (o * F.sizeOf x)) bytes DeviceToHost >>= \\rv ->\n case rv of\n Nothing -> Right `fmap` F.peekArray n hptr\n Just s -> return (Left s)\n\n\n-- |\n-- Store the given value to device memory\n--\npoke :: Storable a => DevicePtr a -> a -> IO (Maybe String)\npoke d v =\n F.with v $ \\hptr ->\n withDevicePtr d $ \\dptr ->\n memcpy dptr hptr (fromIntegral (F.sizeOf v)) HostToDevice\n\n\n-- |\n-- Store the list elements consecutively in device memory\n--\npokeArray :: Storable a => DevicePtr a -> [a] -> IO (Maybe String)\npokeArray = pokeArrayAt 0\n\n\n-- |\n-- Store the list elements consecutively in device memory, beginning at the\n-- specified index (from zero)\n--\npokeArrayAt :: Storable a => Int -> DevicePtr a -> [a] -> IO (Maybe String)\npokeArrayAt o d = doPoke undefined\n where\n doPoke :: Storable a' => a' -> [a'] -> IO (Maybe String)\n doPoke x v = F.withArrayLen v $ \\n hptr ->\n withDevicePtr' d $ \\dptr ->\n let bytes = (fromIntegral n) * (fromIntegral (F.sizeOf x)) in\n memcpy (dptr `plusPtr` (o * F.sizeOf x)) hptr bytes HostToDevice\n\n\n--------------------------------------------------------------------------------\n-- Combined allocation and marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a block of memory on the device and transfer a value into it. The\n-- memory may be deallocated using 'free' when no longer required.\n--\nnew :: Storable a => a -> IO (DevicePtr a)\nnew v =\n let bytes = fromIntegral (F.sizeOf v) in\n forceEither `fmap` malloc bytes >>= \\dptr ->\n poke dptr v >>= \\rv ->\n case rv of\n Nothing -> return dptr\n Just s -> moduleErr \"new\" s\n\n\n-- |\n-- Write the list of storable elements into a newly allocated linear array on\n-- the device. The memory may be deallocated when no longer required.\n--\nnewArray :: Storable a => [a] -> IO (DevicePtr a)\nnewArray v =\n let bytes = fromIntegral (length v) * fromIntegral (F.sizeOf (head v)) in\n forceEither `fmap` malloc bytes >>= \\dptr ->\n pokeArray dptr v >>= \\rv ->\n case rv of\n Nothing -> return dptr\n Just s -> moduleErr \"newArray\" s\n\n\n-- |\n-- Execute a computation passing a pointer to a temporarily allocated block of\n-- device memory containing the value\n--\nwith :: Storable a => a -> (DevicePtr a -> IO b) -> IO b\nwith v f =\n alloca $ \\dptr ->\n poke dptr v >>= \\rv ->\n case rv of\n Nothing -> f dptr\n Just s -> moduleErr \"with\" s\n\n\n-- |\n-- Temporarily store a list of variable in device memory and operate on them\n--\nwithArray :: Storable a => [a] -> (DevicePtr a -> IO b) -> IO b\nwithArray vs f = withArrayLen vs (\\_ -> f)\n\n\n-- |\n-- Like 'withArray', but the action gets the number of values as an additional\n-- parameter\n--\nwithArrayLen :: Storable a => [a] -> (Int -> DevicePtr a -> IO b) -> IO b\nwithArrayLen vs f =\n let l = length vs\n b = fromIntegral l * fromIntegral (F.sizeOf (head vs))\n in\n allocaBytes b $ \\dptr ->\n pokeArray dptr vs >>= \\rv ->\n case rv of\n Nothing -> f l dptr\n Just s -> moduleErr \"withArray\" s\n\n\n--------------------------------------------------------------------------------\n-- Copying\n--------------------------------------------------------------------------------\n\n-- |\n-- Copy data between host and device\n--\nmemcpy :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> IO (Maybe String)\nmemcpy dst src bytes dir =\n nothingIfOk `fmap` cudaMemcpy dst src bytes dir\n\n{# fun unsafe cudaMemcpy\n { castPtr `Ptr a' ,\n castPtr `Ptr a' ,\n cIntConv `Int64' ,\n cFromEnum `CopyDirection' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Stream -- ^ asynchronous stream to operate over\n -> Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> IO (Maybe String)\nmemcpyAsync stream dst src bytes dir =\n nothingIfOk `fmap` cudaMemcpyAsync dst src bytes dir stream\n\n{# fun unsafe cudaMemcpyAsync\n { castPtr `Ptr a' ,\n castPtr `Ptr a' ,\n cIntConv `Int64' ,\n cFromEnum `CopyDirection' ,\n cIntConv `Stream' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal utilities\n--------------------------------------------------------------------------------\n\nmoduleErr :: String -> String -> a\nmoduleErr fun msg = error (\"Foreign.CUDA.\" ++ fun ++ ':':' ':msg)\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Marshal\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Memory allocation and marshalling support for CUDA devices\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Marshal\n (\n DevicePtr,\n withDevicePtr,\n\n -- ** Dynamic allocation\n --\n -- Basic methods to allocate a block of memory on the device. The memory\n -- should be deallocated using 'free' when no longer necessary. The\n -- advantage is that failed allocations will not raise an exception.\n --\n free,\n malloc,\n malloc2D,\n malloc3D,\n memset,\n memset2D,\n memset3D,\n\n -- ** Local allocation\n --\n -- Execute a computation, passing as argument a pointer to a newly allocated\n -- block of memory. The memory is freed when the computation terminates.\n --\n alloca,\n allocaBytes,\n allocaBytesMemset,\n\n -- ** Marshalling\n --\n -- Store and retrieve Haskell lists as arrays on the device\n --\n peek,\n poke,\n peekArray,\n pokeArray,\n\n -- ** Combined allocation and marshalling\n --\n -- Write Haskell values (or lists) to newly allocated device memory. This\n -- may be a temporary store.\n --\n new,\n with,\n newArray,\n withArray,\n withArrayLen,\n\n -- ** Copying\n --\n -- Copy data between the host and device\n --\n )\n where\n\nimport Data.Int\nimport Control.Exception\n\nimport Foreign.C\nimport Foreign.Ptr\nimport Foreign.Concurrent\nimport Foreign.ForeignPtr hiding (newForeignPtr, addForeignPtrFinalizer)\nimport Foreign.Storable (Storable)\n\nimport qualified Foreign.Storable as F\nimport qualified Foreign.Marshal as F\n\nimport Foreign.CUDA.Utils\nimport Foreign.CUDA.Error\nimport Foreign.CUDA.Stream\nimport Foreign.CUDA.Internal.C2HS\n\n#include \n{# context lib=\"cudart\" #}\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A reference to data stored on the device\n--\ntype DevicePtr a = ForeignPtr a\n\n-- |\n-- Unwrap the device pointer, yielding a device memory address that can be\n-- passed to a kernel function callable from the host code. This allows the type\n-- system to strictly separate host and device memory references, a non-obvious\n-- distinction in pure CUDA.\n--\nwithDevicePtr :: DevicePtr a -> (Ptr a -> IO b) -> IO b\nwithDevicePtr = withForeignPtr\n\n--\n-- Internal, unwrap and cast. Required as some functions such as memset work\n-- with untyped `void' data.\n--\nwithDevicePtr' :: DevicePtr a -> (Ptr b -> IO c) -> IO c\nwithDevicePtr' = withForeignPtr . castForeignPtr\n\n--\n-- Wrap a device memory pointer. The memory will be freed once the last\n-- reference to the data is dropped, although there is no guarantee as to\n-- exactly when this will occur.\n--\nnewDevicePtr :: Ptr a -> IO (DevicePtr a)\nnewDevicePtr p = newForeignPtr p (free_ p)\n\n\n--\n-- Memory copy\n--\n{# enum cudaMemcpyKind as CopyDirection {}\n with prefix=\"cudaMemcpy\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Dynamic allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate the specified number of bytes in linear memory on the device. The\n-- memory is suitably aligned for any kind of variable, and is not cleared.\n--\nmalloc :: Int64 -> IO (Either String (DevicePtr a))\nmalloc bytes = do\n (rv,ptr) <- cudaMalloc bytes\n case rv of\n Success -> Right `fmap` newDevicePtr (castPtr ptr)\n _ -> return . Left . describe $ rv\n\n{# fun unsafe cudaMalloc\n { alloca'- `Ptr ()' peek'* ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n where alloca' = F.alloca\n peek' = F.peek\n\n\n-- |\n-- Allocate at least @width * height@ bytes of linear memory on the device. The\n-- function may pad the allocation to ensure corresponding pointers in each row\n-- meet coalescing requirements. The actual allocation width is returned.\n--\nmalloc2D :: (Int64, Int64) -- ^ allocation (width,height) in bytes\n -> IO (Either String (DevicePtr a, Int64))\nmalloc2D (width,height) = do\n (rv,ptr,pitch) <- cudaMallocPitch width height\n case rv of\n Success -> (\\p -> Right (p,pitch)) `fmap` newDevicePtr (castPtr ptr)\n _ -> return . Left . describe $ rv\n\n{# fun unsafe cudaMallocPitch\n { alloca'- `Ptr ()' peek'* ,\n alloca'- `Int64' peekIntConv* ,\n cIntConv `Int64' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n where\n -- C->Haskell doesn't like qualified imports\n --\n alloca' :: Storable a => (Ptr a -> IO b) -> IO b\n alloca' = F.alloca\n peek' = F.peek\n\n\n-- |\n-- Allocate at least @width * height * depth@ bytes of linear memory on the\n-- device. The function may pad the allocation to ensure hardware alignment\n-- requirements are met. The actual allocation pitch is returned\n--\nmalloc3D :: (Int64,Int64,Int64) -- ^ allocation (width,height,depth) in bytes\n -> IO (Either String (DevicePtr a, Int64))\nmalloc3D = moduleErr \"malloc3D\" \"not implemented yet\"\n\n\n-- |\n-- Free previously allocated memory on the device\n--\n\n--free :: DevicePtr a -> IO (Maybe String)\n--free p = nothingIfOk `fmap` (withDevicePtr p cudaFree)\n\nfree :: DevicePtr a -> IO ()\nfree = finalizeForeignPtr\n\nfree_ :: Ptr a -> IO ()\nfree_ p = cudaFree p >>= \\rv ->\n case rv of\n Success -> return ()\n _ -> moduleErr \"free\" (describe rv)\n\n{# fun unsafe cudaFree\n { castPtr `Ptr a' } -> `Status' cToEnum #}\n\nforeign import ccall \"wrapper\"\n doAutoRelease :: (Ptr a -> IO ()) -> IO (FunPtr (Ptr a -> IO ()))\n\n\n-- |\n-- Initialise device memory to a given value\n--\nmemset :: DevicePtr a -- ^ The device memory\n -> Int64 -- ^ Number of bytes\n -> Int -- ^ Value to set for each byte\n -> IO (Maybe String)\nmemset ptr bytes symbol =\n nothingIfOk `fmap` cudaMemset ptr symbol bytes\n\n{# fun unsafe cudaMemset\n { withDevicePtr'* `DevicePtr a' ,\n `Int' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Initialise a matrix to a given value\n--\nmemset2D :: DevicePtr a -- ^ The device memory\n -> (Int64, Int64) -- ^ The (width,height) of the matrix in bytes\n -> Int64 -- ^ The allocation pitch, as returned by 'malloc2D'\n -> Int -- ^ Value to set for each byte\n -> IO (Maybe String)\nmemset2D ptr (width,height) pitch symbol =\n nothingIfOk `fmap` cudaMemset2D ptr pitch symbol width height\n\n{# fun unsafe cudaMemset2D\n { withDevicePtr'* `DevicePtr a' ,\n cIntConv `Int64' ,\n `Int' ,\n cIntConv `Int64' ,\n cIntConv `Int64' } -> `Status' cToEnum #}\n\n\n-- |\n-- Initialise the elements of a 3D array to a given value\n--\nmemset3D :: DevicePtr a -- ^ The device memory\n -> (Int64,Int64,Int64) -- ^ The (width,height,depth) of the array in bytes\n -> Int64 -- ^ The allocation pitch, as returned by 'malloc3D'\n -> Int -- ^ Value to set for each byte\n -> IO (Maybe String)\nmemset3D = moduleErr \"memset3D\" \"not implemented yet\"\n\n\n--------------------------------------------------------------------------------\n-- Local allocation\n--------------------------------------------------------------------------------\n\n-- |\n-- Execute a computation, passing a pointer to a temporarily allocated block of\n-- memory\n--\nalloca :: Storable a => (DevicePtr a -> IO b) -> IO b\nalloca = doAlloca undefined\n where\n doAlloca :: Storable a' => a' -> (DevicePtr a' -> IO b') -> IO b'\n doAlloca x = allocaBytes (fromIntegral (F.sizeOf x))\n\n\n-- |\n-- Execute a computation, passing a pointer to a block of 'n' bytes of memory\n--\nallocaBytes :: Int64 -> (DevicePtr a -> IO b) -> IO b\nallocaBytes bytes =\n bracket (forceEither `fmap` malloc bytes) free\n\n\n-- |\n-- Execute a computation, passing a pointer to a block of memory initialised to\n-- a given value\n--\nallocaBytesMemset :: Int64 -> Int -> (DevicePtr a -> IO b) -> IO b\nallocaBytesMemset bytes symbol f =\n allocaBytes bytes $ \\dptr ->\n memset dptr bytes symbol >>= \\rv ->\n case rv of\n Nothing -> f dptr\n Just e -> error e\n\n\n--------------------------------------------------------------------------------\n-- Marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Retrieve the specified value from device memory\n--\npeek :: Storable a => DevicePtr a -> IO (Either String a)\npeek d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO (Either String a')\n doPeek x = F.alloca $ \\hptr ->\n withDevicePtr' d $ \\dptr ->\n memcpy hptr dptr (fromIntegral (F.sizeOf x)) DeviceToHost >>= \\rv ->\n case rv of\n Nothing -> Right `fmap` F.peek hptr\n Just s -> return (Left s)\n\n\n-- |\n-- Retrieve the specified number of elements from device memory and return as a\n-- Haskell list\n--\npeekArray :: Storable a => Int -> DevicePtr a -> IO (Either String [a])\npeekArray n d = doPeek undefined\n where\n doPeek :: Storable a' => a' -> IO (Either String [a'])\n doPeek x = let bytes = fromIntegral n * (fromIntegral (F.sizeOf x)) in\n F.allocaArray n $ \\hptr ->\n withDevicePtr' d $ \\dptr ->\n memcpy hptr dptr bytes DeviceToHost >>= \\rv ->\n case rv of\n Nothing -> Right `fmap` F.peekArray n hptr\n Just s -> return (Left s)\n\n\n-- |\n-- Store the given value to device memory\n--\npoke :: Storable a => DevicePtr a -> a -> IO (Maybe String)\npoke d v =\n F.with v $ \\hptr ->\n withDevicePtr d $ \\dptr ->\n memcpy dptr hptr (fromIntegral (F.sizeOf v)) HostToDevice\n\n\n-- |\n-- Store the list elements consecutively in device memory\n--\npokeArray :: Storable a => DevicePtr a -> [a] -> IO (Maybe String)\npokeArray d = doPoke undefined\n where\n doPoke :: Storable a' => a' -> [a'] -> IO (Maybe String)\n doPoke x v = F.withArrayLen v $ \\n hptr ->\n withDevicePtr' d $ \\dptr ->\n let bytes = (fromIntegral n) * (fromIntegral (F.sizeOf x)) in\n memcpy dptr hptr bytes HostToDevice\n\n\n--------------------------------------------------------------------------------\n-- Combined allocation and marshalling\n--------------------------------------------------------------------------------\n\n-- |\n-- Allocate a block of memory on the device and transfer a value into it. The\n-- memory may be deallocated using 'free' when no longer required.\n--\nnew :: Storable a => a -> IO (DevicePtr a)\nnew v =\n let bytes = fromIntegral (F.sizeOf v) in\n forceEither `fmap` malloc bytes >>= \\dptr ->\n poke dptr v >>= \\rv ->\n case rv of\n Nothing -> return dptr\n Just s -> moduleErr \"new\" s\n\n\n-- |\n-- Write the list of storable elements into a newly allocated linear array on\n-- the device. The memory may be deallocated when no longer required.\n--\nnewArray :: Storable a => [a] -> IO (DevicePtr a)\nnewArray v =\n let bytes = fromIntegral (length v) * fromIntegral (F.sizeOf (head v)) in\n forceEither `fmap` malloc bytes >>= \\dptr ->\n pokeArray dptr v >>= \\rv ->\n case rv of\n Nothing -> return dptr\n Just s -> moduleErr \"newArray\" s\n\n\n-- |\n-- Execute a computation passing a pointer to a temporarily allocated block of\n-- device memory containing the value\n--\nwith :: Storable a => a -> (DevicePtr a -> IO b) -> IO b\nwith v f =\n alloca $ \\dptr ->\n poke dptr v >>= \\rv ->\n case rv of\n Nothing -> f dptr\n Just s -> moduleErr \"with\" s\n\n\n-- |\n-- Temporarily store a list of variable in device memory and operate on them\n--\nwithArray :: Storable a => [a] -> (DevicePtr a -> IO b) -> IO b\nwithArray vs f = withArrayLen vs (\\_ -> f)\n\n\n-- |\n-- Like 'withArray', but the action gets the number of values as an additional\n-- parameter\n--\nwithArrayLen :: Storable a => [a] -> (Int -> DevicePtr a -> IO b) -> IO b\nwithArrayLen vs f =\n let l = length vs\n b = fromIntegral l * fromIntegral (F.sizeOf (head vs))\n in\n allocaBytes b $ \\dptr ->\n pokeArray dptr vs >>= \\rv ->\n case rv of\n Nothing -> f l dptr\n Just s -> moduleErr \"withArray\" s\n\n\n--------------------------------------------------------------------------------\n-- Copying\n--------------------------------------------------------------------------------\n\n-- |\n-- Copy data between host and device\n--\nmemcpy :: Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> IO (Maybe String)\nmemcpy dst src bytes dir =\n nothingIfOk `fmap` cudaMemcpy dst src bytes dir\n\n{# fun unsafe cudaMemcpy\n { castPtr `Ptr a' ,\n castPtr `Ptr a' ,\n cIntConv `Int64' ,\n cFromEnum `CopyDirection' } -> `Status' cToEnum #}\n\n\n-- |\n-- Copy data between host and device asynchronously\n--\nmemcpyAsync :: Stream -- ^ asynchronous stream to operate over\n -> Ptr a -- ^ destination\n -> Ptr a -- ^ source\n -> Int64 -- ^ number of bytes\n -> CopyDirection\n -> IO (Maybe String)\nmemcpyAsync stream dst src bytes dir =\n nothingIfOk `fmap` cudaMemcpyAsync dst src bytes dir stream\n\n{# fun unsafe cudaMemcpyAsync\n { castPtr `Ptr a' ,\n castPtr `Ptr a' ,\n cIntConv `Int64' ,\n cFromEnum `CopyDirection' ,\n cIntConv `Stream' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal utilities\n--------------------------------------------------------------------------------\n\nmoduleErr :: String -> String -> a\nmoduleErr fun msg = error (\"Foreign.CUDA.\" ++ fun ++ ':':' ':msg)\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"c801bc2f91923389705bcdddd5cdc37309080709","subject":"Bunch of haddock docs in Internal","message":"Bunch of haddock docs in Internal\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Control\/Parallel\/MPI\/Internal.chs","new_file":"src\/Control\/Parallel\/MPI\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n#include \n#include \"init_wrapper.h\"\n#include \"comparison_result.h\"\n#include \"error_classes.h\"\n#include \"thread_support.h\"\n-----------------------------------------------------------------------------\n{- |\nModule : Control.Parallel.MPI.Internal\nCopyright : (c) 2010 Bernie Pope, Dmitry Astapov\nLicense : BSD-style\nMaintainer : florbitous@gmail.com\nStability : experimental\nPortability : ghc\n\nThis module contains low-level Haskell bindings to core MPI functions.\nAll Haskell functions correspond to MPI functions or values with the similar\nname (i.e. @commRank@ is the binding for @MPI_Comm_rank@ etc)\n\nNote that most of this module is re-exported by\n\"Control.Parallel.MPI\", so if you are not interested in writing\nlow-level code, you should probably import \"Control.Parallel.MPI\" and\neither \"Control.Parallel.MPI.Storable\" or \"Control.Parallel.MPI.Serializable\".\n-}\n-----------------------------------------------------------------------------\nmodule Control.Parallel.MPI.Internal\n (\n\n -- * MPI runtime management\n -- ** Initialization, finalization, termination.\n init, finalize, initialized, finalized, abort,\n -- ** Multi-threaded environment support\n ThreadSupport (..), initThread, queryThread, isThreadMain,\n -- ** Predefined constants\n maxProcessorName, maxErrorString,\n -- ** Runtime attributes.\n getProcessorName, Version (..), getVersion,\n\n -- * Requests and statuses.\n Request, Status (..), probe, test, cancel, wait, waitall,\n\n -- * Process management.\n -- ** Communicators.\n Comm, commWorld, commSelf, commTestInter,\n commSize, commRemoteSize, \n commRank, \n commCompare, commGroup, commGetAttr,\n\n -- ** Process groups.\n Group, groupEmpty, groupRank, groupSize, groupUnion,\n groupIntersection, groupDifference, groupCompare, groupExcl,\n groupIncl, groupTranslateRanks,\n -- ** Comparisons.\n ComparisonResult (..),\n\n -- * Error handling.\n Errhandler, errorsAreFatal, errorsReturn, commSetErrhandler, commGetErrhandler,\n ErrorClass (..), MPIError(..),\n\n -- Ranks.\n Rank, rankId, toRank, fromRank, anySource, theRoot, procNull,\n\n -- * Data types.\n Datatype, char, wchar, short, int, long, longLong, unsignedChar, unsignedShort, unsigned, unsignedLong, unsignedLongLong, float, double, longDouble, byte, packed, typeSize,\n\n -- * Point-to-point operations\n -- ** Tags.\n Tag, toTag, fromTag, anyTag, unitTag, tagUpperBound,\n\n -- ** Blocking operations\n BufferPtr, Count, -- XXX: what will break if we don't export those?\n send, bsend, ssend, rsend, recv,\n -- ** Non-blocking operations\n isend, ibsend, issend, irecv,\n isendPtr, ibsendPtr, issendPtr, irecvPtr,\n\n\n -- * Collective operations\n -- ** One-to-all\n bcast, scatter, scatterv,\n -- ** All-to-one\n gather, gatherv, reduce,\n -- ** All-to-all\n allgather, allgatherv,\n alltoall, alltoallv,\n allreduce, reduceScatter,\n barrier,\n\n -- ** Reduction operations.\n Operation, maxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp,\n opCreate, opFree,\n\n -- * Timing.\n wtime, wtick, wtimeIsGlobal, wtimeIsGlobalKey\n\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Data.Maybe (fromMaybe)\nimport Control.Monad (liftM, unless)\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception\n\n{# context prefix = \"MPI\" #}\n\n-- | Pointer to memory buffer that either holds data to be sent or is\n-- used to receive some data. You would\n-- probably have to use 'castPtr' to pass some actual pointers to\n-- API functions.\ntype BufferPtr = Ptr ()\n\n-- | Count of elements in the send\/receive buffer\ntype Count = CInt\n\n{-\nThis module provides Haskell enum that comprises of MPI constants\n@MPI_IDENT@, @MPI_CONGRUENT@, @MPI_SIMILAR@ and @MPI_UNEQUAL@.\n\nThose are used to compare communicators (f.e. 'commCompare') and\nprocess groups (f.e. 'groupCompare'). Refer to those\nfunctions for description of comparison rules.\n-}\n{# enum ComparisonResult {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- Which Haskell type will be used as Comm depends on the MPI\n-- implementation that was selected during compilation. It could be\n-- CInt, Ptr (), Ptr CInt or something else.\ntype MPIComm = {# type MPI_Comm #}\n\n{- | Abstract type representing MPI communicator handle. Different MPI\n implementations use different C types to implement this, so\n concrete Haskell type behind @Comm@ is hidden from user.\n\n In any MPI program you have predefined communicator 'commWorld'\n which includes all running processes. You could create new\n communicators with TODO\n-}\nnewtype Comm = MkComm { fromComm :: MPIComm }\nforeign import ccall \"&mpi_comm_world\" commWorld_ :: Ptr MPIComm\nforeign import ccall \"&mpi_comm_self\" commSelf_ :: Ptr MPIComm\n\n-- | Predefined handle for communicator that includes all running\n-- processes. Similar to @MPI_Comm_world@\ncommWorld :: Comm\ncommWorld = MkComm <$> unsafePerformIO $ peek commWorld_\n\n-- | Predefined handle for communicator that includes only current\n-- process. Similar to @MPI_Comm_self@\ncommSelf :: Comm\ncommSelf = MkComm <$> unsafePerformIO $ peek commSelf_\n\nforeign import ccall \"&mpi_max_processor_name\" max_processor_name_ :: Ptr CInt\nforeign import ccall \"&mpi_max_error_string\" max_error_string_ :: Ptr CInt\nmaxProcessorName :: CInt\nmaxProcessorName = unsafePerformIO $ peek max_processor_name_\nmaxErrorString :: CInt\nmaxErrorString = unsafePerformIO $ peek max_error_string_\n\n-- | Initialize the MPI environment. The MPI environment must be intialized by each\n-- MPI process before any other MPI function is called. Note that\n-- the environment may also be initialized by the functions 'initThread', 'mpi',\n-- and 'mpiWorld'. It is an error to attempt to initialize the environment more\n-- than once for a given MPI program execution. The only MPI functions that may\n-- be called before the MPI environment is initialized are 'getVersion',\n-- 'initialized' and 'finalized'. This function corresponds to @MPI_Init@.\n{# fun unsafe init_wrapper as init {} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been initialized. Returns @True@ if the\n-- environment has been initialized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Initialized@.\n{# fun unsafe Initialized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been finalized. Returns @True@ if the\n-- environment has been finalized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Finalized@.\n{# fun unsafe Finalized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Initialize the MPI environment with a \/required\/ level of thread support.\n-- See the documentation for 'init' for more information about MPI initialization.\n-- The \/provided\/ level of thread support is returned in the result.\n-- There is no guarantee that provided will be greater than or equal to required.\n-- The level of provided thread support depends on the underlying MPI implementation,\n-- and may also depend on information provided when the program is executed\n-- (for example, by supplying appropriate arguments to @mpiexec@).\n-- If the required level of support cannot be provided then it will try to\n-- return the least supported level greater than what was required.\n-- If that cannot be satisfied then it will return the highest supported level\n-- provided by the MPI implementation. See the documentation for 'ThreadSupport'\n-- for information about what levels are available and their relative ordering.\n-- This function corresponds to @MPI_Init_thread@.\n{# fun unsafe init_wrapper_thread as initThread\n {cFromEnum `ThreadSupport', alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\n-- | Returns the current provided level of thread support. This will be the value\n-- returned as \\\"provided level of support\\\" by 'initThread' as well.\n{# fun unsafe Query_thread as ^ {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | This function can be called by a thread to find out whether it is the main thread (the\n-- thread that called 'init' or 'initThread'.\n{# fun unsafe Is_thread_main as ^\n {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Terminate the MPI execution environment.\n-- Once 'finalize' is called no other MPI functions may be called except\n-- 'getVersion', 'initialized' and 'finalized'. Each process must complete\n-- any pending communication that it initiated before calling 'finalize'.\n-- If 'finalize' returns then regular (non-MPI) computations may continue,\n-- but no further MPI computation is possible. Note: the error code returned\n-- by 'finalize' is not checked. This function corresponds to @MPI_Finalize@.\n{# fun unsafe Finalize as ^ {} -> `()' discard*- #}\ndiscard _ = return ()\n-- XXX can't call checkError on finalize, because\n-- checkError calls Internal.errorClass and Internal.errorString.\n-- These cannot be called after finalize (at least on OpenMPI).\n\ngetProcessorName :: IO String\ngetProcessorName = do\n allocaBytes (fromIntegral maxProcessorName) $ \\ptr -> do\n len <- getProcessorName' ptr\n peekCStringLen (ptr, cIntConv len)\n where\n getProcessorName' = {# fun unsafe Get_processor_name as getProcessorName_\n {id `Ptr CChar', alloca- `CInt' peekIntConv*} -> `()' checkError*- #}\n\ndata Version =\n Version { version :: Int, subversion :: Int }\n deriving (Eq, Ord)\n\ninstance Show Version where\n show v = show (version v) ++ \".\" ++ show (subversion v)\n\ngetVersion :: IO Version\ngetVersion = do\n (version, subversion) <- getVersion'\n return $ Version version subversion\n where\n getVersion' = {# fun unsafe Get_version as getVersion_\n {alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Return the number of processes involved in a communicator. For 'commWorld'\n-- it returns the total number of processes available. If the communicator is\n-- and intra-communicator it returns the number of processes in the local group.\n-- This function corresponds to @MPI_Comm_size@.\n{# fun unsafe Comm_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n-- | For intercommunicators, returs size of the remote process group.\n-- Corresponds to @MPI_Comm_remote_size@.\n{# fun unsafe Comm_remote_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n{- | Check whether the given communicator is intercommunicator - that\n is, communicator connecting two different groups of processes.\n\nRefer to MPI Report v2.2, Section 5.2 \"Communicator Argument\" for\nmore details.\n-}\n{# fun unsafe Comm_test_inter as ^\n {fromComm `Comm', alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Look up MPI communicator argument by the given numeric key.\n-- Lookup of some standard MPI arguments is provided by convenience\n-- functions 'tagUpperBound' and 'wtimeIsGlobal'.\ncommGetAttr :: Storable e => Comm -> Int -> IO (Maybe e)\ncommGetAttr comm key = do\n isInitialized <- initialized\n if isInitialized then do\n alloca $ \\ptr -> do\n found <- commGetAttr' comm key (castPtr ptr)\n if found then do ptr2 <- peek ptr\n Just <$> peek ptr2\n else return Nothing\n else return Nothing\n where\n commGetAttr' = {# fun unsafe Comm_get_attr as commGetAttr_\n {fromComm `Comm', cIntConv `Int', id `Ptr ()', alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Maximum tag value supported by the current MPI implementation. Corresponds to the value of standard MPI\n-- attribute @MPI_TAG_UB@.\n--\n-- When called before 'init' or 'initThread' would return 0.\ntagUpperBound :: Int\ntagUpperBound =\n let key = unsafePerformIO (peek tagUB_)\n in fromMaybe 0 $ unsafePerformIO (commGetAttr commWorld key)\n\nforeign import ccall unsafe \"&mpi_tag_ub\" tagUB_ :: Ptr Int\n\n{- | True if clocks at all processes in\n'commWorld' are synchronized, False otherwise. The expectation is that\nthe variation in time, as measured by calls to 'wtime', will be less then one half the\nround-trip time for an MPI message of length zero. \n\nCommunicators other than 'commWorld' could have different clocks.\nYou could find it out by querying attribute 'wtimeIsGlobalKey' with 'commGetAttr'.\n\nWhen wtimeIsGlobal is called before 'init' or 'initThread' it would return False.\n-}\nwtimeIsGlobal :: Bool\nwtimeIsGlobal =\n fromMaybe False $ unsafePerformIO (commGetAttr commWorld wtimeIsGlobalKey)\n\nforeign import ccall unsafe \"&mpi_wtime_is_global\" wtimeIsGlobal_ :: Ptr Int\n\n-- | Numeric key for standard MPI communicator attribute @MPI_WTIME_IS_GLOBAL@.\n-- To be used with 'commGetAttr'.\nwtimeIsGlobalKey :: Int\nwtimeIsGlobalKey = unsafePerformIO (peek wtimeIsGlobal_)\n\n-- | Return the rank of the calling process for the given\n-- communicator. If it is an intercommunicator, returns rank of the\n-- process in the local group.\n{# fun unsafe Comm_rank as ^\n {fromComm `Comm', alloca- `Rank' peekIntConv* } -> `()' checkError*- #}\n\n{- | Compares two communicators.\n\n* If they are handles for the same MPI communicator object, result is 'Identical';\n\n* If both communicators are identical in constituents and rank\n order, result is `Congruent';\n\n* If they have the same members, nbut with different ranks, then\n result is 'Similar';\n\n* Otherwise, result is 'Unequal'.\n\n-}\n{# fun unsafe Comm_compare as ^\n {fromComm `Comm', fromComm `Comm', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- | Test for an incomming message, without actually receiving it.\n-- If a message has been sent from @Rank@ to the current process with @Tag@ on the\n-- communicator @Comm@ then 'probe' will return the 'Status' of the message. Otherwise\n-- it will block the current process until such a matching message is sent.\n-- This allows the current process to check for an incoming message and decide\n-- how to receive it, based on the information in the 'Status'.\n-- This function corresponds to @MPI_Probe@.\n{# fun Probe as ^\n {fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n{- probe :: Rank -- ^ Rank of the sender.\n -> Tag -- ^ Tag of the sent message.\n -> Comm -- ^ Communicator.\n -> IO Status -- ^ Information about the incoming message (but not the content of the message). -}\n\n{# fun unsafe Send as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Bsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Ssend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Rsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Recv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast* } -> `()' checkError*- #}\n{# fun unsafe Isend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n{# fun unsafe Ibsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n{# fun unsafe Issend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n{# fun Irecv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n\n-- | Like 'isend', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun unsafe Isend as isendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'ibsend', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun unsafe Ibsend as ibsendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'issend', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun unsafe Issend as issendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'irecv', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun Irecv as irecvPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n{# fun unsafe Bcast as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocks until all processes on the communicator call this function.\n-- This function corresponds to @MPI_Barrier@.\n{# fun unsafe Barrier as ^ {fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocking test for the completion of a send of receive.\n-- See 'test' for a non-blocking variant.\n-- This function corresponds to @MPI_Wait@.\n{# fun unsafe Wait as ^\n {withRequest* `Request', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Takes pointer to the array of Requests of given size, 'wait's on all of them,\n-- populates array of Statuses of the same size. This function corresponds to @MPI_Waitall@\n{# fun unsafe Waitall as ^\n { id `Count', castPtr `Ptr Request', castPtr `Ptr Status'} -> `()' checkError*- #}\n-- TODO: Make this Storable Array instead of Ptr ?\n\n-- | Non-blocking test for the completion of a send or receive.\n-- Returns @Nothing@ if the request is not complete, otherwise\n-- it returns @Just status@. See 'wait' for a blocking variant.\n-- This function corresponds to @MPI_Test@.\ntest :: Request -> IO (Maybe Status)\ntest request = do\n (flag, status) <- test' request\n if flag\n then return $ Just status\n else return Nothing\n where\n test' = {# fun unsafe Test as test_\n {withRequest* `Request', alloca- `Bool' peekBool*, allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Cancel a pending communication request.\n-- This function corresponds to @MPI_Cancel@.\n{# fun unsafe Cancel as ^\n {withRequest* `Request'} -> `()' checkError*- #}\nwithRequest req f = do alloca $ \\ptr -> do poke ptr req\n f (castPtr ptr)\n{# fun unsafe Scatter as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n{# fun unsafe Gather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- We pass counts\/displs as Ptr CInt so that caller could supply nullPtr here\n-- which would be impossible if we marshal arrays ourselves here.\n{# fun unsafe Scatterv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Gatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Allgather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Allgatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Alltoall as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Alltoallv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\n{# fun Reduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n{# fun Allreduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n{# fun Reduce_scatter as ^\n { id `BufferPtr', id `BufferPtr', id `Ptr CInt', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Op_create as ^\n {castFunPtr `FunPtr (Ptr t -> Ptr t -> Ptr CInt -> Ptr Datatype -> IO ())', cFromEnum `Bool', alloca- `Operation' peekOperation*} -> `()' checkError*- #}\n{# fun Op_free as ^ {withOperation* `Operation'} -> `()' checkError*- #}\n\n{- | Returns a \nfloating-point number of seconds, representing elapsed wallclock\ntime since some time in the past.\n\nThe \\\"time in the past\\\" is guaranteed not to change during the life of the process.\nThe user is responsible for converting large numbers of seconds to other units if they are\npreferred. The time is local to the node that calls @wtime@, but see 'wtimeIsGlobal'.\n-}\n{# fun unsafe Wtime as ^ {} -> `Double' realToFrac #}\n\n{- | Returns the resolution of 'wtime' in seconds. That is, it returns,\nas a double precision value, the number of seconds between successive clock ticks. For\nexample, if the clock is implemented by the hardware as a counter that is incremented\nevery millisecond, the value returned by @wtick@ should be 10^(-3).\n-}\n{# fun unsafe Wtick as ^ {} -> `Double' realToFrac #}\n\n-- | Return the process group from a communicator. With\n-- intercommunicator, returns the local group.\n{# fun unsafe Comm_group as ^\n {fromComm `Comm', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupRank = unsafePerformIO <$> groupRank'\n where groupRank' = {# fun unsafe Group_rank as groupRank_\n {fromGroup `Group', alloca- `Rank' peekIntConv*} -> `()' checkError*- #}\n\ngroupSize = unsafePerformIO <$> groupSize'\n where groupSize' = {# fun unsafe Group_size as groupSize_\n {fromGroup `Group', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\ngroupUnion g1 g2 = unsafePerformIO $ groupUnion' g1 g2\n where groupUnion' = {# fun unsafe Group_union as groupUnion_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupIntersection g1 g2 = unsafePerformIO $ groupIntersection' g1 g2\n where groupIntersection' = {# fun unsafe Group_intersection as groupIntersection_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupDifference g1 g2 = unsafePerformIO $ groupDifference' g1 g2\n where groupDifference' = {# fun unsafe Group_difference as groupDifference_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupCompare g1 g2 = unsafePerformIO $ groupCompare' g1 g2\n where\n groupCompare' = {# fun unsafe Group_compare as groupCompare_\n {fromGroup `Group', fromGroup `Group', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- Technically it might make better sense to make the second argument a Set rather than a list\n-- but the order is significant in the groupIncl function (the other function, not this one).\n-- For the sake of keeping their types in sync, a list is used instead.\n{# fun unsafe Group_excl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n{# fun unsafe Group_incl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupTranslateRanks :: Group -> [Rank] -> Group -> [Rank]\ngroupTranslateRanks group1 ranks group2 =\n unsafePerformIO $ do\n let (rankIntList :: [Int]) = map fromEnum ranks\n withArrayLen rankIntList $ \\size ranksPtr ->\n allocaArray size $ \\resultPtr -> do\n groupTranslateRanks' group1 (cFromEnum size) (castPtr ranksPtr) group2 resultPtr\n map toRank <$> peekArray size resultPtr\n where\n groupTranslateRanks' = {# fun unsafe Group_translate_ranks as groupTranslateRanks_\n {fromGroup `Group', id `CInt', id `Ptr CInt', fromGroup `Group', id `Ptr CInt'} -> `()' checkError*- #}\n\nwithRanksAsInts ranks f = withArrayLen (map fromEnum ranks) $ \\size ptr -> f (cIntConv size, castPtr ptr)\n\n-- | Return the number of bytes used to store an MPI 'Datatype'.\ntypeSize = unsafePerformIO . typeSize'\n where\n typeSize' =\n {# fun unsafe Type_size as typeSize_\n {fromDatatype `Datatype', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n{# fun unsafe Error_class as ^\n { id `CInt', alloca- `CInt' peek*} -> `CInt' id #}\n\n-- | Set the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_set_errhandler@.\n{# fun unsafe Comm_set_errhandler as ^\n {fromComm `Comm', fromErrhandler `Errhandler'} -> `()' checkError*- #}\n\n-- | Get the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_get_errhandler@.\n{# fun unsafe Comm_get_errhandler as ^\n {fromComm `Comm', alloca- `Errhandler' peekErrhandler*} -> `()' checkError*- #}\n\n-- | Tries to terminate all MPI processes in its communicator argument.\n-- The second argument is an error code which \/may\/ be used as the return status\n-- of the MPI process, but this is not guaranteed. On systems where 'Int' has a larger\n-- range than 'CInt', the error code will be clipped to fit into the range of 'CInt'.\n-- This function corresponds to @MPI_Abort@.\nabort :: Comm -> Int -> IO ()\nabort comm code =\n abort' comm (toErrorCode code)\n where\n toErrorCode :: Int -> CInt\n toErrorCode i\n -- Assumes Int always has range at least as big as CInt.\n | i < (fromIntegral (minBound :: CInt)) = minBound\n | i > (fromIntegral (maxBound :: CInt)) = maxBound\n | otherwise = cIntConv i\n\n abort' = {# fun unsafe Abort as abort_ {fromComm `Comm', id `CInt'} -> `()' checkError*- #}\n\n\ntype MPIDatatype = {# type MPI_Datatype #}\n\nnewtype Datatype = MkDatatype { fromDatatype :: MPIDatatype }\n\nforeign import ccall unsafe \"&mpi_char\" char_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_wchar\" wchar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_short\" short_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_int\" int_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long\" long_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_long\" longLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_char\" unsignedChar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_short\" unsignedShort_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned\" unsigned_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long\" unsignedLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long_long\" unsignedLongLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_float\" float_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_double\" double_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_double\" longDouble_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_byte\" byte_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_packed\" packed_ :: Ptr MPIDatatype\n\nchar, wchar, short, int, long, longLong, unsignedChar, unsignedShort :: Datatype\nunsigned, unsignedLong, unsignedLongLong, float, double, longDouble :: Datatype\nbyte, packed :: Datatype\n\nchar = MkDatatype <$> unsafePerformIO $ peek char_\nwchar = MkDatatype <$> unsafePerformIO $ peek wchar_\nshort = MkDatatype <$> unsafePerformIO $ peek short_\nint = MkDatatype <$> unsafePerformIO $ peek int_\nlong = MkDatatype <$> unsafePerformIO $ peek long_\nlongLong = MkDatatype <$> unsafePerformIO $ peek longLong_\nunsignedChar = MkDatatype <$> unsafePerformIO $ peek unsignedChar_\nunsignedShort = MkDatatype <$> unsafePerformIO $ peek unsignedShort_\nunsigned = MkDatatype <$> unsafePerformIO $ peek unsigned_\nunsignedLong = MkDatatype <$> unsafePerformIO $ peek unsignedLong_\nunsignedLongLong = MkDatatype <$> unsafePerformIO $ peek unsignedLongLong_\nfloat = MkDatatype <$> unsafePerformIO $ peek float_\ndouble = MkDatatype <$> unsafePerformIO $ peek double_\nlongDouble = MkDatatype <$> unsafePerformIO $ peek longDouble_\nbyte = MkDatatype <$> unsafePerformIO $ peek byte_\npacked = MkDatatype <$> unsafePerformIO $ peek packed_\n\n\ntype MPIErrhandler = {# type MPI_Errhandler #}\nnewtype Errhandler = MkErrhandler { fromErrhandler :: MPIErrhandler } deriving Storable\npeekErrhandler ptr = MkErrhandler <$> peek ptr\n\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr MPIErrhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr MPIErrhandler\nerrorsAreFatal, errorsReturn :: Errhandler\nerrorsAreFatal = MkErrhandler <$> unsafePerformIO $ peek errorsAreFatal_\nerrorsReturn = MkErrhandler <$> unsafePerformIO $ peek errorsReturn_\n\n{# enum ErrorClass {underscoreToCase} deriving (Eq,Ord,Show,Typeable) #}\n\n-- XXX Should this be a ForeinPtr?\n-- there is a MPI_Group_free function, which we should probably\n-- call when the group is no longer referenced.\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIGroup = {# type MPI_Group #}\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\npeekGroup ptr = MkGroup <$> peek ptr\n\nforeign import ccall \"&mpi_group_empty\" groupEmpty_ :: Ptr MPIGroup\n-- | Predefined handle for group without any members. Corresponds to @MPI_GROUP_EMPTY@\ngroupEmpty :: Group\ngroupEmpty = MkGroup <$> unsafePerformIO $ peek groupEmpty_\n\n\n{-\nThis module provides Haskell type that represents values of @MPI_Op@\ntype (reduction operations), and predefined reduction operations\ndefined in the MPI Report.\n-}\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIOperation = {# type MPI_Op #}\nnewtype Operation = MkOperation { fromOperation :: MPIOperation } deriving Storable\npeekOperation ptr = MkOperation <$> peek ptr\nwithOperation op f = alloca $ \\ptr -> do poke ptr (fromOperation op)\n f (castPtr ptr)\n\nforeign import ccall unsafe \"&mpi_max\" maxOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_min\" minOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_sum\" sumOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_prod\" prodOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_land\" landOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_band\" bandOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lor\" lorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bor\" borOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lxor\" lxorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bxor\" bxorOp_ :: Ptr MPIOperation\n-- foreign import ccall \"mpi_maxloc\" maxlocOp :: MPIOperation\n-- foreign import ccall \"mpi_minloc\" minlocOp :: MPIOperation\n-- foreign import ccall \"mpi_replace\" replaceOp :: MPIOperation\n-- TODO: support for those requires better support for pair datatypes\n\nmaxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp :: Operation\nmaxOp = MkOperation <$> unsafePerformIO $ peek maxOp_\nminOp = MkOperation <$> unsafePerformIO $ peek minOp_\nsumOp = MkOperation <$> unsafePerformIO $ peek sumOp_\nprodOp = MkOperation <$> unsafePerformIO $ peek prodOp_\nlandOp = MkOperation <$> unsafePerformIO $ peek landOp_\nbandOp = MkOperation <$> unsafePerformIO $ peek bandOp_\nlorOp = MkOperation <$> unsafePerformIO $ peek lorOp_\nborOp = MkOperation <$> unsafePerformIO $ peek borOp_\nlxorOp = MkOperation <$> unsafePerformIO $ peek lxorOp_\nbxorOp = MkOperation <$> unsafePerformIO $ peek bxorOp_\n\n\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI rank designations.\n-}\n\nnewtype Rank = MkRank { rankId :: Int }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Rank where\n (MkRank x) + (MkRank y) = MkRank (x+y)\n (MkRank x) * (MkRank y) = MkRank (x*y)\n abs (MkRank x) = MkRank (abs x)\n signum (MkRank x) = MkRank (signum x)\n fromInteger x\n | x > ( fromIntegral (maxBound :: CInt)) = error \"Rank value does not fit into 32 bits\"\n | x < 0 = error \"Negative Rank value\"\n | otherwise = MkRank (fromIntegral x)\n\nforeign import ccall \"mpi_any_source\" anySource_ :: Ptr Int\nforeign import ccall \"mpi_root\" theRoot_ :: Ptr Int\nforeign import ccall \"mpi_proc_null\" procNull_ :: Ptr Int\n\n-- | Predefined rank number that allows reception of point-to-point messages\n-- regardless of their source. Corresponds to @MPI_ANY_SOURCE@\nanySource :: Rank\nanySource = toRank $ unsafePerformIO $ peek anySource_\n\n-- | Predefined rank number that specifies root process during\n-- operations involving intercommunicators. Corresponds to @MPI_ROOT@\ntheRoot :: Rank\ntheRoot = toRank $ unsafePerformIO $ peek theRoot_\n\n-- | Predefined rank number that specifies non-root processes during\n-- operations involving intercommunicators. Corresponds to @MPI_PROC_NULL@\nprocNull :: Rank\nprocNull = toRank $ unsafePerformIO $ peek procNull_\n\ninstance Show Rank where\n show = show . rankId\n\ntoRank :: Enum a => a -> Rank\ntoRank x = MkRank { rankId = fromEnum x }\n\nfromRank :: Enum a => Rank -> a\nfromRank = toEnum . rankId\n\n{- This module provides Haskell representation of the @MPI_Request@ type. -}\ntype MPIRequest = {# type MPI_Request #}\nnewtype Request = MkRequest MPIRequest deriving Storable\npeekRequest ptr = MkRequest <$> peek ptr\n\n{-\nThis module provides Haskell representation of the @MPI_Status@ type\n(request status).\n\nField `status_error' should be used with care:\n\\\"The error field in status is not needed for calls that return only\none status, such as @MPI_WAIT@, since that would only duplicate the\ninformation returned by the function itself. The current design avoids\nthe additional overhead of setting it, in such cases. The field is\nneeded for calls that return multiple statuses, since each request may\nhave had a different failure.\\\"\n(this is a quote from )\n\nThis means that, for example, during the call to @MPI_Wait@\nimplementation is free to leave this field filled with whatever\ngarbage got there during memory allocation. Haskell FFI is not\nblanking out freshly allocated memory, so beware!\n-}\n\n-- | Haskell structure that holds fields of @MPI_Status@.\n--\n-- Please note that MPI report lists only three fields as mandatory:\n-- @status_source@, @status_tag@ and @status_error@. However, all\n-- MPI implementations that were used to test those bindings supported\n-- extended set of fields represented here.\ndata Status =\n Status\n { status_source :: CInt -- ^ rank of the source process\n , status_tag :: CInt -- ^ tag assigned at source\n , status_error :: CInt -- ^ error code, if any\n , status_count :: CInt -- ^ number of received elements, if applicable\n , status_cancelled :: CInt -- ^ whether the request was cancelled\n }\n deriving (Eq, Ord, Show)\n\ninstance Storable Status where\n sizeOf _ = {#sizeof MPI_Status #}\n alignment _ = 4\n peek p = Status\n <$> liftM cIntConv ({#get MPI_Status->MPI_SOURCE #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_TAG #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_ERROR #} p)\n#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields-\n <*> liftM cIntConv ({#get MPI_Status->count #} p)\n <*> liftM cIntConv ({#get MPI_Status->cancelled #} p)\n#else\n <*> liftM cIntConv ({#get MPI_Status->_count #} p)\n <*> liftM cIntConv ({#get MPI_Status->_cancelled #} p)\n#endif\n poke p x = do\n {#set MPI_Status.MPI_SOURCE #} p (cIntConv $ status_source x)\n {#set MPI_Status.MPI_TAG #} p (cIntConv $ status_tag x)\n {#set MPI_Status.MPI_ERROR #} p (cIntConv $ status_error x)\n#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields AND different order of fields\n {#set MPI_Status.count #} p (cIntConv $ status_count x)\n {#set MPI_Status.cancelled #} p (cIntConv $ status_cancelled x)\n#else\n {#set MPI_Status._count #} p (cIntConv $ status_count x)\n {#set MPI_Status._cancelled #} p (cIntConv $ status_cancelled x)\n#endif\n\n-- NOTE: Int here is picked arbitrary\nallocaCast f =\n alloca $ \\(ptr :: Ptr Int) -> f (castPtr ptr :: Ptr ())\npeekCast = peek . castPtr\n\n\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI tags.\n-}\n\nnewtype Tag = MkTag { tagVal :: Int }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Tag where\n (MkTag x) + (MkTag y) = MkTag (x+y)\n (MkTag x) * (MkTag y) = MkTag (x*y)\n abs (MkTag x) = MkTag (abs x)\n signum (MkTag x) = MkTag (signum x)\n fromInteger x\n | fromIntegral x > tagUpperBound = error \"Tag value is over the MPI_TAG_UB\"\n | x < 0 = error \"Negative Tag value\"\n | otherwise = MkTag (fromIntegral x)\n\ninstance Show Tag where\n show = show . tagVal\n\ntoTag :: Enum a => a -> Tag\ntoTag x = MkTag { tagVal = fromEnum x }\n\nfromTag :: Enum a => Tag -> a\nfromTag = toEnum . tagVal\n\nforeign import ccall unsafe \"&mpi_any_tag\" anyTag_ :: Ptr Int\n\n-- | Predefined tag value that allows reception of the messages with\n-- arbitrary tag values. Corresponds to @MPI_ANY_TAG@.\nanyTag :: Tag\nanyTag = toTag $ unsafePerformIO $ peek anyTag_\n\n-- | A tag with unit value. Intended to be used as a convenient default.\nunitTag :: Tag\nunitTag = toTag ()\n\n\n{-\nThis module provides Haskell datatypes that comprises of values of\npredefined MPI constants @MPI_THREAD_SINGLE@, @MPI_THREAD_FUNNELED@,\n@MPI_THREAD_SERIALIZED@, @MPI_THREAD_MULTIPLE@.\n-}\n\n{- | Constants used to describe the required level of multithreading\n support in call to 'initThread'. They also describe provided level\n of multithreading support as returned by 'queryThread' and\n 'initThread'.\n\n[@Single@] Only one thread will execute.\n\n[@Funneled@] The process may be multi-threaded, but the application must\nensure that only the main thread makes MPI calls (see 'isThreadMain').\n\n[@Serialized@] The process may be multi-threaded, and multiple threads may\nmake MPI calls, but only one at a time: MPI calls are not made concurrently from\ntwo distinct threads\n\n[@Multiple@] Multiple threads may call MPI, with no restrictions.\n\n-}\n{# enum ThreadSupport {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- | Value thrown as exception when MPI runtime is instructed to pass\n-- errors to user code (via 'commSetErrhandler' and 'errorsReturn').\n-- Since raw MPI errors codes are not standartized and not portable,\n-- they are not exposed.\ndata MPIError\n = MPIError\n { mpiErrorClass :: ErrorClass -- ^ Broad class of errors this one belongs to\n , mpiErrorString :: String -- ^ Human-readable error description\n }\n deriving (Eq, Show, Typeable)\n\ninstance Exception MPIError\n\ncheckError :: CInt -> IO ()\ncheckError code = do\n -- We ignore the error code from the call to Internal.errorClass\n -- because we call errorClass from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n (_, errClassRaw) <- errorClass code\n let errClass = cToEnum errClassRaw\n unless (errClass == Success) $ do\n errStr <- errorString code\n throwIO $ MPIError errClass errStr\n\n-- | Convert MPI error code human-readable error description. Corresponds to @MPI_Error_string@.\nerrorString :: CInt -> IO String\nerrorString code =\n allocaBytes (fromIntegral maxErrorString) $ \\ptr ->\n alloca $ \\lenPtr -> do\n -- We ignore the error code from the call to Internal.errorString\n -- because we call errorString from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n _ <- errorString' code ptr lenPtr\n len <- peek lenPtr\n peekCStringLen (ptr, cIntConv len)\n where\n errorString' = {# call unsafe Error_string as errorString_ #}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n#include \n#include \"init_wrapper.h\"\n#include \"comparison_result.h\"\n#include \"error_classes.h\"\n#include \"thread_support.h\"\n-----------------------------------------------------------------------------\n{- |\nModule : Control.Parallel.MPI.Internal\nCopyright : (c) 2010 Bernie Pope, Dmitry Astapov\nLicense : BSD-style\nMaintainer : florbitous@gmail.com\nStability : experimental\nPortability : ghc\n\nThis module contains low-level Haskell bindings to core MPI functions.\nAll Haskell functions correspond to MPI functions or values with the similar\nname (i.e. @commRank@ is the binding for @MPI_Comm_rank@ etc)\n\nNote that most of this module is re-exported by\n\"Control.Parallel.MPI\", so if you are not interested in writing\nlow-level code, you should probably import \"Control.Parallel.MPI\" and\neither \"Control.Parallel.MPI.Storable\" or \"Control.Parallel.MPI.Serializable\".\n-}\n-----------------------------------------------------------------------------\nmodule Control.Parallel.MPI.Internal\n (\n\n -- * MPI runtime management\n -- ** Initialization, finalization, termination.\n init, finalize, initialized, finalized, abort,\n -- ** Multi-threaded environment support\n ThreadSupport (..), initThread, queryThread, isThreadMain,\n -- ** Predefined constants\n maxProcessorName, maxErrorString,\n -- ** Runtime attributes.\n getProcessorName, Version (..), getVersion,\n\n -- * Requests and statuses.\n Request, Status (..), probe, test, cancel, wait, waitall,\n\n -- * Process management.\n -- ** Communicators.\n Comm, commWorld, commSelf, commTestInter,\n commSize, commRemoteSize, \n commRank, \n commCompare, commGroup, commGetAttr,\n\n -- ** Process groups.\n Group, groupEmpty, groupRank, groupSize, groupUnion,\n groupIntersection, groupDifference, groupCompare, groupExcl,\n groupIncl, groupTranslateRanks,\n -- ** Comparisons.\n ComparisonResult (..),\n\n -- * Error handling.\n Errhandler, errorsAreFatal, errorsReturn, commSetErrhandler, commGetErrhandler,\n ErrorClass (..), MPIError(..),\n\n -- Ranks.\n Rank, rankId, toRank, fromRank, anySource, theRoot, procNull,\n\n -- * Data types.\n Datatype, char, wchar, short, int, long, longLong, unsignedChar, unsignedShort, unsigned, unsignedLong, unsignedLongLong, float, double, longDouble, byte, packed, typeSize,\n\n -- * Point-to-point operations\n -- ** Tags.\n Tag, toTag, fromTag, anyTag, unitTag, tagUpperBound,\n -- ** Blocking operations\n BufferPtr, Count, -- XXX: what will break if we don't export those?\n send, bsend, ssend, rsend, recv,\n -- ** Non-blocking operations\n isend, ibsend, issend, irecv,\n isendPtr, ibsendPtr, issendPtr, irecvPtr,\n\n\n -- * Collective operations\n -- ** One-to-all\n bcast, scatter, scatterv,\n -- ** All-to-one\n gather, gatherv, reduce,\n -- ** All-to-all\n allgather, allgatherv,\n alltoall, alltoallv,\n allreduce, reduceScatter,\n barrier,\n\n -- ** Reduction operations.\n Operation, maxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp,\n opCreate, opFree,\n\n -- * Timing.\n wtime, wtick,\n\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Data.Maybe (fromMaybe)\nimport Control.Monad (liftM, unless)\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception\n\n{# context prefix = \"MPI\" #}\n\n-- | Pointer to memory buffer that either holds data to be sent or is\n-- used to receive some data. You would\n-- probably have to use 'castPtr' to pass some actual pointers to\n-- API functions.\ntype BufferPtr = Ptr ()\n\n-- | Count of elements in the send\/receive buffer\ntype Count = CInt\n\n{-\nThis module provides Haskell enum that comprises of MPI constants\n@MPI_IDENT@, @MPI_CONGRUENT@, @MPI_SIMILAR@ and @MPI_UNEQUAL@.\n\nThose are used to compare communicators (f.e. 'commCompare') and\nprocess groups (f.e. 'groupCompare').\n-}\n{# enum ComparisonResult {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- | Which Haskell type will be used as @Comm@ depends on the MPI\n-- implementation that was selected during compilation. It could be\n-- @CInt@, @Ptr ()@, @Ptr CInt@ or something else.\ntype MPIComm = {# type MPI_Comm #}\nnewtype Comm = MkComm { fromComm :: MPIComm }\nforeign import ccall \"&mpi_comm_world\" commWorld_ :: Ptr MPIComm\nforeign import ccall \"&mpi_comm_self\" commSelf_ :: Ptr MPIComm\n\n-- | Predefined handle for communicator that includes all running\n-- processes. Similar to @MPI_Comm_world@\ncommWorld :: Comm\ncommWorld = MkComm <$> unsafePerformIO $ peek commWorld_\n\n-- | Predefined handle for communicator that includes only current\n-- process. Similar to @MPI_Comm_self@\ncommSelf :: Comm\ncommSelf = MkComm <$> unsafePerformIO $ peek commSelf_\n\nforeign import ccall \"&mpi_max_processor_name\" max_processor_name_ :: Ptr CInt\nforeign import ccall \"&mpi_max_error_string\" max_error_string_ :: Ptr CInt\nmaxProcessorName :: CInt\nmaxProcessorName = unsafePerformIO $ peek max_processor_name_\nmaxErrorString :: CInt\nmaxErrorString = unsafePerformIO $ peek max_error_string_\n\n-- | Initialize the MPI environment. The MPI environment must be intialized by each\n-- MPI process before any other MPI function is called. Note that\n-- the environment may also be initialized by the functions 'initThread', 'mpi',\n-- and 'mpiWorld'. It is an error to attempt to initialize the environment more\n-- than once for a given MPI program execution. The only MPI functions that may\n-- be called before the MPI environment is initialized are 'getVersion',\n-- 'initialized' and 'finalized'. This function corresponds to @MPI_Init@.\n{# fun unsafe init_wrapper as init {} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been initialized. Returns @True@ if the\n-- environment has been initialized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Initialized@.\n{# fun unsafe Initialized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been finalized. Returns @True@ if the\n-- environment has been finalized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Finalized@.\n{# fun unsafe Finalized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Initialize the MPI environment with a \/required\/ level of thread support.\n-- See the documentation for 'init' for more information about MPI initialization.\n-- The \/provided\/ level of thread support is returned in the result.\n-- There is no guarantee that provided will be greater than or equal to required.\n-- The level of provided thread support depends on the underlying MPI implementation,\n-- and may also depend on information provided when the program is executed\n-- (for example, by supplying appropriate arguments to @mpiexec@).\n-- If the required level of support cannot be provided then it will try to\n-- return the least supported level greater than what was required.\n-- If that cannot be satisfied then it will return the highest supported level\n-- provided by the MPI implementation. See the documentation for 'ThreadSupport'\n-- for information about what levels are available and their relative ordering.\n-- This function corresponds to @MPI_Init_thread@.\n{# fun unsafe init_wrapper_thread as initThread\n {cFromEnum `ThreadSupport', alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\n{# fun unsafe Query_thread as ^ {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n{# fun unsafe Is_thread_main as ^\n {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Terminate the MPI execution environment.\n-- Once 'finalize' is called no other MPI functions may be called except\n-- 'getVersion', 'initialized' and 'finalized'. Each process must complete\n-- any pending communication that it initiated before calling 'finalize'.\n-- If 'finalize' returns then regular (non-MPI) computations may continue,\n-- but no further MPI computation is possible. Note: the error code returned\n-- by 'finalize' is not checked. This function corresponds to @MPI_Finalize@.\n{# fun unsafe Finalize as ^ {} -> `()' discard*- #}\ndiscard _ = return ()\n-- XXX can't call checkError on finalize, because\n-- checkError calls Internal.errorClass and Internal.errorString.\n-- These cannot be called after finalize (at least on OpenMPI).\n\ngetProcessorName :: IO String\ngetProcessorName = do\n allocaBytes (fromIntegral maxProcessorName) $ \\ptr -> do\n len <- getProcessorName' ptr\n peekCStringLen (ptr, cIntConv len)\n where\n getProcessorName' = {# fun unsafe Get_processor_name as getProcessorName_\n {id `Ptr CChar', alloca- `CInt' peekIntConv*} -> `()' checkError*- #}\n\ndata Version =\n Version { version :: Int, subversion :: Int }\n deriving (Eq, Ord)\n\ninstance Show Version where\n show v = show (version v) ++ \".\" ++ show (subversion v)\n\ngetVersion :: IO Version\ngetVersion = do\n (version, subversion) <- getVersion'\n return $ Version version subversion\n where\n getVersion' = {# fun unsafe Get_version as getVersion_\n {alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Return the number of processes involved in a communicator. For 'commWorld'\n-- it returns the total number of processes available. If the communicator is\n-- and intra-communicator it returns the number of processes in the local group.\n-- This function corresponds to @MPI_Comm_size@.\n{# fun unsafe Comm_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n{# fun unsafe Comm_remote_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n{# fun unsafe Comm_test_inter as ^\n {fromComm `Comm', alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\ncommGetAttr :: Storable e => Comm -> Int -> IO (Maybe e)\ncommGetAttr comm key = do\n isInitialized <- initialized\n if isInitialized then do\n alloca $ \\ptr -> do\n found <- commGetAttr' comm key (castPtr ptr)\n if found then do ptr2 <- peek ptr\n Just <$> peek ptr2\n else return Nothing\n else return Nothing\n where\n commGetAttr' = {# fun unsafe Comm_get_attr as commGetAttr_\n {fromComm `Comm', cIntConv `Int', id `Ptr ()', alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\nforeign import ccall unsafe \"&mpi_tag_ub\" tagUB_ :: Ptr Int\n\n-- | Maximum tag value supported by the current MPI implementation. Corresponds to the value of standard MPI\n-- attribute @MPI_TAG_UB@.\n--\n-- When called before 'init' or 'initThread' would return 0.\ntagUpperBound :: Int\ntagUpperBound =\n let key = unsafePerformIO (peek tagUB_)\n in fromMaybe 0 $ unsafePerformIO (commGetAttr commWorld key)\n\nforeign import ccall unsafe \"&mpi_tag_ub\" tagUB_ :: Ptr Int\n\n{- | True if clocks at all processes in\n'commWorld' are synchronized, False otherwise. The expectation is that\nthe variation in time, as measured by calls to 'wtime', will be less then one half the\nround-trip time for an MPI message of length zero. \n\nCommunicators other than 'commWorld' could have different clocks.\nYou could find it out by querying attribute 'wtimeIsGlobalKey' with 'commGetAttr'.\n\nWhen wtimeIsGlobal is called before 'init' or 'initThread' it would return False.\n-}\nwtimeIsGlobal :: Bool\nwtimeIsGlobal =\n fromMaybe False $ unsafePerformIO (commGetAttr commWorld wtimeIsGlobalKey)\n\nforeign import ccall unsafe \"&mpi_wtime_is_global\" wtimeIsGlobal_ :: Ptr Int\n\n-- | Numeric key for standard MPI communicator attribute @MPI_WTIME_IS_GLOBAL@.\n-- To be used with 'commGetAttr'.\nwtimeIsGlobalKey :: Int\nwtimeIsGlobalKey = unsafePerformIO (peek wtimeIsGlobal_)\n\n-- | Return the rank of the calling process for the given\n-- communicator. If it is an intercommunicator, returns rank of the\n-- process in the local group.\n{# fun unsafe Comm_rank as ^\n {fromComm `Comm', alloca- `Rank' peekIntConv* } -> `()' checkError*- #}\n\n{- | Compares two communicators.\n\n* If they are handles for the same MPI communicator object, result is 'Identical';\n\n* If both communicators are identical in constituents and rank\n order, result is `Congruent';\n\n* If they have the same members, nbut with different ranks, then\n result is 'Similar';\n\n* Otherwise, result is 'Unequal'.\n\n-}\n{# fun unsafe Comm_compare as ^\n {fromComm `Comm', fromComm `Comm', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- | Test for an incomming message, without actually receiving it.\n-- If a message has been sent from @Rank@ to the current process with @Tag@ on the\n-- communicator @Comm@ then 'probe' will return the 'Status' of the message. Otherwise\n-- it will block the current process until such a matching message is sent.\n-- This allows the current process to check for an incoming message and decide\n-- how to receive it, based on the information in the 'Status'.\n-- This function corresponds to @MPI_Probe@.\n{# fun Probe as ^\n {fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n{- probe :: Rank -- ^ Rank of the sender.\n -> Tag -- ^ Tag of the sent message.\n -> Comm -- ^ Communicator.\n -> IO Status -- ^ Information about the incoming message (but not the content of the message). -}\n\n{# fun unsafe Send as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Bsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Ssend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Rsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{# fun unsafe Recv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast* } -> `()' checkError*- #}\n{# fun unsafe Isend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n{# fun unsafe Ibsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n{# fun unsafe Issend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n{# fun Irecv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n\n-- | Like 'isend', but stores Request at the supplied pointer. Useful\n-- for making arrays of Requests that could be passed to 'waitall'\n{# fun unsafe Isend as isendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'ibsend', but stores Request at the supplied pointer. Useful\n-- for making arrays of Requests that could be passed to 'waitall'\n{# fun unsafe Ibsend as ibsendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'issend', but stores Request at the supplied pointer. Useful\n-- for making arrays of Requests that could be passed to 'waitall'\n{# fun unsafe Issend as issendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'irecv', but stores Request at the supplied pointer. Useful\n-- for making arrays of Requests that could be passed to 'waitall'\n{# fun Irecv as irecvPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n{# fun unsafe Bcast as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocks until all processes on the communicator call this function.\n-- This function corresponds to @MPI_Barrier@.\n{# fun unsafe Barrier as ^ {fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocking test for the completion of a send of receive.\n-- See 'test' for a non-blocking variant.\n-- This function corresponds to @MPI_Wait@.\n{# fun unsafe Wait as ^\n {withRequest* `Request', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Takes pointer to the array of Requests of given size, 'wait's on all of them,\n-- populates array of Statuses of the same size. This function corresponds to @MPI_Waitall@\n{# fun unsafe Waitall as ^\n { id `Count', castPtr `Ptr Request', castPtr `Ptr Status'} -> `()' checkError*- #}\n-- TODO: Make this Storable Array instead of Ptr ?\n\n-- | Non-blocking test for the completion of a send or receive.\n-- Returns @Nothing@ if the request is not complete, otherwise\n-- it returns @Just status@. See 'wait' for a blocking variant.\n-- This function corresponds to @MPI_Test@.\ntest :: Request -> IO (Maybe Status)\ntest request = do\n (flag, status) <- test' request\n if flag\n then return $ Just status\n else return Nothing\n where\n test' = {# fun unsafe Test as test_\n {withRequest* `Request', alloca- `Bool' peekBool*, allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Cancel a pending communication request.\n-- This function corresponds to @MPI_Cancel@.\n{# fun unsafe Cancel as ^\n {withRequest* `Request'} -> `()' checkError*- #}\nwithRequest req f = do alloca $ \\ptr -> do poke ptr req\n f (castPtr ptr)\n{# fun unsafe Scatter as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n{# fun unsafe Gather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- We pass counts\/displs as Ptr CInt so that caller could supply nullPtr here\n-- which would be impossible if we marshal arrays ourselves here.\n{# fun unsafe Scatterv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Gatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Allgather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Allgatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Alltoall as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Alltoallv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\n{# fun Reduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n{# fun Allreduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n{# fun Reduce_scatter as ^\n { id `BufferPtr', id `BufferPtr', id `Ptr CInt', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n{# fun unsafe Op_create as ^\n {castFunPtr `FunPtr (Ptr t -> Ptr t -> Ptr CInt -> Ptr Datatype -> IO ())', cFromEnum `Bool', alloca- `Operation' peekOperation*} -> `()' checkError*- #}\n{# fun Op_free as ^ {withOperation* `Operation'} -> `()' checkError*- #}\n{# fun unsafe Wtime as ^ {} -> `Double' realToFrac #}\n{# fun unsafe Wtick as ^ {} -> `Double' realToFrac #}\n\n-- | Return the process group from a communicator.\n{# fun unsafe Comm_group as ^\n {fromComm `Comm', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupRank = unsafePerformIO <$> groupRank'\n where groupRank' = {# fun unsafe Group_rank as groupRank_\n {fromGroup `Group', alloca- `Rank' peekIntConv*} -> `()' checkError*- #}\n\ngroupSize = unsafePerformIO <$> groupSize'\n where groupSize' = {# fun unsafe Group_size as groupSize_\n {fromGroup `Group', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\ngroupUnion g1 g2 = unsafePerformIO $ groupUnion' g1 g2\n where groupUnion' = {# fun unsafe Group_union as groupUnion_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupIntersection g1 g2 = unsafePerformIO $ groupIntersection' g1 g2\n where groupIntersection' = {# fun unsafe Group_intersection as groupIntersection_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupDifference g1 g2 = unsafePerformIO $ groupDifference' g1 g2\n where groupDifference' = {# fun unsafe Group_difference as groupDifference_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupCompare g1 g2 = unsafePerformIO $ groupCompare' g1 g2\n where\n groupCompare' = {# fun unsafe Group_compare as groupCompare_\n {fromGroup `Group', fromGroup `Group', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- Technically it might make better sense to make the second argument a Set rather than a list\n-- but the order is significant in the groupIncl function (the other function, not this one).\n-- For the sake of keeping their types in sync, a list is used instead.\n{# fun unsafe Group_excl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n{# fun unsafe Group_incl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\ngroupTranslateRanks :: Group -> [Rank] -> Group -> [Rank]\ngroupTranslateRanks group1 ranks group2 =\n unsafePerformIO $ do\n let (rankIntList :: [Int]) = map fromEnum ranks\n withArrayLen rankIntList $ \\size ranksPtr ->\n allocaArray size $ \\resultPtr -> do\n groupTranslateRanks' group1 (cFromEnum size) (castPtr ranksPtr) group2 resultPtr\n map toRank <$> peekArray size resultPtr\n where\n groupTranslateRanks' = {# fun unsafe Group_translate_ranks as groupTranslateRanks_\n {fromGroup `Group', id `CInt', id `Ptr CInt', fromGroup `Group', id `Ptr CInt'} -> `()' checkError*- #}\n\nwithRanksAsInts ranks f = withArrayLen (map fromEnum ranks) $ \\size ptr -> f (cIntConv size, castPtr ptr)\n\n-- | Return the number of bytes used to store an MPI 'Datatype'.\ntypeSize = unsafePerformIO . typeSize'\n where\n typeSize' =\n {# fun unsafe Type_size as typeSize_\n {fromDatatype `Datatype', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n{# fun unsafe Error_class as ^\n { id `CInt', alloca- `CInt' peek*} -> `CInt' id #}\n\n-- | Set the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_set_errhandler@.\n{# fun unsafe Comm_set_errhandler as ^\n {fromComm `Comm', fromErrhandler `Errhandler'} -> `()' checkError*- #}\n\n-- | Get the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_get_errhandler@.\n{# fun unsafe Comm_get_errhandler as ^\n {fromComm `Comm', alloca- `Errhandler' peekErrhandler*} -> `()' checkError*- #}\n\n-- | Tries to terminate all MPI processes in its communicator argument.\n-- The second argument is an error code which \/may\/ be used as the return status\n-- of the MPI process, but this is not guaranteed. On systems where 'Int' has a larger\n-- range than 'CInt', the error code will be clipped to fit into the range of 'CInt'.\n-- This function corresponds to @MPI_Abort@.\nabort :: Comm -> Int -> IO ()\nabort comm code =\n abort' comm (toErrorCode code)\n where\n toErrorCode :: Int -> CInt\n toErrorCode i\n -- Assumes Int always has range at least as big as CInt.\n | i < (fromIntegral (minBound :: CInt)) = minBound\n | i > (fromIntegral (maxBound :: CInt)) = maxBound\n | otherwise = cIntConv i\n\n abort' = {# fun unsafe Abort as abort_ {fromComm `Comm', id `CInt'} -> `()' checkError*- #}\n\n\ntype MPIDatatype = {# type MPI_Datatype #}\n\nnewtype Datatype = MkDatatype { fromDatatype :: MPIDatatype }\n\nforeign import ccall unsafe \"&mpi_char\" char_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_wchar\" wchar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_short\" short_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_int\" int_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long\" long_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_long\" longLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_char\" unsignedChar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_short\" unsignedShort_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned\" unsigned_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long\" unsignedLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long_long\" unsignedLongLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_float\" float_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_double\" double_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_double\" longDouble_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_byte\" byte_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_packed\" packed_ :: Ptr MPIDatatype\n\nchar, wchar, short, int, long, longLong, unsignedChar, unsignedShort :: Datatype\nunsigned, unsignedLong, unsignedLongLong, float, double, longDouble :: Datatype\nbyte, packed :: Datatype\n\nchar = MkDatatype <$> unsafePerformIO $ peek char_\nwchar = MkDatatype <$> unsafePerformIO $ peek wchar_\nshort = MkDatatype <$> unsafePerformIO $ peek short_\nint = MkDatatype <$> unsafePerformIO $ peek int_\nlong = MkDatatype <$> unsafePerformIO $ peek long_\nlongLong = MkDatatype <$> unsafePerformIO $ peek longLong_\nunsignedChar = MkDatatype <$> unsafePerformIO $ peek unsignedChar_\nunsignedShort = MkDatatype <$> unsafePerformIO $ peek unsignedShort_\nunsigned = MkDatatype <$> unsafePerformIO $ peek unsigned_\nunsignedLong = MkDatatype <$> unsafePerformIO $ peek unsignedLong_\nunsignedLongLong = MkDatatype <$> unsafePerformIO $ peek unsignedLongLong_\nfloat = MkDatatype <$> unsafePerformIO $ peek float_\ndouble = MkDatatype <$> unsafePerformIO $ peek double_\nlongDouble = MkDatatype <$> unsafePerformIO $ peek longDouble_\nbyte = MkDatatype <$> unsafePerformIO $ peek byte_\npacked = MkDatatype <$> unsafePerformIO $ peek packed_\n\n\ntype MPIErrhandler = {# type MPI_Errhandler #}\nnewtype Errhandler = MkErrhandler { fromErrhandler :: MPIErrhandler } deriving Storable\npeekErrhandler ptr = MkErrhandler <$> peek ptr\n\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr MPIErrhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr MPIErrhandler\nerrorsAreFatal, errorsReturn :: Errhandler\nerrorsAreFatal = MkErrhandler <$> unsafePerformIO $ peek errorsAreFatal_\nerrorsReturn = MkErrhandler <$> unsafePerformIO $ peek errorsReturn_\n\n{# enum ErrorClass {underscoreToCase} deriving (Eq,Ord,Show,Typeable) #}\n\n-- XXX Should this be a ForeinPtr?\n-- there is a MPI_Group_free function, which we should probably\n-- call when the group is no longer referenced.\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIGroup = {# type MPI_Group #}\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\npeekGroup ptr = MkGroup <$> peek ptr\n\nforeign import ccall \"&mpi_group_empty\" groupEmpty_ :: Ptr MPIGroup\n-- | Predefined handle for group without any members. Corresponds to @MPI_GROUP_EMPTY@\ngroupEmpty :: Group\ngroupEmpty = MkGroup <$> unsafePerformIO $ peek groupEmpty_\n\n\n{-\nThis module provides Haskell type that represents values of @MPI_Op@\ntype (reduction operations), and predefined reduction operations\ndefined in the MPI Report.\n-}\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIOperation = {# type MPI_Op #}\nnewtype Operation = MkOperation { fromOperation :: MPIOperation } deriving Storable\npeekOperation ptr = MkOperation <$> peek ptr\nwithOperation op f = alloca $ \\ptr -> do poke ptr (fromOperation op)\n f (castPtr ptr)\n\nforeign import ccall unsafe \"&mpi_max\" maxOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_min\" minOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_sum\" sumOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_prod\" prodOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_land\" landOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_band\" bandOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lor\" lorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bor\" borOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lxor\" lxorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bxor\" bxorOp_ :: Ptr MPIOperation\n-- foreign import ccall \"mpi_maxloc\" maxlocOp :: MPIOperation\n-- foreign import ccall \"mpi_minloc\" minlocOp :: MPIOperation\n-- foreign import ccall \"mpi_replace\" replaceOp :: MPIOperation\n-- TODO: support for those requires better support for pair datatypes\n\nmaxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp :: Operation\nmaxOp = MkOperation <$> unsafePerformIO $ peek maxOp_\nminOp = MkOperation <$> unsafePerformIO $ peek minOp_\nsumOp = MkOperation <$> unsafePerformIO $ peek sumOp_\nprodOp = MkOperation <$> unsafePerformIO $ peek prodOp_\nlandOp = MkOperation <$> unsafePerformIO $ peek landOp_\nbandOp = MkOperation <$> unsafePerformIO $ peek bandOp_\nlorOp = MkOperation <$> unsafePerformIO $ peek lorOp_\nborOp = MkOperation <$> unsafePerformIO $ peek borOp_\nlxorOp = MkOperation <$> unsafePerformIO $ peek lxorOp_\nbxorOp = MkOperation <$> unsafePerformIO $ peek bxorOp_\n\n\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI rank designations.\n-}\n\nnewtype Rank = MkRank { rankId :: Int }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Rank where\n (MkRank x) + (MkRank y) = MkRank (x+y)\n (MkRank x) * (MkRank y) = MkRank (x*y)\n abs (MkRank x) = MkRank (abs x)\n signum (MkRank x) = MkRank (signum x)\n fromInteger x\n | x > ( fromIntegral (maxBound :: CInt)) = error \"Rank value does not fit into 32 bits\"\n | x < 0 = error \"Negative Rank value\"\n | otherwise = MkRank (fromIntegral x)\n\nforeign import ccall \"mpi_any_source\" anySource_ :: Ptr Int\nforeign import ccall \"mpi_root\" theRoot_ :: Ptr Int\nforeign import ccall \"mpi_proc_null\" procNull_ :: Ptr Int\n\n-- | Predefined rank number that allows reception of point-to-point messages\n-- regardless of their source. Corresponds to @MPI_ANY_SOURCE@\nanySource :: Rank\nanySource = toRank $ unsafePerformIO $ peek anySource_\n\n-- | Predefined rank number that specifies root process during\n-- operations involving intercommunicators. Corresponds to @MPI_ROOT@\ntheRoot :: Rank\ntheRoot = toRank $ unsafePerformIO $ peek theRoot_\n\n-- | Predefined rank number that specifies non-root processes during\n-- operations involving intercommunicators. Corresponds to @MPI_PROC_NULL@\nprocNull :: Rank\nprocNull = toRank $ unsafePerformIO $ peek procNull_\n\ninstance Show Rank where\n show = show . rankId\n\ntoRank :: Enum a => a -> Rank\ntoRank x = MkRank { rankId = fromEnum x }\n\nfromRank :: Enum a => Rank -> a\nfromRank = toEnum . rankId\n\n{- This module provides Haskell representation of the @MPI_Request@ type. -}\ntype MPIRequest = {# type MPI_Request #}\nnewtype Request = MkRequest MPIRequest deriving Storable\npeekRequest ptr = MkRequest <$> peek ptr\n\n{-\nThis module provides Haskell representation of the @MPI_Status@ type\n(request status).\n\nField `status_error' should be used with care:\n\\\"The error field in status is not needed for calls that return only\none status, such as @MPI_WAIT@, since that would only duplicate the\ninformation returned by the function itself. The current design avoids\nthe additional overhead of setting it, in such cases. The field is\nneeded for calls that return multiple statuses, since each request may\nhave had a different failure.\\\"\n(this is a quote from )\n\nThis means that, for example, during the call to @MPI_Wait@\nimplementation is free to leave this field filled with whatever\ngarbage got there during memory allocation. Haskell FFI is not\nblanking out freshly allocated memory, so beware!\n-}\n\n-- | Haskell structure that holds fields of @MPI_Status@.\n--\n-- Please note that MPI report lists only three fields as mandatory:\n-- @status_source@, @status_tag@ and @status_error@. However, all\n-- MPI implementations that were used to test those bindings supported\n-- extended set of fields represented here.\ndata Status =\n Status\n { status_source :: CInt -- ^ rank of the source process\n , status_tag :: CInt -- ^ tag assigned at source\n , status_error :: CInt -- ^ error code, if any\n , status_count :: CInt -- ^ number of received elements, if applicable\n , status_cancelled :: CInt -- ^ whether the request was cancelled\n }\n deriving (Eq, Ord, Show)\n\ninstance Storable Status where\n sizeOf _ = {#sizeof MPI_Status #}\n alignment _ = 4\n peek p = Status\n <$> liftM cIntConv ({#get MPI_Status->MPI_SOURCE #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_TAG #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_ERROR #} p)\n#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields-\n <*> liftM cIntConv ({#get MPI_Status->count #} p)\n <*> liftM cIntConv ({#get MPI_Status->cancelled #} p)\n#else\n <*> liftM cIntConv ({#get MPI_Status->_count #} p)\n <*> liftM cIntConv ({#get MPI_Status->_cancelled #} p)\n#endif\n poke p x = do\n {#set MPI_Status.MPI_SOURCE #} p (cIntConv $ status_source x)\n {#set MPI_Status.MPI_TAG #} p (cIntConv $ status_tag x)\n {#set MPI_Status.MPI_ERROR #} p (cIntConv $ status_error x)\n#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields AND different order of fields\n {#set MPI_Status.count #} p (cIntConv $ status_count x)\n {#set MPI_Status.cancelled #} p (cIntConv $ status_cancelled x)\n#else\n {#set MPI_Status._count #} p (cIntConv $ status_count x)\n {#set MPI_Status._cancelled #} p (cIntConv $ status_cancelled x)\n#endif\n\n-- NOTE: Int here is picked arbitrary\nallocaCast f =\n alloca $ \\(ptr :: Ptr Int) -> f (castPtr ptr :: Ptr ())\npeekCast = peek . castPtr\n\n\n{-\nThis module provides Haskell datatype that represents values which\ncould be used as MPI tags.\n-}\n\nnewtype Tag = MkTag { tagVal :: Int }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Tag where\n (MkTag x) + (MkTag y) = MkTag (x+y)\n (MkTag x) * (MkTag y) = MkTag (x*y)\n abs (MkTag x) = MkTag (abs x)\n signum (MkTag x) = MkTag (signum x)\n fromInteger x\n | fromIntegral x > tagUpperBound = error \"Tag value is over the MPI_TAG_UB\"\n | x < 0 = error \"Negative Tag value\"\n | otherwise = MkTag (fromIntegral x)\n\ninstance Show Tag where\n show = show . tagVal\n\ntoTag :: Enum a => a -> Tag\ntoTag x = MkTag { tagVal = fromEnum x }\n\nfromTag :: Enum a => Tag -> a\nfromTag = toEnum . tagVal\n\nforeign import ccall unsafe \"&mpi_any_tag\" anyTag_ :: Ptr Int\n\n-- | Predefined tag value that allows reception of the messages with\n-- arbitrary tag values. Corresponds to @MPI_ANY_TAG@.\nanyTag :: Tag\nanyTag = toTag $ unsafePerformIO $ peek anyTag_\n\n-- | A tag with unit value. Intended to be used as a convenient default.\nunitTag :: Tag\nunitTag = toTag ()\n\n\n{-\nThis module provides Haskell datatypes that comprises of values of\npredefined MPI constants @MPI_THREAD_SINGLE@, @MPI_THREAD_FUNNELED@,\n@MPI_THREAD_SERIALIZED@, @MPI_THREAD_MULTIPLE@.\n-}\n\n{# enum ThreadSupport {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- | Value thrown as exception when MPI runtime is instructed to pass\n-- errors to user code (via 'commSetErrhandler' and 'errorsReturn').\n-- Since raw MPI errors codes are not standartized and not portable,\n-- they are not exposed.\ndata MPIError\n = MPIError\n { mpiErrorClass :: ErrorClass -- ^ Broad class of errors this one belongs to\n , mpiErrorString :: String -- ^ Human-readable error description\n }\n deriving (Eq, Show, Typeable)\n\ninstance Exception MPIError\n\ncheckError :: CInt -> IO ()\ncheckError code = do\n -- We ignore the error code from the call to Internal.errorClass\n -- because we call errorClass from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n (_, errClassRaw) <- errorClass code\n let errClass = cToEnum errClassRaw\n unless (errClass == Success) $ do\n errStr <- errorString code\n throwIO $ MPIError errClass errStr\n\n-- | Convert MPI error code human-readable error description. Corresponds to @MPI_Error_string@.\nerrorString :: CInt -> IO String\nerrorString code =\n allocaBytes (fromIntegral maxErrorString) $ \\ptr ->\n alloca $ \\lenPtr -> do\n -- We ignore the error code from the call to Internal.errorString\n -- because we call errorString from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n _ <- errorString' code ptr lenPtr\n len <- peek lenPtr\n peekCStringLen (ptr, cIntConv len)\n where\n errorString' = {# call unsafe Error_string as errorString_ #}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"f601030a29b34345ff625ddf7c33edca58287576","subject":"gio: S.G.File: don't export FileClass's nonexistent methods","message":"gio: S.G.File: don't export FileClass's nonexistent methods\n","repos":"gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte","old_file":"gio\/System\/GIO\/File.chs","new_file":"gio\/System\/GIO\/File.chs","new_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gio -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 13-Oct-2008\n--\n-- Copyright (c) 2008 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GIO, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GIO documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.GIO.File (\n File(..),\n FileClass,\n FileQueryInfoFlags(..),\n FileCreateFlags(..),\n FileCopyFlags(..),\n FileMonitorFlags(..),\n FilesystemPreviewType(..),\n FileProgressCallback,\n FileReadMoreCallback,\n fileFromPath,\n fileFromURI,\n fileFromCommandlineArg,\n fileFromParseName,\n fileEqual,\n fileBasename,\n filePath,\n fileURI,\n fileParseName,\n fileGetChild,\n fileGetChildForDisplayName,\n fileHasPrefix,\n fileGetRelativePath,\n fileResolveRelativePath,\n fileIsNative,\n fileHasURIScheme,\n fileURIScheme,\n fileRead,\n fileReadAsync,\n fileReadFinish,\n fileAppendTo,\n fileCreate,\n fileReplace,\n fileAppendToAsync,\n fileAppendToFinish,\n fileCreateAsync,\n fileCreateFinish,\n fileReplaceAsync,\n fileReplaceFinish,\n fileQueryInfo,\n fileQueryInfoAsync,\n fileQueryInfoFinish,\n fileQueryExists,\n fileQueryFilesystemInfo,\n fileQueryFilesystemInfoAsync,\n fileQueryFilesystemInfoFinish,\n fileQueryDefaultHandler,\n fileFindEnclosingMount,\n fileFindEnclosingMountAsync,\n fileFindEnclosingMountFinish,\n fileEnumerateChildren,\n fileEnumerateChildrenAsync,\n fileEnumerateChildrenFinish,\n fileSetDisplayName,\n fileSetDisplayNameAsync,\n fileSetDisplayNameFinish,\n fileDelete,\n fileTrash,\n fileCopy,\n fileCopyAsync,\n fileCopyFinish,\n fileMove,\n fileMakeDirectory,\n fileMakeDirectoryWithParents,\n fileMakeSymbolicLink,\n fileQuerySettableAttributes,\n fileQueryWritableNamespaces\n ) where\n\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport Data.Typeable\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.UTFString\n\nimport System.GIO.Base\n{#import System.GIO.Types#}\nimport System.GIO.FileAttribute\n\n{# context lib = \"gio\" prefix = \"g\" #}\n\n{# enum GFileQueryInfoFlags as FileQueryInfoFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileQueryInfoFlags\n\n{# enum GFileCreateFlags as FileCreateFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCreateFlags\n\n{# enum GFileCopyFlags as FileCopyFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCopyFlags\n\n{# enum GFileMonitorFlags as FileMonitorFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileMonitorFlags\n\n{# enum GFilesystemPreviewType as FilesystemPreviewType {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\ntype FileProgressCallback = Offset -> Offset -> IO ()\ntype CFileProgressCallback = {# type goffset #} -> {# type goffset #} -> Ptr () -> IO ()\nforeign import ccall \"wrapper\"\n makeFileProgressCallback :: CFileProgressCallback\n -> IO {# type GFileProgressCallback #}\n\nmarshalFileProgressCallback :: FileProgressCallback -> IO {# type GFileProgressCallback #}\nmarshalFileProgressCallback fileProgressCallback =\n makeFileProgressCallback cFileProgressCallback\n where cFileProgressCallback :: CFileProgressCallback\n cFileProgressCallback cCurrentNumBytes cTotalNumBytes _ = do\n fileProgressCallback (fromIntegral cCurrentNumBytes)\n (fromIntegral cTotalNumBytes)\n\ntype FileReadMoreCallback = BS.ByteString -> IO Bool\n\nfileFromPath :: FilePath -> File\nfileFromPath path =\n unsafePerformIO $ withUTFString path $ \\cPath -> {# call file_new_for_path #} cPath >>= takeGObject\n\nfileFromURI :: String -> File\nfileFromURI uri =\n unsafePerformIO $ withUTFString uri $ \\cURI -> {# call file_new_for_uri #} cURI >>= takeGObject\n\nfileFromCommandlineArg :: String -> File\nfileFromCommandlineArg arg =\n unsafePerformIO $ withUTFString arg $ \\cArg -> {# call file_new_for_commandline_arg #} cArg >>= takeGObject\n\nfileFromParseName :: String -> File\nfileFromParseName parseName =\n unsafePerformIO $ withUTFString parseName $ \\cParseName -> {# call file_parse_name #} cParseName >>= takeGObject\n\nfileEqual :: (FileClass file1, FileClass file2)\n => file1 -> file2 -> Bool\nfileEqual file1 file2 =\n unsafePerformIO $ liftM toBool $ {# call file_equal #} (toFile file1) (toFile file2)\n\ninstance Eq File where\n (==) = fileEqual\n\nfileBasename :: FileClass file => file -> String\nfileBasename file =\n unsafePerformIO $ {# call file_get_basename #} (toFile file) >>= readUTFString\n\nfilePath :: FileClass file => file -> FilePath\nfilePath file =\n unsafePerformIO $ {# call file_get_path #} (toFile file) >>= readUTFString\n\nfileURI :: FileClass file => file -> String\nfileURI file =\n unsafePerformIO $ {# call file_get_uri #} (toFile file) >>= readUTFString\n\nfileParseName :: FileClass file => file -> String\nfileParseName file =\n unsafePerformIO $ {# call file_get_parse_name #} (toFile file) >>= readUTFString\n\nfileParent :: FileClass file => file -> Maybe File\nfileParent file =\n unsafePerformIO $ {# call file_get_parent #} (toFile file) >>= maybePeek takeGObject\n\nfileGetChild :: FileClass file => file -> String -> File\nfileGetChild file name =\n unsafePerformIO $\n withUTFString name $ \\cName ->\n {# call file_get_child #} (toFile file) cName >>= takeGObject\n\nfileGetChildForDisplayName :: FileClass file => file -> String -> Maybe File\nfileGetChildForDisplayName file displayName =\n unsafePerformIO $\n withUTFString displayName $ \\cDisplayName ->\n propagateGError ({# call file_get_child_for_display_name #} (toFile file) cDisplayName) >>=\n maybePeek takeGObject\n\nfileHasPrefix :: (FileClass file1, FileClass file2) => file1 -> file2 -> Bool\nfileHasPrefix file1 file2 =\n unsafePerformIO $\n liftM toBool $ {# call file_has_prefix #} (toFile file1) (toFile file2)\n\nfileGetRelativePath :: (FileClass file1, FileClass file2) => file1 -> file2 -> Maybe FilePath\nfileGetRelativePath file1 file2 =\n unsafePerformIO $\n {# call file_get_relative_path #} (toFile file1) (toFile file2) >>=\n maybePeek readUTFString\n\nfileResolveRelativePath :: FileClass file => file -> FilePath -> Maybe File\nfileResolveRelativePath file relativePath =\n unsafePerformIO $\n withUTFString relativePath $ \\cRelativePath ->\n {# call file_resolve_relative_path #} (toFile file) cRelativePath >>=\n maybePeek takeGObject\n\nfileIsNative :: FileClass file => file -> Bool\nfileIsNative =\n unsafePerformIO .\n liftM toBool . {# call file_is_native #} . toFile\n\nfileHasURIScheme :: FileClass file => file -> String -> Bool\nfileHasURIScheme file uriScheme =\n unsafePerformIO $\n withUTFString uriScheme $ \\cURIScheme ->\n liftM toBool $ {# call file_has_uri_scheme #} (toFile file) cURIScheme\n\nfileURIScheme :: FileClass file => file -> String\nfileURIScheme file =\n unsafePerformIO $ {# call file_get_uri_scheme #} (toFile file) >>= readUTFString\n\nfileRead :: FileClass file => file -> Maybe Cancellable -> IO FileInputStream\nfileRead file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_read cFile cCancellable) >>= takeGObject\n where _ = {# call file_read #}\n\nfileReadAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReadAsync file ioPriority mbCancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject mbCancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_read_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_read_async #}\n\nfileReadFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInputStream\nfileReadFinish file asyncResult =\n propagateGError ({# call file_read_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileAppendTo :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileAppendTo file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_append_to cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_append_to #}\n\nfileCreate :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileCreate file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_create cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_create #}\n\nfileReplace :: FileClass file\n => file\n -> Maybe String\n -> Bool\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileReplace file etag makeBackup flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_replace cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_replace #}\n\nfileAppendToAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileAppendToAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_append_to_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_append_to_async #}\n\nfileAppendToFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileAppendToFinish file asyncResult =\n propagateGError ({# call file_append_to_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileCreateAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileCreateAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_create_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_create_async #}\n\nfileCreateFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileCreateFinish file asyncResult =\n propagateGError ({# call file_create_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileReplaceAsync :: FileClass file\n => file\n -> String\n -> Bool\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReplaceAsync file etag makeBackup flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_replace_async cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_replace_async #}\n\nfileReplaceFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileReplaceFinish file asyncResult =\n propagateGError ({# call file_replace_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileQueryInfo :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryInfo file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_info cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_query_info #}\n\nfileQueryInfoAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryInfoAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_info_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_info_async #}\n\nfileQueryInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryInfoFinish file asyncResult =\n propagateGError ({#call file_query_info_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileQueryExists :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Bool\nfileQueryExists file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n liftM toBool $ g_file_query_exists cFile cCancellable\n where _ = {# call file_query_exists #}\n\nfileQueryFilesystemInfo :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryFilesystemInfo file attributes cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_filesystem_info cFile cAttributes cCancellable) >>=\n takeGObject\n where _ = {# call file_query_filesystem_info #}\n\nfileQueryFilesystemInfoAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryFilesystemInfoAsync file attributes ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_filesystem_info_async cFile\n cAttributes\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_filesystem_info_async #}\n\nfileQueryFilesystemInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryFilesystemInfoFinish file asyncResult =\n propagateGError ({# call file_query_filesystem_info_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileQueryDefaultHandler :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO AppInfo\nfileQueryDefaultHandler file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_default_handler cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_query_default_handler #}\n\nfileFindEnclosingMount :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Mount\nfileFindEnclosingMount file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_find_enclosing_mount cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_find_enclosing_mount #}\n\nfileFindEnclosingMountAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileFindEnclosingMountAsync file ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_find_enclosing_mount_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_find_enclosing_mount_async #}\n\nfileFindEnclosingMountFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Mount\nfileFindEnclosingMountFinish file asyncResult =\n propagateGError ({# call file_find_enclosing_mount_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileEnumerateChildren :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileEnumerator\nfileEnumerateChildren file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_enumerate_children cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_enumerate_children #}\n\nfileEnumerateChildrenAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileEnumerateChildrenAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_enumerate_children_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_enumerate_children_async #}\n\nfileEnumerateChildrenFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileEnumerator\nfileEnumerateChildrenFinish file asyncResult =\n propagateGError ({# call file_enumerate_children_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileSetDisplayName :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO File\nfileSetDisplayName file displayName cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_set_display_name cFile cDisplayName cCancellable) >>=\n takeGObject\n where _ = {# call file_set_display_name #}\n\nfileSetDisplayNameAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileSetDisplayNameAsync file displayName ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_set_display_name_async cFile\n cDisplayName\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_set_display_name_async #}\n\nfileSetDisplayNameFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO File\nfileSetDisplayNameFinish file asyncResult =\n propagateGError ({# call file_set_display_name_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileDelete :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileDelete file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_delete cFile cCancellable) >> return ()\n where _ = {# call file_delete #}\n\nfileTrash :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileTrash file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_trash cFile cCancellable) >> return ()\n where _ = {# call file_trash #}\n\nfileCopy :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileCopy source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_copy cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_copy #}\n\nfileCopyAsync :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Int\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> AsyncReadyCallback\n -> IO ()\nfileCopyAsync source destination flags ioPriority cancellable progressCallback callback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n cCallback <- marshalAsyncReadyCallback $ \\sourceObject res -> do\n freeHaskellFunPtr cProgressCallback\n callback sourceObject res\n g_file_copy_async cSource\n cDestination\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cProgressCallback\n nullPtr\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_copy_async #}\n\nfileCopyFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Bool\nfileCopyFinish file asyncResult =\n liftM toBool $ propagateGError ({# call file_copy_finish #} (toFile file) asyncResult)\n\nfileMove :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileMove source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_move cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_move #}\n\nfileMakeDirectory :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectory file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory cFile cCancellable\n return ()\n where _ = {# call file_make_directory #}\n\nfileMakeDirectoryWithParents :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectoryWithParents file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory_with_parents cFile cCancellable\n return ()\n where _ = {# call file_make_directory_with_parents #}\n\nfileMakeSymbolicLink :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO ()\nfileMakeSymbolicLink file symlinkValue cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString symlinkValue $ \\cSymlinkValue ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_symbolic_link cFile cSymlinkValue cCancellable\n return ()\n where _ = {# call file_make_symbolic_link #}\n\n{# pointer *FileAttributeInfoList newtype #}\ntakeFileAttributeInfoList :: Ptr FileAttributeInfoList\n -> IO [FileAttributeInfo]\ntakeFileAttributeInfoList ptr =\n do cInfos <- liftM castPtr $ {# get FileAttributeInfoList->infos #} ptr\n cNInfos <- {# get FileAttributeInfoList->n_infos #} ptr\n infos <- peekArray (fromIntegral cNInfos) cInfos\n g_file_attribute_info_list_unref ptr\n return infos\n where _ = {# call file_attribute_info_list_unref #}\n\nfileQuerySettableAttributes :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO [FileAttributeInfo]\nfileQuerySettableAttributes file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n ptr <- propagateGError $ g_file_query_settable_attributes cFile cCancellable\n infos <- takeFileAttributeInfoList ptr\n return infos\n where _ = {# call file_query_settable_attributes #}\n\nfileQueryWritableNamespaces :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO [FileAttributeInfo]\nfileQueryWritableNamespaces file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n ptr <- propagateGError $ g_file_query_writable_namespaces cFile cCancellable\n infos <- takeFileAttributeInfoList ptr\n return infos\n where _ = {# call file_query_writable_namespaces #}\n\n","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gio -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 13-Oct-2008\n--\n-- Copyright (c) 2008 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GIO, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GIO documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.GIO.File (\n File(..),\n FileClass(..),\n FileQueryInfoFlags(..),\n FileCreateFlags(..),\n FileCopyFlags(..),\n FileMonitorFlags(..),\n FilesystemPreviewType(..),\n FileProgressCallback,\n FileReadMoreCallback,\n fileFromPath,\n fileFromURI,\n fileFromCommandlineArg,\n fileFromParseName,\n fileEqual,\n fileBasename,\n filePath,\n fileURI,\n fileParseName,\n fileGetChild,\n fileGetChildForDisplayName,\n fileHasPrefix,\n fileGetRelativePath,\n fileResolveRelativePath,\n fileIsNative,\n fileHasURIScheme,\n fileURIScheme,\n fileRead,\n fileReadAsync,\n fileReadFinish,\n fileAppendTo,\n fileCreate,\n fileReplace,\n fileAppendToAsync,\n fileAppendToFinish,\n fileCreateAsync,\n fileCreateFinish,\n fileReplaceAsync,\n fileReplaceFinish,\n fileQueryInfo,\n fileQueryInfoAsync,\n fileQueryInfoFinish,\n fileQueryExists,\n fileQueryFilesystemInfo,\n fileQueryFilesystemInfoAsync,\n fileQueryFilesystemInfoFinish,\n fileQueryDefaultHandler,\n fileFindEnclosingMount,\n fileFindEnclosingMountAsync,\n fileFindEnclosingMountFinish,\n fileEnumerateChildren,\n fileEnumerateChildrenAsync,\n fileEnumerateChildrenFinish,\n fileSetDisplayName,\n fileSetDisplayNameAsync,\n fileSetDisplayNameFinish,\n fileDelete,\n fileTrash,\n fileCopy,\n fileCopyAsync,\n fileCopyFinish,\n fileMove,\n fileMakeDirectory,\n fileMakeDirectoryWithParents,\n fileMakeSymbolicLink,\n fileQuerySettableAttributes,\n fileQueryWritableNamespaces\n ) where\n\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport Data.Typeable\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.UTFString\n\nimport System.GIO.Base\n{#import System.GIO.Types#}\nimport System.GIO.FileAttribute\n\n{# context lib = \"gio\" prefix = \"g\" #}\n\n{# enum GFileQueryInfoFlags as FileQueryInfoFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileQueryInfoFlags\n\n{# enum GFileCreateFlags as FileCreateFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCreateFlags\n\n{# enum GFileCopyFlags as FileCopyFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCopyFlags\n\n{# enum GFileMonitorFlags as FileMonitorFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileMonitorFlags\n\n{# enum GFilesystemPreviewType as FilesystemPreviewType {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\ntype FileProgressCallback = Offset -> Offset -> IO ()\ntype CFileProgressCallback = {# type goffset #} -> {# type goffset #} -> Ptr () -> IO ()\nforeign import ccall \"wrapper\"\n makeFileProgressCallback :: CFileProgressCallback\n -> IO {# type GFileProgressCallback #}\n\nmarshalFileProgressCallback :: FileProgressCallback -> IO {# type GFileProgressCallback #}\nmarshalFileProgressCallback fileProgressCallback =\n makeFileProgressCallback cFileProgressCallback\n where cFileProgressCallback :: CFileProgressCallback\n cFileProgressCallback cCurrentNumBytes cTotalNumBytes _ = do\n fileProgressCallback (fromIntegral cCurrentNumBytes)\n (fromIntegral cTotalNumBytes)\n\ntype FileReadMoreCallback = BS.ByteString -> IO Bool\n\nfileFromPath :: FilePath -> File\nfileFromPath path =\n unsafePerformIO $ withUTFString path $ \\cPath -> {# call file_new_for_path #} cPath >>= takeGObject\n\nfileFromURI :: String -> File\nfileFromURI uri =\n unsafePerformIO $ withUTFString uri $ \\cURI -> {# call file_new_for_uri #} cURI >>= takeGObject\n\nfileFromCommandlineArg :: String -> File\nfileFromCommandlineArg arg =\n unsafePerformIO $ withUTFString arg $ \\cArg -> {# call file_new_for_commandline_arg #} cArg >>= takeGObject\n\nfileFromParseName :: String -> File\nfileFromParseName parseName =\n unsafePerformIO $ withUTFString parseName $ \\cParseName -> {# call file_parse_name #} cParseName >>= takeGObject\n\nfileEqual :: (FileClass file1, FileClass file2)\n => file1 -> file2 -> Bool\nfileEqual file1 file2 =\n unsafePerformIO $ liftM toBool $ {# call file_equal #} (toFile file1) (toFile file2)\n\ninstance Eq File where\n (==) = fileEqual\n\nfileBasename :: FileClass file => file -> String\nfileBasename file =\n unsafePerformIO $ {# call file_get_basename #} (toFile file) >>= readUTFString\n\nfilePath :: FileClass file => file -> FilePath\nfilePath file =\n unsafePerformIO $ {# call file_get_path #} (toFile file) >>= readUTFString\n\nfileURI :: FileClass file => file -> String\nfileURI file =\n unsafePerformIO $ {# call file_get_uri #} (toFile file) >>= readUTFString\n\nfileParseName :: FileClass file => file -> String\nfileParseName file =\n unsafePerformIO $ {# call file_get_parse_name #} (toFile file) >>= readUTFString\n\nfileParent :: FileClass file => file -> Maybe File\nfileParent file =\n unsafePerformIO $ {# call file_get_parent #} (toFile file) >>= maybePeek takeGObject\n\nfileGetChild :: FileClass file => file -> String -> File\nfileGetChild file name =\n unsafePerformIO $\n withUTFString name $ \\cName ->\n {# call file_get_child #} (toFile file) cName >>= takeGObject\n\nfileGetChildForDisplayName :: FileClass file => file -> String -> Maybe File\nfileGetChildForDisplayName file displayName =\n unsafePerformIO $\n withUTFString displayName $ \\cDisplayName ->\n propagateGError ({# call file_get_child_for_display_name #} (toFile file) cDisplayName) >>=\n maybePeek takeGObject\n\nfileHasPrefix :: (FileClass file1, FileClass file2) => file1 -> file2 -> Bool\nfileHasPrefix file1 file2 =\n unsafePerformIO $\n liftM toBool $ {# call file_has_prefix #} (toFile file1) (toFile file2)\n\nfileGetRelativePath :: (FileClass file1, FileClass file2) => file1 -> file2 -> Maybe FilePath\nfileGetRelativePath file1 file2 =\n unsafePerformIO $\n {# call file_get_relative_path #} (toFile file1) (toFile file2) >>=\n maybePeek readUTFString\n\nfileResolveRelativePath :: FileClass file => file -> FilePath -> Maybe File\nfileResolveRelativePath file relativePath =\n unsafePerformIO $\n withUTFString relativePath $ \\cRelativePath ->\n {# call file_resolve_relative_path #} (toFile file) cRelativePath >>=\n maybePeek takeGObject\n\nfileIsNative :: FileClass file => file -> Bool\nfileIsNative =\n unsafePerformIO .\n liftM toBool . {# call file_is_native #} . toFile\n\nfileHasURIScheme :: FileClass file => file -> String -> Bool\nfileHasURIScheme file uriScheme =\n unsafePerformIO $\n withUTFString uriScheme $ \\cURIScheme ->\n liftM toBool $ {# call file_has_uri_scheme #} (toFile file) cURIScheme\n\nfileURIScheme :: FileClass file => file -> String\nfileURIScheme file =\n unsafePerformIO $ {# call file_get_uri_scheme #} (toFile file) >>= readUTFString\n\nfileRead :: FileClass file => file -> Maybe Cancellable -> IO FileInputStream\nfileRead file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_read cFile cCancellable) >>= takeGObject\n where _ = {# call file_read #}\n\nfileReadAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReadAsync file ioPriority mbCancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject mbCancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_read_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_read_async #}\n\nfileReadFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInputStream\nfileReadFinish file asyncResult =\n propagateGError ({# call file_read_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileAppendTo :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileAppendTo file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_append_to cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_append_to #}\n\nfileCreate :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileCreate file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_create cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_create #}\n\nfileReplace :: FileClass file\n => file\n -> Maybe String\n -> Bool\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileReplace file etag makeBackup flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_replace cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_replace #}\n\nfileAppendToAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileAppendToAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_append_to_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_append_to_async #}\n\nfileAppendToFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileAppendToFinish file asyncResult =\n propagateGError ({# call file_append_to_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileCreateAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileCreateAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_create_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_create_async #}\n\nfileCreateFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileCreateFinish file asyncResult =\n propagateGError ({# call file_create_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileReplaceAsync :: FileClass file\n => file\n -> String\n -> Bool\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReplaceAsync file etag makeBackup flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_replace_async cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_replace_async #}\n\nfileReplaceFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileReplaceFinish file asyncResult =\n propagateGError ({# call file_replace_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileQueryInfo :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryInfo file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_info cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_query_info #}\n\nfileQueryInfoAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryInfoAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_info_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_info_async #}\n\nfileQueryInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryInfoFinish file asyncResult =\n propagateGError ({#call file_query_info_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileQueryExists :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Bool\nfileQueryExists file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n liftM toBool $ g_file_query_exists cFile cCancellable\n where _ = {# call file_query_exists #}\n\nfileQueryFilesystemInfo :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryFilesystemInfo file attributes cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_filesystem_info cFile cAttributes cCancellable) >>=\n takeGObject\n where _ = {# call file_query_filesystem_info #}\n\nfileQueryFilesystemInfoAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryFilesystemInfoAsync file attributes ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_filesystem_info_async cFile\n cAttributes\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_filesystem_info_async #}\n\nfileQueryFilesystemInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryFilesystemInfoFinish file asyncResult =\n propagateGError ({# call file_query_filesystem_info_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileQueryDefaultHandler :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO AppInfo\nfileQueryDefaultHandler file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_default_handler cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_query_default_handler #}\n\nfileFindEnclosingMount :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Mount\nfileFindEnclosingMount file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_find_enclosing_mount cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_find_enclosing_mount #}\n\nfileFindEnclosingMountAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileFindEnclosingMountAsync file ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_find_enclosing_mount_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_find_enclosing_mount_async #}\n\nfileFindEnclosingMountFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Mount\nfileFindEnclosingMountFinish file asyncResult =\n propagateGError ({# call file_find_enclosing_mount_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileEnumerateChildren :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileEnumerator\nfileEnumerateChildren file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_enumerate_children cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_enumerate_children #}\n\nfileEnumerateChildrenAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileEnumerateChildrenAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_enumerate_children_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_enumerate_children_async #}\n\nfileEnumerateChildrenFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileEnumerator\nfileEnumerateChildrenFinish file asyncResult =\n propagateGError ({# call file_enumerate_children_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileSetDisplayName :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO File\nfileSetDisplayName file displayName cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_set_display_name cFile cDisplayName cCancellable) >>=\n takeGObject\n where _ = {# call file_set_display_name #}\n\nfileSetDisplayNameAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileSetDisplayNameAsync file displayName ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_set_display_name_async cFile\n cDisplayName\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_set_display_name_async #}\n\nfileSetDisplayNameFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO File\nfileSetDisplayNameFinish file asyncResult =\n propagateGError ({# call file_set_display_name_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileDelete :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileDelete file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_delete cFile cCancellable) >> return ()\n where _ = {# call file_delete #}\n\nfileTrash :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileTrash file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_trash cFile cCancellable) >> return ()\n where _ = {# call file_trash #}\n\nfileCopy :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileCopy source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_copy cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_copy #}\n\nfileCopyAsync :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Int\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> AsyncReadyCallback\n -> IO ()\nfileCopyAsync source destination flags ioPriority cancellable progressCallback callback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n cCallback <- marshalAsyncReadyCallback $ \\sourceObject res -> do\n freeHaskellFunPtr cProgressCallback\n callback sourceObject res\n g_file_copy_async cSource\n cDestination\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cProgressCallback\n nullPtr\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_copy_async #}\n\nfileCopyFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Bool\nfileCopyFinish file asyncResult =\n liftM toBool $ propagateGError ({# call file_copy_finish #} (toFile file) asyncResult)\n\nfileMove :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileMove source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_move cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_move #}\n\nfileMakeDirectory :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectory file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory cFile cCancellable\n return ()\n where _ = {# call file_make_directory #}\n\nfileMakeDirectoryWithParents :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectoryWithParents file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory_with_parents cFile cCancellable\n return ()\n where _ = {# call file_make_directory_with_parents #}\n\nfileMakeSymbolicLink :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO ()\nfileMakeSymbolicLink file symlinkValue cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString symlinkValue $ \\cSymlinkValue ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_symbolic_link cFile cSymlinkValue cCancellable\n return ()\n where _ = {# call file_make_symbolic_link #}\n\n{# pointer *FileAttributeInfoList newtype #}\ntakeFileAttributeInfoList :: Ptr FileAttributeInfoList\n -> IO [FileAttributeInfo]\ntakeFileAttributeInfoList ptr =\n do cInfos <- liftM castPtr $ {# get FileAttributeInfoList->infos #} ptr\n cNInfos <- {# get FileAttributeInfoList->n_infos #} ptr\n infos <- peekArray (fromIntegral cNInfos) cInfos\n g_file_attribute_info_list_unref ptr\n return infos\n where _ = {# call file_attribute_info_list_unref #}\n\nfileQuerySettableAttributes :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO [FileAttributeInfo]\nfileQuerySettableAttributes file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n ptr <- propagateGError $ g_file_query_settable_attributes cFile cCancellable\n infos <- takeFileAttributeInfoList ptr\n return infos\n where _ = {# call file_query_settable_attributes #}\n\nfileQueryWritableNamespaces :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO [FileAttributeInfo]\nfileQueryWritableNamespaces file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n ptr <- propagateGError $ g_file_query_writable_namespaces cFile cCancellable\n infos <- takeFileAttributeInfoList ptr\n return infos\n where _ = {# call file_query_writable_namespaces #}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"38e7152a6e995d124003fed2b2022039813c0931","subject":"Check if the prog was linked with -threaded and if so fail on initialisation","message":"Check if the prog was linked with -threaded and if so fail on initialisation\n\ndarcs-hash:20060809100824-b4c10-515828e223d9cfcc7a77a47127d15138a417d0f0.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/Graphics\/UI\/Gtk\/General\/General.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/General\/General.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) General\n--\n-- Author : Axel Simon, Manuel M. T. Chakravarty\n--\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.13 $ from $Date: 2005\/11\/06 19:10:16 $\n--\n-- Copyright (C) 2000..2005 Axel Simon, Manuel M. T. Chakravarty\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- TODO\n--\n-- quitAddDestroy, quitAdd, quitRemove\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- library initialization, main event loop, and events\n--\nmodule Graphics.UI.Gtk.General.General (\n-- getDefaultLanguage,\n initGUI,\n eventsPending,\n mainGUI,\n mainLevel,\n mainQuit,\n mainIteration,\n mainIterationDo,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n Priority,\n priorityLow,\n priorityDefaultIdle,\n priorityHighIdle,\n priorityDefault,\n priorityHigh,\n timeoutAdd,\n timeoutAddFull,\n timeoutRemove,\n idleAdd,\n idleRemove,\n inputAdd,\n inputRemove,\n IOCondition,\n HandlerId\n ) where\n\nimport System.Environment (getProgName, getArgs)\nimport Control.Monad (liftM, mapM, when)\nimport Control.Exception (ioError, Exception(ErrorCall))\nimport Control.Concurrent (rtsSupportsBoundThreads)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t\t(DestroyNotify, mkFunPtrDestroyNotify)\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n{-\n-- | Retreive the current language.\n-- * This function returns a String which's pointer can be used later on for\n-- comarisions.\n--\n--getDefaultLanguage :: IO String\n--getDefaultLanguage = do\n-- strPtr <- {#call unsafe get_default_language#}\n-- str <- peekUTFString strPtr\n-- destruct strPtr\n-- return str\n-}\n\n-- We compile this module using -#includ\"gtk\/wingtk.h\" to bypass the win32 abi\n-- check however we do not compile users programs with this headder so if\n-- initGUI was ever inlined in a users program, then that program would not\n-- bypass the abi check and would fail on startup. So to stop that we must\n-- prevent initGUI from being inlined.\n{-# NOINLINE initGUI #-}\n-- | Initialize the GUI binding.\n--\n-- * This function initialized the GUI toolkit and parses all Gtk\n-- specific arguments. The remaining arguments are returned. If the\n-- initialization of the toolkit fails for whatever reason, an exception\n-- is thrown.\n--\n-- * Throws: @ErrorCall \\\"Cannot initialize GUI.\\\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n when rtsSupportsBoundThreads\n (fail $ \"initGUI: Gtk2Hs does not currently support the threaded RTS\\n\"\n ++ \"see http:\/\/haskell.org\/gtk2hs\/archives\/2005\/07\/24\/writing-multi-threaded-guis\/2\/\\n\"\n\t ++ \"Please relink your program without using the '-threaded' flag.\")\n prog <- getProgName\n args <- getArgs\n let allArgs = (prog:args)\n withMany withUTFString allArgs $ \\addrs ->\n withArrayLen addrs $ \\argc argv ->\n with\t argv $ \\argvp ->\n with\t argc $ \\argcp -> do \n res <- {#call unsafe init_check#} (castPtr argcp) (castPtr argvp)\n if (toBool res) then do\n argc' <- peek argcp\n argv' <- peek argvp\n _:addrs' <- peekArray argc' argv' -- drop the program name\n mapM peekUTFString addrs'\n else error \"Cannot initialize GUI.\"\n\n-- | Inquire the number of events pending on the event queue\n--\neventsPending :: IO Int\neventsPending = liftM fromIntegral {#call unsafe events_pending#}\n\n-- | Run the Gtk+ main event loop.\n--\nmainGUI :: IO ()\nmainGUI = {#call main#}\n\n-- | Inquire the main loop level.\n--\n-- * Callbacks that take more time to process can call 'mainIteration' to keep\n-- the GUI responsive. Each time the main loop is restarted this way, the main\n-- loop counter is increased. This function returns this counter.\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- | Exit the main event loop.\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- | Process an event, block if necessary.\n--\n-- * Returns @True@ if 'mainQuit' was called while processing the event.\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- | Process a single event.\n--\n-- * Called with @True@, this function behaves as 'mainIteration' in that it\n-- waits until an event is available for processing. It will return\n-- immediately, if passed @False@.\n--\n-- * Returns @True@ if the 'mainQuit' was called while processing the event.\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- | add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- | inquire current grab widget\n--\ngrabGetCurrent :: IO (Maybe Widget)\ngrabGetCurrent = do\n wPtr <- {#call grab_get_current#}\n if (wPtr==nullPtr) then return Nothing else \n liftM Just $ makeNewObject mkWidget (return wPtr)\n\n-- | remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) General\n--\n-- Author : Axel Simon, Manuel M. T. Chakravarty\n--\n-- Created: 8 December 1998\n--\n-- Version $Revision: 1.13 $ from $Date: 2005\/11\/06 19:10:16 $\n--\n-- Copyright (C) 2000..2005 Axel Simon, Manuel M. T. Chakravarty\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- TODO\n--\n-- quitAddDestroy, quitAdd, quitRemove\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- library initialization, main event loop, and events\n--\nmodule Graphics.UI.Gtk.General.General (\n-- getDefaultLanguage,\n initGUI,\n eventsPending,\n mainGUI,\n mainLevel,\n mainQuit,\n mainIteration,\n mainIterationDo,\n grabAdd,\n grabGetCurrent,\n grabRemove,\n Priority,\n priorityLow,\n priorityDefaultIdle,\n priorityHighIdle,\n priorityDefault,\n priorityHigh,\n timeoutAdd,\n timeoutAddFull,\n timeoutRemove,\n idleAdd,\n idleRemove,\n inputAdd,\n inputRemove,\n IOCondition,\n HandlerId\n ) where\n\nimport System (getProgName, getArgs)\nimport Monad\t(liftM, mapM)\nimport Control.Exception (ioError, Exception(ErrorCall))\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GObject\t\t(DestroyNotify, mkFunPtrDestroyNotify)\nimport System.Glib.MainLoop\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n\n{#context lib=\"gtk\" prefix =\"gtk\"#}\n\n{-\n-- | Retreive the current language.\n-- * This function returns a String which's pointer can be used later on for\n-- comarisions.\n--\n--getDefaultLanguage :: IO String\n--getDefaultLanguage = do\n-- strPtr <- {#call unsafe get_default_language#}\n-- str <- peekUTFString strPtr\n-- destruct strPtr\n-- return str\n-}\n\n-- We compile this module using -#includ\"gtk\/wingtk.h\" to bypass the win32 abi\n-- check however we do not compile users programs with this headder so if\n-- initGUI was ever inlined in a users program, then that program would not\n-- bypass the abi check and would fail on startup. So to stop that we must\n-- prevent initGUI from being inlined.\n{-# NOINLINE initGUI #-}\n-- | Initialize the GUI binding.\n--\n-- * This function initialized the GUI toolkit and parses all Gtk\n-- specific arguments. The remaining arguments are returned. If the\n-- initialization of the toolkit fails for whatever reason, an exception\n-- is thrown.\n--\n-- * Throws: @ErrorCall \\\"Cannot initialize GUI.\\\"@\n--\ninitGUI :: IO [String]\ninitGUI = do\n prog <- getProgName\n args <- getArgs\n let allArgs = (prog:args)\n withMany withUTFString allArgs $ \\addrs ->\n withArrayLen addrs $ \\argc argv ->\n with\t argv $ \\argvp ->\n with\t argc $ \\argcp -> do \n res <- {#call unsafe init_check#} (castPtr argcp) (castPtr argvp)\n if (toBool res) then do\n argc' <- peek argcp\n argv' <- peek argvp\n _:addrs' <- peekArray argc' argv' -- drop the program name\n mapM peekUTFString addrs'\n else error \"Cannot initialize GUI.\"\n\n-- | Inquire the number of events pending on the event queue\n--\neventsPending :: IO Int\neventsPending = liftM fromIntegral {#call unsafe events_pending#}\n\n-- | Run the Gtk+ main event loop.\n--\nmainGUI :: IO ()\nmainGUI = {#call main#}\n\n-- | Inquire the main loop level.\n--\n-- * Callbacks that take more time to process can call 'mainIteration' to keep\n-- the GUI responsive. Each time the main loop is restarted this way, the main\n-- loop counter is increased. This function returns this counter.\n--\nmainLevel :: IO Int\nmainLevel = liftM (toEnum.fromEnum) {#call unsafe main_level#}\n\n-- | Exit the main event loop.\n--\nmainQuit :: IO ()\nmainQuit = {#call main_quit#}\n\n-- | Process an event, block if necessary.\n--\n-- * Returns @True@ if 'mainQuit' was called while processing the event.\n--\nmainIteration :: IO Bool\nmainIteration = liftM toBool {#call main_iteration#}\n\n-- | Process a single event.\n--\n-- * Called with @True@, this function behaves as 'mainIteration' in that it\n-- waits until an event is available for processing. It will return\n-- immediately, if passed @False@.\n--\n-- * Returns @True@ if the 'mainQuit' was called while processing the event.\n--\nmainIterationDo :: Bool -> IO Bool\nmainIterationDo blocking = \n liftM toBool $ {#call main_iteration_do#} (fromBool blocking)\n\n-- | add a grab widget\n--\ngrabAdd :: WidgetClass wd => wd -> IO ()\ngrabAdd = {#call grab_add#} . toWidget\n\n-- | inquire current grab widget\n--\ngrabGetCurrent :: IO (Maybe Widget)\ngrabGetCurrent = do\n wPtr <- {#call grab_get_current#}\n if (wPtr==nullPtr) then return Nothing else \n liftM Just $ makeNewObject mkWidget (return wPtr)\n\n-- | remove a grab widget\n--\ngrabRemove :: WidgetClass w => w -> IO ()\ngrabRemove = {#call grab_remove#} . toWidget\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"a3e84241d2c674aad2d79c4deac0064285d8abdc","subject":"Bindings for MPI_UNDEFINED","message":"Bindings for MPI_UNDEFINED\n","repos":"bjpop\/haskell-mpi,bjpop\/haskell-mpi,bjpop\/haskell-mpi","old_file":"src\/Control\/Parallel\/MPI\/Internal.chs","new_file":"src\/Control\/Parallel\/MPI\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n#include \n#include \"init_wrapper.h\"\n#include \"comparison_result.h\"\n#include \"error_classes.h\"\n#include \"thread_support.h\"\n-----------------------------------------------------------------------------\n{- |\nModule : Control.Parallel.MPI.Internal\nCopyright : (c) 2010 Bernie Pope, Dmitry Astapov\nLicense : BSD-style\nMaintainer : florbitous@gmail.com\nStability : experimental\nPortability : ghc\n\nThis module contains low-level Haskell bindings to core MPI functions.\nAll Haskell functions correspond to MPI functions or values with the similar\nname (i.e. @commRank@ is the binding for @MPI_Comm_rank@ etc)\n\nNote that most of this module is re-exported by\n\"Control.Parallel.MPI\", so if you are not interested in writing\nlow-level code, you should probably import \"Control.Parallel.MPI\" and\neither \"Control.Parallel.MPI.Storable\" or \"Control.Parallel.MPI.Serializable\".\n-}\n-----------------------------------------------------------------------------\nmodule Control.Parallel.MPI.Internal\n (\n\n -- * MPI runtime management.\n -- ** Initialization, finalization, termination.\n init, finalize, initialized, finalized, abort,\n -- ** Multi-threaded environment support.\n ThreadSupport (..), initThread, queryThread, isThreadMain,\n\n -- ** Runtime attributes.\n getProcessorName, Version (..), getVersion, Implementation(..), getImplementation,\n\n -- * Requests and statuses.\n Request, Status (..), probe, test, cancel, wait, waitall,\n\n -- * Process management.\n -- ** Communicators.\n Comm, commWorld, commSelf, commTestInter,\n commSize, commRemoteSize, \n commRank, \n commCompare, commGroup, commGetAttr,\n\n -- ** Process groups.\n Group, groupEmpty, groupRank, groupSize, groupUnion,\n groupIntersection, groupDifference, groupCompare, groupExcl,\n groupIncl, groupTranslateRanks,\n -- ** Comparisons.\n ComparisonResult (..),\n\n -- * Error handling.\n Errhandler, errorsAreFatal, errorsReturn, errorsThrowExceptions, commSetErrhandler, commGetErrhandler,\n ErrorClass (..), MPIError(..), mpiUndefined,\n\n -- * Ranks.\n Rank, rankId, toRank, fromRank, anySource, theRoot, procNull,\n\n -- * Data types.\n Datatype, char, wchar, short, int, long, longLong, unsignedChar, unsignedShort, unsigned, unsignedLong, unsignedLongLong, float, double, longDouble, byte, packed, typeSize,\n\n -- * Point-to-point operations.\n -- ** Tags.\n Tag, toTag, fromTag, anyTag, unitTag, tagUpperBound,\n\n -- ** Blocking operations.\n BufferPtr, Count, -- XXX: what will break if we don't export those?\n send, ssend, rsend, recv,\n -- ** Non-blocking operations.\n isend, issend, irecv,\n isendPtr, issendPtr, irecvPtr,\n\n\n -- * Collective operations.\n -- ** One-to-all.\n bcast, scatter, scatterv,\n -- ** All-to-one.\n gather, gatherv, reduce,\n -- ** All-to-all.\n allgather, allgatherv,\n alltoall, alltoallv,\n allreduce, \n reduceScatterBlock,\n reduceScatter,\n barrier,\n\n -- ** Reduction operations.\n Operation, maxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp,\n opCreate, opFree,\n\n -- * Timing.\n wtime, wtick, wtimeIsGlobal, wtimeIsGlobalKey\n\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Data.Maybe (fromMaybe)\nimport Control.Monad (liftM, unless)\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception\n\n{# context prefix = \"MPI\" #}\n\n-- | Pointer to memory buffer that either holds data to be sent or is\n-- used to receive some data. You would\n-- probably have to use 'castPtr' to pass some actual pointers to\n-- API functions.\ntype BufferPtr = Ptr ()\n\n-- | Count of elements in the send\/receive buffer\ntype Count = CInt\n\n{- |\nHaskell enum that contains MPI constants\n@MPI_IDENT@, @MPI_CONGRUENT@, @MPI_SIMILAR@ and @MPI_UNEQUAL@.\n\nThose are used to compare communicators ('commCompare') and\nprocess groups ('groupCompare'). Refer to those\nfunctions for description of comparison rules.\n-}\n{# enum ComparisonResult {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- Which Haskell type will be used as Comm depends on the MPI\n-- implementation that was selected during compilation. It could be\n-- CInt, Ptr (), Ptr CInt or something else.\ntype MPIComm = {# type MPI_Comm #}\n\n{- | Abstract type representing MPI communicator handle. Different MPI\n implementations use different C types to implement this, so\n concrete Haskell type behind @Comm@ is hidden from user.\n\n In any MPI program you have predefined communicator 'commWorld'\n which includes all running processes. You could create new\n communicators with TODO\n-}\nnewtype Comm = MkComm { fromComm :: MPIComm }\nforeign import ccall \"&mpi_comm_world\" commWorld_ :: Ptr MPIComm\nforeign import ccall \"&mpi_comm_self\" commSelf_ :: Ptr MPIComm\n\n-- | Predefined handle for communicator that includes all running\n-- processes. Similar to @MPI_Comm_world@\ncommWorld :: Comm\ncommWorld = MkComm <$> unsafePerformIO $ peek commWorld_\n\n-- | Predefined handle for communicator that includes only current\n-- process. Similar to @MPI_Comm_self@\ncommSelf :: Comm\ncommSelf = MkComm <$> unsafePerformIO $ peek commSelf_\n\nforeign import ccall \"&mpi_max_processor_name\" max_processor_name_ :: Ptr CInt\nforeign import ccall \"&mpi_max_error_string\" max_error_string_ :: Ptr CInt\n\n-- | Max length of \"processor name\" as returned by 'getProcessorName'\nmaxProcessorName :: CInt\nmaxProcessorName = unsafePerformIO $ peek max_processor_name_\n\n-- | Max length of error description as returned by 'errorString'\nmaxErrorString :: CInt\nmaxErrorString = unsafePerformIO $ peek max_error_string_\n\n-- | Initialize the MPI environment. The MPI environment must be intialized by each\n-- MPI process before any other MPI function is called. Note that\n-- the environment may also be initialized by the functions 'initThread', 'mpi',\n-- and 'mpiWorld'. It is an error to attempt to initialize the environment more\n-- than once for a given MPI program execution. The only MPI functions that may\n-- be called before the MPI environment is initialized are 'getVersion',\n-- 'initialized' and 'finalized'. This function corresponds to @MPI_Init@.\n{# fun unsafe init_wrapper as init {} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been initialized. Returns @True@ if the\n-- environment has been initialized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Initialized@.\n{# fun unsafe Initialized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been finalized. Returns @True@ if the\n-- environment has been finalized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Finalized@.\n{# fun unsafe Finalized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Initialize the MPI environment with a \/required\/ level of thread support.\n-- See the documentation for 'init' for more information about MPI initialization.\n-- The \/provided\/ level of thread support is returned in the result.\n-- There is no guarantee that provided will be greater than or equal to required.\n-- The level of provided thread support depends on the underlying MPI implementation,\n-- and may also depend on information provided when the program is executed\n-- (for example, by supplying appropriate arguments to @mpiexec@).\n-- If the required level of support cannot be provided then it will try to\n-- return the least supported level greater than what was required.\n-- If that cannot be satisfied then it will return the highest supported level\n-- provided by the MPI implementation. See the documentation for 'ThreadSupport'\n-- for information about what levels are available and their relative ordering.\n-- This function corresponds to @MPI_Init_thread@.\n{# fun unsafe init_wrapper_thread as initThread\n {cFromEnum `ThreadSupport', alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\n-- | Returns the current provided level of thread support. This will be the value\n-- returned as \\\"provided level of support\\\" by 'initThread' as well. This function\n-- corresponds to @MPI_Query_thread@.\n{# fun unsafe Query_thread as ^ {alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\n-- | This function can be called by a thread to find out whether it is the main thread (the\n-- thread that called 'init' or 'initThread'.\n{# fun unsafe Is_thread_main as ^\n {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Terminate the MPI execution environment.\n-- Once 'finalize' is called no other MPI functions may be called except\n-- 'getVersion', 'initialized' and 'finalized', however non-MPI computations\n-- may continue. Each process must complete\n-- any pending communication that it initiated before calling 'finalize'.\n-- Note: the error code returned\n-- by 'finalize' is not checked. This function corresponds to @MPI_Finalize@.\n{# fun unsafe Finalize as ^ {} -> `()' discard*- #}\ndiscard _ = return ()\n-- XXX can't call checkError on finalize, because\n-- checkError calls Internal.errorClass and Internal.errorString.\n-- These cannot be called after finalize (at least on OpenMPI).\n\n-- | Return the name of the current processing host. From this value it\n-- must be possible to identify a specic piece of hardware on which\n-- the code is running.\ngetProcessorName :: IO String\ngetProcessorName = do\n allocaBytes (fromIntegral maxProcessorName) $ \\ptr -> do\n len <- getProcessorName' ptr\n peekCStringLen (ptr, cIntConv len)\n where\n getProcessorName' = {# fun unsafe Get_processor_name as getProcessorName_\n {id `Ptr CChar', alloca- `CInt' peekIntConv*} -> `()' checkError*- #}\n\n-- | MPI implementation version\ndata Version =\n Version { version :: Int, subversion :: Int }\n deriving (Eq, Ord)\n\ninstance Show Version where\n show v = show (version v) ++ \".\" ++ show (subversion v)\n\n-- | Which MPI version the code is running on.\ngetVersion :: IO Version\ngetVersion = do\n (version, subversion) <- getVersion'\n return $ Version version subversion\n where\n getVersion' = {# fun unsafe Get_version as getVersion_\n {alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Supported MPI implementations\ndata Implementation = MPICH2 | OpenMPI deriving (Eq,Show)\n\n-- | Which MPI implementation was used during linking\ngetImplementation :: Implementation\ngetImplementation =\n#ifdef MPICH2\n MPICH2\n#else\n OpenMPI\n#endif\n\n-- | Return the number of processes involved in a communicator. For 'commWorld'\n-- it returns the total number of processes available. If the communicator is\n-- and intra-communicator it returns the number of processes in the local group.\n-- This function corresponds to @MPI_Comm_size@.\n{# fun unsafe Comm_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n-- | For intercommunicators, returs size of the remote process group.\n-- Corresponds to @MPI_Comm_remote_size@.\n{# fun unsafe Comm_remote_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n{- | Check whether the given communicator is intercommunicator - that\n is, communicator connecting two different groups of processes.\n\nRefer to MPI Report v2.2, Section 5.2 \"Communicator Argument\" for\nmore details.\n-}\n{# fun unsafe Comm_test_inter as ^\n {fromComm `Comm', alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Look up MPI communicator argument by the given numeric key.\n-- Lookup of some standard MPI arguments is provided by convenience\n-- functions 'tagUpperBound' and 'wtimeIsGlobal'.\ncommGetAttr :: Storable e => Comm -> Int -> IO (Maybe e)\ncommGetAttr comm key = do\n isInitialized <- initialized\n if isInitialized then do\n alloca $ \\ptr -> do\n found <- commGetAttr' comm key (castPtr ptr)\n if found then do ptr2 <- peek ptr\n Just <$> peek ptr2\n else return Nothing\n else return Nothing\n where\n commGetAttr' = {# fun unsafe Comm_get_attr as commGetAttr_\n {fromComm `Comm', cIntConv `Int', id `Ptr ()', alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Maximum tag value supported by the current MPI implementation. Corresponds to the value of standard MPI\n-- attribute @MPI_TAG_UB@.\n--\n-- When called before 'init' or 'initThread' would return 0.\ntagUpperBound :: Int\ntagUpperBound =\n let key = unsafePerformIO (peek tagUB_)\n in fromMaybe 0 $ unsafePerformIO (commGetAttr commWorld key)\n\nforeign import ccall unsafe \"&mpi_tag_ub\" tagUB_ :: Ptr Int\n\n{- | True if clocks at all processes in\n'commWorld' are synchronized, False otherwise. The expectation is that\nthe variation in time, as measured by calls to 'wtime', will be less then one half the\nround-trip time for an MPI message of length zero. \n\nCommunicators other than 'commWorld' could have different clocks.\nYou could find it out by querying attribute 'wtimeIsGlobalKey' with 'commGetAttr'.\n\nWhen wtimeIsGlobal is called before 'init' or 'initThread' it would return False.\n-}\nwtimeIsGlobal :: Bool\nwtimeIsGlobal =\n fromMaybe False $ unsafePerformIO (commGetAttr commWorld wtimeIsGlobalKey)\n\nforeign import ccall unsafe \"&mpi_wtime_is_global\" wtimeIsGlobal_ :: Ptr Int\n\n-- | Numeric key for standard MPI communicator attribute @MPI_WTIME_IS_GLOBAL@.\n-- To be used with 'commGetAttr'.\nwtimeIsGlobalKey :: Int\nwtimeIsGlobalKey = unsafePerformIO (peek wtimeIsGlobal_)\n\n-- | Return the rank of the calling process for the given\n-- communicator. If it is an intercommunicator, returns rank of the\n-- process in the local group.\n{# fun unsafe Comm_rank as ^\n {fromComm `Comm', alloca- `Rank' peekIntConv* } -> `()' checkError*- #}\n\n{- | Compares two communicators.\n\n* If they are handles for the same MPI communicator object, result is 'Identical';\n\n* If both communicators are identical in constituents and rank\n order, result is `Congruent';\n\n* If they have the same members, but with different ranks, then\n result is 'Similar';\n\n* Otherwise, result is 'Unequal'.\n\n-}\n{# fun unsafe Comm_compare as ^\n {fromComm `Comm', fromComm `Comm', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- | Test for an incomming message, without actually receiving it.\n-- If a message has been sent from @Rank@ to the current process with @Tag@ on the\n-- communicator @Comm@ then 'probe' will return the 'Status' of the message. Otherwise\n-- it will block the current process until such a matching message is sent.\n-- This allows the current process to check for an incoming message and decide\n-- how to receive it, based on the information in the 'Status'.\n-- This function corresponds to @MPI_Probe@.\n{# fun Probe as ^\n {fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n{- probe :: Rank -- ^ Rank of the sender.\n -> Tag -- ^ Tag of the sent message.\n -> Comm -- ^ Communicator.\n -> IO Status -- ^ Information about the incoming message (but not the content of the message). -}\n\n{-| Send the values (as specified by @BufferPtr@, @Count@, @Datatype@) to\n the process specified by (@Comm@, @Rank@, @Tag@). Caller will\n block until data is copied from the send buffer by the MPI\n-}\n{# fun unsafe Send as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{-| Variant of 'send' that would terminate only when receiving side\nactually starts receiving data. \n-}\n{# fun unsafe Ssend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{-| Variant of 'send' that expects the relevant 'recv' to be already\nstarted, otherwise this call could terminate with MPI error.\n-}\n{# fun unsafe Rsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n-- | Receives data from the process\n-- specified by (@Comm@, @Rank@, @Tag@) and stores it into buffer specified\n-- by (@BufferPtr@, @Count@, @Datatype@).\n{# fun unsafe Recv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast* } -> `()' checkError*- #}\n-- | Send the values (as specified by @BufferPtr@, @Count@, @Datatype@) to\n-- the process specified by (@Comm@, @Rank@, @Tag@) in non-blocking mode.\n-- \n-- Use 'probe' or 'test' to check the status of the operation,\n-- 'cancel' to terminate it or 'wait' to block until it completes.\n-- Operation would be considered complete as soon as MPI finishes\n-- copying the data from the send buffer. \n{# fun unsafe Isend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n-- | Variant of the 'isend' that would be considered complete only when\n-- receiving side actually starts receiving data. \n{# fun unsafe Issend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n-- | Non-blocking variant of 'recv'. Receives data from the process\n-- specified by (@Comm@, @Rank@, @Tag@) and stores it into buffer specified\n-- by (@BufferPtr@, @Count@, @Datatype@).\n{# fun Irecv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n\n-- | Like 'isend', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun unsafe Isend as isendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'issend', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun unsafe Issend as issendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'irecv', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun Irecv as irecvPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Broadcast data from one member to all members of the communicator.\n{# fun unsafe Bcast as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocks until all processes on the communicator call this function.\n-- This function corresponds to @MPI_Barrier@.\n{# fun unsafe Barrier as ^ {fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocking test for the completion of a send of receive.\n-- See 'test' for a non-blocking variant.\n-- This function corresponds to @MPI_Wait@.\n{# fun unsafe Wait as ^\n {withRequest* `Request', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Takes pointer to the array of Requests of given size, 'wait's on all of them,\n-- populates array of Statuses of the same size. This function corresponds to @MPI_Waitall@\n{# fun unsafe Waitall as ^\n { id `Count', castPtr `Ptr Request', castPtr `Ptr Status'} -> `()' checkError*- #}\n-- TODO: Make this Storable Array instead of Ptr ?\n\n-- | Non-blocking test for the completion of a send or receive.\n-- Returns @Nothing@ if the request is not complete, otherwise\n-- it returns @Just status@. See 'wait' for a blocking variant.\n-- This function corresponds to @MPI_Test@.\ntest :: Request -> IO (Maybe Status)\ntest request = do\n (flag, status) <- test' request\n if flag\n then return $ Just status\n else return Nothing\n where\n test' = {# fun unsafe Test as test_\n {withRequest* `Request', alloca- `Bool' peekBool*, allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Cancel a pending communication request.\n-- This function corresponds to @MPI_Cancel@.\n{# fun unsafe Cancel as ^\n {withRequest* `Request'} -> `()' checkError*- #}\nwithRequest req f = do alloca $ \\ptr -> do poke ptr req\n f (castPtr ptr)\n\n-- | Scatter data from one member to all members of\n-- a group.\n{# fun unsafe Scatter as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Gather data from all members of a group to one\n-- member.\n{# fun unsafe Gather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- Note: We pass counts\/displs as Ptr CInt so that caller could supply nullPtr here\n-- which would be impossible if we marshal arrays ourselves here.\n\n-- | A variation of 'scatter' which allows to use data segments of\n-- different length.\n{# fun unsafe Scatterv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'gather' which allows to use data segments of\n-- different length.\n{# fun unsafe Gatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'gather' where all members of\n-- a group receive the result.\n{# fun unsafe Allgather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'allgather' that allows to use data segments of\n-- different length.\n{# fun unsafe Allgatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Scatter\/Gather data from all\n-- members to all members of a group (also called complete exchange)\n{# fun unsafe Alltoall as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variant of 'alltoall' allows to use data segments of different length.\n{# fun unsafe Alltoallv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\n\n-- | Applies predefined or user-defined reduction operations to data,\n-- and delivers result to the single process.\n{# fun Reduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Applies predefined or user-defined reduction operations to data,\n-- and delivers result to all members of the group.\n{# fun Allreduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A combined reduction and scatter operation - result is split and\n-- parts are distributed among the participating processes.\n--\n-- See 'reduceScatter' for variant that allows to specify personal\n-- block size for each process.\n--\n-- Note that this call is not supported with some MPI implementations,\n-- like OpenMPI <= 1.5 and would cause a run-time 'error' in that case.\n#if 0\n{# fun Reduce_scatter_block as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n#else\nreduceScatterBlock :: BufferPtr -> BufferPtr -> Count -> Datatype -> Operation -> Comm -> IO ()\nreduceScatterBlock = error \"reduceScatterBlock is not supported by OpenMPI\"\n#endif\n\n-- | A combined reduction and scatter operation - result is split and\n-- parts are distributed among the participating processes.\n{# fun Reduce_scatter as ^\n { id `BufferPtr', id `BufferPtr', id `Ptr CInt', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n\n-- TODO: In the following haddock block, mention SCAN and EXSCAN once\n-- they are implemented \n\n{- | Binds a user-dened reduction operation to an 'Operation' handle that can\nsubsequently be used in 'reduce', 'allreduce', and 'reduceScatter'.\nThe user-defined operation is assumed to be associative. \n\nIf second argument to @opCreate@ is @True@, then the operation should be both commutative and associative. If\nit is not commutative, then the order of operands is fixed and is defined to be in ascending,\nprocess rank order, beginning with process zero. The order of evaluation can be changed,\ntaking advantage of the associativity of the operation. If operation\nis commutative then the order\nof evaluation can be changed, taking advantage of commutativity and\nassociativity.\n\nUser-defined operation accepts four arguments, @invec@, @inoutvec@,\n@len@ and @datatype@:\n\n[@invec@] first input vector\n\n[@inoutvec@] second input vector, which is also the output vector\n\n[@len@] length of both vectors\n\n[@datatype@] type of the elements in both vectors.\n\nFunction is expected to apply reduction operation to the elements\nof @invec@ and @inoutvec@ in pariwise manner:\n\n@\ninoutvec[i] = op invec[i] inoutvec[i]\n@\n\nFull example with user-defined function that mimics standard operation\n'sumOp':\n\n@\nimport \"Control.Parallel.MPI.Fast\"\n\nforeign import ccall \\\"wrapper\\\" \n wrap :: (Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()) \n -> IO (FunPtr (Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()))\nreduceUserOpTest myRank = do\n numProcs <- commSize commWorld\n userSumPtr <- wrap userSum\n mySumOp <- opCreate True userSumPtr\n (src :: StorableArray Int Double) <- newListArray (0,99) [0..99]\n if myRank \/= root\n then reduceSend commWorld root sumOp src\n else do\n (result :: StorableArray Int Double) <- intoNewArray_ (0,99) $ reduceRecv commWorld root mySumOp src\n recvMsg <- getElems result\n freeHaskellFunPtr userSumPtr\n where\n userSum :: Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()\n userSum inPtr inoutPtr lenPtr _ = do\n len <- peek lenPtr\n let offs = sizeOf ( undefined :: CDouble )\n let loop 0 _ _ = return ()\n loop n inPtr inoutPtr = do\n a <- peek inPtr\n b <- peek inoutPtr\n poke inoutPtr (a+b)\n loop (n-1) (plusPtr inPtr offs) (plusPtr inoutPtr offs)\n loop len inPtr inoutPtr\n@\n-}\n{# fun unsafe Op_create as ^\n {castFunPtr `FunPtr (Ptr t -> Ptr t -> Ptr CInt -> Ptr Datatype -> IO ())', cFromEnum `Bool', alloca- `Operation' peekOperation*} -> `()' checkError*- #}\n\n{- | Free the handle for user-defined reduction operation created by 'opCreate'\n-}\n{# fun Op_free as ^ {withOperation* `Operation'} -> `()' checkError*- #}\n\n{- | Returns a \nfloating-point number of seconds, representing elapsed wallclock\ntime since some time in the past.\n\nThe \\\"time in the past\\\" is guaranteed not to change during the life of the process.\nThe user is responsible for converting large numbers of seconds to other units if they are\npreferred. The time is local to the node that calls @wtime@, but see 'wtimeIsGlobal'.\n-}\n{# fun unsafe Wtime as ^ {} -> `Double' realToFrac #}\n\n{- | Returns the resolution of 'wtime' in seconds. That is, it returns,\nas a double precision value, the number of seconds between successive clock ticks. For\nexample, if the clock is implemented by the hardware as a counter that is incremented\nevery millisecond, the value returned by @wtick@ should be 10^(-3).\n-}\n{# fun unsafe Wtick as ^ {} -> `Double' realToFrac #}\n\n-- | Return the process group from a communicator. With\n-- intercommunicator, returns the local group.\n{# fun unsafe Comm_group as ^\n {fromComm `Comm', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Returns the rank of the calling process in the given group. This function corresponds to @MPI_Group_rank@.\ngroupRank :: Group -> Rank\ngroupRank = unsafePerformIO <$> groupRank'\n where groupRank' = {# fun unsafe Group_rank as groupRank_\n {fromGroup `Group', alloca- `Rank' peekIntConv*} -> `()' checkError*- #}\n\n-- | Returns the size of a group. This function corresponds to @MPI_Group_size@.\ngroupSize :: Group -> Int\ngroupSize = unsafePerformIO <$> groupSize'\n where groupSize' = {# fun unsafe Group_size as groupSize_\n {fromGroup `Group', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Constructs the union of two groups: all the members of the first group, followed by all the members of the \n-- second group that do not appear in the first group. This function corresponds to @MPI_Group_union@.\ngroupUnion :: Group -> Group -> Group\ngroupUnion g1 g2 = unsafePerformIO $ groupUnion' g1 g2\n where groupUnion' = {# fun unsafe Group_union as groupUnion_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Constructs a new group which is the intersection of two groups. This function corresponds to @MPI_Group_intersection@.\ngroupIntersection :: Group -> Group -> Group\ngroupIntersection g1 g2 = unsafePerformIO $ groupIntersection' g1 g2\n where groupIntersection' = {# fun unsafe Group_intersection as groupIntersection_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Constructs a new group which contains all the elements of the first group which are not in the second group. \n-- This function corresponds to @MPI_Group_difference@.\ngroupDifference :: Group -> Group -> Group\ngroupDifference g1 g2 = unsafePerformIO $ groupDifference' g1 g2\n where groupDifference' = {# fun unsafe Group_difference as groupDifference_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Compares two groups. Returns 'MPI_IDENT' if the order and members of the two groups are the same,\n-- 'MPI_SIMILAR' if only the members are the same, and 'MPI_UNEQUAL' otherwise.\ngroupCompare :: Group -> Group -> ComparisonResult\ngroupCompare g1 g2 = unsafePerformIO $ groupCompare' g1 g2\n where\n groupCompare' = {# fun unsafe Group_compare as groupCompare_\n {fromGroup `Group', fromGroup `Group', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- Technically it might make better sense to make the second argument a Set rather than a list\n-- but the order is significant in the groupIncl function (the other function, not this one).\n-- For the sake of keeping their types in sync, a list is used instead.\n{- | Create a new @Group@ from the given one. Exclude processes\nwith given @Rank@s from the new @Group@. Processes in new @Group@ will\nhave ranks @[0...]@.\n-}\n{# fun unsafe Group_excl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n{- | Create a new @Group@ from the given one. Include only processes\nwith given @Rank@s in the new @Group@. Processes in new @Group@ will\nhave ranks @[0...]@.\n-}\n{# fun unsafe Group_incl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n{- | Given two @Group@s and list of @Rank@s of some processes in the\nfirst @Group@, return @Rank@s of those processes in the second\n@Group@. If there are no corresponding @Rank@ in the second @Group@,\n'mpiUndefined' is returned.\n\nThis function is important for determining the relative numbering of the same processes\nin two different groups. For instance, if one knows the ranks of certain processes in the group\nof 'commWorld', one might want to know their ranks in a subset of that group.\nNote that 'procNull' is a valid rank for input to @groupTranslateRanks@, which\nreturns 'procNull' as the translated rank.\n-}\ngroupTranslateRanks :: Group -> [Rank] -> Group -> [Rank]\ngroupTranslateRanks group1 ranks group2 =\n unsafePerformIO $ do\n let (rankIntList :: [Int]) = map fromEnum ranks\n withArrayLen rankIntList $ \\size ranksPtr ->\n allocaArray size $ \\resultPtr -> do\n groupTranslateRanks' group1 (cFromEnum size) (castPtr ranksPtr) group2 resultPtr\n map toRank <$> peekArray size resultPtr\n where\n groupTranslateRanks' = {# fun unsafe Group_translate_ranks as groupTranslateRanks_\n {fromGroup `Group', id `CInt', id `Ptr CInt', fromGroup `Group', id `Ptr CInt'} -> `()' checkError*- #}\n\nwithRanksAsInts ranks f = withArrayLen (map fromEnum ranks) $ \\size ptr -> f (cIntConv size, castPtr ptr)\n\nforeign import ccall \"mpi_undefined\" mpiUndefined_ :: Ptr Int\n\n-- | Predefined constant that might be returned as @Rank@ by calls\n-- like 'groupTranslateRanks'. Corresponds to @MPI_UNDEFINED@. Please\n-- refer to \\\"MPI Report Constant And Predefined Handle Index\\\" for a\n-- list of situations where @mpiUndefined@ could appear.\nmpiUndefined :: Int\nmpiUndefined = unsafePerformIO $ peek mpiUndefined_\n\n-- | Return the number of bytes used to store an MPI @Datatype@.\ntypeSize :: Datatype -> Int\ntypeSize = unsafePerformIO . typeSize'\n where\n typeSize' =\n {# fun unsafe Type_size as typeSize_\n {fromDatatype `Datatype', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n{# fun unsafe Error_class as ^\n { id `CInt', alloca- `CInt' peek*} -> `CInt' id #}\n\n-- | Set the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_set_errhandler@.\n{# fun unsafe Comm_set_errhandler as ^\n {fromComm `Comm', fromErrhandler `Errhandler'} -> `()' checkError*- #}\n\n-- | Get the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_get_errhandler@.\n{# fun unsafe Comm_get_errhandler as ^\n {fromComm `Comm', alloca- `Errhandler' peekErrhandler*} -> `()' checkError*- #}\n\n-- | Tries to terminate all MPI processes in its communicator argument.\n-- The second argument is an error code which \/may\/ be used as the return status\n-- of the MPI process, but this is not guaranteed. On systems where 'Int' has a larger\n-- range than 'CInt', the error code will be clipped to fit into the range of 'CInt'.\n-- This function corresponds to @MPI_Abort@.\nabort :: Comm -> Int -> IO ()\nabort comm code =\n abort' comm (toErrorCode code)\n where\n toErrorCode :: Int -> CInt\n toErrorCode i\n -- Assumes Int always has range at least as big as CInt.\n | i < (fromIntegral (minBound :: CInt)) = minBound\n | i > (fromIntegral (maxBound :: CInt)) = maxBound\n | otherwise = cIntConv i\n\n abort' = {# fun unsafe Abort as abort_ {fromComm `Comm', id `CInt'} -> `()' checkError*- #}\n\n\ntype MPIDatatype = {# type MPI_Datatype #}\n\n-- | Haskell datatype used to represent @MPI_Datatype@. \n-- Please refer to Chapter 4 of MPI Report v. 2.2 for a description\n-- of various datatypes.\nnewtype Datatype = MkDatatype { fromDatatype :: MPIDatatype }\n\nforeign import ccall unsafe \"&mpi_char\" char_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_wchar\" wchar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_short\" short_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_int\" int_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long\" long_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_long\" longLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_char\" unsignedChar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_short\" unsignedShort_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned\" unsigned_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long\" unsignedLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long_long\" unsignedLongLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_float\" float_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_double\" double_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_double\" longDouble_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_byte\" byte_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_packed\" packed_ :: Ptr MPIDatatype\n\nchar, wchar, short, int, long, longLong, unsignedChar, unsignedShort :: Datatype\nunsigned, unsignedLong, unsignedLongLong, float, double, longDouble :: Datatype\nbyte, packed :: Datatype\n\nchar = MkDatatype <$> unsafePerformIO $ peek char_\nwchar = MkDatatype <$> unsafePerformIO $ peek wchar_\nshort = MkDatatype <$> unsafePerformIO $ peek short_\nint = MkDatatype <$> unsafePerformIO $ peek int_\nlong = MkDatatype <$> unsafePerformIO $ peek long_\nlongLong = MkDatatype <$> unsafePerformIO $ peek longLong_\nunsignedChar = MkDatatype <$> unsafePerformIO $ peek unsignedChar_\nunsignedShort = MkDatatype <$> unsafePerformIO $ peek unsignedShort_\nunsigned = MkDatatype <$> unsafePerformIO $ peek unsigned_\nunsignedLong = MkDatatype <$> unsafePerformIO $ peek unsignedLong_\nunsignedLongLong = MkDatatype <$> unsafePerformIO $ peek unsignedLongLong_\nfloat = MkDatatype <$> unsafePerformIO $ peek float_\ndouble = MkDatatype <$> unsafePerformIO $ peek double_\nlongDouble = MkDatatype <$> unsafePerformIO $ peek longDouble_\nbyte = MkDatatype <$> unsafePerformIO $ peek byte_\npacked = MkDatatype <$> unsafePerformIO $ peek packed_\n\ntype MPIErrhandler = {# type MPI_Errhandler #}\n\n-- | Haskell datatype that represents values usable as @MPI_Errhandler@\nnewtype Errhandler = MkErrhandler { fromErrhandler :: MPIErrhandler } deriving Storable\npeekErrhandler ptr = MkErrhandler <$> peek ptr\n\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr MPIErrhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr MPIErrhandler\n\n-- | Predefined @Errhandler@ that will terminate the process on any\n-- MPI error\nerrorsAreFatal :: Errhandler\nerrorsAreFatal = MkErrhandler <$> unsafePerformIO $ peek errorsAreFatal_\n\n-- | Predefined @Errhandler@ that will convert errors into Haskell\n-- exceptions. Mimics the semantics of @MPI_Errors_return@\nerrorsReturn :: Errhandler\nerrorsReturn = MkErrhandler <$> unsafePerformIO $ peek errorsReturn_\n\n-- | Same as 'errorsReturn', but with a more meaningful name.\nerrorsThrowExceptions :: Errhandler\nerrorsThrowExceptions = errorsReturn\n\n{# enum ErrorClass {underscoreToCase} deriving (Eq,Ord,Show,Typeable) #}\n\n-- XXX Should this be a ForeinPtr?\n-- there is a MPI_Group_free function, which we should probably\n-- call when the group is no longer referenced.\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIGroup = {# type MPI_Group #}\n\n-- | Haskell datatype representing MPI process groups.\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\npeekGroup ptr = MkGroup <$> peek ptr\n\nforeign import ccall \"&mpi_group_empty\" groupEmpty_ :: Ptr MPIGroup\n-- | A predefined group without any members. Corresponds to @MPI_GROUP_EMPTY@.\ngroupEmpty :: Group\ngroupEmpty = MkGroup <$> unsafePerformIO $ peek groupEmpty_\n\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIOperation = {# type MPI_Op #}\n\n{- | Abstract type representing handle for MPI reduction operation\n(that can be used with 'reduce', 'allreduce', and 'reduceScatter').\n-}\nnewtype Operation = MkOperation { fromOperation :: MPIOperation } deriving Storable\npeekOperation ptr = MkOperation <$> peek ptr\nwithOperation op f = alloca $ \\ptr -> do poke ptr (fromOperation op)\n f (castPtr ptr)\n\nforeign import ccall unsafe \"&mpi_max\" maxOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_min\" minOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_sum\" sumOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_prod\" prodOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_land\" landOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_band\" bandOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lor\" lorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bor\" borOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lxor\" lxorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bxor\" bxorOp_ :: Ptr MPIOperation\n-- foreign import ccall \"mpi_maxloc\" maxlocOp :: MPIOperation\n-- foreign import ccall \"mpi_minloc\" minlocOp :: MPIOperation\n-- foreign import ccall \"mpi_replace\" replaceOp :: MPIOperation\n-- TODO: support for those requires better support for pair datatypes\n\n-- | Predefined reduction operation: maximum\nmaxOp :: Operation\nmaxOp = MkOperation <$> unsafePerformIO $ peek maxOp_\n\n-- | Predefined reduction operation: minimum\nminOp :: Operation\nminOp = MkOperation <$> unsafePerformIO $ peek minOp_\n\n-- | Predefined reduction operation: (+)\nsumOp :: Operation\nsumOp = MkOperation <$> unsafePerformIO $ peek sumOp_\n\n-- | Predefined reduction operation: (*)\nprodOp :: Operation\nprodOp = MkOperation <$> unsafePerformIO $ peek prodOp_\n\n-- | Predefined reduction operation: logical \\\"and\\\"\nlandOp :: Operation\nlandOp = MkOperation <$> unsafePerformIO $ peek landOp_\n\n-- | Predefined reduction operation: bit-wise \\\"and\\\"\nbandOp :: Operation\nbandOp = MkOperation <$> unsafePerformIO $ peek bandOp_\n\n-- | Predefined reduction operation: logical \\\"or\\\"\nlorOp :: Operation\nlorOp = MkOperation <$> unsafePerformIO $ peek lorOp_\n\n-- | Predefined reduction operation: bit-wise \\\"or\\\"\nborOp :: Operation\nborOp = MkOperation <$> unsafePerformIO $ peek borOp_\n\n-- | Predefined reduction operation: logical \\\"xor\\\"\nlxorOp :: Operation\nlxorOp = MkOperation <$> unsafePerformIO $ peek lxorOp_\n\n-- | Predefined reduction operation: bit-wise \\\"xor\\\"\nbxorOp :: Operation\nbxorOp = MkOperation <$> unsafePerformIO $ peek bxorOp_\n\n\n{- | Haskell datatype that represents values which\n could be used as MPI rank designations. Low-level MPI calls require\n that you use 32-bit non-negative integer values as ranks, so any\n non-numeric Haskell Ranks should provide a sensible instances of\n 'Enum'.\n\nAttempt to supply a value that does not fit into 32 bits will cause a\nrun-time 'error'.\n-}\nnewtype Rank = MkRank { rankId :: Int -- ^ Extract numeric value of the 'Rank'\n }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Rank where\n (MkRank x) + (MkRank y) = MkRank (x+y)\n (MkRank x) * (MkRank y) = MkRank (x*y)\n abs (MkRank x) = MkRank (abs x)\n signum (MkRank x) = MkRank (signum x)\n fromInteger x\n | x > ( fromIntegral (maxBound :: CInt)) = error \"Rank value does not fit into 32 bits\"\n | x < 0 = error \"Negative Rank value\"\n | otherwise = MkRank (fromIntegral x)\n\nforeign import ccall \"mpi_any_source\" anySource_ :: Ptr Int\nforeign import ccall \"mpi_root\" theRoot_ :: Ptr Int\nforeign import ccall \"mpi_proc_null\" procNull_ :: Ptr Int\n\n-- | Predefined rank number that allows reception of point-to-point messages\n-- regardless of their source. Corresponds to @MPI_ANY_SOURCE@\nanySource :: Rank\nanySource = toRank $ unsafePerformIO $ peek anySource_\n\n-- | Predefined rank number that specifies root process during\n-- operations involving intercommunicators. Corresponds to @MPI_ROOT@\ntheRoot :: Rank\ntheRoot = toRank $ unsafePerformIO $ peek theRoot_\n\n-- | Predefined rank number that specifies non-root processes during\n-- operations involving intercommunicators. Corresponds to @MPI_PROC_NULL@\nprocNull :: Rank\nprocNull = toRank $ unsafePerformIO $ peek procNull_\n\ninstance Show Rank where\n show = show . rankId\n\n-- | Map arbitrary 'Enum' value to 'Rank'\ntoRank :: Enum a => a -> Rank\ntoRank x = MkRank { rankId = fromEnum x }\n\n-- | Map 'Rank' to arbitrary 'Enum'\nfromRank :: Enum a => Rank -> a\nfromRank = toEnum . rankId\n\ntype MPIRequest = {# type MPI_Request #}\n{-| Haskell representation of the @MPI_Request@ type. Returned by\nnon-blocking communication operations, could be further processed with\n'probe', 'test', 'cancel' or 'wait'. -}\nnewtype Request = MkRequest MPIRequest deriving Storable\npeekRequest ptr = MkRequest <$> peek ptr\n\n{-\nThis module provides Haskell representation of the @MPI_Status@ type\n(request status).\n\nField `status_error' should be used with care:\n\\\"The error field in status is not needed for calls that return only\none status, such as @MPI_WAIT@, since that would only duplicate the\ninformation returned by the function itself. The current design avoids\nthe additional overhead of setting it, in such cases. The field is\nneeded for calls that return multiple statuses, since each request may\nhave had a different failure.\\\"\n(this is a quote from )\n\nThis means that, for example, during the call to @MPI_Wait@\nimplementation is free to leave this field filled with whatever\ngarbage got there during memory allocation. Haskell FFI is not\nblanking out freshly allocated memory, so beware!\n-}\n\n-- | Haskell structure that holds fields of @MPI_Status@.\n--\n-- Please note that MPI report lists only three fields as mandatory:\n-- @status_source@, @status_tag@ and @status_error@. However, all\n-- MPI implementations that were used to test those bindings supported\n-- extended set of fields represented here.\ndata Status =\n Status\n { status_source :: Rank -- ^ rank of the source process\n , status_tag :: Tag -- ^ tag assigned at source\n , status_error :: CInt -- ^ error code, if any\n , status_count :: CInt -- ^ number of received elements, if applicable\n , status_cancelled :: Bool -- ^ whether the request was cancelled\n }\n deriving (Eq, Ord, Show)\n\ninstance Storable Status where\n sizeOf _ = {#sizeof MPI_Status #}\n alignment _ = 4\n peek p = Status\n <$> liftM (MkRank . cIntConv) ({#get MPI_Status->MPI_SOURCE #} p)\n <*> liftM (MkTag . cIntConv) ({#get MPI_Status->MPI_TAG #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_ERROR #} p)\n#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields-\n <*> liftM cIntConv ({#get MPI_Status->count #} p)\n <*> liftM cToEnum ({#get MPI_Status->cancelled #} p)\n#else\n <*> liftM cIntConv ({#get MPI_Status->_count #} p)\n <*> liftM cToEnum ({#get MPI_Status->_cancelled #} p)\n#endif\n poke p x = do\n {#set MPI_Status.MPI_SOURCE #} p (fromRank $ status_source x)\n {#set MPI_Status.MPI_TAG #} p (fromTag $ status_tag x)\n {#set MPI_Status.MPI_ERROR #} p (cIntConv $ status_error x)\n#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields AND different order of fields\n {#set MPI_Status.count #} p (cIntConv $ status_count x)\n {#set MPI_Status.cancelled #} p (cFromEnum $ status_cancelled x)\n#else\n {#set MPI_Status._count #} p (cIntConv $ status_count x)\n {#set MPI_Status._cancelled #} p (cFromEnum $ status_cancelled x)\n#endif\n\n-- NOTE: Int here is picked arbitrary\nallocaCast f =\n alloca $ \\(ptr :: Ptr Int) -> f (castPtr ptr :: Ptr ())\npeekCast = peek . castPtr\n\n\n{-| Haskell datatype that represents values which could be used as\ntags for point-to-point transfers.\n-}\nnewtype Tag = MkTag { tagVal :: Int -- ^ Extract numeric value of the Tag\n }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Tag where\n (MkTag x) + (MkTag y) = MkTag (x+y)\n (MkTag x) * (MkTag y) = MkTag (x*y)\n abs (MkTag x) = MkTag (abs x)\n signum (MkTag x) = MkTag (signum x)\n fromInteger x\n | fromIntegral x > tagUpperBound = error \"Tag value is over the MPI_TAG_UB\"\n | x < 0 = error \"Negative Tag value\"\n | otherwise = MkTag (fromIntegral x)\n\ninstance Show Tag where\n show = show . tagVal\n\n-- | Map arbitrary 'Enum' value to 'Tag'\ntoTag :: Enum a => a -> Tag\ntoTag x = MkTag { tagVal = fromEnum x }\n\n-- | Map 'Tag' to arbitrary 'Enum'\nfromTag :: Enum a => Tag -> a\nfromTag = toEnum . tagVal\n\nforeign import ccall unsafe \"&mpi_any_tag\" anyTag_ :: Ptr Int\n\n-- | Predefined tag value that allows reception of the messages with\n-- arbitrary tag values. Corresponds to @MPI_ANY_TAG@.\nanyTag :: Tag\nanyTag = toTag $ unsafePerformIO $ peek anyTag_\n\n-- | A tag with unit value. Intended to be used as a convenient default.\nunitTag :: Tag\nunitTag = toTag ()\n\n{- | Constants used to describe the required level of multithreading\n support in call to 'initThread'. They also describe provided level\n of multithreading support as returned by 'queryThread' and\n 'initThread'.\n\n[@Single@] Only one thread will execute.\n\n[@Funneled@] The process may be multi-threaded, but the application must\nensure that only the main thread makes MPI calls (see 'isThreadMain').\n\n[@Serialized@] The process may be multi-threaded, and multiple threads may\nmake MPI calls, but only one at a time: MPI calls are not made concurrently from\ntwo distinct threads\n\n[@Multiple@] Multiple threads may call MPI, with no restrictions.\n\nXXX Make sure we have the correct ordering as defined by MPI. Also we should\ndescribe the ordering here (other parts of the docs need it to be explained - see initThread).\n\n-}\n{# enum ThreadSupport {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- | Value thrown as exception when MPI runtime is instructed to pass\n-- errors to user code (via 'commSetErrhandler' and 'errorsReturn').\n-- Since raw MPI errors codes are not standartized and not portable,\n-- they are not exposed.\ndata MPIError\n = MPIError\n { mpiErrorClass :: ErrorClass -- ^ Broad class of errors this one belongs to\n , mpiErrorString :: String -- ^ Human-readable error description\n }\n deriving (Eq, Show, Typeable)\n\ninstance Exception MPIError\n\ncheckError :: CInt -> IO ()\ncheckError code = do\n -- We ignore the error code from the call to Internal.errorClass\n -- because we call errorClass from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n (_, errClassRaw) <- errorClass code\n let errClass = cToEnum errClassRaw\n unless (errClass == Success) $ do\n errStr <- errorString code\n throwIO $ MPIError errClass errStr\n\n-- | Convert MPI error code human-readable error description. Corresponds to @MPI_Error_string@.\nerrorString :: CInt -> IO String\nerrorString code =\n allocaBytes (fromIntegral maxErrorString) $ \\ptr ->\n alloca $ \\lenPtr -> do\n -- We ignore the error code from the call to Internal.errorString\n -- because we call errorString from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n _ <- errorString' code ptr lenPtr\n len <- peek lenPtr\n peekCStringLen (ptr, cIntConv len)\n where\n errorString' = {# call unsafe Error_string as errorString_ #}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface, DeriveDataTypeable, GeneralizedNewtypeDeriving, ScopedTypeVariables #-}\n\n{-# OPTIONS_GHC -fno-warn-missing-signatures #-}\n#include \n#include \"init_wrapper.h\"\n#include \"comparison_result.h\"\n#include \"error_classes.h\"\n#include \"thread_support.h\"\n-----------------------------------------------------------------------------\n{- |\nModule : Control.Parallel.MPI.Internal\nCopyright : (c) 2010 Bernie Pope, Dmitry Astapov\nLicense : BSD-style\nMaintainer : florbitous@gmail.com\nStability : experimental\nPortability : ghc\n\nThis module contains low-level Haskell bindings to core MPI functions.\nAll Haskell functions correspond to MPI functions or values with the similar\nname (i.e. @commRank@ is the binding for @MPI_Comm_rank@ etc)\n\nNote that most of this module is re-exported by\n\"Control.Parallel.MPI\", so if you are not interested in writing\nlow-level code, you should probably import \"Control.Parallel.MPI\" and\neither \"Control.Parallel.MPI.Storable\" or \"Control.Parallel.MPI.Serializable\".\n-}\n-----------------------------------------------------------------------------\nmodule Control.Parallel.MPI.Internal\n (\n\n -- * MPI runtime management.\n -- ** Initialization, finalization, termination.\n init, finalize, initialized, finalized, abort,\n -- ** Multi-threaded environment support.\n ThreadSupport (..), initThread, queryThread, isThreadMain,\n\n -- ** Runtime attributes.\n getProcessorName, Version (..), getVersion, Implementation(..), getImplementation,\n\n -- * Requests and statuses.\n Request, Status (..), probe, test, cancel, wait, waitall,\n\n -- * Process management.\n -- ** Communicators.\n Comm, commWorld, commSelf, commTestInter,\n commSize, commRemoteSize, \n commRank, \n commCompare, commGroup, commGetAttr,\n\n -- ** Process groups.\n Group, groupEmpty, groupRank, groupSize, groupUnion,\n groupIntersection, groupDifference, groupCompare, groupExcl,\n groupIncl, groupTranslateRanks,\n -- ** Comparisons.\n ComparisonResult (..),\n\n -- * Error handling.\n Errhandler, errorsAreFatal, errorsReturn, errorsThrowExceptions, commSetErrhandler, commGetErrhandler,\n ErrorClass (..), MPIError(..),\n\n -- * Ranks.\n Rank, rankId, toRank, fromRank, anySource, theRoot, procNull,\n\n -- * Data types.\n Datatype, char, wchar, short, int, long, longLong, unsignedChar, unsignedShort, unsigned, unsignedLong, unsignedLongLong, float, double, longDouble, byte, packed, typeSize,\n\n -- * Point-to-point operations.\n -- ** Tags.\n Tag, toTag, fromTag, anyTag, unitTag, tagUpperBound,\n\n -- ** Blocking operations.\n BufferPtr, Count, -- XXX: what will break if we don't export those?\n send, ssend, rsend, recv,\n -- ** Non-blocking operations.\n isend, issend, irecv,\n isendPtr, issendPtr, irecvPtr,\n\n\n -- * Collective operations.\n -- ** One-to-all.\n bcast, scatter, scatterv,\n -- ** All-to-one.\n gather, gatherv, reduce,\n -- ** All-to-all.\n allgather, allgatherv,\n alltoall, alltoallv,\n allreduce, \n reduceScatterBlock,\n reduceScatter,\n barrier,\n\n -- ** Reduction operations.\n Operation, maxOp, minOp, sumOp, prodOp, landOp, bandOp, lorOp, borOp, lxorOp, bxorOp,\n opCreate, opFree,\n\n -- * Timing.\n wtime, wtick, wtimeIsGlobal, wtimeIsGlobalKey\n\n ) where\n\nimport Prelude hiding (init)\nimport C2HS\nimport Data.Typeable\nimport Data.Maybe (fromMaybe)\nimport Control.Monad (liftM, unless)\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception\n\n{# context prefix = \"MPI\" #}\n\n-- | Pointer to memory buffer that either holds data to be sent or is\n-- used to receive some data. You would\n-- probably have to use 'castPtr' to pass some actual pointers to\n-- API functions.\ntype BufferPtr = Ptr ()\n\n-- | Count of elements in the send\/receive buffer\ntype Count = CInt\n\n{- |\nHaskell enum that contains MPI constants\n@MPI_IDENT@, @MPI_CONGRUENT@, @MPI_SIMILAR@ and @MPI_UNEQUAL@.\n\nThose are used to compare communicators ('commCompare') and\nprocess groups ('groupCompare'). Refer to those\nfunctions for description of comparison rules.\n-}\n{# enum ComparisonResult {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- Which Haskell type will be used as Comm depends on the MPI\n-- implementation that was selected during compilation. It could be\n-- CInt, Ptr (), Ptr CInt or something else.\ntype MPIComm = {# type MPI_Comm #}\n\n{- | Abstract type representing MPI communicator handle. Different MPI\n implementations use different C types to implement this, so\n concrete Haskell type behind @Comm@ is hidden from user.\n\n In any MPI program you have predefined communicator 'commWorld'\n which includes all running processes. You could create new\n communicators with TODO\n-}\nnewtype Comm = MkComm { fromComm :: MPIComm }\nforeign import ccall \"&mpi_comm_world\" commWorld_ :: Ptr MPIComm\nforeign import ccall \"&mpi_comm_self\" commSelf_ :: Ptr MPIComm\n\n-- | Predefined handle for communicator that includes all running\n-- processes. Similar to @MPI_Comm_world@\ncommWorld :: Comm\ncommWorld = MkComm <$> unsafePerformIO $ peek commWorld_\n\n-- | Predefined handle for communicator that includes only current\n-- process. Similar to @MPI_Comm_self@\ncommSelf :: Comm\ncommSelf = MkComm <$> unsafePerformIO $ peek commSelf_\n\nforeign import ccall \"&mpi_max_processor_name\" max_processor_name_ :: Ptr CInt\nforeign import ccall \"&mpi_max_error_string\" max_error_string_ :: Ptr CInt\n\n-- | Max length of \"processor name\" as returned by 'getProcessorName'\nmaxProcessorName :: CInt\nmaxProcessorName = unsafePerformIO $ peek max_processor_name_\n\n-- | Max length of error description as returned by 'errorString'\nmaxErrorString :: CInt\nmaxErrorString = unsafePerformIO $ peek max_error_string_\n\n-- | Initialize the MPI environment. The MPI environment must be intialized by each\n-- MPI process before any other MPI function is called. Note that\n-- the environment may also be initialized by the functions 'initThread', 'mpi',\n-- and 'mpiWorld'. It is an error to attempt to initialize the environment more\n-- than once for a given MPI program execution. The only MPI functions that may\n-- be called before the MPI environment is initialized are 'getVersion',\n-- 'initialized' and 'finalized'. This function corresponds to @MPI_Init@.\n{# fun unsafe init_wrapper as init {} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been initialized. Returns @True@ if the\n-- environment has been initialized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Initialized@.\n{# fun unsafe Initialized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Determine if the MPI environment has been finalized. Returns @True@ if the\n-- environment has been finalized and @False@ otherwise. This function\n-- may be called before the MPI environment has been initialized and after it\n-- has been finalized.\n-- This function corresponds to @MPI_Finalized@.\n{# fun unsafe Finalized as ^ {alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Initialize the MPI environment with a \/required\/ level of thread support.\n-- See the documentation for 'init' for more information about MPI initialization.\n-- The \/provided\/ level of thread support is returned in the result.\n-- There is no guarantee that provided will be greater than or equal to required.\n-- The level of provided thread support depends on the underlying MPI implementation,\n-- and may also depend on information provided when the program is executed\n-- (for example, by supplying appropriate arguments to @mpiexec@).\n-- If the required level of support cannot be provided then it will try to\n-- return the least supported level greater than what was required.\n-- If that cannot be satisfied then it will return the highest supported level\n-- provided by the MPI implementation. See the documentation for 'ThreadSupport'\n-- for information about what levels are available and their relative ordering.\n-- This function corresponds to @MPI_Init_thread@.\n{# fun unsafe init_wrapper_thread as initThread\n {cFromEnum `ThreadSupport', alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\n-- | Returns the current provided level of thread support. This will be the value\n-- returned as \\\"provided level of support\\\" by 'initThread' as well. This function\n-- corresponds to @MPI_Query_thread@.\n{# fun unsafe Query_thread as ^ {alloca- `ThreadSupport' peekEnum* } -> `()' checkError*- #}\n\n-- | This function can be called by a thread to find out whether it is the main thread (the\n-- thread that called 'init' or 'initThread'.\n{# fun unsafe Is_thread_main as ^\n {alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Terminate the MPI execution environment.\n-- Once 'finalize' is called no other MPI functions may be called except\n-- 'getVersion', 'initialized' and 'finalized', however non-MPI computations\n-- may continue. Each process must complete\n-- any pending communication that it initiated before calling 'finalize'.\n-- Note: the error code returned\n-- by 'finalize' is not checked. This function corresponds to @MPI_Finalize@.\n{# fun unsafe Finalize as ^ {} -> `()' discard*- #}\ndiscard _ = return ()\n-- XXX can't call checkError on finalize, because\n-- checkError calls Internal.errorClass and Internal.errorString.\n-- These cannot be called after finalize (at least on OpenMPI).\n\n-- | Return the name of the current processing host. From this value it\n-- must be possible to identify a specic piece of hardware on which\n-- the code is running.\ngetProcessorName :: IO String\ngetProcessorName = do\n allocaBytes (fromIntegral maxProcessorName) $ \\ptr -> do\n len <- getProcessorName' ptr\n peekCStringLen (ptr, cIntConv len)\n where\n getProcessorName' = {# fun unsafe Get_processor_name as getProcessorName_\n {id `Ptr CChar', alloca- `CInt' peekIntConv*} -> `()' checkError*- #}\n\n-- | MPI implementation version\ndata Version =\n Version { version :: Int, subversion :: Int }\n deriving (Eq, Ord)\n\ninstance Show Version where\n show v = show (version v) ++ \".\" ++ show (subversion v)\n\n-- | Which MPI version the code is running on.\ngetVersion :: IO Version\ngetVersion = do\n (version, subversion) <- getVersion'\n return $ Version version subversion\n where\n getVersion' = {# fun unsafe Get_version as getVersion_\n {alloca- `Int' peekIntConv*, alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Supported MPI implementations\ndata Implementation = MPICH2 | OpenMPI deriving (Eq,Show)\n\n-- | Which MPI implementation was used during linking\ngetImplementation :: Implementation\ngetImplementation =\n#ifdef MPICH2\n MPICH2\n#else\n OpenMPI\n#endif\n\n-- | Return the number of processes involved in a communicator. For 'commWorld'\n-- it returns the total number of processes available. If the communicator is\n-- and intra-communicator it returns the number of processes in the local group.\n-- This function corresponds to @MPI_Comm_size@.\n{# fun unsafe Comm_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n-- | For intercommunicators, returs size of the remote process group.\n-- Corresponds to @MPI_Comm_remote_size@.\n{# fun unsafe Comm_remote_size as ^\n {fromComm `Comm', alloca- `Int' peekIntConv* } -> `()' checkError*- #}\n\n{- | Check whether the given communicator is intercommunicator - that\n is, communicator connecting two different groups of processes.\n\nRefer to MPI Report v2.2, Section 5.2 \"Communicator Argument\" for\nmore details.\n-}\n{# fun unsafe Comm_test_inter as ^\n {fromComm `Comm', alloca- `Bool' peekBool* } -> `()' checkError*- #}\n\n-- | Look up MPI communicator argument by the given numeric key.\n-- Lookup of some standard MPI arguments is provided by convenience\n-- functions 'tagUpperBound' and 'wtimeIsGlobal'.\ncommGetAttr :: Storable e => Comm -> Int -> IO (Maybe e)\ncommGetAttr comm key = do\n isInitialized <- initialized\n if isInitialized then do\n alloca $ \\ptr -> do\n found <- commGetAttr' comm key (castPtr ptr)\n if found then do ptr2 <- peek ptr\n Just <$> peek ptr2\n else return Nothing\n else return Nothing\n where\n commGetAttr' = {# fun unsafe Comm_get_attr as commGetAttr_\n {fromComm `Comm', cIntConv `Int', id `Ptr ()', alloca- `Bool' peekBool*} -> `()' checkError*- #}\n\n-- | Maximum tag value supported by the current MPI implementation. Corresponds to the value of standard MPI\n-- attribute @MPI_TAG_UB@.\n--\n-- When called before 'init' or 'initThread' would return 0.\ntagUpperBound :: Int\ntagUpperBound =\n let key = unsafePerformIO (peek tagUB_)\n in fromMaybe 0 $ unsafePerformIO (commGetAttr commWorld key)\n\nforeign import ccall unsafe \"&mpi_tag_ub\" tagUB_ :: Ptr Int\n\n{- | True if clocks at all processes in\n'commWorld' are synchronized, False otherwise. The expectation is that\nthe variation in time, as measured by calls to 'wtime', will be less then one half the\nround-trip time for an MPI message of length zero. \n\nCommunicators other than 'commWorld' could have different clocks.\nYou could find it out by querying attribute 'wtimeIsGlobalKey' with 'commGetAttr'.\n\nWhen wtimeIsGlobal is called before 'init' or 'initThread' it would return False.\n-}\nwtimeIsGlobal :: Bool\nwtimeIsGlobal =\n fromMaybe False $ unsafePerformIO (commGetAttr commWorld wtimeIsGlobalKey)\n\nforeign import ccall unsafe \"&mpi_wtime_is_global\" wtimeIsGlobal_ :: Ptr Int\n\n-- | Numeric key for standard MPI communicator attribute @MPI_WTIME_IS_GLOBAL@.\n-- To be used with 'commGetAttr'.\nwtimeIsGlobalKey :: Int\nwtimeIsGlobalKey = unsafePerformIO (peek wtimeIsGlobal_)\n\n-- | Return the rank of the calling process for the given\n-- communicator. If it is an intercommunicator, returns rank of the\n-- process in the local group.\n{# fun unsafe Comm_rank as ^\n {fromComm `Comm', alloca- `Rank' peekIntConv* } -> `()' checkError*- #}\n\n{- | Compares two communicators.\n\n* If they are handles for the same MPI communicator object, result is 'Identical';\n\n* If both communicators are identical in constituents and rank\n order, result is `Congruent';\n\n* If they have the same members, but with different ranks, then\n result is 'Similar';\n\n* Otherwise, result is 'Unequal'.\n\n-}\n{# fun unsafe Comm_compare as ^\n {fromComm `Comm', fromComm `Comm', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- | Test for an incomming message, without actually receiving it.\n-- If a message has been sent from @Rank@ to the current process with @Tag@ on the\n-- communicator @Comm@ then 'probe' will return the 'Status' of the message. Otherwise\n-- it will block the current process until such a matching message is sent.\n-- This allows the current process to check for an incoming message and decide\n-- how to receive it, based on the information in the 'Status'.\n-- This function corresponds to @MPI_Probe@.\n{# fun Probe as ^\n {fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n{- probe :: Rank -- ^ Rank of the sender.\n -> Tag -- ^ Tag of the sent message.\n -> Comm -- ^ Communicator.\n -> IO Status -- ^ Information about the incoming message (but not the content of the message). -}\n\n{-| Send the values (as specified by @BufferPtr@, @Count@, @Datatype@) to\n the process specified by (@Comm@, @Rank@, @Tag@). Caller will\n block until data is copied from the send buffer by the MPI\n-}\n{# fun unsafe Send as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{-| Variant of 'send' that would terminate only when receiving side\nactually starts receiving data. \n-}\n{# fun unsafe Ssend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n{-| Variant of 'send' that expects the relevant 'recv' to be already\nstarted, otherwise this call could terminate with MPI error.\n-}\n{# fun unsafe Rsend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm' } -> `()' checkError*- #}\n-- | Receives data from the process\n-- specified by (@Comm@, @Rank@, @Tag@) and stores it into buffer specified\n-- by (@BufferPtr@, @Count@, @Datatype@).\n{# fun unsafe Recv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', allocaCast- `Status' peekCast* } -> `()' checkError*- #}\n-- | Send the values (as specified by @BufferPtr@, @Count@, @Datatype@) to\n-- the process specified by (@Comm@, @Rank@, @Tag@) in non-blocking mode.\n-- \n-- Use 'probe' or 'test' to check the status of the operation,\n-- 'cancel' to terminate it or 'wait' to block until it completes.\n-- Operation would be considered complete as soon as MPI finishes\n-- copying the data from the send buffer. \n{# fun unsafe Isend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n-- | Variant of the 'isend' that would be considered complete only when\n-- receiving side actually starts receiving data. \n{# fun unsafe Issend as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n-- | Non-blocking variant of 'recv'. Receives data from the process\n-- specified by (@Comm@, @Rank@, @Tag@) and stores it into buffer specified\n-- by (@BufferPtr@, @Count@, @Datatype@).\n{# fun Irecv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', alloca- `Request' peekRequest*} -> `()' checkError*- #}\n\n-- | Like 'isend', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun unsafe Isend as isendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'issend', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun unsafe Issend as issendPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Like 'irecv', but stores @Request@ at the supplied pointer. Useful\n-- for making arrays of @Requests@ that could be passed to 'waitall'\n{# fun Irecv as irecvPtr\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromTag `Tag', fromComm `Comm', castPtr `Ptr Request'} -> `()' checkError*- #}\n\n-- | Broadcast data from one member to all members of the communicator.\n{# fun unsafe Bcast as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocks until all processes on the communicator call this function.\n-- This function corresponds to @MPI_Barrier@.\n{# fun unsafe Barrier as ^ {fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Blocking test for the completion of a send of receive.\n-- See 'test' for a non-blocking variant.\n-- This function corresponds to @MPI_Wait@.\n{# fun unsafe Wait as ^\n {withRequest* `Request', allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Takes pointer to the array of Requests of given size, 'wait's on all of them,\n-- populates array of Statuses of the same size. This function corresponds to @MPI_Waitall@\n{# fun unsafe Waitall as ^\n { id `Count', castPtr `Ptr Request', castPtr `Ptr Status'} -> `()' checkError*- #}\n-- TODO: Make this Storable Array instead of Ptr ?\n\n-- | Non-blocking test for the completion of a send or receive.\n-- Returns @Nothing@ if the request is not complete, otherwise\n-- it returns @Just status@. See 'wait' for a blocking variant.\n-- This function corresponds to @MPI_Test@.\ntest :: Request -> IO (Maybe Status)\ntest request = do\n (flag, status) <- test' request\n if flag\n then return $ Just status\n else return Nothing\n where\n test' = {# fun unsafe Test as test_\n {withRequest* `Request', alloca- `Bool' peekBool*, allocaCast- `Status' peekCast*} -> `()' checkError*- #}\n\n-- | Cancel a pending communication request.\n-- This function corresponds to @MPI_Cancel@.\n{# fun unsafe Cancel as ^\n {withRequest* `Request'} -> `()' checkError*- #}\nwithRequest req f = do alloca $ \\ptr -> do poke ptr req\n f (castPtr ptr)\n\n-- | Scatter data from one member to all members of\n-- a group.\n{# fun unsafe Scatter as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Gather data from all members of a group to one\n-- member.\n{# fun unsafe Gather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- Note: We pass counts\/displs as Ptr CInt so that caller could supply nullPtr here\n-- which would be impossible if we marshal arrays ourselves here.\n\n-- | A variation of 'scatter' which allows to use data segments of\n-- different length.\n{# fun unsafe Scatterv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'gather' which allows to use data segments of\n-- different length.\n{# fun unsafe Gatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'gather' where all members of\n-- a group receive the result.\n{# fun unsafe Allgather as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variation of 'allgather' that allows to use data segments of\n-- different length.\n{# fun unsafe Allgatherv as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Scatter\/Gather data from all\n-- members to all members of a group (also called complete exchange)\n{# fun unsafe Alltoall as ^\n { id `BufferPtr', id `Count', fromDatatype `Datatype',\n id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A variant of 'alltoall' allows to use data segments of different length.\n{# fun unsafe Alltoallv as ^\n { id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n id `BufferPtr', id `Ptr CInt', id `Ptr CInt', fromDatatype `Datatype',\n fromComm `Comm'} -> `()' checkError*- #}\n\n-- Reduce, allreduce and reduceScatter could call back to Haskell\n-- via user-defined ops, so they should be imported in \"safe\" mode\n\n-- | Applies predefined or user-defined reduction operations to data,\n-- and delivers result to the single process.\n{# fun Reduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromRank `Rank', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | Applies predefined or user-defined reduction operations to data,\n-- and delivers result to all members of the group.\n{# fun Allreduce as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n\n-- | A combined reduction and scatter operation - result is split and\n-- parts are distributed among the participating processes.\n--\n-- See 'reduceScatter' for variant that allows to specify personal\n-- block size for each process.\n--\n-- Note that this call is not supported with some MPI implementations,\n-- like OpenMPI <= 1.5 and would cause a run-time 'error' in that case.\n#if 0\n{# fun Reduce_scatter_block as ^\n { id `BufferPtr', id `BufferPtr', id `Count', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n#else\nreduceScatterBlock :: BufferPtr -> BufferPtr -> Count -> Datatype -> Operation -> Comm -> IO ()\nreduceScatterBlock = error \"reduceScatterBlock is not supported by OpenMPI\"\n#endif\n\n-- | A combined reduction and scatter operation - result is split and\n-- parts are distributed among the participating processes.\n{# fun Reduce_scatter as ^\n { id `BufferPtr', id `BufferPtr', id `Ptr CInt', fromDatatype `Datatype',\n fromOperation `Operation', fromComm `Comm'} -> `()' checkError*- #}\n\n-- TODO: In the following haddock block, mention SCAN and EXSCAN once\n-- they are implemented \n\n{- | Binds a user-dened reduction operation to an 'Operation' handle that can\nsubsequently be used in 'reduce', 'allreduce', and 'reduceScatter'.\nThe user-defined operation is assumed to be associative. \n\nIf second argument to @opCreate@ is @True@, then the operation should be both commutative and associative. If\nit is not commutative, then the order of operands is fixed and is defined to be in ascending,\nprocess rank order, beginning with process zero. The order of evaluation can be changed,\ntaking advantage of the associativity of the operation. If operation\nis commutative then the order\nof evaluation can be changed, taking advantage of commutativity and\nassociativity.\n\nUser-defined operation accepts four arguments, @invec@, @inoutvec@,\n@len@ and @datatype@:\n\n[@invec@] first input vector\n\n[@inoutvec@] second input vector, which is also the output vector\n\n[@len@] length of both vectors\n\n[@datatype@] type of the elements in both vectors.\n\nFunction is expected to apply reduction operation to the elements\nof @invec@ and @inoutvec@ in pariwise manner:\n\n@\ninoutvec[i] = op invec[i] inoutvec[i]\n@\n\nFull example with user-defined function that mimics standard operation\n'sumOp':\n\n@\nimport \"Control.Parallel.MPI.Fast\"\n\nforeign import ccall \\\"wrapper\\\" \n wrap :: (Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()) \n -> IO (FunPtr (Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()))\nreduceUserOpTest myRank = do\n numProcs <- commSize commWorld\n userSumPtr <- wrap userSum\n mySumOp <- opCreate True userSumPtr\n (src :: StorableArray Int Double) <- newListArray (0,99) [0..99]\n if myRank \/= root\n then reduceSend commWorld root sumOp src\n else do\n (result :: StorableArray Int Double) <- intoNewArray_ (0,99) $ reduceRecv commWorld root mySumOp src\n recvMsg <- getElems result\n freeHaskellFunPtr userSumPtr\n where\n userSum :: Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()\n userSum inPtr inoutPtr lenPtr _ = do\n len <- peek lenPtr\n let offs = sizeOf ( undefined :: CDouble )\n let loop 0 _ _ = return ()\n loop n inPtr inoutPtr = do\n a <- peek inPtr\n b <- peek inoutPtr\n poke inoutPtr (a+b)\n loop (n-1) (plusPtr inPtr offs) (plusPtr inoutPtr offs)\n loop len inPtr inoutPtr\n@\n-}\n{# fun unsafe Op_create as ^\n {castFunPtr `FunPtr (Ptr t -> Ptr t -> Ptr CInt -> Ptr Datatype -> IO ())', cFromEnum `Bool', alloca- `Operation' peekOperation*} -> `()' checkError*- #}\n\n{- | Free the handle for user-defined reduction operation created by 'opCreate'\n-}\n{# fun Op_free as ^ {withOperation* `Operation'} -> `()' checkError*- #}\n\n{- | Returns a \nfloating-point number of seconds, representing elapsed wallclock\ntime since some time in the past.\n\nThe \\\"time in the past\\\" is guaranteed not to change during the life of the process.\nThe user is responsible for converting large numbers of seconds to other units if they are\npreferred. The time is local to the node that calls @wtime@, but see 'wtimeIsGlobal'.\n-}\n{# fun unsafe Wtime as ^ {} -> `Double' realToFrac #}\n\n{- | Returns the resolution of 'wtime' in seconds. That is, it returns,\nas a double precision value, the number of seconds between successive clock ticks. For\nexample, if the clock is implemented by the hardware as a counter that is incremented\nevery millisecond, the value returned by @wtick@ should be 10^(-3).\n-}\n{# fun unsafe Wtick as ^ {} -> `Double' realToFrac #}\n\n-- | Return the process group from a communicator. With\n-- intercommunicator, returns the local group.\n{# fun unsafe Comm_group as ^\n {fromComm `Comm', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Returns the rank of the calling process in the given group. This function corresponds to @MPI_Group_rank@.\ngroupRank :: Group -> Rank\ngroupRank = unsafePerformIO <$> groupRank'\n where groupRank' = {# fun unsafe Group_rank as groupRank_\n {fromGroup `Group', alloca- `Rank' peekIntConv*} -> `()' checkError*- #}\n\n-- | Returns the size of a group. This function corresponds to @MPI_Group_size@.\ngroupSize :: Group -> Int\ngroupSize = unsafePerformIO <$> groupSize'\n where groupSize' = {# fun unsafe Group_size as groupSize_\n {fromGroup `Group', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n-- | Constructs the union of two groups: all the members of the first group, followed by all the members of the \n-- second group that do not appear in the first group. This function corresponds to @MPI_Group_union@.\ngroupUnion :: Group -> Group -> Group\ngroupUnion g1 g2 = unsafePerformIO $ groupUnion' g1 g2\n where groupUnion' = {# fun unsafe Group_union as groupUnion_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Constructs a new group which is the intersection of two groups. This function corresponds to @MPI_Group_intersection@.\ngroupIntersection :: Group -> Group -> Group\ngroupIntersection g1 g2 = unsafePerformIO $ groupIntersection' g1 g2\n where groupIntersection' = {# fun unsafe Group_intersection as groupIntersection_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Constructs a new group which contains all the elements of the first group which are not in the second group. \n-- This function corresponds to @MPI_Group_difference@.\ngroupDifference :: Group -> Group -> Group\ngroupDifference g1 g2 = unsafePerformIO $ groupDifference' g1 g2\n where groupDifference' = {# fun unsafe Group_difference as groupDifference_\n {fromGroup `Group', fromGroup `Group', alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n-- | Compares two groups. Returns 'MPI_IDENT' if the order and members of the two groups are the same,\n-- 'MPI_SIMILAR' if only the members are the same, and 'MPI_UNEQUAL' otherwise.\ngroupCompare :: Group -> Group -> ComparisonResult\ngroupCompare g1 g2 = unsafePerformIO $ groupCompare' g1 g2\n where\n groupCompare' = {# fun unsafe Group_compare as groupCompare_\n {fromGroup `Group', fromGroup `Group', alloca- `ComparisonResult' peekEnum*} -> `()' checkError*- #}\n\n-- Technically it might make better sense to make the second argument a Set rather than a list\n-- but the order is significant in the groupIncl function (the other function, not this one).\n-- For the sake of keeping their types in sync, a list is used instead.\n{- | Create a new @Group@ from the given one. Exclude processes\nwith given @Rank@s from the new @Group@. Processes in new @Group@ will\nhave ranks @[0...]@.\n-}\n{# fun unsafe Group_excl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n{- | Create a new @Group@ from the given one. Include only processes\nwith given @Rank@s in the new @Group@. Processes in new @Group@ will\nhave ranks @[0...]@.\n-}\n{# fun unsafe Group_incl as ^\n {fromGroup `Group', withRanksAsInts* `[Rank]'&, alloca- `Group' peekGroup*} -> `()' checkError*- #}\n\n{- | Given two @Group@s and list of @Rank@s of some processes in the\nfirst @Group@, return @Rank@s of those processes in the second\n@Group@. If there are no corresponding @Rank@ in the second @Group@,\n'mpiUndefined' is returned.\n\nThis function is important for determining the relative numbering of the same processes\nin two different groups. For instance, if one knows the ranks of certain processes in the group\nof 'commWorld', one might want to know their ranks in a subset of that group.\nNote that 'procNull' is a valid rank for input to @groupTranslateRanks@, which\nreturns 'procNull' as the translated rank.\n-}\ngroupTranslateRanks :: Group -> [Rank] -> Group -> [Rank]\ngroupTranslateRanks group1 ranks group2 =\n unsafePerformIO $ do\n let (rankIntList :: [Int]) = map fromEnum ranks\n withArrayLen rankIntList $ \\size ranksPtr ->\n allocaArray size $ \\resultPtr -> do\n groupTranslateRanks' group1 (cFromEnum size) (castPtr ranksPtr) group2 resultPtr\n map toRank <$> peekArray size resultPtr\n where\n groupTranslateRanks' = {# fun unsafe Group_translate_ranks as groupTranslateRanks_\n {fromGroup `Group', id `CInt', id `Ptr CInt', fromGroup `Group', id `Ptr CInt'} -> `()' checkError*- #}\n\nwithRanksAsInts ranks f = withArrayLen (map fromEnum ranks) $ \\size ptr -> f (cIntConv size, castPtr ptr)\n\n-- | Return the number of bytes used to store an MPI @Datatype@.\ntypeSize :: Datatype -> Int\ntypeSize = unsafePerformIO . typeSize'\n where\n typeSize' =\n {# fun unsafe Type_size as typeSize_\n {fromDatatype `Datatype', alloca- `Int' peekIntConv*} -> `()' checkError*- #}\n\n{# fun unsafe Error_class as ^\n { id `CInt', alloca- `CInt' peek*} -> `CInt' id #}\n\n-- | Set the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_set_errhandler@.\n{# fun unsafe Comm_set_errhandler as ^\n {fromComm `Comm', fromErrhandler `Errhandler'} -> `()' checkError*- #}\n\n-- | Get the error handler for a communicator.\n-- This function corresponds to @MPI_Comm_get_errhandler@.\n{# fun unsafe Comm_get_errhandler as ^\n {fromComm `Comm', alloca- `Errhandler' peekErrhandler*} -> `()' checkError*- #}\n\n-- | Tries to terminate all MPI processes in its communicator argument.\n-- The second argument is an error code which \/may\/ be used as the return status\n-- of the MPI process, but this is not guaranteed. On systems where 'Int' has a larger\n-- range than 'CInt', the error code will be clipped to fit into the range of 'CInt'.\n-- This function corresponds to @MPI_Abort@.\nabort :: Comm -> Int -> IO ()\nabort comm code =\n abort' comm (toErrorCode code)\n where\n toErrorCode :: Int -> CInt\n toErrorCode i\n -- Assumes Int always has range at least as big as CInt.\n | i < (fromIntegral (minBound :: CInt)) = minBound\n | i > (fromIntegral (maxBound :: CInt)) = maxBound\n | otherwise = cIntConv i\n\n abort' = {# fun unsafe Abort as abort_ {fromComm `Comm', id `CInt'} -> `()' checkError*- #}\n\n\ntype MPIDatatype = {# type MPI_Datatype #}\n\n-- | Haskell datatype used to represent @MPI_Datatype@. \n-- Please refer to Chapter 4 of MPI Report v. 2.2 for a description\n-- of various datatypes.\nnewtype Datatype = MkDatatype { fromDatatype :: MPIDatatype }\n\nforeign import ccall unsafe \"&mpi_char\" char_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_wchar\" wchar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_short\" short_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_int\" int_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long\" long_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_long\" longLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_char\" unsignedChar_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_short\" unsignedShort_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned\" unsigned_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long\" unsignedLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_unsigned_long_long\" unsignedLongLong_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_float\" float_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_double\" double_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_long_double\" longDouble_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_byte\" byte_ :: Ptr MPIDatatype\nforeign import ccall unsafe \"&mpi_packed\" packed_ :: Ptr MPIDatatype\n\nchar, wchar, short, int, long, longLong, unsignedChar, unsignedShort :: Datatype\nunsigned, unsignedLong, unsignedLongLong, float, double, longDouble :: Datatype\nbyte, packed :: Datatype\n\nchar = MkDatatype <$> unsafePerformIO $ peek char_\nwchar = MkDatatype <$> unsafePerformIO $ peek wchar_\nshort = MkDatatype <$> unsafePerformIO $ peek short_\nint = MkDatatype <$> unsafePerformIO $ peek int_\nlong = MkDatatype <$> unsafePerformIO $ peek long_\nlongLong = MkDatatype <$> unsafePerformIO $ peek longLong_\nunsignedChar = MkDatatype <$> unsafePerformIO $ peek unsignedChar_\nunsignedShort = MkDatatype <$> unsafePerformIO $ peek unsignedShort_\nunsigned = MkDatatype <$> unsafePerformIO $ peek unsigned_\nunsignedLong = MkDatatype <$> unsafePerformIO $ peek unsignedLong_\nunsignedLongLong = MkDatatype <$> unsafePerformIO $ peek unsignedLongLong_\nfloat = MkDatatype <$> unsafePerformIO $ peek float_\ndouble = MkDatatype <$> unsafePerformIO $ peek double_\nlongDouble = MkDatatype <$> unsafePerformIO $ peek longDouble_\nbyte = MkDatatype <$> unsafePerformIO $ peek byte_\npacked = MkDatatype <$> unsafePerformIO $ peek packed_\n\ntype MPIErrhandler = {# type MPI_Errhandler #}\n\n-- | Haskell datatype that represents values usable as @MPI_Errhandler@\nnewtype Errhandler = MkErrhandler { fromErrhandler :: MPIErrhandler } deriving Storable\npeekErrhandler ptr = MkErrhandler <$> peek ptr\n\nforeign import ccall \"&mpi_errors_are_fatal\" errorsAreFatal_ :: Ptr MPIErrhandler\nforeign import ccall \"&mpi_errors_return\" errorsReturn_ :: Ptr MPIErrhandler\n\n-- | Predefined @Errhandler@ that will terminate the process on any\n-- MPI error\nerrorsAreFatal :: Errhandler\nerrorsAreFatal = MkErrhandler <$> unsafePerformIO $ peek errorsAreFatal_\n\n-- | Predefined @Errhandler@ that will convert errors into Haskell\n-- exceptions. Mimics the semantics of @MPI_Errors_return@\nerrorsReturn :: Errhandler\nerrorsReturn = MkErrhandler <$> unsafePerformIO $ peek errorsReturn_\n\n-- | Same as 'errorsReturn', but with a more meaningful name.\nerrorsThrowExceptions :: Errhandler\nerrorsThrowExceptions = errorsReturn\n\n{# enum ErrorClass {underscoreToCase} deriving (Eq,Ord,Show,Typeable) #}\n\n-- XXX Should this be a ForeinPtr?\n-- there is a MPI_Group_free function, which we should probably\n-- call when the group is no longer referenced.\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIGroup = {# type MPI_Group #}\n\n-- | Haskell datatype representing MPI process groups.\nnewtype Group = MkGroup { fromGroup :: MPIGroup } deriving Storable\npeekGroup ptr = MkGroup <$> peek ptr\n\nforeign import ccall \"&mpi_group_empty\" groupEmpty_ :: Ptr MPIGroup\n-- | A predefined group without any members. Corresponds to @MPI_GROUP_EMPTY@.\ngroupEmpty :: Group\ngroupEmpty = MkGroup <$> unsafePerformIO $ peek groupEmpty_\n\n\n-- | Actual Haskell type used depends on the MPI implementation.\ntype MPIOperation = {# type MPI_Op #}\n\n{- | Abstract type representing handle for MPI reduction operation\n(that can be used with 'reduce', 'allreduce', and 'reduceScatter').\n-}\nnewtype Operation = MkOperation { fromOperation :: MPIOperation } deriving Storable\npeekOperation ptr = MkOperation <$> peek ptr\nwithOperation op f = alloca $ \\ptr -> do poke ptr (fromOperation op)\n f (castPtr ptr)\n\nforeign import ccall unsafe \"&mpi_max\" maxOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_min\" minOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_sum\" sumOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_prod\" prodOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_land\" landOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_band\" bandOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lor\" lorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bor\" borOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_lxor\" lxorOp_ :: Ptr MPIOperation\nforeign import ccall unsafe \"&mpi_bxor\" bxorOp_ :: Ptr MPIOperation\n-- foreign import ccall \"mpi_maxloc\" maxlocOp :: MPIOperation\n-- foreign import ccall \"mpi_minloc\" minlocOp :: MPIOperation\n-- foreign import ccall \"mpi_replace\" replaceOp :: MPIOperation\n-- TODO: support for those requires better support for pair datatypes\n\n-- | Predefined reduction operation: maximum\nmaxOp :: Operation\nmaxOp = MkOperation <$> unsafePerformIO $ peek maxOp_\n\n-- | Predefined reduction operation: minimum\nminOp :: Operation\nminOp = MkOperation <$> unsafePerformIO $ peek minOp_\n\n-- | Predefined reduction operation: (+)\nsumOp :: Operation\nsumOp = MkOperation <$> unsafePerformIO $ peek sumOp_\n\n-- | Predefined reduction operation: (*)\nprodOp :: Operation\nprodOp = MkOperation <$> unsafePerformIO $ peek prodOp_\n\n-- | Predefined reduction operation: logical \\\"and\\\"\nlandOp :: Operation\nlandOp = MkOperation <$> unsafePerformIO $ peek landOp_\n\n-- | Predefined reduction operation: bit-wise \\\"and\\\"\nbandOp :: Operation\nbandOp = MkOperation <$> unsafePerformIO $ peek bandOp_\n\n-- | Predefined reduction operation: logical \\\"or\\\"\nlorOp :: Operation\nlorOp = MkOperation <$> unsafePerformIO $ peek lorOp_\n\n-- | Predefined reduction operation: bit-wise \\\"or\\\"\nborOp :: Operation\nborOp = MkOperation <$> unsafePerformIO $ peek borOp_\n\n-- | Predefined reduction operation: logical \\\"xor\\\"\nlxorOp :: Operation\nlxorOp = MkOperation <$> unsafePerformIO $ peek lxorOp_\n\n-- | Predefined reduction operation: bit-wise \\\"xor\\\"\nbxorOp :: Operation\nbxorOp = MkOperation <$> unsafePerformIO $ peek bxorOp_\n\n\n{- | Haskell datatype that represents values which\n could be used as MPI rank designations. Low-level MPI calls require\n that you use 32-bit non-negative integer values as ranks, so any\n non-numeric Haskell Ranks should provide a sensible instances of\n 'Enum'.\n\nAttempt to supply a value that does not fit into 32 bits will cause a\nrun-time 'error'.\n-}\nnewtype Rank = MkRank { rankId :: Int -- ^ Extract numeric value of the 'Rank'\n }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Rank where\n (MkRank x) + (MkRank y) = MkRank (x+y)\n (MkRank x) * (MkRank y) = MkRank (x*y)\n abs (MkRank x) = MkRank (abs x)\n signum (MkRank x) = MkRank (signum x)\n fromInteger x\n | x > ( fromIntegral (maxBound :: CInt)) = error \"Rank value does not fit into 32 bits\"\n | x < 0 = error \"Negative Rank value\"\n | otherwise = MkRank (fromIntegral x)\n\nforeign import ccall \"mpi_any_source\" anySource_ :: Ptr Int\nforeign import ccall \"mpi_root\" theRoot_ :: Ptr Int\nforeign import ccall \"mpi_proc_null\" procNull_ :: Ptr Int\n\n-- | Predefined rank number that allows reception of point-to-point messages\n-- regardless of their source. Corresponds to @MPI_ANY_SOURCE@\nanySource :: Rank\nanySource = toRank $ unsafePerformIO $ peek anySource_\n\n-- | Predefined rank number that specifies root process during\n-- operations involving intercommunicators. Corresponds to @MPI_ROOT@\ntheRoot :: Rank\ntheRoot = toRank $ unsafePerformIO $ peek theRoot_\n\n-- | Predefined rank number that specifies non-root processes during\n-- operations involving intercommunicators. Corresponds to @MPI_PROC_NULL@\nprocNull :: Rank\nprocNull = toRank $ unsafePerformIO $ peek procNull_\n\ninstance Show Rank where\n show = show . rankId\n\n-- | Map arbitrary 'Enum' value to 'Rank'\ntoRank :: Enum a => a -> Rank\ntoRank x = MkRank { rankId = fromEnum x }\n\n-- | Map 'Rank' to arbitrary 'Enum'\nfromRank :: Enum a => Rank -> a\nfromRank = toEnum . rankId\n\ntype MPIRequest = {# type MPI_Request #}\n{-| Haskell representation of the @MPI_Request@ type. Returned by\nnon-blocking communication operations, could be further processed with\n'probe', 'test', 'cancel' or 'wait'. -}\nnewtype Request = MkRequest MPIRequest deriving Storable\npeekRequest ptr = MkRequest <$> peek ptr\n\n{-\nThis module provides Haskell representation of the @MPI_Status@ type\n(request status).\n\nField `status_error' should be used with care:\n\\\"The error field in status is not needed for calls that return only\none status, such as @MPI_WAIT@, since that would only duplicate the\ninformation returned by the function itself. The current design avoids\nthe additional overhead of setting it, in such cases. The field is\nneeded for calls that return multiple statuses, since each request may\nhave had a different failure.\\\"\n(this is a quote from )\n\nThis means that, for example, during the call to @MPI_Wait@\nimplementation is free to leave this field filled with whatever\ngarbage got there during memory allocation. Haskell FFI is not\nblanking out freshly allocated memory, so beware!\n-}\n\n-- | Haskell structure that holds fields of @MPI_Status@.\n--\n-- Please note that MPI report lists only three fields as mandatory:\n-- @status_source@, @status_tag@ and @status_error@. However, all\n-- MPI implementations that were used to test those bindings supported\n-- extended set of fields represented here.\ndata Status =\n Status\n { status_source :: Rank -- ^ rank of the source process\n , status_tag :: Tag -- ^ tag assigned at source\n , status_error :: CInt -- ^ error code, if any\n , status_count :: CInt -- ^ number of received elements, if applicable\n , status_cancelled :: Bool -- ^ whether the request was cancelled\n }\n deriving (Eq, Ord, Show)\n\ninstance Storable Status where\n sizeOf _ = {#sizeof MPI_Status #}\n alignment _ = 4\n peek p = Status\n <$> liftM (MkRank . cIntConv) ({#get MPI_Status->MPI_SOURCE #} p)\n <*> liftM (MkTag . cIntConv) ({#get MPI_Status->MPI_TAG #} p)\n <*> liftM cIntConv ({#get MPI_Status->MPI_ERROR #} p)\n#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields-\n <*> liftM cIntConv ({#get MPI_Status->count #} p)\n <*> liftM cToEnum ({#get MPI_Status->cancelled #} p)\n#else\n <*> liftM cIntConv ({#get MPI_Status->_count #} p)\n <*> liftM cToEnum ({#get MPI_Status->_cancelled #} p)\n#endif\n poke p x = do\n {#set MPI_Status.MPI_SOURCE #} p (fromRank $ status_source x)\n {#set MPI_Status.MPI_TAG #} p (fromTag $ status_tag x)\n {#set MPI_Status.MPI_ERROR #} p (cIntConv $ status_error x)\n#ifdef MPICH2\n -- MPICH2 and OpenMPI use different names for the status struct\n -- fields AND different order of fields\n {#set MPI_Status.count #} p (cIntConv $ status_count x)\n {#set MPI_Status.cancelled #} p (cFromEnum $ status_cancelled x)\n#else\n {#set MPI_Status._count #} p (cIntConv $ status_count x)\n {#set MPI_Status._cancelled #} p (cFromEnum $ status_cancelled x)\n#endif\n\n-- NOTE: Int here is picked arbitrary\nallocaCast f =\n alloca $ \\(ptr :: Ptr Int) -> f (castPtr ptr :: Ptr ())\npeekCast = peek . castPtr\n\n\n{-| Haskell datatype that represents values which could be used as\ntags for point-to-point transfers.\n-}\nnewtype Tag = MkTag { tagVal :: Int -- ^ Extract numeric value of the Tag\n }\n deriving (Eq, Ord, Enum, Integral, Real)\n\ninstance Num Tag where\n (MkTag x) + (MkTag y) = MkTag (x+y)\n (MkTag x) * (MkTag y) = MkTag (x*y)\n abs (MkTag x) = MkTag (abs x)\n signum (MkTag x) = MkTag (signum x)\n fromInteger x\n | fromIntegral x > tagUpperBound = error \"Tag value is over the MPI_TAG_UB\"\n | x < 0 = error \"Negative Tag value\"\n | otherwise = MkTag (fromIntegral x)\n\ninstance Show Tag where\n show = show . tagVal\n\n-- | Map arbitrary 'Enum' value to 'Tag'\ntoTag :: Enum a => a -> Tag\ntoTag x = MkTag { tagVal = fromEnum x }\n\n-- | Map 'Tag' to arbitrary 'Enum'\nfromTag :: Enum a => Tag -> a\nfromTag = toEnum . tagVal\n\nforeign import ccall unsafe \"&mpi_any_tag\" anyTag_ :: Ptr Int\n\n-- | Predefined tag value that allows reception of the messages with\n-- arbitrary tag values. Corresponds to @MPI_ANY_TAG@.\nanyTag :: Tag\nanyTag = toTag $ unsafePerformIO $ peek anyTag_\n\n-- | A tag with unit value. Intended to be used as a convenient default.\nunitTag :: Tag\nunitTag = toTag ()\n\n{- | Constants used to describe the required level of multithreading\n support in call to 'initThread'. They also describe provided level\n of multithreading support as returned by 'queryThread' and\n 'initThread'.\n\n[@Single@] Only one thread will execute.\n\n[@Funneled@] The process may be multi-threaded, but the application must\nensure that only the main thread makes MPI calls (see 'isThreadMain').\n\n[@Serialized@] The process may be multi-threaded, and multiple threads may\nmake MPI calls, but only one at a time: MPI calls are not made concurrently from\ntwo distinct threads\n\n[@Multiple@] Multiple threads may call MPI, with no restrictions.\n\nXXX Make sure we have the correct ordering as defined by MPI. Also we should\ndescribe the ordering here (other parts of the docs need it to be explained - see initThread).\n\n-}\n{# enum ThreadSupport {underscoreToCase} deriving (Eq,Ord,Show) #}\n\n-- | Value thrown as exception when MPI runtime is instructed to pass\n-- errors to user code (via 'commSetErrhandler' and 'errorsReturn').\n-- Since raw MPI errors codes are not standartized and not portable,\n-- they are not exposed.\ndata MPIError\n = MPIError\n { mpiErrorClass :: ErrorClass -- ^ Broad class of errors this one belongs to\n , mpiErrorString :: String -- ^ Human-readable error description\n }\n deriving (Eq, Show, Typeable)\n\ninstance Exception MPIError\n\ncheckError :: CInt -> IO ()\ncheckError code = do\n -- We ignore the error code from the call to Internal.errorClass\n -- because we call errorClass from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n (_, errClassRaw) <- errorClass code\n let errClass = cToEnum errClassRaw\n unless (errClass == Success) $ do\n errStr <- errorString code\n throwIO $ MPIError errClass errStr\n\n-- | Convert MPI error code human-readable error description. Corresponds to @MPI_Error_string@.\nerrorString :: CInt -> IO String\nerrorString code =\n allocaBytes (fromIntegral maxErrorString) $ \\ptr ->\n alloca $ \\lenPtr -> do\n -- We ignore the error code from the call to Internal.errorString\n -- because we call errorString from checkError. We'd end up\n -- with an infinite loop if we called checkError here.\n _ <- errorString' code ptr lenPtr\n len <- peek lenPtr\n peekCStringLen (ptr, cIntConv len)\n where\n errorString' = {# call unsafe Error_string as errorString_ #}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"263638dc00802029d07b8968253e0377c0b10aeb","subject":"[project @ 2002-06-13 23:03:12 by as49] Reversing the argument order flipped some arguments which weren't supposed to move. Jens Petersen pointed that out.","message":"[project @ 2002-06-13 23:03:12 by as49]\nReversing the argument order flipped some arguments which weren't supposed to\nmove. Jens Petersen pointed that out.\n","repos":"vincenthz\/webkit","old_file":"gtk\/multiline\/TextIter.chs","new_file":"gtk\/multiline\/TextIter.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry TextIter abstract datatype@\n--\n-- Author : Axel Simon\n-- \n-- Created: 23 February 2002\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/06\/13 23:03:12 $\n--\n-- This file is free software; you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation; either version 2 of the License, or\n-- (at your option) any later version.\n--\n-- This file is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- * An iterator is an abstract datatype representing a pointer into a \n-- @TextBuffer.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * The following functions do not make sense due to Haskell's wide character\n-- representation of Unicode:\n-- gtk_text_iter_get_line_index\n-- gtk_text_iter_get_visible_line_index\n-- gtk_text_iter_get_bytes_in_line\n-- gtk_text_iter_set_line_index\n-- gtk_text_iter_set_visible_line_index\n--\n-- * The functions gtk_text_iter_in_range and gtk_text_iter_order are not bound\n-- because they are only convenience functions which can replaced by calls\n-- to textIterCompare.\n--\n-- * All offsets are counted from 0.\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * Bind the following function when GSList is bound:\n-- gtk_text_iter_get_marks\n-- gtk_text_iter_get_toggled_tags\n-- gtk_text_iter_get_tags\n--\n-- * Bind the following functions when we are sure about anchors \n-- (see @TextBuffer):\n-- gtk_text_iter_get_anchor\n--\n-- * Bind TextAttribute functions when I am clear how to model them. \n-- gtk_text_iter_get_attribute\n--\n-- * Forward exceptions in the two callback functions.\n--\nmodule TextIter(\n TextIter(TextIter),\n mkTextIter,\n makeEmptyTextIter,\t-- for internal use only\n textIterGetBuffer,\n textIterCopy,\n textIterGetOffset,\n textIterGetLine,\n textIterGetLineOffset,\n textIterGetVisibleLineOffset,\n textIterGetChar,\n textIterGetSlice,\n textIterGetText,\n textIterGetVisibleSlice,\n textIterGetVisibleText,\n textIterGetPixbuf,\n textIterBeginsTag,\n textIterEndsTag,\n textIterTogglesTag,\n textIterHasTag,\n textIterEditable,\n textIterCanInsert,\n textIterStartsWord,\n textIterEndsWord,\n textIterInsideWord,\n textIterStartsLine,\n textIterEndsLine,\n textIterStartsSentence,\n textIterEndsSentence,\n textIterInsideSentence,\n textIterIsCursorPosition,\n textIterGetCharsInLine,\n textIterIsEnd,\n textIterIsStart,\n textIterForwardChar,\n textIterBackwardChar,\n textIterForwardChars,\n textIterBackwardChars,\n textIterForwardLine,\n textIterBackwardLine,\n textIterForwardLines,\n textIterBackwardLines,\n textIterForwardWordEnds,\n textIterBackwardWordStarts,\n textIterForwardWordEnd,\n textIterBackwardWordStart,\n textIterForwardCursorPosition,\n textIterBackwardCursorPosition,\n textIterForwardCursorPositions,\n textIterBackwardCursorPositions,\n textIterForwardSentenceEnds,\n textIterBackwardSentenceStarts,\n textIterForwardSentenceEnd,\n textIterBackwardSentenceStart,\n textIterSetOffset,\n textIterSetLine,\n textIterSetLineOffset,\n textIterSetVisibleLineOffset,\n textIterForwardToEnd,\n textIterForwardToLineEnd,\n textIterForwardToTagToggle,\n textIterBackwardToTagToggle,\n textIterForwardFindChar,\n textIterBackwardFindChar,\n textIterForwardSearch,\n textIterBackwardSearch,\n textIterEqual,\n textIterCompare\n ) where\n\nimport Monad\t(liftM)\nimport Maybe\t(fromMaybe)\nimport Char\t(chr)\nimport Foreign\nimport CForeign\nimport GObject\t(makeNewGObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Structs (nullForeignPtr, textIterSize)\nimport Enums\t(TextSearchFlags, Flags(fromFlags))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n{#pointer *TextIter foreign newtype #}\n\n-- Create a @TextIter from a pointer.\n--\nmkTextIter :: Ptr TextIter -> IO TextIter\nmkTextIter iterPtr = liftM TextIter $ \n newForeignPtr iterPtr (textIterFree iterPtr)\n\n-- Allocate memory to be filled with a @TextIter.\n--\nmakeEmptyTextIter :: IO TextIter\nmakeEmptyTextIter = do\n iterPtr <- mallocBytes textIterSize\n liftM TextIter $ newForeignPtr iterPtr (textIterFree iterPtr)\n\n-- Free a @TextIter pointer.\n--\nforeign import ccall \"gtk_text_iter_free\" unsafe \n textIterFree :: Ptr TextIter -> IO ()\n\n\n-- @method textIterGetBuffer@ Return the @ref type TextBuffer@ this iterator\n-- is associated with.\n--\ntextIterGetBuffer :: TextIter -> IO TextBuffer\ntextIterGetBuffer ti = makeNewGObject mkTextBuffer $\n {#call unsafe text_iter_get_buffer#} ti\n\n-- @method textIterCopy@ Copy the iterator.\n--\ntextIterCopy :: TextIter -> IO TextIter\ntextIterCopy ti = do\n iterPtr <- {#call unsafe text_iter_copy#} ti\n liftM TextIter $ newForeignPtr iterPtr (textIterFree iterPtr)\n\n-- @method textIterGetOffset@ Extract the offset relative to the beginning of\n-- the buffer.\n--\ntextIterGetOffset :: TextIter -> IO Int\ntextIterGetOffset ti = liftM fromIntegral $\n {#call unsafe text_iter_get_offset#} ti\n\n-- @method textIterGetLine@ Extract the line of the buffer.\n--\ntextIterGetLine :: TextIter -> IO Int\ntextIterGetLine ti = liftM fromIntegral $\n {#call unsafe text_iter_get_line#} ti\n\n-- @method textIterGetLineOffset@ Extract the offset relative to the beginning\n-- of the line.\n--\ntextIterGetLineOffset :: TextIter -> IO Int\ntextIterGetLineOffset ti = liftM fromIntegral $\n {#call unsafe text_iter_get_line_offset#} ti\n\n-- @method textIterGetVisibleLineOffset@ Extract the offset relative to the\n-- beginning of the line skipping invisible parts of the line.\n--\ntextIterGetVisibleLineOffset :: TextIter -> IO Int\ntextIterGetVisibleLineOffset ti = liftM fromIntegral $\n {#call unsafe text_iter_get_visible_line_offset#} ti\n\n-- @method textIterGetChar@ Return the character at this iterator.\n--\ntextIterGetChar :: TextIter -> IO (Maybe Char)\ntextIterGetChar ti = do\n (res::Int) <- liftM fromIntegral $ {#call unsafe text_iter_get_char#} ti\n return $ if res==0 then Nothing else Just (chr res)\n\n-- @method textIterGetSlice@ Return the text in a given range.\n--\n-- * Pictures (and other objects) are represented by 0xFFFC.\n--\ntextIterGetSlice :: TextIter -> TextIter -> IO String\ntextIterGetSlice end start = do\n cStr <- {#call text_iter_get_slice#} start end\n str <- peekCString cStr\n {#call unsafe g_free#} (castPtr cStr)\n return str\n\n-- @method textIterGetText@ Return the text in a given range.\n--\n-- * Pictures (and other objects) are stripped form the output.\n--\ntextIterGetText :: TextIter -> TextIter -> IO String\ntextIterGetText start end = do\n cStr <- {#call text_iter_get_text#} start end\n str <- peekCString cStr\n {#call unsafe g_free#} (castPtr cStr)\n return str\n\n-- @method textIterGetVisibleSlice@ Return the visible text in a given range.\n--\n-- * Pictures (and other objects) are represented by 0xFFFC.\n--\ntextIterGetVisibleSlice :: TextIter -> TextIter -> IO String\ntextIterGetVisibleSlice start end = do\n cStr <- {#call text_iter_get_visible_slice#} start end\n str <- peekCString cStr\n {#call unsafe g_free#} (castPtr cStr)\n return str\n\n-- @method textIterGetVisibleText@ Return the visible text in a given range.\n--\n-- * Pictures (and other objects) are stripped form the output.\n--\ntextIterGetVisibleText :: TextIter -> TextIter -> IO String\ntextIterGetVisibleText start end = do\n cStr <- {#call text_iter_get_visible_text#} start end\n str <- peekCString cStr\n {#call unsafe g_free#} (castPtr cStr)\n return str\n\n-- @method textIterGetPixbuf@ Get the @ref arg GdkPixbuf@ under the iterator.\n--\ntextIterGetPixbuf :: TextIter -> IO (Maybe GdkPixbuf)\ntextIterGetPixbuf it = do\n pbPtr <- {#call unsafe text_iter_get_pixbuf#} it\n if pbPtr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkGdkPixbuf (return pbPtr)\n\n\n-- @method textIterBeginsTag@ Query whether a @ref type TextIter@ is at the\n-- start of a @ref type TextTag@.\n--\ntextIterBeginsTag :: TextIter -> TextTag -> IO Bool\ntextIterBeginsTag ti tt = liftM toBool $\n {#call unsafe text_iter_begins_tag#} ti tt\n\n\n-- @method textIterEndsTag@ Query whether a @ref type TextIter@ is at the end\n-- of a @ref type TextTag@.\n--\ntextIterEndsTag :: TextIter -> TextTag -> IO Bool\ntextIterEndsTag ti tt = liftM toBool $\n {#call unsafe text_iter_ends_tag#} ti tt\n\n-- @method textIterTogglesTag@ Query if the @ref type TextIter@ is at the\n-- beginning or the end of a @ref type TextTag@.\n--\ntextIterTogglesTag :: TextIter -> TextTag -> IO Bool\ntextIterTogglesTag ti tt = liftM toBool $\n {#call unsafe text_iter_toggles_tag#} ti tt\n\n-- @method textIterHasTag@ Check if @ref type TextIter@ is within a range\n-- tagged with tag.\n--\ntextIterHasTag :: TextIter -> TextTag -> IO Bool\ntextIterHasTag ti tt = liftM toBool $\n {#call unsafe text_iter_has_tag#} ti tt\n\n-- @method textIterEditable@ Check if @ref type TextIter@ is within an\n-- editable region.\n--\n-- * If no tags that affect editability are attached to the current position\n-- @ref arg def@ will be returned.\n--\n-- * This function cannot be used to decide whether text can be inserted at\n-- @ref type TextIter@. Use the @ref method textIterCanInsert@ function for\n-- this purpose.\n--\ntextIterEditable :: TextIter -> Bool -> IO Bool\ntextIterEditable ti def = liftM toBool $ \n {#call unsafe text_iter_editable#} ti (fromBool def)\n\n-- @method textIterCanInsert@ Check if new text can be inserted at\n-- @ref type TextIter@.\n--\n-- * Use @ref method textBufferInsertInteractive@ if you want to insert text\n-- depending on the current editable status.\n--\ntextIterCanInsert :: TextIter -> Bool -> IO Bool\ntextIterCanInsert ti def = liftM toBool $ \n {#call unsafe text_iter_can_insert#} ti (fromBool def)\n\n-- @method textIterStartsWord@ Determine if @ref type TextIter@ begins a new\n-- natural-language word.\n--\ntextIterStartsWord :: TextIter -> IO Bool\ntextIterStartsWord ti = liftM toBool $ {#call unsafe text_iter_starts_word#} ti\n\n\n-- @method textIterEndsWord@ Determine if @ref type TextIter@ ends a new\n-- natural-language word.\n--\ntextIterEndsWord :: TextIter -> IO Bool\ntextIterEndsWord ti = liftM toBool $ {#call unsafe text_iter_ends_word#} ti\n\n-- @method textIterInsideWord@ Determine if @ref type TextIter@ is inside a\n-- word.\n--\ntextIterInsideWord :: TextIter -> IO Bool\ntextIterInsideWord ti = liftM toBool $ {#call unsafe text_iter_inside_word#} ti\n\n-- @method textIterStartsLine@ Determine if @ref type TextIter@ begins a new\n-- line.\n--\ntextIterStartsLine :: TextIter -> IO Bool\ntextIterStartsLine ti = liftM toBool $ {#call unsafe text_iter_starts_line#} ti\n\n-- @method textIterEndsLine@ Determine if @ref type TextIter@ point to the\n-- beginning of a line delimiter.\n--\n-- * Returns False if @ref type TextIter@ points to the \\n in a \\r\\n sequence.\n--\ntextIterEndsLine :: TextIter -> IO Bool\ntextIterEndsLine ti = liftM toBool $ {#call unsafe text_iter_ends_line#} ti\n\n-- @method textIterStartsSentence@ Determine if @ref type TextIter@ starts a\n-- sentence.\n--\ntextIterStartsSentence :: TextIter -> IO Bool\ntextIterStartsSentence ti = liftM toBool $ \n {#call unsafe text_iter_starts_sentence#} ti\n\n-- @method textIterEndsSentence@ Determine if @ref type TextIter@ ends a\n-- sentence.\n--\ntextIterEndsSentence :: TextIter -> IO Bool\ntextIterEndsSentence ti = liftM toBool $ \n {#call unsafe text_iter_ends_sentence#} ti\n\n-- @method textIterInsideSentence@ Determine if @ref type TextIter@ is inside\n-- a sentence.\n--\ntextIterInsideSentence :: TextIter -> IO Bool\ntextIterInsideSentence ti = liftM toBool $ \n {#call unsafe text_iter_inside_sentence#} ti\n\n-- @method textIterIsCursorPosition@ Determine if @ref type TextIter@ is at a\n-- cursor position.\n--\ntextIterIsCursorPosition :: TextIter -> IO Bool\ntextIterIsCursorPosition ti = liftM toBool $ \n {#call unsafe text_iter_is_cursor_position#} ti\n\n-- @method textIterGetCharsInLine@ Return number of characters in this line.\n--\n-- * The return value includes delimiters.\n--\ntextIterGetCharsInLine :: TextIter -> IO Int\ntextIterGetCharsInLine ti = liftM fromIntegral $\n {#call unsafe text_iter_get_chars_in_line#} ti\n\n-- @dunno@Get the text attributes at the iterator.\n-- * The @ta argument gives the default values if no specific attributes are\n-- set at that specific location.\n--\n-- * The function returns Nothing if the text at the iterator has the same\n-- attributes.\n\n-- @method textIterIsEnd@ Determine if @ref type TextIter@ is at the end of\n-- the buffer.\n--\ntextIterIsEnd :: TextIter -> IO Bool\ntextIterIsEnd ti = liftM toBool $ \n {#call unsafe text_iter_is_end#} ti\n\n-- @method textIterIsStart@ Determine if @ref type TextIter@ is at the\n-- beginning of the buffer.\n--\ntextIterIsStart :: TextIter -> IO Bool\ntextIterIsStart ti = liftM toBool $ \n {#call unsafe text_iter_is_start#} ti\n\n-- @method textIterForwardChar@ Move @ref type TextIter@ forwards.\n--\n-- * Retuns True if the iterator is pointing to a character.\n--\ntextIterForwardChar :: TextIter -> IO Bool\ntextIterForwardChar ti = liftM toBool $ \n {#call unsafe text_iter_forward_char#} ti\n\n-- @method textIterBackwardChar@ Move @ref type TextIter@ backwards.\n--\n-- * Retuns True if the movement was possible.\n--\ntextIterBackwardChar :: TextIter -> IO Bool\ntextIterBackwardChar ti = liftM toBool $ \n {#call unsafe text_iter_backward_char#} ti\n\n-- @method textIterForwardChars@ Move @ref type TextIter@ forwards by\n-- @ref arg n@ characters.\n--\n-- * Retuns True if the iterator is pointing to a new character (and False if\n-- the iterator points to a picture or has not moved).\n--\ntextIterForwardChars :: TextIter -> Int -> IO Bool\ntextIterForwardChars ti n = liftM toBool $ \n {#call unsafe text_iter_forward_chars#} ti (fromIntegral n)\n\n-- @method textIterBackwardChars@ Move @ref type TextIter@ backwards by\n-- @ref arg n@ characters.\n--\n-- * Retuns True if the iterator is pointing to a new character (and False if\n-- the iterator points to a picture or has not moved).\n--\ntextIterBackwardChars :: TextIter -> Int -> IO Bool\ntextIterBackwardChars ti n = liftM toBool $ \n {#call unsafe text_iter_backward_chars#} ti (fromIntegral n)\n\n\n-- @method textIterForwardLine@ Move @ref type TextIter@ forwards.\n--\n-- * Retuns True if the iterator is pointing to a new line (and False if the\n-- iterator points to a picture or has not moved).\n--\n-- * If @ref type TextIter@ is on the first line, it will be moved to the\n-- beginning of the buffer.\n--\ntextIterForwardLine :: TextIter -> IO Bool\ntextIterForwardLine ti = liftM toBool $ \n {#call unsafe text_iter_forward_line#} ti\n\n-- @method textIterBackwardLine@ Move @ref type TextIter@ backwards.\n--\n-- * Retuns True if the iterator is pointing to a new line (and False if the\n-- iterator points to a picture or has not moved).\n--\n-- * If @ref type TextIter@ is on the first line, it will be moved to the end\n-- of the buffer.\n--\ntextIterBackwardLine :: TextIter -> IO Bool\ntextIterBackwardLine ti = liftM toBool $ \n {#call unsafe text_iter_backward_line#} ti\n\n\n-- @method textIterForwardLines@ Move @ref type TextIter@ forwards by\n-- @ref arg n@ lines.\n--\n-- * Retuns True if the iterator is pointing to a new line (and False if the\n-- iterator points to a picture or has not moved).\n--\n-- * If @ref type TextIter@ is on the first line, it will be moved to the\n-- beginning of the buffer.\n--\n-- * @ref arg n@ can be negative.\n--\ntextIterForwardLines :: TextIter -> Int -> IO Bool\ntextIterForwardLines ti n = liftM toBool $ \n {#call unsafe text_iter_forward_lines#} ti (fromIntegral n)\n\n-- @method textIterBackwardLines@ Move @ref type TextIter@ backwards by\n-- @ref arg n@ lines.\n--\n-- * Retuns True if the iterator is pointing to a new line (and False if the\n-- iterator points to a picture or has not moved).\n--\n-- * If @ref type TextIter@ is on the first line, it will be moved to the end\n-- of the buffer.\n--\n-- * @ref arg n@ can be negative.\n--\ntextIterBackwardLines :: TextIter -> Int -> IO Bool\ntextIterBackwardLines ti n = liftM toBool $ \n {#call unsafe text_iter_backward_lines#} ti (fromIntegral n)\n\n-- @method textIterForwardWordEnds@ Move @ref type TextIter@ forwards by\n-- @ref arg n@ word ends.\n--\n-- * Retuns True if the iterator is pointing to a new word end.\n--\ntextIterForwardWordEnds :: TextIter -> Int -> IO Bool\ntextIterForwardWordEnds ti n = liftM toBool $ \n {#call unsafe text_iter_forward_word_ends#} ti (fromIntegral n)\n\n-- @method textIterBackwardWordStarts@ Move @ref type TextIter@ backwards by\n-- @ref arg n@ word beginnings.\n--\n-- * Retuns True if the iterator is pointing to a new word start.\n--\ntextIterBackwardWordStarts :: TextIter -> Int -> IO Bool\ntextIterBackwardWordStarts ti n = liftM toBool $ \n {#call unsafe text_iter_backward_word_starts#} ti (fromIntegral n)\n\n-- @method textIterForwardWordEnd@ Move @ref type TextIter@ forwards to the\n-- next word end.\n--\n-- * Retuns True if the iterator has moved to a new word end.\n--\ntextIterForwardWordEnd :: TextIter -> IO Bool\ntextIterForwardWordEnd ti = liftM toBool $ \n {#call unsafe text_iter_forward_word_end#} ti\n\n-- @method textIterBackwardWordStart@ Move @ref type TextIter@ backwards to\n-- the next word beginning.\n--\n-- * Retuns True if the iterator has moved to a new word beginning.\n--\ntextIterBackwardWordStart :: TextIter -> IO Bool\ntextIterBackwardWordStart ti = liftM toBool $ \n {#call unsafe text_iter_backward_word_start#} ti\n\n-- @method textIterForwardCursorPosition@ Move @ref type TextIter@ forwards to\n-- the next cursor position.\n--\n-- * Some characters are composed of two Unicode codes. This function ensures\n-- that @ref type TextIter@ does not point inbetween such double characters.\n--\n-- * Returns True if @ref type TextIter@ moved and points to a character (not\n-- to an object).\n--\ntextIterForwardCursorPosition :: TextIter -> IO Bool\ntextIterForwardCursorPosition ti = liftM toBool $\n {#call unsafe text_iter_forward_cursor_position#} ti\n\n-- @method textIterBackwardCursorPosition@ Move @ref type TextIter@ backwards\n-- to the next cursor position.\n--\n-- * Some characters are composed of two Unicode codes. This function ensures\n-- that @ref type TextIter@ does not point inbetween such double characters.\n--\n-- * Returns True if @ref type TextIter@ moved and points to a character (not\n-- to an object).\n--\ntextIterBackwardCursorPosition :: TextIter -> IO Bool\ntextIterBackwardCursorPosition ti = liftM toBool $\n {#call unsafe text_iter_backward_cursor_position#} ti\n\n-- @method textIterForwardCursorPositions@ Move @ref type TextIter@ forwards\n-- by @ref arg n@ cursor positions.\n--\n-- * Returns True if @ref type TextIter@ moved and points to a character (not\n-- to an object).\n--\ntextIterForwardCursorPositions :: TextIter -> Int -> IO Bool\ntextIterForwardCursorPositions ti n = liftM toBool $ \n {#call unsafe text_iter_forward_cursor_positions#} ti (fromIntegral n)\n\n-- @method textIterBackwardCursorPositions@ Move @ref type TextIter@ backwards\n-- by @ref arg n@ cursor positions.\n--\n-- * Returns True if @ref type TextIter@ moved and points to a character (not\n-- to an object).\n--\ntextIterBackwardCursorPositions :: TextIter -> Int -> IO Bool\ntextIterBackwardCursorPositions ti n = liftM toBool $ \n {#call unsafe text_iter_backward_cursor_positions#} ti (fromIntegral n)\n\n\n-- @method textIterForwardSentenceEnds@ Move @ref type TextIter@ forwards by\n-- @ref arg n@ sentence ends.\n--\n-- * Retuns True if the iterator is pointing to a new sentence end.\n--\ntextIterForwardSentenceEnds :: TextIter -> Int -> IO Bool\ntextIterForwardSentenceEnds ti n = liftM toBool $ \n {#call unsafe text_iter_forward_sentence_ends#} ti (fromIntegral n)\n\n-- @method textIterBackwardSentenceStarts@ Move @ref type TextIter@ backwards\n-- by @ref arg n@ sentence beginnings.\n--\n-- * Retuns True if the iterator is pointing to a new sentence start.\n--\ntextIterBackwardSentenceStarts :: TextIter -> Int -> IO Bool\ntextIterBackwardSentenceStarts ti n = liftM toBool $ \n {#call unsafe text_iter_backward_sentence_starts#} ti (fromIntegral n)\n\n-- @method textIterForwardSentenceEnd@ Move @ref type TextIter@ forwards to\n-- the next sentence end.\n--\n-- * Retuns True if the iterator has moved to a new sentence end.\n--\ntextIterForwardSentenceEnd :: TextIter -> IO Bool\ntextIterForwardSentenceEnd ti = liftM toBool $ \n {#call unsafe text_iter_forward_sentence_end#} ti\n\n-- @method textIterBackwardSentenceStart@ Move @ref type TextIter@ backwards\n-- to the next sentence beginning.\n--\n-- * Retuns True if the iterator has moved to a new sentence beginning.\n--\ntextIterBackwardSentenceStart :: TextIter -> IO Bool\ntextIterBackwardSentenceStart ti = liftM toBool $ \n {#call unsafe text_iter_backward_sentence_start#} ti\n\n-- @method textIterSetOffset@ Set @ref type TextIter@ to an offset within the\n-- buffer.\n--\ntextIterSetOffset :: TextIter -> Int -> IO ()\ntextIterSetOffset ti n = \n {#call unsafe text_iter_set_offset#} ti (fromIntegral n)\n\n-- @method textIterSetLine@ Set @ref type TextIter@ to a line within the\n-- buffer.\n--\ntextIterSetLine :: TextIter -> Int -> IO ()\ntextIterSetLine ti n = \n {#call unsafe text_iter_set_line#} ti (fromIntegral n)\n\n-- @method textIterSetLineOffset@ Set @ref type TextIter@ to an offset within\n-- the line.\n--\ntextIterSetLineOffset :: TextIter -> Int -> IO ()\ntextIterSetLineOffset ti n = \n {#call unsafe text_iter_set_line_offset#} ti (fromIntegral n)\n\n-- @method textIterSetVisibleLineOffset@ Set @ref type TextIter@ to an visible\n-- character within the line.\n--\ntextIterSetVisibleLineOffset :: TextIter -> Int -> IO ()\ntextIterSetVisibleLineOffset ti n = \n {#call unsafe text_iter_set_visible_line_offset#} ti (fromIntegral n)\n\n-- @method textIterForwardToEnd@ Moves @ref type TextIter@ to the end of the\n-- buffer.\n--\ntextIterForwardToEnd :: TextIter -> IO ()\ntextIterForwardToEnd ti = {#call unsafe text_iter_forward_to_end#} ti\n\n-- @method textIterForwardToLineEnd@ Moves @ref type TextIter@ to the end of\n-- the line.\n--\n-- * Returns True if @ref type TextIter@ moved to a new location which is not\n-- the buffer end iterator.\n--\ntextIterForwardToLineEnd :: TextIter -> IO Bool\ntextIterForwardToLineEnd ti = liftM toBool $\n {#call unsafe text_iter_forward_to_line_end#} ti\n\n-- @method textIterForwardToTagToggle@ Moves @ref type TextIter@ forward to\n-- the next change of a @ref type TextTag@.\n--\n-- * If Nothing is supplied, any @ref type TextTag@ will be matched.\n--\n-- * Returns True if there was a tag toggle after @ref type TextIter@.\n--\ntextIterForwardToTagToggle :: TextIter -> Maybe TextTag -> IO Bool\ntextIterForwardToTagToggle ti tt = liftM toBool $\n {#call unsafe text_iter_forward_to_tag_toggle#} ti \n (fromMaybe (mkTextTag nullForeignPtr) tt)\n\n-- @method textIterBackwardToTagToggle@ Moves @ref type TextIter@ backward to\n-- the next change of a @ref type TextTag@.\n--\n-- * If Nothing is supplied, any @ref type TextTag@ will be matched.\n--\n-- * Returns True if there was a tag toggle before @ref type TextIter@.\n--\ntextIterBackwardToTagToggle :: TextIter -> Maybe TextTag -> IO Bool\ntextIterBackwardToTagToggle ti tt = liftM toBool $\n {#call unsafe text_iter_backward_to_tag_toggle#} ti \n (fromMaybe (mkTextTag nullForeignPtr) tt)\n\n-- Setup a callback for a predicate function.\n--\ntype TextCharPredicateCB = Char -> Bool\n\n{#pointer TextCharPredicate#}\n\nforeign export dynamic mkTextCharPredicate ::\n ({#type gunichar#} -> Ptr () -> {#type gboolean#}) -> IO TextCharPredicate\n\n-- @method textIterForwardFindChar@ Move @ref type TextIter@ forward until a\n-- predicate function returns True.\n--\n-- * If @ref arg pred@ returns True before @ref arg limit@ is reached, the\n-- search is stopped and the return value is True.\n--\n-- * If @ref arg limit@ is Nothing, the search stops at the end of the buffer.\n--\ntextIterForwardFindChar :: TextIter -> (Char -> Bool) -> Maybe TextIter ->\n IO Bool\ntextIterForwardFindChar ti pred limit = do\n fPtr <- mkTextCharPredicate (\\c _ -> fromBool $ pred (chr (fromIntegral c)))\n res <- liftM toBool $ {#call text_iter_forward_find_char#} \n ti fPtr nullPtr (fromMaybe (TextIter nullForeignPtr) limit)\n freeHaskellFunPtr fPtr\n return res\n\n-- @method textIterBackwardFindChar@ Move @ref type TextIter@ backward until a\n-- predicate function returns True.\n--\n-- * If @ref arg pred@ returns True before @ref arg limit@ is reached, the\n-- search is stopped and the return value is True.\n--\n-- * If @ref arg limit@ is Nothing, the search stops at the end of the buffer.\n--\ntextIterBackwardFindChar :: TextIter -> (Char -> Bool) -> Maybe TextIter ->\n IO Bool\ntextIterBackwardFindChar ti pred limit = do\n fPtr <- mkTextCharPredicate (\\c _ -> fromBool $ pred (chr (fromIntegral c)))\n res <- liftM toBool $ {#call text_iter_backward_find_char#} \n ti fPtr nullPtr (fromMaybe (TextIter nullForeignPtr) limit)\n freeHaskellFunPtr fPtr\n return res\n\n-- @method textIterForwardSearch@ Search forward for a specific string.\n--\n-- * If specified, the last character which is tested against that start of\n-- the search pattern will be @ref arg limit@.\n--\n-- * @ref type TextSearchFlags@ may be empty.\n--\n-- * Returns the start and end position of the string found.\n--\ntextIterForwardSearch :: TextIter -> String -> [TextSearchFlags] ->\n Maybe TextIter -> IO (Maybe (TextIter, TextIter))\ntextIterForwardSearch ti str flags limit = do\n start <- makeEmptyTextIter\n end <- makeEmptyTextIter\n found <- liftM toBool $ withCString str $ \\cStr ->\n {#call unsafe text_iter_forward_search#} ti cStr \n ((fromIntegral.fromFlags) flags) start end \n (fromMaybe (TextIter nullForeignPtr) limit)\n return $ if found then Just (start,end) else Nothing\n\n-- @method textIterBackwardSearch@ Search backward for a specific string.\n--\n-- * If specified, the last character which is tested against that start of\n-- the search pattern will be @ref arg limit@.\n--\n-- * @ref type TextSearchFlags@ my be empty.\n--\n-- * Returns the start and end position of the string found.\n--\ntextIterBackwardSearch :: TextIter -> String -> [TextSearchFlags] ->\n Maybe TextIter -> IO (Maybe (TextIter, TextIter))\ntextIterBackwardSearch ti str flags limit = do\n start <- makeEmptyTextIter\n end <- makeEmptyTextIter\n found <- liftM toBool $ withCString str $ \\cStr ->\n {#call unsafe text_iter_backward_search#} ti cStr \n ((fromIntegral.fromFlags) flags) start end \n (fromMaybe (TextIter nullForeignPtr) limit)\n return $ if found then Just (start,end) else Nothing\n\n-- @method textIterEqual@ Compare two @ref type TextIter@ for equality.\n--\n-- * @ref type TextIter@ could be in class Eq and Ord if there is a guarantee\n-- that each iterator is copied before it is modified in place. This is done\n-- the next abstraction layer.\n--\ntextIterEqual :: TextIter -> TextIter -> IO Bool\ntextIterEqual ti2 ti1 = liftM toBool $ {#call unsafe text_iter_equal#} ti1 ti2\n\n-- @method textIterCompare@ Compare two @ref type TextIter@.\n--\n-- * @ref type TextIter@ could be in class Eq and Ord if there is a guarantee\n-- that each iterator is copied before it is modified in place. This could\n-- be done the next abstraction layer.\n--\ntextIterCompare :: TextIter -> TextIter -> IO Ordering\ntextIterCompare ti2 ti1 = do\n res <- {#call unsafe text_iter_compare#} ti1 ti2\n return $ case res of\n (-1) -> LT\n 0\t -> EQ\n 1\t -> GT\n\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry TextIter abstract datatype@\n--\n-- Author : Axel Simon\n-- \n-- Created: 23 February 2002\n--\n-- Version $Revision: 1.2 $ from $Date: 2002\/05\/24 09:43:25 $\n--\n-- This file is free software; you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation; either version 2 of the License, or\n-- (at your option) any later version.\n--\n-- This file is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- * An iterator is an abstract datatype representing a pointer into a \n-- @TextBuffer.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * The following functions do not make sense due to Haskell's wide character\n-- representation of Unicode:\n-- gtk_text_iter_get_line_index\n-- gtk_text_iter_get_visible_line_index\n-- gtk_text_iter_get_bytes_in_line\n-- gtk_text_iter_set_line_index\n-- gtk_text_iter_set_visible_line_index\n--\n-- * The functions gtk_text_iter_in_range and gtk_text_iter_order are not bound\n-- because they are only convenience functions which can replaced by calls\n-- to textIterCompare.\n--\n-- * All offsets are counted from 0.\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * Bind the following function when GSList is bound:\n-- gtk_text_iter_get_marks\n-- gtk_text_iter_get_toggled_tags\n-- gtk_text_iter_get_tags\n--\n-- * Bind the following functions when we are sure about anchors \n-- (see @TextBuffer):\n-- gtk_text_iter_get_anchor\n--\n-- * Bind TextAttribute functions when I am clear how to model them. \n-- gtk_text_iter_get_attribute\n--\n-- * Forward exceptions in the two callback functions.\n--\nmodule TextIter(\n TextIter(TextIter),\n mkTextIter,\n makeEmptyTextIter,\t-- for internal use only\n textIterGetBuffer,\n textIterCopy,\n textIterGetOffset,\n textIterGetLine,\n textIterGetLineOffset,\n textIterGetVisibleLineOffset,\n textIterGetChar,\n textIterGetSlice,\n textIterGetText,\n textIterGetVisibleSlice,\n textIterGetVisibleText,\n textIterGetPixbuf,\n textIterBeginsTag,\n textIterEndsTag,\n textIterTogglesTag,\n textIterHasTag,\n textIterEditable,\n textIterCanInsert,\n textIterStartsWord,\n textIterEndsWord,\n textIterInsideWord,\n textIterStartsLine,\n textIterEndsLine,\n textIterStartsSentence,\n textIterEndsSentence,\n textIterInsideSentence,\n textIterIsCursorPosition,\n textIterGetCharsInLine,\n textIterIsEnd,\n textIterIsStart,\n textIterForwardChar,\n textIterBackwardChar,\n textIterForwardChars,\n textIterBackwardChars,\n textIterForwardLine,\n textIterBackwardLine,\n textIterForwardLines,\n textIterBackwardLines,\n textIterForwardWordEnds,\n textIterBackwardWordStarts,\n textIterForwardWordEnd,\n textIterBackwardWordStart,\n textIterForwardCursorPosition,\n textIterBackwardCursorPosition,\n textIterForwardCursorPositions,\n textIterBackwardCursorPositions,\n textIterForwardSentenceEnds,\n textIterBackwardSentenceStarts,\n textIterForwardSentenceEnd,\n textIterBackwardSentenceStart,\n textIterSetOffset,\n textIterSetLine,\n textIterSetLineOffset,\n textIterSetVisibleLineOffset,\n textIterForwardToEnd,\n textIterForwardToLineEnd,\n textIterForwardToTagToggle,\n textIterBackwardToTagToggle,\n textIterForwardFindChar,\n textIterBackwardFindChar,\n textIterForwardSearch,\n textIterBackwardSearch,\n textIterEqual,\n textIterCompare\n ) where\n\nimport Monad\t(liftM)\nimport Maybe\t(fromMaybe)\nimport Char\t(chr)\nimport Foreign\nimport CForeign\nimport GObject\t(makeNewGObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Structs (nullForeignPtr, textIterSize)\nimport Enums\t(TextSearchFlags, Flags(fromFlags))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n{#pointer *TextIter foreign newtype #}\n\n-- Create a @TextIter from a pointer.\n--\nmkTextIter :: Ptr TextIter -> IO TextIter\nmkTextIter iterPtr = liftM TextIter $ \n newForeignPtr iterPtr (textIterFree iterPtr)\n\n-- Allocate memory to be filled with a @TextIter.\n--\nmakeEmptyTextIter :: IO TextIter\nmakeEmptyTextIter = do\n iterPtr <- mallocBytes textIterSize\n liftM TextIter $ newForeignPtr iterPtr (textIterFree iterPtr)\n\n-- Free a @TextIter pointer.\n--\nforeign import ccall \"gtk_text_iter_free\" unsafe \n textIterFree :: Ptr TextIter -> IO ()\n\n\n-- @method textIterGetBuffer@ Return the @ref type TextBuffer@ this iterator\n-- is associated with.\n--\ntextIterGetBuffer :: TextIter -> IO TextBuffer\ntextIterGetBuffer ti = makeNewGObject mkTextBuffer $\n {#call unsafe text_iter_get_buffer#} ti\n\n-- @method textIterCopy@ Copy the iterator.\n--\ntextIterCopy :: TextIter -> IO TextIter\ntextIterCopy ti = do\n iterPtr <- {#call unsafe text_iter_copy#} ti\n liftM TextIter $ newForeignPtr iterPtr (textIterFree iterPtr)\n\n-- @method textIterGetOffset@ Extract the offset relative to the beginning of\n-- the buffer.\n--\ntextIterGetOffset :: TextIter -> IO Int\ntextIterGetOffset ti = liftM fromIntegral $\n {#call unsafe text_iter_get_offset#} ti\n\n-- @method textIterGetLine@ Extract the line of the buffer.\n--\ntextIterGetLine :: TextIter -> IO Int\ntextIterGetLine ti = liftM fromIntegral $\n {#call unsafe text_iter_get_line#} ti\n\n-- @method textIterGetLineOffset@ Extract the offset relative to the beginning\n-- of the line.\n--\ntextIterGetLineOffset :: TextIter -> IO Int\ntextIterGetLineOffset ti = liftM fromIntegral $\n {#call unsafe text_iter_get_line_offset#} ti\n\n-- @method textIterGetVisibleLineOffset@ Extract the offset relative to the\n-- beginning of the line skipping invisible parts of the line.\n--\ntextIterGetVisibleLineOffset :: TextIter -> IO Int\ntextIterGetVisibleLineOffset ti = liftM fromIntegral $\n {#call unsafe text_iter_get_visible_line_offset#} ti\n\n-- @method textIterGetChar@ Return the character at this iterator.\n--\ntextIterGetChar :: TextIter -> IO (Maybe Char)\ntextIterGetChar ti = do\n (res::Int) <- liftM fromIntegral $ {#call unsafe text_iter_get_char#} ti\n return $ if res==0 then Nothing else Just (chr res)\n\n-- @method textIterGetSlice@ Return the text in a given range.\n--\n-- * Pictures (and other objects) are represented by 0xFFFC.\n--\ntextIterGetSlice :: TextIter -> TextIter -> IO String\ntextIterGetSlice end start = do\n cStr <- {#call text_iter_get_slice#} start end\n str <- peekCString cStr\n {#call unsafe g_free#} (castPtr cStr)\n return str\n\n-- @method textIterGetText@ Return the text in a given range.\n--\n-- * Pictures (and other objects) are stripped form the output.\n--\ntextIterGetText :: TextIter -> TextIter -> IO String\ntextIterGetText end start = do\n cStr <- {#call text_iter_get_text#} start end\n str <- peekCString cStr\n {#call unsafe g_free#} (castPtr cStr)\n return str\n\n-- @method textIterGetVisibleSlice@ Return the visible text in a given range.\n--\n-- * Pictures (and other objects) are represented by 0xFFFC.\n--\ntextIterGetVisibleSlice :: TextIter -> TextIter -> IO String\ntextIterGetVisibleSlice end start = do\n cStr <- {#call text_iter_get_visible_slice#} start end\n str <- peekCString cStr\n {#call unsafe g_free#} (castPtr cStr)\n return str\n\n-- @method textIterGetVisibleText@ Return the visible text in a given range.\n--\n-- * Pictures (and other objects) are stripped form the output.\n--\ntextIterGetVisibleText :: TextIter -> TextIter -> IO String\ntextIterGetVisibleText end start = do\n cStr <- {#call text_iter_get_visible_text#} start end\n str <- peekCString cStr\n {#call unsafe g_free#} (castPtr cStr)\n return str\n\n-- @method textIterGetPixbuf@ Get the @ref arg GdkPixbuf@ under the iterator.\n--\ntextIterGetPixbuf :: TextIter -> IO (Maybe GdkPixbuf)\ntextIterGetPixbuf it = do\n pbPtr <- {#call unsafe text_iter_get_pixbuf#} it\n if pbPtr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkGdkPixbuf (return pbPtr)\n\n\n-- @method textIterBeginsTag@ Query whether a @ref type TextIter@ is at the\n-- start of a @ref type TextTag@.\n--\ntextIterBeginsTag :: TextIter -> TextTag -> IO Bool\ntextIterBeginsTag ti tt = liftM toBool $\n {#call unsafe text_iter_begins_tag#} ti tt\n\n\n-- @method textIterEndsTag@ Query whether a @ref type TextIter@ is at the end\n-- of a @ref type TextTag@.\n--\ntextIterEndsTag :: TextIter -> TextTag -> IO Bool\ntextIterEndsTag ti tt = liftM toBool $\n {#call unsafe text_iter_ends_tag#} ti tt\n\n-- @method textIterTogglesTag@ Query if the @ref type TextIter@ is at the\n-- beginning or the end of a @ref type TextTag@.\n--\ntextIterTogglesTag :: TextIter -> TextTag -> IO Bool\ntextIterTogglesTag ti tt = liftM toBool $\n {#call unsafe text_iter_toggles_tag#} ti tt\n\n-- @method textIterHasTag@ Check if @ref type TextIter@ is within a range\n-- tagged with tag.\n--\ntextIterHasTag :: TextIter -> TextTag -> IO Bool\ntextIterHasTag ti tt = liftM toBool $\n {#call unsafe text_iter_has_tag#} ti tt\n\n-- @method textIterEditable@ Check if @ref type TextIter@ is within an\n-- editable region.\n--\n-- * If no tags that affect editability are attached to the current position\n-- @ref arg def@ will be returned.\n--\n-- * This function cannot be used to decide whether text can be inserted at\n-- @ref type TextIter@. Use the @ref method textIterCanInsert@ function for\n-- this purpose.\n--\ntextIterEditable :: TextIter -> Bool -> IO Bool\ntextIterEditable ti def = liftM toBool $ \n {#call unsafe text_iter_editable#} ti (fromBool def)\n\n-- @method textIterCanInsert@ Check if new text can be inserted at\n-- @ref type TextIter@.\n--\n-- * Use @ref method textBufferInsertInteractive@ if you want to insert text\n-- depending on the current editable status.\n--\ntextIterCanInsert :: TextIter -> Bool -> IO Bool\ntextIterCanInsert ti def = liftM toBool $ \n {#call unsafe text_iter_can_insert#} ti (fromBool def)\n\n-- @method textIterStartsWord@ Determine if @ref type TextIter@ begins a new\n-- natural-language word.\n--\ntextIterStartsWord :: TextIter -> IO Bool\ntextIterStartsWord ti = liftM toBool $ {#call unsafe text_iter_starts_word#} ti\n\n\n-- @method textIterEndsWord@ Determine if @ref type TextIter@ ends a new\n-- natural-language word.\n--\ntextIterEndsWord :: TextIter -> IO Bool\ntextIterEndsWord ti = liftM toBool $ {#call unsafe text_iter_ends_word#} ti\n\n-- @method textIterInsideWord@ Determine if @ref type TextIter@ is inside a\n-- word.\n--\ntextIterInsideWord :: TextIter -> IO Bool\ntextIterInsideWord ti = liftM toBool $ {#call unsafe text_iter_inside_word#} ti\n\n-- @method textIterStartsLine@ Determine if @ref type TextIter@ begins a new\n-- line.\n--\ntextIterStartsLine :: TextIter -> IO Bool\ntextIterStartsLine ti = liftM toBool $ {#call unsafe text_iter_starts_line#} ti\n\n-- @method textIterEndsLine@ Determine if @ref type TextIter@ point to the\n-- beginning of a line delimiter.\n--\n-- * Returns False if @ref type TextIter@ points to the \\n in a \\r\\n sequence.\n--\ntextIterEndsLine :: TextIter -> IO Bool\ntextIterEndsLine ti = liftM toBool $ {#call unsafe text_iter_ends_line#} ti\n\n-- @method textIterStartsSentence@ Determine if @ref type TextIter@ starts a\n-- sentence.\n--\ntextIterStartsSentence :: TextIter -> IO Bool\ntextIterStartsSentence ti = liftM toBool $ \n {#call unsafe text_iter_starts_sentence#} ti\n\n-- @method textIterEndsSentence@ Determine if @ref type TextIter@ ends a\n-- sentence.\n--\ntextIterEndsSentence :: TextIter -> IO Bool\ntextIterEndsSentence ti = liftM toBool $ \n {#call unsafe text_iter_ends_sentence#} ti\n\n-- @method textIterInsideSentence@ Determine if @ref type TextIter@ is inside\n-- a sentence.\n--\ntextIterInsideSentence :: TextIter -> IO Bool\ntextIterInsideSentence ti = liftM toBool $ \n {#call unsafe text_iter_inside_sentence#} ti\n\n-- @method textIterIsCursorPosition@ Determine if @ref type TextIter@ is at a\n-- cursor position.\n--\ntextIterIsCursorPosition :: TextIter -> IO Bool\ntextIterIsCursorPosition ti = liftM toBool $ \n {#call unsafe text_iter_is_cursor_position#} ti\n\n-- @method textIterGetCharsInLine@ Return number of characters in this line.\n--\n-- * The return value includes delimiters.\n--\ntextIterGetCharsInLine :: TextIter -> IO Int\ntextIterGetCharsInLine ti = liftM fromIntegral $\n {#call unsafe text_iter_get_chars_in_line#} ti\n\n-- @dunno@Get the text attributes at the iterator.\n-- * The @ta argument gives the default values if no specific attributes are\n-- set at that specific location.\n--\n-- * The function returns Nothing if the text at the iterator has the same\n-- attributes.\n\n-- @method textIterIsEnd@ Determine if @ref type TextIter@ is at the end of\n-- the buffer.\n--\ntextIterIsEnd :: TextIter -> IO Bool\ntextIterIsEnd ti = liftM toBool $ \n {#call unsafe text_iter_is_end#} ti\n\n-- @method textIterIsStart@ Determine if @ref type TextIter@ is at the\n-- beginning of the buffer.\n--\ntextIterIsStart :: TextIter -> IO Bool\ntextIterIsStart ti = liftM toBool $ \n {#call unsafe text_iter_is_start#} ti\n\n-- @method textIterForwardChar@ Move @ref type TextIter@ forwards.\n--\n-- * Retuns True if the iterator is pointing to a character.\n--\ntextIterForwardChar :: TextIter -> IO Bool\ntextIterForwardChar ti = liftM toBool $ \n {#call unsafe text_iter_forward_char#} ti\n\n-- @method textIterBackwardChar@ Move @ref type TextIter@ backwards.\n--\n-- * Retuns True if the movement was possible.\n--\ntextIterBackwardChar :: TextIter -> IO Bool\ntextIterBackwardChar ti = liftM toBool $ \n {#call unsafe text_iter_backward_char#} ti\n\n-- @method textIterForwardChars@ Move @ref type TextIter@ forwards by\n-- @ref arg n@ characters.\n--\n-- * Retuns True if the iterator is pointing to a new character (and False if\n-- the iterator points to a picture or has not moved).\n--\ntextIterForwardChars :: TextIter -> Int -> IO Bool\ntextIterForwardChars ti n = liftM toBool $ \n {#call unsafe text_iter_forward_chars#} ti (fromIntegral n)\n\n-- @method textIterBackwardChars@ Move @ref type TextIter@ backwards by\n-- @ref arg n@ characters.\n--\n-- * Retuns True if the iterator is pointing to a new character (and False if\n-- the iterator points to a picture or has not moved).\n--\ntextIterBackwardChars :: TextIter -> Int -> IO Bool\ntextIterBackwardChars ti n = liftM toBool $ \n {#call unsafe text_iter_backward_chars#} ti (fromIntegral n)\n\n\n-- @method textIterForwardLine@ Move @ref type TextIter@ forwards.\n--\n-- * Retuns True if the iterator is pointing to a new line (and False if the\n-- iterator points to a picture or has not moved).\n--\n-- * If @ref type TextIter@ is on the first line, it will be moved to the\n-- beginning of the buffer.\n--\ntextIterForwardLine :: TextIter -> IO Bool\ntextIterForwardLine ti = liftM toBool $ \n {#call unsafe text_iter_forward_line#} ti\n\n-- @method textIterBackwardLine@ Move @ref type TextIter@ backwards.\n--\n-- * Retuns True if the iterator is pointing to a new line (and False if the\n-- iterator points to a picture or has not moved).\n--\n-- * If @ref type TextIter@ is on the first line, it will be moved to the end\n-- of the buffer.\n--\ntextIterBackwardLine :: TextIter -> IO Bool\ntextIterBackwardLine ti = liftM toBool $ \n {#call unsafe text_iter_backward_line#} ti\n\n\n-- @method textIterForwardLines@ Move @ref type TextIter@ forwards by\n-- @ref arg n@ lines.\n--\n-- * Retuns True if the iterator is pointing to a new line (and False if the\n-- iterator points to a picture or has not moved).\n--\n-- * If @ref type TextIter@ is on the first line, it will be moved to the\n-- beginning of the buffer.\n--\n-- * @ref arg n@ can be negative.\n--\ntextIterForwardLines :: TextIter -> Int -> IO Bool\ntextIterForwardLines ti n = liftM toBool $ \n {#call unsafe text_iter_forward_lines#} ti (fromIntegral n)\n\n-- @method textIterBackwardLines@ Move @ref type TextIter@ backwards by\n-- @ref arg n@ lines.\n--\n-- * Retuns True if the iterator is pointing to a new line (and False if the\n-- iterator points to a picture or has not moved).\n--\n-- * If @ref type TextIter@ is on the first line, it will be moved to the end\n-- of the buffer.\n--\n-- * @ref arg n@ can be negative.\n--\ntextIterBackwardLines :: TextIter -> Int -> IO Bool\ntextIterBackwardLines ti n = liftM toBool $ \n {#call unsafe text_iter_backward_lines#} ti (fromIntegral n)\n\n-- @method textIterForwardWordEnds@ Move @ref type TextIter@ forwards by\n-- @ref arg n@ word ends.\n--\n-- * Retuns True if the iterator is pointing to a new word end.\n--\ntextIterForwardWordEnds :: TextIter -> Int -> IO Bool\ntextIterForwardWordEnds ti n = liftM toBool $ \n {#call unsafe text_iter_forward_word_ends#} ti (fromIntegral n)\n\n-- @method textIterBackwardWordStarts@ Move @ref type TextIter@ backwards by\n-- @ref arg n@ word beginnings.\n--\n-- * Retuns True if the iterator is pointing to a new word start.\n--\ntextIterBackwardWordStarts :: TextIter -> Int -> IO Bool\ntextIterBackwardWordStarts ti n = liftM toBool $ \n {#call unsafe text_iter_backward_word_starts#} ti (fromIntegral n)\n\n-- @method textIterForwardWordEnd@ Move @ref type TextIter@ forwards to the\n-- next word end.\n--\n-- * Retuns True if the iterator has moved to a new word end.\n--\ntextIterForwardWordEnd :: TextIter -> IO Bool\ntextIterForwardWordEnd ti = liftM toBool $ \n {#call unsafe text_iter_forward_word_end#} ti\n\n-- @method textIterBackwardWordStart@ Move @ref type TextIter@ backwards to\n-- the next word beginning.\n--\n-- * Retuns True if the iterator has moved to a new word beginning.\n--\ntextIterBackwardWordStart :: TextIter -> IO Bool\ntextIterBackwardWordStart ti = liftM toBool $ \n {#call unsafe text_iter_backward_word_start#} ti\n\n-- @method textIterForwardCursorPosition@ Move @ref type TextIter@ forwards to\n-- the next cursor position.\n--\n-- * Some characters are composed of two Unicode codes. This function ensures\n-- that @ref type TextIter@ does not point inbetween such double characters.\n--\n-- * Returns True if @ref type TextIter@ moved and points to a character (not\n-- to an object).\n--\ntextIterForwardCursorPosition :: TextIter -> IO Bool\ntextIterForwardCursorPosition ti = liftM toBool $\n {#call unsafe text_iter_forward_cursor_position#} ti\n\n-- @method textIterBackwardCursorPosition@ Move @ref type TextIter@ backwards\n-- to the next cursor position.\n--\n-- * Some characters are composed of two Unicode codes. This function ensures\n-- that @ref type TextIter@ does not point inbetween such double characters.\n--\n-- * Returns True if @ref type TextIter@ moved and points to a character (not\n-- to an object).\n--\ntextIterBackwardCursorPosition :: TextIter -> IO Bool\ntextIterBackwardCursorPosition ti = liftM toBool $\n {#call unsafe text_iter_backward_cursor_position#} ti\n\n-- @method textIterForwardCursorPositions@ Move @ref type TextIter@ forwards\n-- by @ref arg n@ cursor positions.\n--\n-- * Returns True if @ref type TextIter@ moved and points to a character (not\n-- to an object).\n--\ntextIterForwardCursorPositions :: TextIter -> Int -> IO Bool\ntextIterForwardCursorPositions ti n = liftM toBool $ \n {#call unsafe text_iter_forward_cursor_positions#} ti (fromIntegral n)\n\n-- @method textIterBackwardCursorPositions@ Move @ref type TextIter@ backwards\n-- by @ref arg n@ cursor positions.\n--\n-- * Returns True if @ref type TextIter@ moved and points to a character (not\n-- to an object).\n--\ntextIterBackwardCursorPositions :: TextIter -> Int -> IO Bool\ntextIterBackwardCursorPositions ti n = liftM toBool $ \n {#call unsafe text_iter_backward_cursor_positions#} ti (fromIntegral n)\n\n\n-- @method textIterForwardSentenceEnds@ Move @ref type TextIter@ forwards by\n-- @ref arg n@ sentence ends.\n--\n-- * Retuns True if the iterator is pointing to a new sentence end.\n--\ntextIterForwardSentenceEnds :: TextIter -> Int -> IO Bool\ntextIterForwardSentenceEnds ti n = liftM toBool $ \n {#call unsafe text_iter_forward_sentence_ends#} ti (fromIntegral n)\n\n-- @method textIterBackwardSentenceStarts@ Move @ref type TextIter@ backwards\n-- by @ref arg n@ sentence beginnings.\n--\n-- * Retuns True if the iterator is pointing to a new sentence start.\n--\ntextIterBackwardSentenceStarts :: TextIter -> Int -> IO Bool\ntextIterBackwardSentenceStarts ti n = liftM toBool $ \n {#call unsafe text_iter_backward_sentence_starts#} ti (fromIntegral n)\n\n-- @method textIterForwardSentenceEnd@ Move @ref type TextIter@ forwards to\n-- the next sentence end.\n--\n-- * Retuns True if the iterator has moved to a new sentence end.\n--\ntextIterForwardSentenceEnd :: TextIter -> IO Bool\ntextIterForwardSentenceEnd ti = liftM toBool $ \n {#call unsafe text_iter_forward_sentence_end#} ti\n\n-- @method textIterBackwardSentenceStart@ Move @ref type TextIter@ backwards\n-- to the next sentence beginning.\n--\n-- * Retuns True if the iterator has moved to a new sentence beginning.\n--\ntextIterBackwardSentenceStart :: TextIter -> IO Bool\ntextIterBackwardSentenceStart ti = liftM toBool $ \n {#call unsafe text_iter_backward_sentence_start#} ti\n\n-- @method textIterSetOffset@ Set @ref type TextIter@ to an offset within the\n-- buffer.\n--\ntextIterSetOffset :: TextIter -> Int -> IO ()\ntextIterSetOffset ti n = \n {#call unsafe text_iter_set_offset#} ti (fromIntegral n)\n\n-- @method textIterSetLine@ Set @ref type TextIter@ to a line within the\n-- buffer.\n--\ntextIterSetLine :: TextIter -> Int -> IO ()\ntextIterSetLine ti n = \n {#call unsafe text_iter_set_line#} ti (fromIntegral n)\n\n-- @method textIterSetLineOffset@ Set @ref type TextIter@ to an offset within\n-- the line.\n--\ntextIterSetLineOffset :: TextIter -> Int -> IO ()\ntextIterSetLineOffset ti n = \n {#call unsafe text_iter_set_line_offset#} ti (fromIntegral n)\n\n-- @method textIterSetVisibleLineOffset@ Set @ref type TextIter@ to an visible\n-- character within the line.\n--\ntextIterSetVisibleLineOffset :: TextIter -> Int -> IO ()\ntextIterSetVisibleLineOffset ti n = \n {#call unsafe text_iter_set_visible_line_offset#} ti (fromIntegral n)\n\n-- @method textIterForwardToEnd@ Moves @ref type TextIter@ to the end of the\n-- buffer.\n--\ntextIterForwardToEnd :: TextIter -> IO ()\ntextIterForwardToEnd ti = {#call unsafe text_iter_forward_to_end#} ti\n\n-- @method textIterForwardToLineEnd@ Moves @ref type TextIter@ to the end of\n-- the line.\n--\n-- * Returns True if @ref type TextIter@ moved to a new location which is not\n-- the buffer end iterator.\n--\ntextIterForwardToLineEnd :: TextIter -> IO Bool\ntextIterForwardToLineEnd ti = liftM toBool $\n {#call unsafe text_iter_forward_to_line_end#} ti\n\n-- @method textIterForwardToTagToggle@ Moves @ref type TextIter@ forward to\n-- the next change of a @ref type TextTag@.\n--\n-- * If Nothing is supplied, any @ref type TextTag@ will be matched.\n--\n-- * Returns True if there was a tag toggle after @ref type TextIter@.\n--\ntextIterForwardToTagToggle :: TextIter -> Maybe TextTag -> IO Bool\ntextIterForwardToTagToggle ti tt = liftM toBool $\n {#call unsafe text_iter_forward_to_tag_toggle#} ti \n (fromMaybe (mkTextTag nullForeignPtr) tt)\n\n-- @method textIterBackwardToTagToggle@ Moves @ref type TextIter@ backward to\n-- the next change of a @ref type TextTag@.\n--\n-- * If Nothing is supplied, any @ref type TextTag@ will be matched.\n--\n-- * Returns True if there was a tag toggle before @ref type TextIter@.\n--\ntextIterBackwardToTagToggle :: TextIter -> Maybe TextTag -> IO Bool\ntextIterBackwardToTagToggle ti tt = liftM toBool $\n {#call unsafe text_iter_backward_to_tag_toggle#} ti \n (fromMaybe (mkTextTag nullForeignPtr) tt)\n\n-- Setup a callback for a predicate function.\n--\ntype TextCharPredicateCB = Char -> Bool\n\n{#pointer TextCharPredicate#}\n\nforeign export dynamic mkTextCharPredicate ::\n ({#type gunichar#} -> Ptr () -> {#type gboolean#}) -> IO TextCharPredicate\n\n-- @method textIterForwardFindChar@ Move @ref type TextIter@ forward until a\n-- predicate function returns True.\n--\n-- * If @ref arg pred@ returns True before @ref arg limit@ is reached, the\n-- search is stopped and the return value is True.\n--\n-- * If @ref arg limit@ is Nothing, the search stops at the end of the buffer.\n--\ntextIterForwardFindChar :: TextIter -> (Char -> Bool) -> Maybe TextIter ->\n IO Bool\ntextIterForwardFindChar ti pred limit = do\n fPtr <- mkTextCharPredicate (\\c _ -> fromBool $ pred (chr (fromIntegral c)))\n res <- liftM toBool $ {#call text_iter_forward_find_char#} \n ti fPtr nullPtr (fromMaybe (TextIter nullForeignPtr) limit)\n freeHaskellFunPtr fPtr\n return res\n\n-- @method textIterBackwardFindChar@ Move @ref type TextIter@ backward until a\n-- predicate function returns True.\n--\n-- * If @ref arg pred@ returns True before @ref arg limit@ is reached, the\n-- search is stopped and the return value is True.\n--\n-- * If @ref arg limit@ is Nothing, the search stops at the end of the buffer.\n--\ntextIterBackwardFindChar :: TextIter -> (Char -> Bool) -> Maybe TextIter ->\n IO Bool\ntextIterBackwardFindChar ti pred limit = do\n fPtr <- mkTextCharPredicate (\\c _ -> fromBool $ pred (chr (fromIntegral c)))\n res <- liftM toBool $ {#call text_iter_backward_find_char#} \n ti fPtr nullPtr (fromMaybe (TextIter nullForeignPtr) limit)\n freeHaskellFunPtr fPtr\n return res\n\n-- @method textIterForwardSearch@ Search forward for a specific string.\n--\n-- * If specified, the last character which is tested against that start of\n-- the search pattern will be @ref arg limit@.\n--\n-- * @ref type TextSearchFlags@ may be empty.\n--\n-- * Returns the start and end position of the string found.\n--\ntextIterForwardSearch :: TextIter -> String -> [TextSearchFlags] ->\n Maybe TextIter -> IO (Maybe (TextIter, TextIter))\ntextIterForwardSearch ti str flags limit = do\n start <- makeEmptyTextIter\n end <- makeEmptyTextIter\n found <- liftM toBool $ withCString str $ \\cStr ->\n {#call unsafe text_iter_forward_search#} ti cStr \n ((fromIntegral.fromFlags) flags) start end \n (fromMaybe (TextIter nullForeignPtr) limit)\n return $ if found then Just (start,end) else Nothing\n\n-- @method textIterBackwardSearch@ Search backward for a specific string.\n--\n-- * If specified, the last character which is tested against that start of\n-- the search pattern will be @ref arg limit@.\n--\n-- * @ref type TextSearchFlags@ my be empty.\n--\n-- * Returns the start and end position of the string found.\n--\ntextIterBackwardSearch :: TextIter -> String -> [TextSearchFlags] ->\n Maybe TextIter -> IO (Maybe (TextIter, TextIter))\ntextIterBackwardSearch ti str flags limit = do\n start <- makeEmptyTextIter\n end <- makeEmptyTextIter\n found <- liftM toBool $ withCString str $ \\cStr ->\n {#call unsafe text_iter_backward_search#} ti cStr \n ((fromIntegral.fromFlags) flags) start end \n (fromMaybe (TextIter nullForeignPtr) limit)\n return $ if found then Just (start,end) else Nothing\n\n-- @method textIterEqual@ Compare two @ref type TextIter@ for equality.\n--\n-- * @ref type TextIter@ could be in class Eq and Ord if there is a guarantee\n-- that each iterator is copied before it is modified in place. This is done\n-- the next abstraction layer.\n--\ntextIterEqual :: TextIter -> TextIter -> IO Bool\ntextIterEqual ti2 ti1 = liftM toBool $ {#call unsafe text_iter_equal#} ti1 ti2\n\n-- @method textIterCompare@ Compare two @ref type TextIter@.\n--\n-- * @ref type TextIter@ could be in class Eq and Ord if there is a guarantee\n-- that each iterator is copied before it is modified in place. This could\n-- be done the next abstraction layer.\n--\ntextIterCompare :: TextIter -> TextIter -> IO Ordering\ntextIterCompare ti2 ti1 = do\n res <- {#call unsafe text_iter_compare#} ti1 ti2\n return $ case res of\n (-1) -> LT\n 0\t -> EQ\n 1\t -> GT\n\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"9f53dd58db590465a4766c300774ed1d24908a35","subject":"refs #11: add context properties","message":"refs #11: add context properties\n","repos":"IFCA\/opencl,IFCA\/opencl,Delan90\/opencl,Delan90\/opencl","old_file":"src\/Control\/Parallel\/OpenCL\/Context.chs","new_file":"src\/Control\/Parallel\/OpenCL\/Context.chs","new_contents":"{- Copyright (c) 2011 Luis Cabellos,\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided\n with the distribution.\n\n * Neither the name of nor the names of other\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables, CPP #-}\nmodule Control.Parallel.OpenCL.Context(\n -- * Types\n CLContext, CLContextProperty(..),\n -- * Context Functions\n clCreateContext, clCreateContextFromType, clRetainContext, clReleaseContext,\n clGetContextReferenceCount, clGetContextDevices, clGetContextProperties )\n where\n\n-- -----------------------------------------------------------------------------\nimport Foreign( \n Ptr, FunPtr, nullPtr, castPtr, alloca, allocaArray, peek, peekArray, \n ptrToIntPtr, intPtrToPtr, withArray )\nimport Foreign.C.Types( CSize )\nimport Foreign.C.String( CString, peekCString )\nimport Foreign.Storable( sizeOf )\nimport Control.Parallel.OpenCL.Types( \n CLuint, CLint, CLDeviceType_, CLContextInfo_, CLContextProperty_, CLDeviceID, \n CLContext, CLDeviceType, CLPlatformID, bitmaskFromFlags, getCLValue, getEnumCL,\n whenSuccess, wrapCheckSuccess, wrapPError, wrapGetInfo )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\ntype ContextCallback = CString -> Ptr () -> CSize -> Ptr () -> IO ()\nforeign import CALLCONV \"wrapper\" wrapContextCallback :: \n ContextCallback -> IO (FunPtr ContextCallback)\nforeign import CALLCONV \"clCreateContext\" raw_clCreateContext ::\n Ptr CLContextProperty_ -> CLuint -> Ptr CLDeviceID -> FunPtr ContextCallback -> \n Ptr () -> Ptr CLint -> IO CLContext\nforeign import CALLCONV \"clCreateContextFromType\" raw_clCreateContextFromType :: \n Ptr CLContextProperty_ -> CLDeviceType_ -> FunPtr ContextCallback -> \n Ptr () -> Ptr CLint -> IO CLContext\nforeign import CALLCONV \"clRetainContext\" raw_clRetainContext :: \n CLContext -> IO CLint\nforeign import CALLCONV \"clReleaseContext\" raw_clReleaseContext :: \n CLContext -> IO CLint\nforeign import CALLCONV \"clGetContextInfo\" raw_clGetContextInfo :: \n CLContext -> CLContextInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLContextProperties {\n cL_CONTEXT_PLATFORM_=CL_CONTEXT_PLATFORM,\n };\n#endc\n{#enum CLContextProperties {upcaseFirstLetter} #}\n\n-- | Specifies a context property name and its corresponding value.\ndata CLContextProperty = CL_CONTEXT_PLATFORM CLPlatformID \n -- ^ Specifies the platform to use.\n deriving( Show )\n\npackContextProperties :: [CLContextProperty] -> [CLContextProperty_]\npackContextProperties [] = [0]\npackContextProperties (CL_CONTEXT_PLATFORM pid : xs) = getCLValue CL_CONTEXT_PLATFORM_ \n : (fromIntegral . ptrToIntPtr $ pid) \n : packContextProperties xs\n\nunpackContextProperties :: [CLContextProperty_] -> [CLContextProperty]\nunpackContextProperties [] = error \"non-exhaustive Context Property list\"\nunpackContextProperties [x] \n | x == 0 = []\n | otherwise = error \"non-exhaustive Context Property list\"\nunpackContextProperties (x:y:xs) = let ys = unpackContextProperties xs \n in case getEnumCL x of\n CL_CONTEXT_PLATFORM_ \n -> CL_CONTEXT_PLATFORM \n (intPtrToPtr . fromIntegral $ y) : ys\n \n-- -----------------------------------------------------------------------------\nmkContextCallback :: (String -> IO ()) -> ContextCallback\nmkContextCallback f msg _ _ _ = peekCString msg >>= f\n\n-- | Creates an OpenCL context.\n-- An OpenCL context is created with one or more devices. Contexts are used by \n-- the OpenCL runtime for managing objects such as command-queues, memory, \n-- program and kernel objects and for executing kernels on one or more devices \n-- specified in the context.\nclCreateContext :: [CLContextProperty] -> [CLDeviceID] -> (String -> IO ()) \n -> IO CLContext\nclCreateContext [] devs f = withArray devs $ \\pdevs ->\n wrapPError $ \\perr -> do\n fptr <- wrapContextCallback $ mkContextCallback f\n raw_clCreateContext nullPtr cndevs pdevs fptr nullPtr perr\n where\n cndevs = fromIntegral . length $ devs\nclCreateContext props devs f = withArray devs $ \\pdevs ->\n wrapPError $ \\perr -> do\n fptr <- wrapContextCallback $ mkContextCallback f\n withArray (packContextProperties props) $ \\pprops ->\n raw_clCreateContext pprops cndevs pdevs fptr nullPtr perr \n where\n cndevs = fromIntegral . length $ devs\n\n-- | Create an OpenCL context from a device type that identifies the specific \n-- device(s) to use.\nclCreateContextFromType :: [CLContextProperty] -> [CLDeviceType] \n -> (String -> IO ()) -> IO CLContext\nclCreateContextFromType [] xs f = wrapPError $ \\perr -> do\n fptr <- wrapContextCallback $ mkContextCallback f\n raw_clCreateContextFromType nullPtr types fptr nullPtr perr\n where\n types = bitmaskFromFlags xs\nclCreateContextFromType props xs f = wrapPError $ \\perr -> do\n fptr <- wrapContextCallback $ mkContextCallback f\n withArray (packContextProperties props) $ \\pprops -> \n raw_clCreateContextFromType pprops types fptr nullPtr perr\n where\n types = bitmaskFromFlags xs\n\n-- | Increment the context reference count.\n-- 'clCreateContext' and 'clCreateContextFromType' perform an implicit retain. \n-- This is very helpful for 3rd party libraries, which typically get a context \n-- passed to them by the application. However, it is possible that the \n-- application may delete the context without informing the library. Allowing \n-- functions to attach to (i.e. retain) and release a context solves the \n-- problem of a context being used by a library no longer being valid.\n-- Returns 'True' if the function is executed successfully, or 'False' if \n-- context is not a valid OpenCL context.\nclRetainContext :: CLContext -> IO Bool\nclRetainContext ctx = wrapCheckSuccess $ raw_clRetainContext ctx \n\n-- | Decrement the context reference count.\n-- After the context reference count becomes zero and all the objects attached \n-- to context (such as memory objects, command-queues) are released, the \n-- context is deleted.\n-- Returns 'True' if the function is executed successfully, or 'False' if \n-- context is not a valid OpenCL context.\nclReleaseContext :: CLContext -> IO Bool\nclReleaseContext ctx = wrapCheckSuccess $ raw_clReleaseContext ctx \n\ngetContextInfoSize :: CLContext -> CLContextInfo_ -> IO CSize\ngetContextInfoSize ctx infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n whenSuccess (raw_clGetContextInfo ctx infoid 0 nullPtr value_size)\n $ peek value_size\n\n#c\nenum CLContextInfo {\n cL_CONTEXT_REFERENCE_COUNT=CL_CONTEXT_REFERENCE_COUNT,\n cL_CONTEXT_DEVICES=CL_CONTEXT_DEVICES,\n cL_CONTEXT_PROPERTIES=CL_CONTEXT_PROPERTIES\n };\n#endc\n{#enum CLContextInfo {upcaseFirstLetter} #}\n\n-- | Return the context reference count. The reference count returned should be \n-- considered immediately stale. It is unsuitable for general use in \n-- applications. This feature is provided for identifying memory leaks.\n--\n-- This function execute OpenCL clGetContextInfo with 'CL_CONTEXT_REFERENCE_COUNT'.\nclGetContextReferenceCount :: CLContext -> IO CLuint\nclGetContextReferenceCount ctx =\n wrapGetInfo (\\(dat :: Ptr CLuint) ->\n raw_clGetContextInfo ctx infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_CONTEXT_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the list of devices in context.\n--\n-- This function execute OpenCL clGetContextInfo with 'CL_CONTEXT_DEVICES'.\nclGetContextDevices :: CLContext -> IO [CLDeviceID]\nclGetContextDevices ctx = do\n size <- getContextInfoSize ctx infoid\n let n = (fromIntegral size) `div` elemSize \n \n allocaArray n $ \\(buff :: Ptr CLDeviceID) -> do\n whenSuccess (raw_clGetContextInfo ctx infoid size (castPtr buff) nullPtr)\n $ peekArray n buff\n where\n infoid = getCLValue CL_CONTEXT_DEVICES\n elemSize = sizeOf (nullPtr :: CLDeviceID)\n\nclGetContextProperties :: CLContext -> IO [CLContextProperty]\nclGetContextProperties ctx = do\n size <- getContextInfoSize ctx infoid\n let n = (fromIntegral size) `div` elemSize \n \n if n == 0 \n then return []\n else allocaArray n $ \\(buff :: Ptr CLContextProperty_) ->\n whenSuccess (raw_clGetContextInfo ctx infoid size (castPtr buff) nullPtr)\n $ fmap unpackContextProperties $ peekArray n buff\n where\n infoid = getCLValue CL_CONTEXT_PROPERTIES\n elemSize = sizeOf (nullPtr :: CLDeviceID)\n \n-- -----------------------------------------------------------------------------\n","old_contents":"{- Copyright (c) 2011 Luis Cabellos,\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided\n with the distribution.\n\n * Neither the name of nor the names of other\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables, CPP #-}\nmodule Control.Parallel.OpenCL.Context(\n -- * Types\n CLContext,\n -- * Context Functions\n clCreateContext, clCreateContextFromType, clRetainContext, clReleaseContext,\n clGetContextReferenceCount, clGetContextDevices )\n where\n\n-- -----------------------------------------------------------------------------\nimport Foreign( \n Ptr, FunPtr, nullPtr, castPtr, alloca, allocaArray, peek, peekArray, \n pokeArray )\nimport Foreign.C.Types( CSize )\nimport Foreign.C.String( CString, peekCString )\nimport Foreign.Storable( sizeOf )\nimport Control.Parallel.OpenCL.Types( \n CLuint, CLint, CLDeviceType_, CLContextInfo_, CLContextProperty_, CLDeviceID, \n CLContext, CLDeviceType, bitmaskFromFlags, getCLValue,\n whenSuccess, wrapCheckSuccess, wrapPError, wrapGetInfo )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\ntype ContextCallback = CString -> Ptr () -> CSize -> Ptr () -> IO ()\nforeign import CALLCONV \"wrapper\" wrapContextCallback :: \n ContextCallback -> IO (FunPtr ContextCallback)\nforeign import CALLCONV \"clCreateContext\" raw_clCreateContext ::\n Ptr CLContextProperty_ -> CLuint -> Ptr CLDeviceID -> FunPtr ContextCallback -> \n Ptr () -> Ptr CLint -> IO CLContext\nforeign import CALLCONV \"clCreateContextFromType\" raw_clCreateContextFromType :: \n Ptr CLContextProperty_ -> CLDeviceType_ -> FunPtr ContextCallback -> \n Ptr () -> Ptr CLint -> IO CLContext\nforeign import CALLCONV \"clRetainContext\" raw_clRetainContext :: \n CLContext -> IO CLint\nforeign import CALLCONV \"clReleaseContext\" raw_clReleaseContext :: \n CLContext -> IO CLint\nforeign import CALLCONV \"clGetContextInfo\" raw_clGetContextInfo :: \n CLContext -> CLContextInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\nmkContextCallback :: (String -> IO ()) -> ContextCallback\nmkContextCallback f msg _ _ _ = peekCString msg >>= f\n\n-- | Creates an OpenCL context.\n-- An OpenCL context is created with one or more devices. Contexts are used by \n-- the OpenCL runtime for managing objects such as command-queues, memory, \n-- program and kernel objects and for executing kernels on one or more devices \n-- specified in the context.\nclCreateContext :: [CLDeviceID] -> (String -> IO ()) -> IO CLContext\nclCreateContext devs f = allocaArray ndevs $ \\pdevs -> do\n pokeArray pdevs devs\n wrapPError $ \\perr -> do\n fptr <- wrapContextCallback $ mkContextCallback f\n raw_clCreateContext nullPtr cndevs pdevs fptr nullPtr perr\n where\n ndevs = length devs\n cndevs = fromIntegral ndevs\n\n-- | Create an OpenCL context from a device type that identifies the specific \n-- device(s) to use.\nclCreateContextFromType :: [CLDeviceType] -> (String -> IO ()) \n -> IO CLContext\nclCreateContextFromType xs f = wrapPError $ \\perr -> do\n fptr <- wrapContextCallback $ mkContextCallback f\n raw_clCreateContextFromType nullPtr types fptr nullPtr perr\n where\n types = bitmaskFromFlags xs\n\n-- | Increment the context reference count.\n-- 'clCreateContext' and 'clCreateContextFromType' perform an implicit retain. \n-- This is very helpful for 3rd party libraries, which typically get a context \n-- passed to them by the application. However, it is possible that the \n-- application may delete the context without informing the library. Allowing \n-- functions to attach to (i.e. retain) and release a context solves the \n-- problem of a context being used by a library no longer being valid.\n-- Returns 'True' if the function is executed successfully, or 'False' if \n-- context is not a valid OpenCL context.\nclRetainContext :: CLContext -> IO Bool\nclRetainContext ctx = wrapCheckSuccess $ raw_clRetainContext ctx \n\n-- | Decrement the context reference count.\n-- After the context reference count becomes zero and all the objects attached \n-- to context (such as memory objects, command-queues) are released, the \n-- context is deleted.\n-- Returns 'True' if the function is executed successfully, or 'False' if \n-- context is not a valid OpenCL context.\nclReleaseContext :: CLContext -> IO Bool\nclReleaseContext ctx = wrapCheckSuccess $ raw_clReleaseContext ctx \n\ngetContextInfoSize :: CLContext -> CLContextInfo_ -> IO CSize\ngetContextInfoSize ctx infoid = alloca $ \\(value_size :: Ptr CSize) -> do\n whenSuccess (raw_clGetContextInfo ctx infoid 0 nullPtr value_size)\n $ peek value_size\n\n#c\nenum CLContextInfo {\n cL_CONTEXT_REFERENCE_COUNT=CL_CONTEXT_REFERENCE_COUNT,\n cL_CONTEXT_DEVICES=CL_CONTEXT_DEVICES,\n cL_CONTEXT_PROPERTIES=CL_CONTEXT_PROPERTIES\n };\n#endc\n{#enum CLContextInfo {upcaseFirstLetter} #}\n\n-- | Return the context reference count. The reference count returned should be \n-- considered immediately stale. It is unsuitable for general use in \n-- applications. This feature is provided for identifying memory leaks.\n--\n-- This function execute OpenCL clGetContextInfo with 'CL_CONTEXT_REFERENCE_COUNT'.\nclGetContextReferenceCount :: CLContext -> IO CLuint\nclGetContextReferenceCount ctx =\n wrapGetInfo (\\(dat :: Ptr CLuint) ->\n raw_clGetContextInfo ctx infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_CONTEXT_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n-- | Return the list of devices in context.\n--\n-- This function execute OpenCL clGetContextInfo with 'CL_CONTEXT_DEVICES'.\nclGetContextDevices :: CLContext -> IO [CLDeviceID]\nclGetContextDevices ctx = do\n size <- getContextInfoSize ctx infoid\n let n = (fromIntegral size) `div` elemSize \n \n allocaArray n $ \\(buff :: Ptr CLDeviceID) -> do\n whenSuccess (raw_clGetContextInfo ctx infoid size (castPtr buff) nullPtr)\n $ peekArray n buff\n where\n infoid = getCLValue CL_CONTEXT_DEVICES\n elemSize = sizeOf (nullPtr :: CLDeviceID)\n\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"71d48da2e3169585eef8e048b81339ee7b5a6414","subject":"Make the TreeList\/Types module work with haddock","message":"Make the TreeList\/Types module work with haddock","repos":"vincenthz\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/TreeList\/Types.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/TreeList\/Types.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) CustomStore TreeModel\n--\n-- Author : Duncan Coutts\n--\n-- Created: 31 March 2006\n--\n-- Copyright (C) 2006 Duncan Coutts\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Common types and classes for the TreeList modules.\n--\nmodule Graphics.UI.Gtk.TreeList.Types (\n TypedTreeModel(..),\n TypedTreeModelClass,\n toTypedTreeModel,\n ) where\n\nimport GHC.Exts (unsafeCoerce#)\n\nimport System.Glib.FFI\n{#import Graphics.UI.Gtk.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\nnewtype TypedTreeModel row = TypedTreeModel (ForeignPtr (TypedTreeModel row))\n\nclass TypedTreeModelClass model where\n dummy :: model a -> a\n -- this is to get the right kind for model :: * -> *\n -- TODO: when haddock is fixed we can use an explicit kind annotation\n\ntoTypedTreeModel :: TypedTreeModelClass model => model row -> TypedTreeModel row\ntoTypedTreeModel = unsafeCoerce#\n\ninstance TypedTreeModelClass TypedTreeModel\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) CustomStore TreeModel\n--\n-- Author : Duncan Coutts\n--\n-- Created: 31 March 2006\n--\n-- Copyright (C) 2006 Duncan Coutts\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Common types and classes for the TreeList modules.\n--\nmodule Graphics.UI.Gtk.TreeList.Types (\n TypedTreeModel(..),\n TypedTreeModelClass,\n toTypedTreeModel,\n ) where\n\nimport GHC.Exts (unsafeCoerce#)\n\nimport System.Glib.FFI\n{#import Graphics.UI.Gtk.Types#}\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\nnewtype TypedTreeModel row = TypedTreeModel (ForeignPtr (TypedTreeModel row))\n\nclass TypedTreeModelClass (model :: * -> *) where\ntoTypedTreeModel :: TypedTreeModelClass model => model row -> TypedTreeModel row\ntoTypedTreeModel = unsafeCoerce#\n\ninstance TypedTreeModelClass TypedTreeModel\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"6092dac833ba1a5759777415ee7a86e6d7aaf0a5","subject":"[project @ 2004-05-20 16:53:58 by duncan_coutts] haddock fix","message":"[project @ 2004-05-20 16:53:58 by duncan_coutts]\nhaddock fix\n","repos":"vincenthz\/webkit","old_file":"gtk\/gdk\/Pixbuf.chs","new_file":"gtk\/gdk\/Pixbuf.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Pixbuf@\n--\n-- Author : Vincenzo Ciancia, Axel Simon\n-- Created: 26 March 2002\n--\n-- Version $Revision: 1.6 $ from $Date: 2004\/05\/20 16:53:58 $\n--\n-- Copyright (c) 2002 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Library General Public\n-- License as published by the Free Software Foundation; either\n-- version 2 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Library General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- @ref data Pixbuf@s are bitmap images in memory.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * A Pixbuf is used to represent images. It contains information\n-- about the image's pixel data, its color space, bits per sample, width\n-- and height, and the rowstride or number of bytes between rows.\n--\n-- * This module contains functions to scale and crop\n-- @ref data Pixbuf@s and to scale and crop a @ref data Pixbuf@ and \n-- compose the result with an existing image.\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * if there is a portable way of modifying external arrays in Haskell do:\n--\tgdk_pixbuf_get_pixels, gdk_pixbuf_new_from_data, everything in\n--\tInline data, \n--\n-- * if anybody writes an image manipulation program, do the checker board\n-- functions: gdk_pixbuf_composite_color_simple and\n-- gdk_pixbuf_composite_color. Moreover, do: pixbuf_saturate_and_pixelate\n--\n-- * the animation functions\n--\n-- * pixbuf loader\n--\n-- * module interface\n--\n-- * rendering function for Bitmaps and Pixmaps when the latter are added\n--\nmodule Pixbuf(\n Pixbuf,\n PixbufClass,\n PixbufError(..),\n Colorspace(..),\n pixbufGetColorSpace,\n pixbufGetNChannels,\n pixbufGetHasAlpha,\n pixbufGetBitsPerSample,\n pixbufGetWidth,\n pixbufGetHeight,\n pixbufGetRowstride,\n pixbufGetOption,\n pixbufNewFromFile,\n ImageType,\n pixbufGetFormats,\n pixbufSave,\n pixbufNew,\n pixbufNewFromXPMData,\n InlineImage,\n pixbufNewFromInline,\n pixbufNewSubpixbuf,\n pixbufCopy,\n InterpType(..),\n pixbufScaleSimple,\n pixbufScale,\n pixbufComposite,\n pixbufAddAlpha,\n pixbufCopyArea,\n pixbufFill,\n pixbufGetFromDrawable\n ) where\n\nimport FFI\n{#import Hierarchy#}\nimport GObject\nimport Monad\n\nimport Structs\t\t(GError(..), GQuark, Rectangle(..))\nimport LocalData\t(unsafePerformIO)\nimport Exception\t(bracket)\nimport LocalData\t((.|.), shiftL)\n\n{#context prefix=\"gdk\" #}\n\n-- @data PixbufError@ Error codes for loading image files.\n--\n{#enum PixbufError {underscoreToCase} #}\n\n\n-- @data Colorspace@ Enumerate all supported color spaces.\n--\n-- * Only RGB is supported right now.\n--\n{#enum Colorspace {underscoreToCase} #}\n\n-- @method pixbufGetColorSpace@ Queries the color space of a pixbuf.\n--\npixbufGetColorSpace :: Pixbuf -> IO Colorspace\npixbufGetColorSpace pb = liftM (toEnum . fromIntegral) $\n {#call unsafe pixbuf_get_colorspace#} pb\n\n-- @method pixbufGetNChannels@ Queries the number of colors for each pixel.\n--\npixbufGetNChannels :: Pixbuf -> IO Int\npixbufGetNChannels pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_n_channels#} pb\n\n-- @method pixbufGetHasAlpha@ Query if the image has an alpha channel.\n--\n-- * The alpha channel determines the opaqueness of the pixel.\n--\npixbufGetHasAlpha :: Pixbuf -> IO Bool\npixbufGetHasAlpha pb =\n liftM toBool $ {#call unsafe pixbuf_get_has_alpha#} pb\n\n-- @method pixbufGetBitsPerSample@ Queries the number of bits for each color.\n--\n-- * Each pixel is has a number of cannels for each pixel, each channel\n-- has this many bits.\n--\npixbufGetBitsPerSample :: Pixbuf -> IO Int\npixbufGetBitsPerSample pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_bits_per_sample#} pb\n\n-- @method pixbufGetWidth@ Queries the width of this image.\n--\npixbufGetWidth :: Pixbuf -> IO Int\npixbufGetWidth pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_width#} pb\n\n-- @method pixbufGetHeight@ Queries the height of this image.\n--\npixbufGetHeight :: Pixbuf -> IO Int\npixbufGetHeight pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_height#} pb\n\n-- @method pixbufGetRowstride@ Queries the rowstride of this image.\n--\n-- * Queries the rowstride of a pixbuf, which is the number of bytes between\n-- rows. Use this value to caculate the offset to a certain row.\n--\npixbufGetRowstride :: Pixbuf -> IO Int\npixbufGetRowstride pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_rowstride#} pb\n\n-- @method pixbufGetOption@ Returns an attribut of an image.\n--\n-- * Looks up if some information was stored under the @ref arg key@ when\n-- this image was saved.\n--\npixbufGetOption :: Pixbuf -> String -> IO (Maybe String)\npixbufGetOption pb key = withUTFString key $ \\strPtr -> do\n resPtr <- {#call unsafe pixbuf_get_option#} pb strPtr\n if (resPtr==nullPtr) then return Nothing else\n liftM Just $ peekUTFString resPtr\n\n-- pixbufErrorDomain -- helper function\npixbufErrorDomain :: GQuark\npixbufErrorDomain = unsafePerformIO {#call unsafe pixbuf_error_quark#}\n\n-- @constructor pixbufNewFromFile@ Load an image synchonously.\n--\n-- * Use this function to load only small images as this call will block.\n--\n-- * The function will return @literal Left (err,msg)@ where @ref arg err@\n-- is the error code and @ref arg msg@ is a human readable description\n-- of the error. If an error occurs which is not captured by any of\n-- those in @ref data PixbufError@, an exception is thrown.\n--\npixbufNewFromFile :: FilePath -> IO (Either (PixbufError,String) Pixbuf)\npixbufNewFromFile fname = withUTFString fname $ \\strPtr ->\n alloca $ \\errPtrPtr -> do\n pbPtr <- {#call unsafe pixbuf_new_from_file#} strPtr (castPtr errPtrPtr)\n if pbPtr\/=nullPtr then liftM Right $ makeNewGObject mkPixbuf (return pbPtr)\n else do\n errPtr <- peek errPtrPtr\n (GError dom code msg) <- peek errPtr\n if dom==pixbufErrorDomain then\n return (Left (toEnum (fromIntegral code), msg))\n else\n\terror msg\n\n-- @type ImageType@ A string representing an image file format.\n--\ntype ImageType = String\n\n-- @constant pixbufGetFormats@ A list of valid image file formats.\n--\npixbufGetFormats :: [ImageType]\n\npixbufGetFormats = [\"png\",\"bmp\",\"wbmp\", \"gif\",\"ico\",\"ani\",\"jpeg\",\"pnm\",\n\t\t \"ras\",\"tiff\",\"xpm\",\"xbm\",\"tga\"]\n\n-- @method pixbufSave@ Save an image to disk.\n--\n-- * The function takes a list of key - value pairs to specify\n-- either how an image is saved or to actually save this additional\n-- data with the image. JPEG images can be saved with a \"quality\"\n-- parameter; its value should be in the range [0,100]. Text chunks\n-- can be attached to PNG images by specifying parameters of the form\n-- \"tEXt::key\", where key is an ASCII string of length 1-79.\n-- The values are Unicode strings.\n--\n-- * The function returns @literal Nothing@ if writing was successful.\n-- Otherwise the error code and a description is returned or,\n-- if the error is not captured by one of the error codes in\n-- @ref data PixbufError@, an exception is thrown.\n--\npixbufSave :: Pixbuf -> FilePath -> ImageType -> [(String, String)] ->\n\t IO (Maybe (PixbufError, String))\npixbufSave pb fname iType options =\n let (keys, values) = unzip options in\n let optLen = length keys in\n withUTFString fname $ \\fnPtr ->\n withUTFString iType $ \\tyPtr ->\n allocaArray0 optLen $ \\keysPtr ->\n allocaArray optLen $ \\valuesPtr ->\n alloca $ \\errPtrPtr -> do\n keyPtrs <- mapM newUTFString keys\n valuePtrs <- mapM newUTFString values\n pokeArray keysPtr keyPtrs\n pokeArray valuesPtr valuePtrs\n res <- {#call unsafe pixbuf_savev#} pb fnPtr tyPtr keysPtr valuesPtr\n\t\t\t\t\t(castPtr errPtrPtr)\n mapM_ free keyPtrs\n mapM_ free valuePtrs\n if not (toBool res) then return Nothing else do\n errPtr <- peek errPtrPtr\n (GError dom code msg) <- peek errPtr\n if dom==pixbufErrorDomain then\n return (Just (toEnum (fromIntegral code), msg))\n else\n\terror msg\n\n-- @constructor pixbufNew@ Create a new image in memory.\n--\n-- * Creates a new pixbuf structure and allocates a buffer for\n-- it. Note that the buffer is not cleared initially.\n--\npixbufNew :: Colorspace -> Bool -> Int -> Int -> Int -> IO Pixbuf\npixbufNew colorspace hasAlpha bitsPerSample width height =\n makeNewGObject mkPixbuf $ \n {#call pixbuf_new#} ((fromIntegral . fromEnum) colorspace)\n (fromBool hasAlpha) (fromIntegral bitsPerSample) (fromIntegral width)\n (fromIntegral height)\n\n-- @constructor pixbufNewFromXPMData@ Create a new image from a String.\n--\n-- * Creates a new pixbuf from a string description.\n--\npixbufNewFromXPMData :: [String] -> IO Pixbuf\npixbufNewFromXPMData s =\n bracket (mapM newUTFString s) (mapM free) $ \\strPtrs ->\n withArray0 nullPtr strPtrs $ \\strsPtr ->\n makeNewGObject mkPixbuf $ {#call pixbuf_new_from_xpm_data#} strsPtr\n\n-- @data InlineImage@ A dymmy type for inline picture data.\n--\n-- * This dummy type is used to declare pointers to image data\n-- that is embedded in the executable. See\n-- @ref constructor pixbufNewFromInline@ for an example.\n--\ndata InlineImage = InlineImage\n\n-- @constructor pixbufNewFromInline@ Create a new image from a static pointer.\n--\n-- * Like @ref constructor pixbufNewFromXPMData@, this function allows to\n-- include images in the final binary program. The method used by this\n-- function uses a binary representation and therefore needs less space\n-- in the final executable. Save the image you want to include as\n-- @literal png@ and run @prog\n-- echo #include \"my_image.h\" > my_image.c\n-- gdk-pixbuf-csource --raw --extern --name=my_image myimage.png >> my_image.c\n-- @ on it. Write a header file @literal my_image.h@ containing @prog\n-- #include \n-- extern guint8 my_image\\[\\];\n-- @ and save it in the current directory.\n-- The created file can be compiled with @prog\n-- cc -c my_image.c `pkg-config --cflags gdk-2.0`\n-- @ into an object file which must be linked into your Haskell program by\n-- specifying @literal my_image.o@ and @literal \"-#include my_image.h\"@ on\n-- the command line of GHC.\n-- Within you application you delcare a pointer to this image: @prog\n-- foreign label \"my_image\" myImage :: Ptr InlineImage\n-- @ Calling @ref constructor pixbufNewFromInline@ with this pointer will\n-- return the image in the object file. Creating the C file with\n-- the @literal --raw@ flag will result in a non-compressed image in the\n-- object file. The advantage is that the picture will not be\n-- copied when this function is called.\n--\n--\npixbufNewFromInline :: Ptr InlineImage -> IO Pixbuf\npixbufNewFromInline iPtr = alloca $ \\errPtrPtr -> do\n pbPtr <- {#call unsafe pixbuf_new_from_inline#} (-1) (castPtr iPtr)\n (fromBool False) (castPtr errPtrPtr)\n if pbPtr\/=nullPtr then makeNewGObject mkPixbuf (return pbPtr)\n else do\n errPtr <- peek errPtrPtr\n (GError dom code msg) <- peek errPtr\n error msg\n\n-- @method pixbufNewSubpixbuf@ Create a restricted view of an image.\n--\n-- * This function returns a @ref data Pixbuf@ object which shares\n-- the image of the original one but only shows a part of it.\n-- Modifying either buffer will affect the other.\n--\n-- * This function throw an exception if the requested bounds are invalid.\n--\npixbufNewSubpixbuf :: Pixbuf -> Int -> Int -> Int -> Int -> IO Pixbuf\npixbufNewSubpixbuf pb srcX srcY height width =\n makeNewGObject mkPixbuf $ do\n pbPtr <- {#call unsafe pixbuf_new_subpixbuf#} pb\n (fromIntegral srcX) (fromIntegral srcY)\n (fromIntegral height) (fromIntegral width)\n if pbPtr==nullPtr then error \"pixbufNewSubpixbuf: invalid bounds\"\n else return pbPtr\n\n-- @constructor pixbufCopy@ Create a deep copy of an image.\n--\npixbufCopy :: Pixbuf -> IO Pixbuf\npixbufCopy pb = makeNewGObject mkPixbuf $ {#call unsafe pixbuf_copy#} pb\n\n\n-- @data InterpType@ How an image is scaled.\n--\n--\n-- * @variant InterpNearest@ Nearest neighbor sampling; this is the\n-- fastest and lowest quality mode. Quality is normally unacceptable when\n-- scaling down, but may be OK when scaling up.\n--\n-- * @variant InterpTiles@ This is an accurate simulation of the\n-- PostScript image operator without any interpolation enabled. Each\n-- pixel is rendered as a tiny parallelogram of solid color, the edges of\n-- which are implemented with antialiasing. It resembles nearest neighbor\n-- for enlargement, and bilinear for reduction.\n--\n-- * @variant InterpBilinear@ Best quality\/speed balance; use this\n-- mode by default. Bilinear interpolation. For enlargement, it is\n-- equivalent to point-sampling the ideal bilinear-interpolated\n-- image. For reduction, it is equivalent to laying down small tiles and\n-- integrating over the coverage area.\n--\n-- * @variant InterpHyper@ This is the slowest and highest quality\n-- reconstruction function. It is derived from the hyperbolic filters in\n-- Wolberg's \"Digital Image Warping\", and is formally defined as the\n-- hyperbolic-filter sampling the ideal hyperbolic-filter interpolated\n-- image (the filter is designed to be idempotent for 1:1 pixel mapping).\n--\n{#enum InterpType {underscoreToCase} #}\n\n-- @method pixbufScaleSimple@ Scale an image.\n--\n-- * Creates a new @ref data GdkPixbuf@ containing a copy of \n-- @ref arg src@ scaled to the given measures. Leaves @ref arg src@\n-- unaffected. \n--\n-- * @ref arg interp@ affects the quality and speed of the scaling function.\n-- @variant InterpNearest@ is the fastest option but yields very poor\n-- quality when scaling down. @variant InterpBilinear@ is a good\n-- trade-off between speed and quality and should thus be used as a\n-- default.\n--\npixbufScaleSimple :: Pixbuf -> Int -> Int -> InterpType -> IO Pixbuf\npixbufScaleSimple pb width height interp =\n makeNewGObject mkPixbuf $ liftM castPtr $ \n\t{#call pixbuf_scale_simple#} (toPixbuf pb) \n\t(fromIntegral width) (fromIntegral height)\n\t(fromIntegral $ fromEnum interp)\n\n-- @method pixbufScale@ Copy a scaled image part to another image.\n--\n-- * This function is the generic version of @ref method pixbufScaleSimple@.\n-- It scales @ref arg src@ by @ref arg scaleX@ and @ref arg scaleY@ and\n-- translate the image by @ref arg offsetX@ and @ref arg offsetY@. Whatever\n-- is in the intersection with the rectangle @ref arg destX@,\n-- @ref arg destY@, @ref arg destWidth@, @ref arg destHeight@ will be\n-- rendered into @ref arg dest@.\n--\n-- * The rectangle in the destination is simply overwritten. Use\n-- @ref method pixbufComposite@ if you need to blend the source\n-- image onto the destination.\n--\npixbufScale :: Pixbuf -> Pixbuf -> Int -> Int -> Int -> Int ->\n\t Double -> Double -> Double -> Double -> InterpType -> IO ()\npixbufScale src dest destX destY destWidth destHeight offsetX offsetY\n scaleX scaleY interp = {#call unsafe pixbuf_scale#} src dest\n (fromIntegral destX) (fromIntegral destY) (fromIntegral destHeight)\n (fromIntegral destWidth) (realToFrac offsetX) (realToFrac offsetY)\n (realToFrac scaleX) (realToFrac scaleY)\n ((fromIntegral . fromEnum) interp)\n\n-- @method pixbufComposite@ Blend a scaled image part onto another image.\n--\n-- * This function is similar to @ref method pixbufScale@ but allows the\n-- original image to \"shine through\". The @ref arg alpha@ value determines\n-- how opaque the source image is. Passing @literal 0@ is\n-- equivalent to not calling this function at all, passing\n-- @literal 255@ has the\n-- same effect as calling @ref method pixbufScale@.\n--\npixbufComposite :: Pixbuf -> Pixbuf -> Int -> Int -> Int -> Int ->\n\t\t Double -> Double -> Double -> Double -> InterpType ->\n\t \t Word8 -> IO ()\npixbufComposite src dest destX destY destWidth destHeight\n offsetX offsetY scaleX scaleY interp alpha =\n {#call unsafe pixbuf_composite#} src dest\n (fromIntegral destX) (fromIntegral destY) (fromIntegral destHeight)\n (fromIntegral destWidth) (realToFrac offsetX) (realToFrac offsetY)\n (realToFrac scaleX) (realToFrac scaleY)\n ((fromIntegral . fromEnum) interp) (fromIntegral alpha)\n\n-- @method pixbufAddAlpha@ Add an opacity layer to the @ref data Pixbuf@.\n--\n-- * This function returns a copy of the given @ref arg src@\n-- @ref data Pixbuf@, leaving @ref arg src@ unmodified.\n-- The new @ref data Pixbuf@ has an alpha (opacity)\n-- channel which defaults to @literal 255@ (fully opaque pixels)\n-- unless @ref arg src@ already had an alpha channel in which case\n-- the original values are kept.\n-- Passing in a color triple @literal (r,g,b)@ makes all\n-- pixels that have this color fully transparent\n-- (opacity of @literal 0@). The pixel color itself remains unchanged\n-- during this substitution.\n--\npixbufAddAlpha :: Pixbuf -> Maybe (Word8, Word8, Word8) -> IO Pixbuf\npixbufAddAlpha pb Nothing = makeNewGObject mkPixbuf $\n {#call unsafe pixbuf_add_alpha#} pb (fromBool False) 0 0 0\npixbufAddAlpha pb (Just (r,g,b)) = makeNewGObject mkPixbuf $\n {#call unsafe pixbuf_add_alpha#} pb (fromBool True)\n (fromIntegral r) (fromIntegral g) (fromIntegral b)\n\n-- @method pixbufCopyArea@ Copy a rectangular portion into another\n-- @ref data Pixbuf@.\n--\n-- * The source @ref data Pixbuf@ remains unchanged. Converion between\n-- different formats is done automatically.\n--\npixbufCopyArea :: Pixbuf -> Int -> Int -> Int -> Int ->\n\t\t Pixbuf -> Int -> Int -> IO ()\npixbufCopyArea src srcX srcY srcWidth srcHeight dest destX destY =\n {#call unsafe pixbuf_copy_area#} src (fromIntegral srcX)\n (fromIntegral srcY) (fromIntegral srcHeight) (fromIntegral srcWidth)\n dest (fromIntegral destX) (fromIntegral destY)\n\n-- @method pixbufFill@ Fills a @ref data Pixbuf@ with a color.\n--\n-- * The passed-in color is a quadruple consisting of the red, green, blue\n-- and alpha component of the pixel. If the @ref data Pixbuf@ does not\n-- have an alpha channel, the alpha value is ignored.\n--\npixbufFill :: Pixbuf -> Word8 -> Word8 -> Word8 -> Word8 -> IO ()\npixbufFill pb red green blue alpha = {#call unsafe pixbuf_fill#} pb\n ((fromIntegral red) `shiftL` 24 .|.\n (fromIntegral green) `shiftL` 16 .|.\n (fromIntegral blue) `shiftL` 8 .|.\n (fromIntegral alpha))\n\n-- @method pixbufGetFromDrawable@ Take a screenshot of a @ref data Drawable@.\n--\n-- * This function creates a @ref data Pixbuf@ and fills it with the image\n-- currently in the @ref data Drawable@ (which might be invalid if the\n-- window is obscured or minimized). Note that this transfers data from\n-- the server to the client on X Windows.\n--\n-- * This function will return a @ref data Pixbuf@ with no alpha channel\n-- containing the part of the @ref data Drawable@ specified by the\n-- rectangle. The function will return @literal Nothing@ if the window\n-- is not currently visible.\n--\npixbufGetFromDrawable :: DrawableClass d => d -> Rectangle -> IO (Maybe Pixbuf)\npixbufGetFromDrawable d (Rectangle x y width height) = do\n pbPtr <- {#call unsafe pixbuf_get_from_drawable#} \n (mkPixbuf nullForeignPtr) (toDrawable d) (mkColormap nullForeignPtr)\n (fromIntegral x) (fromIntegral y) 0 0\n (fromIntegral width) (fromIntegral height)\n if pbPtr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkPixbuf (return pbPtr)\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Pixbuf@\n--\n-- Author : Vincenzo Ciancia, Axel Simon\n-- Created: 26 March 2002\n--\n-- Version $Revision: 1.5 $ from $Date: 2003\/07\/09 22:42:44 $\n--\n-- Copyright (c) 2002 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Library General Public\n-- License as published by the Free Software Foundation; either\n-- version 2 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Library General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- @ref data Pixbuf@s are bitmap images in memory.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n-- * A Pixbuf is used to represent images. It contains information\n-- about the image's pixel data, its color space, bits per sample, width\n-- and height, and the rowstride or number of bytes between rows.\n--\n-- * This module contains functions to scale and crop\n-- @ref data Pixbuf@s and to scale and crop a @ref data Pixbuf@ and \n-- compose the result with an existing image.\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n-- * if there is a portable way of modifying external arrays in Haskell do:\n--\tgdk_pixbuf_get_pixels, gdk_pixbuf_new_from_data, everything in\n--\tInline data, \n--\n-- * if anybody writes an image manipulation program, do the checker board\n-- functions: gdk_pixbuf_composite_color_simple and\n-- gdk_pixbuf_composite_color. Moreover, do: pixbuf_saturate_and_pixelate\n--\n-- * the animation functions\n--\n-- * pixbuf loader\n--\n-- * module interface\n--\n-- * rendering function for Bitmaps and Pixmaps when the latter are added\n--\nmodule Pixbuf(\n Pixbuf,\n PixbufClass,\n PixbufError(..),\n Colorspace(..),\n pixbufGetColorSpace,\n pixbufGetNChannels,\n pixbufGetHasAlpha,\n pixbufGetBitsPerSample,\n pixbufGetWidth,\n pixbufGetHeight,\n pixbufGetRowstride,\n pixbufGetOption,\n pixbufNewFromFile,\n ImageType,\n pixbufGetFormats,\n pixbufSave,\n pixbufNew,\n pixbufNewFromXPMData,\n InlineImage,\n pixbufNewFromInline,\n pixbufNewSubpixbuf,\n pixbufCopy,\n InterpType(..),\n pixbufScaleSimple,\n pixbufScale,\n pixbufComposite,\n pixbufAddAlpha,\n pixbufCopyArea,\n pixbufFill,\n pixbufGetFromDrawable\n ) where\n\nimport FFI\n{#import Hierarchy#}\nimport GObject\nimport Monad\n\nimport Structs\t\t(GError(..), GQuark, Rectangle(..))\nimport LocalData\t(unsafePerformIO)\nimport Exception\t(bracket)\nimport LocalData\t((.|.), shiftL)\n\n{#context prefix=\"gdk\" #}\n\n-- @data PixbufError@ Error codes for loading image files.\n--\n{#enum PixbufError {underscoreToCase} #}\n\n\n-- @data Colorspace@ Enumerate all supported color spaces.\n--\n-- * Only RGB is supported right now.\n--\n{#enum Colorspace {underscoreToCase} #}\n\n-- @method pixbufGetColorSpace@ Queries the color space of a pixbuf.\n--\npixbufGetColorSpace :: Pixbuf -> IO Colorspace\npixbufGetColorSpace pb = liftM (toEnum . fromIntegral) $\n {#call unsafe pixbuf_get_colorspace#} pb\n\n-- @method pixbufGetNChannels@ Queries the number of colors for each pixel.\n--\npixbufGetNChannels :: Pixbuf -> IO Int\npixbufGetNChannels pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_n_channels#} pb\n\n-- @method pixbufGetHasAlpha@ Query if the image has an alpha channel.\n--\n-- * The alpha channel determines the opaqueness of the pixel.\n--\npixbufGetHasAlpha :: Pixbuf -> IO Bool\npixbufGetHasAlpha pb =\n liftM toBool $ {#call unsafe pixbuf_get_has_alpha#} pb\n\n-- @method pixbufGetBitsPerSample@ Queries the number of bits for each color.\n--\n-- * Each pixel is has a number of cannels for each pixel, each channel\n-- has this many bits.\n--\npixbufGetBitsPerSample :: Pixbuf -> IO Int\npixbufGetBitsPerSample pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_bits_per_sample#} pb\n\n-- @method pixbufGetWidth@ Queries the width of this image.\n--\npixbufGetWidth :: Pixbuf -> IO Int\npixbufGetWidth pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_width#} pb\n\n-- @method pixbufGetHeight@ Queries the height of this image.\n--\npixbufGetHeight :: Pixbuf -> IO Int\npixbufGetHeight pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_height#} pb\n\n-- @method pixbufGetRowstride@ Queries the rowstride of this image.\n--\n-- * Queries the rowstride of a pixbuf, which is the number of bytes between\n-- rows. Use this value to caculate the offset to a certain row.\n--\npixbufGetRowstride :: Pixbuf -> IO Int\npixbufGetRowstride pb = liftM fromIntegral $\n {#call unsafe pixbuf_get_rowstride#} pb\n\n-- @method pixbufGetOption@ Returns an attribut of an image.\n--\n-- * Looks up if some information was stored under the @ref arg key@ when\n-- this image was saved.\n--\npixbufGetOption :: Pixbuf -> String -> IO (Maybe String)\npixbufGetOption pb key = withUTFString key $ \\strPtr -> do\n resPtr <- {#call unsafe pixbuf_get_option#} pb strPtr\n if (resPtr==nullPtr) then return Nothing else\n liftM Just $ peekUTFString resPtr\n\n-- pixbufErrorDomain -- helper function\npixbufErrorDomain :: GQuark\npixbufErrorDomain = unsafePerformIO {#call unsafe pixbuf_error_quark#}\n\n-- @constructor pixbufNewFromFile@ Load an image synchonously.\n--\n-- * Use this function to load only small images as this call will block.\n--\n-- * The function will return @literal Left (err,msg)@ where @ref arg err@\n-- is the error code and @ref arg msg@ is a human readable description\n-- of the error. If an error occurs which is not captured by any of\n-- those in @ref data PixbufError@, an exception is thrown.\n--\npixbufNewFromFile :: FilePath -> IO (Either (PixbufError,String) Pixbuf)\npixbufNewFromFile fname = withUTFString fname $ \\strPtr ->\n alloca $ \\errPtrPtr -> do\n pbPtr <- {#call unsafe pixbuf_new_from_file#} strPtr (castPtr errPtrPtr)\n if pbPtr\/=nullPtr then liftM Right $ makeNewGObject mkPixbuf (return pbPtr)\n else do\n errPtr <- peek errPtrPtr\n (GError dom code msg) <- peek errPtr\n if dom==pixbufErrorDomain then\n return (Left (toEnum (fromIntegral code), msg))\n else\n\terror msg\n\n-- @type ImageType@ A string representing an image file format.\n--\ntype ImageType = String\n\n-- @constant pixbufGetFormats@ A list of valid image file formats.\n--\npixbufGetFormats :: [ImageType]\n\npixbufGetFormats = [\"png\",\"bmp\",\"wbmp\", \"gif\",\"ico\",\"ani\",\"jpeg\",\"pnm\",\n\t\t \"ras\",\"tiff\",\"xpm\",\"xbm\",\"tga\"]\n\n-- @method pixbufSave@ Save an image to disk.\n--\n-- * The function takes a list of key - value pairs to specify\n-- either how an image is saved or to actually save this additional\n-- data with the image. JPEG images can be saved with a \"quality\"\n-- parameter; its value should be in the range [0,100]. Text chunks\n-- can be attached to PNG images by specifying parameters of the form\n-- \"tEXt::key\", where key is an ASCII string of length 1-79.\n-- The values are Unicode strings.\n--\n-- * The function returns @literal Nothing@ if writing was successful.\n-- Otherwise the error code and a description is returned or,\n-- if the error is not captured by one of the error codes in\n-- @ref data PixbufError@, an exception is thrown.\n--\npixbufSave :: Pixbuf -> FilePath -> ImageType -> [(String, String)] ->\n\t IO (Maybe (PixbufError, String))\npixbufSave pb fname iType options =\n let (keys, values) = unzip options in\n let optLen = length keys in\n withUTFString fname $ \\fnPtr ->\n withUTFString iType $ \\tyPtr ->\n allocaArray0 optLen $ \\keysPtr ->\n allocaArray optLen $ \\valuesPtr ->\n alloca $ \\errPtrPtr -> do\n keyPtrs <- mapM newUTFString keys\n valuePtrs <- mapM newUTFString values\n pokeArray keysPtr keyPtrs\n pokeArray valuesPtr valuePtrs\n res <- {#call unsafe pixbuf_savev#} pb fnPtr tyPtr keysPtr valuesPtr\n\t\t\t\t\t(castPtr errPtrPtr)\n mapM_ free keyPtrs\n mapM_ free valuePtrs\n if not (toBool res) then return Nothing else do\n errPtr <- peek errPtrPtr\n (GError dom code msg) <- peek errPtr\n if dom==pixbufErrorDomain then\n return (Just (toEnum (fromIntegral code), msg))\n else\n\terror msg\n\n-- @constructor pixbufNew@ Create a new image in memory.\n--\n-- * Creates a new pixbuf structure and allocates a buffer for\n-- it. Note that the buffer is not cleared initially.\n--\npixbufNew :: Colorspace -> Bool -> Int -> Int -> Int -> IO Pixbuf\npixbufNew colorspace hasAlpha bitsPerSample width height =\n makeNewGObject mkPixbuf $ \n {#call pixbuf_new#} ((fromIntegral . fromEnum) colorspace)\n (fromBool hasAlpha) (fromIntegral bitsPerSample) (fromIntegral width)\n (fromIntegral height)\n\n-- @constructor pixbufNewFromXPMData@ Create a new image from a String.\n--\n-- * Creates a new pixbuf from a string description.\n--\npixbufNewFromXPMData :: [String] -> IO Pixbuf\npixbufNewFromXPMData s =\n bracket (mapM newUTFString s) (mapM free) $ \\strPtrs ->\n withArray0 nullPtr strPtrs $ \\strsPtr ->\n makeNewGObject mkPixbuf $ {#call pixbuf_new_from_xpm_data#} strsPtr\n\n-- @data InlineImage@ A dymmy type for inline picture data.\n--\n-- * This dummy type is used to declare pointers to image data\n-- that is embedded in the executable. See\n-- @ref constructor pixbufNewFromInline@ for an example.\n--\ndata InlineImage = InlineImage\n\n-- @constructor pixbufNewFromInline@ Create a new image from a static pointer.\n--\n-- * Like @ref constructor pixbufNewFromXPMData@, this function allows to\n-- include images in the final binary program. The method used by this\n-- function uses a binary representation and therefore needs less space\n-- in the final executable. Save the image you want to include as\n-- @literal png@ and run @prog\n-- echo #include \"my_image.h\" > my_image.c\n-- gdk-pixbuf-csource --raw --extern --name=my_image myimage.png >> my_image.c\n-- @ on it. Write a header file @literal my_image.h@ containing @prog\n-- #include \n-- extern guint8 my_image[];\n-- @ and save it in the current directory.\n-- The created file can be compiled with @prog\n-- cc -c my_image.c `pkg-config --cflags gdk-2.0`\n-- @ into an object file which must be linked into your Haskell program by\n-- specifying @literal my_image.o@ and @literal \"-#include my_image.h\"@ on\n-- the command line of GHC.\n-- Within you application you delcare a pointer to this image: @prog\n-- foreign label \"my_image\" myImage :: Ptr InlineImage\n-- @ Calling @ref constructor pixbufNewFromInline@ with this pointer will\n-- return the image in the object file. Creating the C file with\n-- the @literal --raw@ flag will result in a non-compressed image in the\n-- object file. The advantage is that the picture will not be\n-- copied when this function is called.\n--\n--\npixbufNewFromInline :: Ptr InlineImage -> IO Pixbuf\npixbufNewFromInline iPtr = alloca $ \\errPtrPtr -> do\n pbPtr <- {#call unsafe pixbuf_new_from_inline#} (-1) (castPtr iPtr)\n (fromBool False) (castPtr errPtrPtr)\n if pbPtr\/=nullPtr then makeNewGObject mkPixbuf (return pbPtr)\n else do\n errPtr <- peek errPtrPtr\n (GError dom code msg) <- peek errPtr\n error msg\n\n-- @method pixbufNewSubpixbuf@ Create a restricted view of an image.\n--\n-- * This function returns a @ref data Pixbuf@ object which shares\n-- the image of the original one but only shows a part of it.\n-- Modifying either buffer will affect the other.\n--\n-- * This function throw an exception if the requested bounds are invalid.\n--\npixbufNewSubpixbuf :: Pixbuf -> Int -> Int -> Int -> Int -> IO Pixbuf\npixbufNewSubpixbuf pb srcX srcY height width =\n makeNewGObject mkPixbuf $ do\n pbPtr <- {#call unsafe pixbuf_new_subpixbuf#} pb\n (fromIntegral srcX) (fromIntegral srcY)\n (fromIntegral height) (fromIntegral width)\n if pbPtr==nullPtr then error \"pixbufNewSubpixbuf: invalid bounds\"\n else return pbPtr\n\n-- @constructor pixbufCopy@ Create a deep copy of an image.\n--\npixbufCopy :: Pixbuf -> IO Pixbuf\npixbufCopy pb = makeNewGObject mkPixbuf $ {#call unsafe pixbuf_copy#} pb\n\n\n-- @data InterpType@ How an image is scaled.\n--\n--\n-- * @variant InterpNearest@ Nearest neighbor sampling; this is the\n-- fastest and lowest quality mode. Quality is normally unacceptable when\n-- scaling down, but may be OK when scaling up.\n--\n-- * @variant InterpTiles@ This is an accurate simulation of the\n-- PostScript image operator without any interpolation enabled. Each\n-- pixel is rendered as a tiny parallelogram of solid color, the edges of\n-- which are implemented with antialiasing. It resembles nearest neighbor\n-- for enlargement, and bilinear for reduction.\n--\n-- * @variant InterpBilinear@ Best quality\/speed balance; use this\n-- mode by default. Bilinear interpolation. For enlargement, it is\n-- equivalent to point-sampling the ideal bilinear-interpolated\n-- image. For reduction, it is equivalent to laying down small tiles and\n-- integrating over the coverage area.\n--\n-- * @variant InterpHyper@ This is the slowest and highest quality\n-- reconstruction function. It is derived from the hyperbolic filters in\n-- Wolberg's \"Digital Image Warping\", and is formally defined as the\n-- hyperbolic-filter sampling the ideal hyperbolic-filter interpolated\n-- image (the filter is designed to be idempotent for 1:1 pixel mapping).\n--\n{#enum InterpType {underscoreToCase} #}\n\n-- @method pixbufScaleSimple@ Scale an image.\n--\n-- * Creates a new @ref data GdkPixbuf@ containing a copy of \n-- @ref arg src@ scaled to the given measures. Leaves @ref arg src@\n-- unaffected. \n--\n-- * @ref arg interp@ affects the quality and speed of the scaling function.\n-- @variant InterpNearest@ is the fastest option but yields very poor\n-- quality when scaling down. @variant InterpBilinear@ is a good\n-- trade-off between speed and quality and should thus be used as a\n-- default.\n--\npixbufScaleSimple :: Pixbuf -> Int -> Int -> InterpType -> IO Pixbuf\npixbufScaleSimple pb width height interp =\n makeNewGObject mkPixbuf $ liftM castPtr $ \n\t{#call pixbuf_scale_simple#} (toPixbuf pb) \n\t(fromIntegral width) (fromIntegral height)\n\t(fromIntegral $ fromEnum interp)\n\n-- @method pixbufScale@ Copy a scaled image part to another image.\n--\n-- * This function is the generic version of @ref method pixbufScaleSimple@.\n-- It scales @ref arg src@ by @ref arg scaleX@ and @ref arg scaleY@ and\n-- translate the image by @ref arg offsetX@ and @ref arg offsetY@. Whatever\n-- is in the intersection with the rectangle @ref arg destX@,\n-- @ref arg destY@, @ref arg destWidth@, @ref arg destHeight@ will be\n-- rendered into @ref arg dest@.\n--\n-- * The rectangle in the destination is simply overwritten. Use\n-- @ref method pixbufComposite@ if you need to blend the source\n-- image onto the destination.\n--\npixbufScale :: Pixbuf -> Pixbuf -> Int -> Int -> Int -> Int ->\n\t Double -> Double -> Double -> Double -> InterpType -> IO ()\npixbufScale src dest destX destY destWidth destHeight offsetX offsetY\n scaleX scaleY interp = {#call unsafe pixbuf_scale#} src dest\n (fromIntegral destX) (fromIntegral destY) (fromIntegral destHeight)\n (fromIntegral destWidth) (realToFrac offsetX) (realToFrac offsetY)\n (realToFrac scaleX) (realToFrac scaleY)\n ((fromIntegral . fromEnum) interp)\n\n-- @method pixbufComposite@ Blend a scaled image part onto another image.\n--\n-- * This function is similar to @ref method pixbufScale@ but allows the\n-- original image to \"shine through\". The @ref arg alpha@ value determines\n-- how opaque the source image is. Passing @literal 0@ is\n-- equivalent to not calling this function at all, passing\n-- @literal 255@ has the\n-- same effect as calling @ref method pixbufScale@.\n--\npixbufComposite :: Pixbuf -> Pixbuf -> Int -> Int -> Int -> Int ->\n\t\t Double -> Double -> Double -> Double -> InterpType ->\n\t \t Word8 -> IO ()\npixbufComposite src dest destX destY destWidth destHeight\n offsetX offsetY scaleX scaleY interp alpha =\n {#call unsafe pixbuf_composite#} src dest\n (fromIntegral destX) (fromIntegral destY) (fromIntegral destHeight)\n (fromIntegral destWidth) (realToFrac offsetX) (realToFrac offsetY)\n (realToFrac scaleX) (realToFrac scaleY)\n ((fromIntegral . fromEnum) interp) (fromIntegral alpha)\n\n-- @method pixbufAddAlpha@ Add an opacity layer to the @ref data Pixbuf@.\n--\n-- * This function returns a copy of the given @ref arg src@\n-- @ref data Pixbuf@, leaving @ref arg src@ unmodified.\n-- The new @ref data Pixbuf@ has an alpha (opacity)\n-- channel which defaults to @literal 255@ (fully opaque pixels)\n-- unless @ref arg src@ already had an alpha channel in which case\n-- the original values are kept.\n-- Passing in a color triple @literal (r,g,b)@ makes all\n-- pixels that have this color fully transparent\n-- (opacity of @literal 0@). The pixel color itself remains unchanged\n-- during this substitution.\n--\npixbufAddAlpha :: Pixbuf -> Maybe (Word8, Word8, Word8) -> IO Pixbuf\npixbufAddAlpha pb Nothing = makeNewGObject mkPixbuf $\n {#call unsafe pixbuf_add_alpha#} pb (fromBool False) 0 0 0\npixbufAddAlpha pb (Just (r,g,b)) = makeNewGObject mkPixbuf $\n {#call unsafe pixbuf_add_alpha#} pb (fromBool True)\n (fromIntegral r) (fromIntegral g) (fromIntegral b)\n\n-- @method pixbufCopyArea@ Copy a rectangular portion into another\n-- @ref data Pixbuf@.\n--\n-- * The source @ref data Pixbuf@ remains unchanged. Converion between\n-- different formats is done automatically.\n--\npixbufCopyArea :: Pixbuf -> Int -> Int -> Int -> Int ->\n\t\t Pixbuf -> Int -> Int -> IO ()\npixbufCopyArea src srcX srcY srcWidth srcHeight dest destX destY =\n {#call unsafe pixbuf_copy_area#} src (fromIntegral srcX)\n (fromIntegral srcY) (fromIntegral srcHeight) (fromIntegral srcWidth)\n dest (fromIntegral destX) (fromIntegral destY)\n\n-- @method pixbufFill@ Fills a @ref data Pixbuf@ with a color.\n--\n-- * The passed-in color is a quadruple consisting of the red, green, blue\n-- and alpha component of the pixel. If the @ref data Pixbuf@ does not\n-- have an alpha channel, the alpha value is ignored.\n--\npixbufFill :: Pixbuf -> Word8 -> Word8 -> Word8 -> Word8 -> IO ()\npixbufFill pb red green blue alpha = {#call unsafe pixbuf_fill#} pb\n ((fromIntegral red) `shiftL` 24 .|.\n (fromIntegral green) `shiftL` 16 .|.\n (fromIntegral blue) `shiftL` 8 .|.\n (fromIntegral alpha))\n\n-- @method pixbufGetFromDrawable@ Take a screenshot of a @ref data Drawable@.\n--\n-- * This function creates a @ref data Pixbuf@ and fills it with the image\n-- currently in the @ref data Drawable@ (which might be invalid if the\n-- window is obscured or minimized). Note that this transfers data from\n-- the server to the client on X Windows.\n--\n-- * This function will return a @ref data Pixbuf@ with no alpha channel\n-- containing the part of the @ref data Drawable@ specified by the\n-- rectangle. The function will return @literal Nothing@ if the window\n-- is not currently visible.\n--\npixbufGetFromDrawable :: DrawableClass d => d -> Rectangle -> IO (Maybe Pixbuf)\npixbufGetFromDrawable d (Rectangle x y width height) = do\n pbPtr <- {#call unsafe pixbuf_get_from_drawable#} \n (mkPixbuf nullForeignPtr) (toDrawable d) (mkColormap nullForeignPtr)\n (fromIntegral x) (fromIntegral y) 0 0\n (fromIntegral width) (fromIntegral height)\n if pbPtr==nullPtr then return Nothing else liftM Just $\n makeNewGObject mkPixbuf (return pbPtr)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"5e67dfd1118bc4bee5fc728a067ac20ac8b476a0","subject":"Remove \"Allocating: ...\" message in newVar","message":"Remove \"Allocating: ...\" message in newVar","repos":"m4lvin\/hBDD","old_file":"hBDD-CUDD\/Data\/Boolean\/CUDD.chs","new_file":"hBDD-CUDD\/Data\/Boolean\/CUDD.chs","new_contents":"-- -*- haskell -*-- -----------------------------------------------\n-- |\n-- Module : Data.Boolean.CUDD\n-- Copyright : (C) 2002-2005, 2009 University of New South Wales, (C) 2009-2011 Peter Gammie\n-- License : LGPL (see COPYING.LIB for details)\n--\n-- A binding for CUDD (Fabio Somenzi, University of Colorado).\n--\n-- Note this library is not thread-safe.\n-------------------------------------------------------------------\nmodule Data.Boolean.CUDD\n (\n BDD\n ,\tmodule Data.Boolean\n\n -- * CUDD-specific functions\n-- ,\tgc\n ,\tstats\n ,\treorder\n ,\tdynamicReordering\n ,\tvarIndices\n ,\tbddSize\n ,\tprintInfo\n ) where\n\n-------------------------------------------------------------------\n-- Dependencies.\n-------------------------------------------------------------------\n\n#include \"cudd_im.h\"\n\nimport Control.DeepSeq ( NFData )\nimport Control.Monad\t( foldM, liftM, mapAndUnzipM, zipWithM_ )\n\nimport Data.IORef\t( IORef, newIORef, readIORef, writeIORef )\nimport Data.List\t( genericLength )\nimport Data.Maybe\t( fromJust, isJust )\n\nimport Data.Map ( Map )\nimport qualified Data.Map as Map\n\nimport Foreign\t\t( ForeignPtr, withForeignPtr, newForeignPtr, newForeignPtr_, finalizerFree, touchForeignPtr\n , Ptr, advancePtr, castPtr, peek, pokeElemOff, ptrToIntPtr\n , mallocArray )\nimport Foreign.C\n\nimport GHC.ForeignPtr ( newConcForeignPtr )\n\nimport System.IO\t( Handle, hIsReadable, hIsWritable )\n-- import System.Mem\t( performGC )\nimport System.Posix.IO\t( handleToFd )\nimport System.IO.Unsafe\t( unsafePerformIO )\n\nimport Data.Boolean\n\n-------------------------------------------------------------------\n-- Extra FFI functions.\n-------------------------------------------------------------------\n\n-- | A C file handle.\n{#pointer *FILE -> CFile#}\n\n-- | Convert a Haskell Handle into a C FILE *.\n-- - FIXME: throw exception on error.\n-- - suggested by Simon Marlow.\nhandleToCFile :: Handle -> IO FILE\nhandleToCFile h =\n do r <- hIsReadable h\n w <- hIsWritable h\n modestr <- newCString $ mode r w\n fd <- handleToFd h\n {#call unsafe fdopen#} (cToNum fd) modestr\n where mode :: Bool -> Bool -> String\n mode False False = error \"Handle not readable or writable!\"\n mode False True = \"w\"\n mode True False = \"r\"\n mode True True = \"r+\" -- FIXME\n\n-- | The Haskell Handle is unusable after calling 'handleToCFile',\n-- so provide a neutered \"fprintf\"-style thing here.\nprintCFile :: FILE -> String -> IO ()\nprintCFile file str =\n withCString str ({#call unsafe fprintf_neutered#} file)\n\n-- Close a C FILE *.\n-- - FIXME: throw exception on error.\n-- closeCFile :: FILE -> IO ()\n-- closeCFile cfile = do {#call unsafe fclose#} cfile\n-- return ()\n\ncToNum :: (Num i, Integral e) => e -> i\ncToNum = fromIntegral . toInteger\n{-# INLINE cToNum #-}\n\ncFromEnum :: (Integral i, Enum e) => e -> i\ncFromEnum = fromIntegral . fromEnum\n{-# INLINE cFromEnum #-}\n\n-------------------------------------------------------------------\n-- Types.\n-------------------------------------------------------------------\n\n-- | The BDD manager, which we hide from clients.\n{#pointer *DdManager as DDManager newtype#}\n\n-- | The arguments to 'Cudd_Init'.\n{#enum CuddSubtableSize {} #}\n{#enum CuddCacheSize {} #}\n\n-- | Variable reordering tree options.\n{#enum CuddMTRParams {} #}\n\n-- | The abstract type of BDDs.\n{#pointer *DdNode as BDD foreign newtype#}\n\n{-# INLINE withBDD #-}\n\n-- BDDs are just pointers, so there's no work to do when we @deepseq@ them.\ninstance Control.DeepSeq.NFData BDD\n\n-- Belt-and-suspenders equality checking and ordering.\ninstance Eq BDD where\n bdd0 == bdd1 = unsafePerformIO $\n withBDD bdd0 $ \\bdd0p -> withBDD bdd1 $ \\bdd1p ->\n return $ bdd0p == bdd1p\n\ninstance Ord BDD where\n bdd0 <= bdd1 = unsafePerformIO $\n withBDD bdd0 $ \\bdd0p -> withBDD bdd1 $ \\bdd1p ->\n return $ bdd0p == bdd1p || bdd0p < bdd1p\n\ninstance Show BDD where\n-- Print out the BDD as a sum-of-products.\n showsPrec _ = sop\n\n-------------------------------------------------------------------\n-- Administrative functions.\n-------------------------------------------------------------------\n\n-- | The BDD manager. This needs to be invoked before any of the\n-- following functions... which we arrange for automagically.\nddmanager :: DDManager\nddmanager = unsafePerformIO $\n {#call unsafe Cudd_Init as _cudd_Init #}\n 0 0 (cFromEnum UNIQUE_SLOTS) (cFromEnum CACHE_SLOTS) 0\n{-# NOINLINE ddmanager #-}\n\n-- | A map to and from BDD variable numbers.\n-- FIXME: the second one would be more efficiently Data.IntMap, but we don't use it often.\ntype VarMap = (Map String BDD, Map CUInt String)\n\n-- | Tracks existing variables.\nbdd_vars :: IORef VarMap\nbdd_vars = unsafePerformIO $ newIORef (Map.empty, Map.empty)\n{-# NOINLINE bdd_vars #-}\n\n-- | Attaches a finalizer to a BDD object.\n-- The call to \"Cudd_Ref\" happens in C to ensure atomicity.\n-- Returning objects with initial refcount 0 is a bad design decision.\naddBDDfinalizer :: Ptr BDD -> IO BDD\naddBDDfinalizer bddp = liftM BDD $ newConcForeignPtr bddp bddf\n where bddf = {#call unsafe Cudd_RecursiveDeref as _cudd_RecursiveDeref#} ddmanager bddp\n >> return ()\n{-# INLINE addBDDfinalizer #-}\n\n-- | Attaches a null finalizer to a 'BDD' object.\n-- Used for variables and constants.\naddBDDnullFinalizer :: Ptr BDD -> IO BDD\naddBDDnullFinalizer bddp = fmap BDD $ newForeignPtr_ bddp\n{-# INLINE addBDDnullFinalizer #-}\n\n-- Simulate an \"apply\" function to simplify atomic refcount incrementing.\n{#enum CuddBinOp {} #}\n\n-------------------------------------------------------------------\n-- Logical operations.\n-------------------------------------------------------------------\n\n-- | Allocate a variable.\nnewVar :: IO (Ptr BDD) -> String -> IO (Maybe CUInt, BDD)\nnewVar allocVar label =\n do (toBDD, fromBDD) <- readIORef bdd_vars\n case label `Map.lookup` toBDD of\n Just bdd -> return (Nothing, bdd)\n Nothing ->\n do bddp <- allocVar\n vid <- fmap cToNum $\n {#call unsafe Cudd_NodeReadIndex as _cudd_NodeReadIndex#} bddp\n --putStrLn $ label ++ \" -> \" ++ (show (vid, bdd))\n bdd <- addBDDnullFinalizer bddp\n writeIORef bdd_vars ( Map.insert label bdd toBDD\n , Map.insert vid label fromBDD )\n return (Just vid, bdd)\n\ninstance BooleanVariable BDD where\n bvar label = unsafePerformIO $\n fmap snd $ newVar ({#call unsafe Cudd_bddNewVar as _cudd_bddNewVar#} ddmanager) label\n\n bvars labels =\n case labels of\n [] -> []\n ls -> unsafePerformIO $\n do (vids, vars) <- mapAndUnzipM (newVar ({#call unsafe Cudd_bddNewVar as _cudd_bddNewVar#} ddmanager)) ls\n if all isJust vids\n then groupVars (fromJust (head vids)) (genericLength vids)\n else putStrLn $ \"hBDD-CUDD warning: not grouping variables \" ++ show ls\n return vars\n where\n -- FIXME why one or the other?\n groupVars vid len = makeTreeNode ddmanager vid len (cFromEnum CUDD_MTR_DEFAULT) >> return ()\n -- groupVars vid len = makeTreeNode ddmanager vid len (cFromEnum CUDD_MTR_FIXED) >> return ()\n makeTreeNode = {#call unsafe Cudd_MakeTreeNode as _cudd_MakeTreeNode#}\n\n unbvar bdd = unsafePerformIO $ bdd `seq`\n withBDD bdd $ \\bddp ->\n do vid <- {#call unsafe Cudd_NodeReadIndex as _cudd_NodeReadIndex#} bddp\n (_, fromBDD) <- readIORef bdd_vars\n return $ case cToNum vid `Map.lookup` fromBDD of\n Nothing -> \"(VID: \" ++ show vid ++ \")\"\n Just v -> v\n\ninstance Boolean BDD where\n true = cudd_constant {#call unsafe Cudd_ReadOne as _cudd_ReadOne#}\n false = cudd_constant {#call unsafe Cudd_ReadLogicZero as _cudd_ReadLogicZero#}\n\n (\/\\) = bddBinOp AND\n neg x = unsafePerformIO $ withBDD x $ \\xp ->\n {#call unsafe cudd_bddNot#} xp >>= addBDDfinalizer\n\n nand = bddBinOp NAND\n (\\\/) = bddBinOp OR\n nor = bddBinOp NOR\n xor = bddBinOp XOR\n -- (-->) = FIXME ???\n (<->) = bddBinOp XNOR\n\n -- bITE i t e = unsafePerformIO $\n -- withBDD i $ \\ip -> withBDD t $ \\tp -> withBDD e $ \\ep ->\n -- {#call unsafe cudd_bddIte#} ddmanager ip tp ep\n -- >>= addBDDfinalizer\n\ncudd_constant :: (DDManager -> IO (Ptr BDD)) -> BDD\ncudd_constant f = unsafePerformIO $ f ddmanager >>= addBDDnullFinalizer\n{-# INLINE cudd_constant #-}\n\nbddBinOp :: CuddBinOp -> BDD -> BDD -> BDD\nbddBinOp op x y = unsafePerformIO $\n withBDD x $ \\xp -> withBDD y $ \\yp ->\n {#call unsafe cudd_BinOp#} ddmanager (cFromEnum op) xp yp >>= addBDDfinalizer\n{-# INLINE bddBinOp #-}\n\ninstance QBF BDD where\n data Group BDD = MkGroup !BDD\n\n mkGroup = MkGroup . conjoin -- FIXME maybe use Cudd_bddComputeCube\n exists = cudd_exists\n forall = cudd_forall\n rel_product = cudd_rel_product\n\ninstance Substitution BDD where\n -- Cache substitution arrays.\n data Subst BDD = MkSubst {-# UNPACK #-} !Int\n {-# UNPACK #-} !(ForeignPtr (Ptr BDD))\n {-# UNPACK #-} !(ForeignPtr (Ptr BDD))\n\n mkSubst = cudd_mkSubst\n rename = cudd_rename\n substitute = error \"CUDD substitute\" -- cudd_substitute\n\ncudd_mkSubst :: [(BDD, BDD)] -> Subst BDD\ncudd_mkSubst subst = unsafePerformIO $\n do arrayx <- mallocArray len\n arrayx' <- mallocArray len\n zipWithM_ (pokeSubst arrayx arrayx') subst [0..]\n fpx <- newForeignPtr finalizerFree arrayx\n fpx' <- newForeignPtr finalizerFree arrayx'\n return (MkSubst len fpx fpx')\n where\n pokeSubst :: Ptr (Ptr BDD) -> Ptr (Ptr BDD) -> (BDD, BDD) -> Int -> IO ()\n pokeSubst arrayx arrayx' (v, v') i =\n do withBDD v $ pokeElemOff arrayx i\n withBDD v' $ pokeElemOff arrayx' i\n\n len = length subst\n{-# INLINE cudd_mkSubst #-}\n\ninstance BDDOps BDD where\n get_bdd_ptr bdd = unsafePerformIO $ withBDD bdd (return . ptrToIntPtr)\n bif bdd = unsafePerformIO $\n do vid <- withBDD bdd {#call unsafe Cudd_NodeReadIndex as _cudd_NodeReadIndex#}\n {#call unsafe Cudd_bddIthVar as _cudd_bddIthVar#} ddmanager (cToNum vid)\n >>= addBDDnullFinalizer\n bthen bdd = unsafePerformIO $\n withBDD bdd $ \\bddp ->\n {#call unsafe cudd_bddT#} bddp >>= addBDDfinalizer\n belse bdd = unsafePerformIO $\n withBDD bdd $ \\bddp ->\n {#call unsafe cudd_bddE#} bddp >>= addBDDfinalizer\n\n reduce = cudd_reduce\n satisfy = cudd_satisfy\n support = cudd_support\n\n-------------------------------------------------------------------\n-- Implementations.\n-------------------------------------------------------------------\n\nwithGroup :: Group BDD -> (Ptr BDD -> IO a) -> IO a\nwithGroup (MkGroup g) = withBDD g\n\ncudd_exists :: Group BDD -> BDD -> BDD\ncudd_exists group bdd = unsafePerformIO $ bdd `seq`\n withGroup group $ \\groupp -> withBDD bdd $ \\bddp ->\n {#call unsafe cudd_bddExistAbstract#} ddmanager bddp groupp\n >>= addBDDfinalizer\n{-# INLINE cudd_exists #-}\n\ncudd_forall :: Group BDD -> BDD -> BDD\ncudd_forall group bdd = unsafePerformIO $ bdd `seq`\n withGroup group $ \\groupp -> withBDD bdd $ \\bddp ->\n {#call unsafe cudd_bddUnivAbstract#} ddmanager bddp groupp\n >>= addBDDfinalizer\n{-# INLINE cudd_forall #-}\n\ncudd_rel_product :: Group BDD -> BDD -> BDD -> BDD\ncudd_rel_product group f g = unsafePerformIO $\n withGroup group $ \\groupp -> withBDD f $ \\fp -> withBDD g $ \\gp ->\n {#call unsafe cudd_bddAndAbstract#} ddmanager fp gp groupp\n >>= addBDDfinalizer\n{-# INLINE cudd_rel_product #-}\n\n-- | This function swaps variables, as it uses\n-- @cudd_bddSwapVariables@. This is not exactly a \"rename\" behaviour.\ncudd_rename :: Subst BDD -> BDD -> BDD\ncudd_rename s@(MkSubst len fpx fpx') f = unsafePerformIO $ s `seq` f `seq`\n withBDD f $ \\fp ->\n withForeignPtr fpx $ \\arrayx -> withForeignPtr fpx' $ \\arrayx' ->\n {#call unsafe cudd_bddSwapVariables#} ddmanager fp arrayx arrayx' (fromIntegral len)\n >>= addBDDfinalizer\n{-# INLINE cudd_rename #-}\n\n-- FIXME verify implementation.\ncudd_reduce :: BDD -> BDD -> BDD\ncudd_reduce f g = unsafePerformIO $\n withBDD f $ \\fp -> withBDD g $ \\gp ->\n {#call unsafe cudd_bddLICompaction#} ddmanager fp gp\n >>= addBDDfinalizer\n\n-- FIXME verify implementation.\ncudd_satisfy :: BDD -> BDD\ncudd_satisfy bdd = unsafePerformIO $\n withBDD bdd ({#call unsafe cudd_satone#} ddmanager) >>= addBDDfinalizer\n\ncudd_support :: BDD -> [BDD]\ncudd_support bdd = unsafePerformIO $\n do varBitArray <- withBDD bdd ({#call unsafe Cudd_SupportIndex as _cudd_SupportIndex#} ddmanager)\n touchForeignPtr (case bdd of BDD fp -> fp)\n -- The array is as long as the number of variables allocated.\n (_toBDD, fromBDD) <- readIORef bdd_vars\n bdds <- foldM (toBDDs varBitArray) [] (Map.toList fromBDD)\n {#call unsafe cFree#} (castPtr varBitArray)\n return bdds\n where\n toBDDs varBitArray bdds (vid, var) =\n do varInSupport <- peek (advancePtr varBitArray (cToNum vid))\n return $ if varInSupport \/= 0\n then bvar var : bdds\n else bdds\n\n-------------------------------------------------------------------\n-- Operations specific to this BDD binding.\n-------------------------------------------------------------------\n\n-- | Dump usage statistics to the given 'Handle'.\nstats :: Handle -> IO ()\nstats handle =\n do cfile <- handleToCFile handle\n printCFile cfile \"CUDD stats\\n\"\n _ <- {#call unsafe Cudd_PrintInfo as _cudd_PrintInfo#} ddmanager cfile\n printCFile cfile \"\\nVariable groups\\n\"\n {#call unsafe cudd_printVarGroups#} ddmanager\n\n----------------------------------------\n-- Variable Reordering.\n----------------------------------------\n\n{#enum Cudd_ReorderingType as CUDDReorderingMethod {} deriving (Eq, Ord, Show)#}\n\ndecodeROM :: ReorderingMethod -> CInt\ndecodeROM rom = cFromEnum $ case rom of\n ReorderNone -> CUDD_REORDER_NONE\n ReorderSift -> CUDD_REORDER_SIFT\n ReorderSiftSym -> CUDD_REORDER_SYMM_SIFT\n ReorderStableWindow3 -> CUDD_REORDER_WINDOW3\n\n-- | Reorder the variables now.\nreorder :: ReorderingMethod -> IO ()\nreorder rom = {#call unsafe Cudd_ReduceHeap as _cudd_ReduceHeap#} ddmanager (decodeROM rom) 1 >> return ()\n\n-- | Set the dynamic variable ordering heuristic.\ndynamicReordering :: ReorderingMethod -> IO ()\ndynamicReordering rom = {#call unsafe Cudd_AutodynEnable as _cudd_AutodynEnable#} ddmanager (decodeROM rom) >> return ()\n\n----------------------------------------\n-- | Returns the relationship between BDD indices, BDD ids and\n-- variable names. This may be useful for discovering what the\n-- dynamic reordering is doing.\n--\n-- The intention of this function is to return\n-- @[(position in variable order, immutable variable id, label)]@\n-- so that the variable order can be saved.\n----------------------------------------\n\nvarIndices :: IO [(CInt, CInt, String)]\nvarIndices = do (toBDD, _fromBDD) <- readIORef bdd_vars\n mapM procVar $ Map.toList toBDD\n where -- procVar :: (String, BDD) -> IO (CUInt, CUInt, String)\n procVar (var, bdd) =\n do -- FIXME CUDD inconsistently uses signed and unsigned ints.\n vid <- fmap cToNum $\n withBDD bdd {#call unsafe Cudd_NodeReadIndex as _cudd_NodeReadIndex#}\n level <- {#call unsafe Cudd_ReadPerm as _cudd_ReadPerm#} ddmanager vid\n return (level, vid, var)\n{-# NOINLINE varIndices #-}\n\n----------------------------------------\n-- BDD Statistics.\n----------------------------------------\n\n-- | Determine the size of a BDD.\nbddSize :: BDD -> Int\nbddSize bdd = unsafePerformIO $\n do size <- withBDD bdd ({#call unsafe Cudd_DagSize as _cudd_DagSize#})\n return $ cToNum size\n\nprintInfo :: IO ()\nprintInfo = {#call unsafe print_stats#} ddmanager\n","old_contents":"-- -*- haskell -*-- -----------------------------------------------\n-- |\n-- Module : Data.Boolean.CUDD\n-- Copyright : (C) 2002-2005, 2009 University of New South Wales, (C) 2009-2011 Peter Gammie\n-- License : LGPL (see COPYING.LIB for details)\n--\n-- A binding for CUDD (Fabio Somenzi, University of Colorado).\n--\n-- Note this library is not thread-safe.\n-------------------------------------------------------------------\nmodule Data.Boolean.CUDD\n (\n BDD\n ,\tmodule Data.Boolean\n\n -- * CUDD-specific functions\n-- ,\tgc\n ,\tstats\n ,\treorder\n ,\tdynamicReordering\n ,\tvarIndices\n ,\tbddSize\n ,\tprintInfo\n ) where\n\n-------------------------------------------------------------------\n-- Dependencies.\n-------------------------------------------------------------------\n\n#include \"cudd_im.h\"\n\nimport Control.DeepSeq ( NFData )\nimport Control.Monad\t( foldM, liftM, mapAndUnzipM, zipWithM_ )\n\nimport Data.IORef\t( IORef, newIORef, readIORef, writeIORef )\nimport Data.List\t( genericLength )\nimport Data.Maybe\t( fromJust, isJust )\n\nimport Data.Map ( Map )\nimport qualified Data.Map as Map\n\nimport Foreign\t\t( ForeignPtr, withForeignPtr, newForeignPtr, newForeignPtr_, finalizerFree, touchForeignPtr\n , Ptr, advancePtr, castPtr, peek, pokeElemOff, ptrToIntPtr\n , mallocArray )\nimport Foreign.C\n\nimport GHC.ForeignPtr ( newConcForeignPtr )\n\nimport System.IO\t( Handle, hIsReadable, hIsWritable )\n-- import System.Mem\t( performGC )\nimport System.Posix.IO\t( handleToFd )\nimport System.IO.Unsafe\t( unsafePerformIO )\n\nimport Data.Boolean\n\n-------------------------------------------------------------------\n-- Extra FFI functions.\n-------------------------------------------------------------------\n\n-- | A C file handle.\n{#pointer *FILE -> CFile#}\n\n-- | Convert a Haskell Handle into a C FILE *.\n-- - FIXME: throw exception on error.\n-- - suggested by Simon Marlow.\nhandleToCFile :: Handle -> IO FILE\nhandleToCFile h =\n do r <- hIsReadable h\n w <- hIsWritable h\n modestr <- newCString $ mode r w\n fd <- handleToFd h\n {#call unsafe fdopen#} (cToNum fd) modestr\n where mode :: Bool -> Bool -> String\n mode False False = error \"Handle not readable or writable!\"\n mode False True = \"w\"\n mode True False = \"r\"\n mode True True = \"r+\" -- FIXME\n\n-- | The Haskell Handle is unusable after calling 'handleToCFile',\n-- so provide a neutered \"fprintf\"-style thing here.\nprintCFile :: FILE -> String -> IO ()\nprintCFile file str =\n withCString str ({#call unsafe fprintf_neutered#} file)\n\n-- Close a C FILE *.\n-- - FIXME: throw exception on error.\n-- closeCFile :: FILE -> IO ()\n-- closeCFile cfile = do {#call unsafe fclose#} cfile\n-- return ()\n\ncToNum :: (Num i, Integral e) => e -> i\ncToNum = fromIntegral . toInteger\n{-# INLINE cToNum #-}\n\ncFromEnum :: (Integral i, Enum e) => e -> i\ncFromEnum = fromIntegral . fromEnum\n{-# INLINE cFromEnum #-}\n\n-------------------------------------------------------------------\n-- Types.\n-------------------------------------------------------------------\n\n-- | The BDD manager, which we hide from clients.\n{#pointer *DdManager as DDManager newtype#}\n\n-- | The arguments to 'Cudd_Init'.\n{#enum CuddSubtableSize {} #}\n{#enum CuddCacheSize {} #}\n\n-- | Variable reordering tree options.\n{#enum CuddMTRParams {} #}\n\n-- | The abstract type of BDDs.\n{#pointer *DdNode as BDD foreign newtype#}\n\n{-# INLINE withBDD #-}\n\n-- BDDs are just pointers, so there's no work to do when we @deepseq@ them.\ninstance Control.DeepSeq.NFData BDD\n\n-- Belt-and-suspenders equality checking and ordering.\ninstance Eq BDD where\n bdd0 == bdd1 = unsafePerformIO $\n withBDD bdd0 $ \\bdd0p -> withBDD bdd1 $ \\bdd1p ->\n return $ bdd0p == bdd1p\n\ninstance Ord BDD where\n bdd0 <= bdd1 = unsafePerformIO $\n withBDD bdd0 $ \\bdd0p -> withBDD bdd1 $ \\bdd1p ->\n return $ bdd0p == bdd1p || bdd0p < bdd1p\n\ninstance Show BDD where\n-- Print out the BDD as a sum-of-products.\n showsPrec _ = sop\n\n-------------------------------------------------------------------\n-- Administrative functions.\n-------------------------------------------------------------------\n\n-- | The BDD manager. This needs to be invoked before any of the\n-- following functions... which we arrange for automagically.\nddmanager :: DDManager\nddmanager = unsafePerformIO $\n {#call unsafe Cudd_Init as _cudd_Init #}\n 0 0 (cFromEnum UNIQUE_SLOTS) (cFromEnum CACHE_SLOTS) 0\n{-# NOINLINE ddmanager #-}\n\n-- | A map to and from BDD variable numbers.\n-- FIXME: the second one would be more efficiently Data.IntMap, but we don't use it often.\ntype VarMap = (Map String BDD, Map CUInt String)\n\n-- | Tracks existing variables.\nbdd_vars :: IORef VarMap\nbdd_vars = unsafePerformIO $ newIORef (Map.empty, Map.empty)\n{-# NOINLINE bdd_vars #-}\n\n-- | Attaches a finalizer to a BDD object.\n-- The call to \"Cudd_Ref\" happens in C to ensure atomicity.\n-- Returning objects with initial refcount 0 is a bad design decision.\naddBDDfinalizer :: Ptr BDD -> IO BDD\naddBDDfinalizer bddp = liftM BDD $ newConcForeignPtr bddp bddf\n where bddf = {#call unsafe Cudd_RecursiveDeref as _cudd_RecursiveDeref#} ddmanager bddp\n >> return ()\n{-# INLINE addBDDfinalizer #-}\n\n-- | Attaches a null finalizer to a 'BDD' object.\n-- Used for variables and constants.\naddBDDnullFinalizer :: Ptr BDD -> IO BDD\naddBDDnullFinalizer bddp = fmap BDD $ newForeignPtr_ bddp\n{-# INLINE addBDDnullFinalizer #-}\n\n-- Simulate an \"apply\" function to simplify atomic refcount incrementing.\n{#enum CuddBinOp {} #}\n\n-------------------------------------------------------------------\n-- Logical operations.\n-------------------------------------------------------------------\n\n-- | Allocate a variable.\nnewVar :: IO (Ptr BDD) -> String -> IO (Maybe CUInt, BDD)\nnewVar allocVar label =\n do (toBDD, fromBDD) <- readIORef bdd_vars\n case label `Map.lookup` toBDD of\n Just bdd -> return (Nothing, bdd)\n Nothing ->\n do putStrLn $ \"Allocating: \" ++ label\n bddp <- allocVar\n vid <- fmap cToNum $\n {#call unsafe Cudd_NodeReadIndex as _cudd_NodeReadIndex#} bddp\n --putStrLn $ label ++ \" -> \" ++ (show (vid, bdd))\n bdd <- addBDDnullFinalizer bddp\n writeIORef bdd_vars ( Map.insert label bdd toBDD\n , Map.insert vid label fromBDD )\n return (Just vid, bdd)\n\ninstance BooleanVariable BDD where\n bvar label = unsafePerformIO $\n fmap snd $ newVar ({#call unsafe Cudd_bddNewVar as _cudd_bddNewVar#} ddmanager) label\n\n bvars labels =\n case labels of\n [] -> []\n ls -> unsafePerformIO $\n do (vids, vars) <- mapAndUnzipM (newVar ({#call unsafe Cudd_bddNewVar as _cudd_bddNewVar#} ddmanager)) ls\n if all isJust vids\n then groupVars (fromJust (head vids)) (genericLength vids)\n else putStrLn $ \"hBDD-CUDD warning: not grouping variables \" ++ show ls\n return vars\n where\n -- FIXME why one or the other?\n groupVars vid len = makeTreeNode ddmanager vid len (cFromEnum CUDD_MTR_DEFAULT) >> return ()\n -- groupVars vid len = makeTreeNode ddmanager vid len (cFromEnum CUDD_MTR_FIXED) >> return ()\n makeTreeNode = {#call unsafe Cudd_MakeTreeNode as _cudd_MakeTreeNode#}\n\n unbvar bdd = unsafePerformIO $ bdd `seq`\n withBDD bdd $ \\bddp ->\n do vid <- {#call unsafe Cudd_NodeReadIndex as _cudd_NodeReadIndex#} bddp\n (_, fromBDD) <- readIORef bdd_vars\n return $ case cToNum vid `Map.lookup` fromBDD of\n Nothing -> \"(VID: \" ++ show vid ++ \")\"\n Just v -> v\n\ninstance Boolean BDD where\n true = cudd_constant {#call unsafe Cudd_ReadOne as _cudd_ReadOne#}\n false = cudd_constant {#call unsafe Cudd_ReadLogicZero as _cudd_ReadLogicZero#}\n\n (\/\\) = bddBinOp AND\n neg x = unsafePerformIO $ withBDD x $ \\xp ->\n {#call unsafe cudd_bddNot#} xp >>= addBDDfinalizer\n\n nand = bddBinOp NAND\n (\\\/) = bddBinOp OR\n nor = bddBinOp NOR\n xor = bddBinOp XOR\n -- (-->) = FIXME ???\n (<->) = bddBinOp XNOR\n\n -- bITE i t e = unsafePerformIO $\n -- withBDD i $ \\ip -> withBDD t $ \\tp -> withBDD e $ \\ep ->\n -- {#call unsafe cudd_bddIte#} ddmanager ip tp ep\n -- >>= addBDDfinalizer\n\ncudd_constant :: (DDManager -> IO (Ptr BDD)) -> BDD\ncudd_constant f = unsafePerformIO $ f ddmanager >>= addBDDnullFinalizer\n{-# INLINE cudd_constant #-}\n\nbddBinOp :: CuddBinOp -> BDD -> BDD -> BDD\nbddBinOp op x y = unsafePerformIO $\n withBDD x $ \\xp -> withBDD y $ \\yp ->\n {#call unsafe cudd_BinOp#} ddmanager (cFromEnum op) xp yp >>= addBDDfinalizer\n{-# INLINE bddBinOp #-}\n\ninstance QBF BDD where\n data Group BDD = MkGroup !BDD\n\n mkGroup = MkGroup . conjoin -- FIXME maybe use Cudd_bddComputeCube\n exists = cudd_exists\n forall = cudd_forall\n rel_product = cudd_rel_product\n\ninstance Substitution BDD where\n -- Cache substitution arrays.\n data Subst BDD = MkSubst {-# UNPACK #-} !Int\n {-# UNPACK #-} !(ForeignPtr (Ptr BDD))\n {-# UNPACK #-} !(ForeignPtr (Ptr BDD))\n\n mkSubst = cudd_mkSubst\n rename = cudd_rename\n substitute = error \"CUDD substitute\" -- cudd_substitute\n\ncudd_mkSubst :: [(BDD, BDD)] -> Subst BDD\ncudd_mkSubst subst = unsafePerformIO $\n do arrayx <- mallocArray len\n arrayx' <- mallocArray len\n zipWithM_ (pokeSubst arrayx arrayx') subst [0..]\n fpx <- newForeignPtr finalizerFree arrayx\n fpx' <- newForeignPtr finalizerFree arrayx'\n return (MkSubst len fpx fpx')\n where\n pokeSubst :: Ptr (Ptr BDD) -> Ptr (Ptr BDD) -> (BDD, BDD) -> Int -> IO ()\n pokeSubst arrayx arrayx' (v, v') i =\n do withBDD v $ pokeElemOff arrayx i\n withBDD v' $ pokeElemOff arrayx' i\n\n len = length subst\n{-# INLINE cudd_mkSubst #-}\n\ninstance BDDOps BDD where\n get_bdd_ptr bdd = unsafePerformIO $ withBDD bdd (return . ptrToIntPtr)\n bif bdd = unsafePerformIO $\n do vid <- withBDD bdd {#call unsafe Cudd_NodeReadIndex as _cudd_NodeReadIndex#}\n {#call unsafe Cudd_bddIthVar as _cudd_bddIthVar#} ddmanager (cToNum vid)\n >>= addBDDnullFinalizer\n bthen bdd = unsafePerformIO $\n withBDD bdd $ \\bddp ->\n {#call unsafe cudd_bddT#} bddp >>= addBDDfinalizer\n belse bdd = unsafePerformIO $\n withBDD bdd $ \\bddp ->\n {#call unsafe cudd_bddE#} bddp >>= addBDDfinalizer\n\n reduce = cudd_reduce\n satisfy = cudd_satisfy\n support = cudd_support\n\n-------------------------------------------------------------------\n-- Implementations.\n-------------------------------------------------------------------\n\nwithGroup :: Group BDD -> (Ptr BDD -> IO a) -> IO a\nwithGroup (MkGroup g) = withBDD g\n\ncudd_exists :: Group BDD -> BDD -> BDD\ncudd_exists group bdd = unsafePerformIO $ bdd `seq`\n withGroup group $ \\groupp -> withBDD bdd $ \\bddp ->\n {#call unsafe cudd_bddExistAbstract#} ddmanager bddp groupp\n >>= addBDDfinalizer\n{-# INLINE cudd_exists #-}\n\ncudd_forall :: Group BDD -> BDD -> BDD\ncudd_forall group bdd = unsafePerformIO $ bdd `seq`\n withGroup group $ \\groupp -> withBDD bdd $ \\bddp ->\n {#call unsafe cudd_bddUnivAbstract#} ddmanager bddp groupp\n >>= addBDDfinalizer\n{-# INLINE cudd_forall #-}\n\ncudd_rel_product :: Group BDD -> BDD -> BDD -> BDD\ncudd_rel_product group f g = unsafePerformIO $\n withGroup group $ \\groupp -> withBDD f $ \\fp -> withBDD g $ \\gp ->\n {#call unsafe cudd_bddAndAbstract#} ddmanager fp gp groupp\n >>= addBDDfinalizer\n{-# INLINE cudd_rel_product #-}\n\n-- | This function swaps variables, as it uses\n-- @cudd_bddSwapVariables@. This is not exactly a \"rename\" behaviour.\ncudd_rename :: Subst BDD -> BDD -> BDD\ncudd_rename s@(MkSubst len fpx fpx') f = unsafePerformIO $ s `seq` f `seq`\n withBDD f $ \\fp ->\n withForeignPtr fpx $ \\arrayx -> withForeignPtr fpx' $ \\arrayx' ->\n {#call unsafe cudd_bddSwapVariables#} ddmanager fp arrayx arrayx' (fromIntegral len)\n >>= addBDDfinalizer\n{-# INLINE cudd_rename #-}\n\n-- FIXME verify implementation.\ncudd_reduce :: BDD -> BDD -> BDD\ncudd_reduce f g = unsafePerformIO $\n withBDD f $ \\fp -> withBDD g $ \\gp ->\n {#call unsafe cudd_bddLICompaction#} ddmanager fp gp\n >>= addBDDfinalizer\n\n-- FIXME verify implementation.\ncudd_satisfy :: BDD -> BDD\ncudd_satisfy bdd = unsafePerformIO $\n withBDD bdd ({#call unsafe cudd_satone#} ddmanager) >>= addBDDfinalizer\n\ncudd_support :: BDD -> [BDD]\ncudd_support bdd = unsafePerformIO $\n do varBitArray <- withBDD bdd ({#call unsafe Cudd_SupportIndex as _cudd_SupportIndex#} ddmanager)\n touchForeignPtr (case bdd of BDD fp -> fp)\n -- The array is as long as the number of variables allocated.\n (_toBDD, fromBDD) <- readIORef bdd_vars\n bdds <- foldM (toBDDs varBitArray) [] (Map.toList fromBDD)\n {#call unsafe cFree#} (castPtr varBitArray)\n return bdds\n where\n toBDDs varBitArray bdds (vid, var) =\n do varInSupport <- peek (advancePtr varBitArray (cToNum vid))\n return $ if varInSupport \/= 0\n then bvar var : bdds\n else bdds\n\n-------------------------------------------------------------------\n-- Operations specific to this BDD binding.\n-------------------------------------------------------------------\n\n-- | Dump usage statistics to the given 'Handle'.\nstats :: Handle -> IO ()\nstats handle =\n do cfile <- handleToCFile handle\n printCFile cfile \"CUDD stats\\n\"\n _ <- {#call unsafe Cudd_PrintInfo as _cudd_PrintInfo#} ddmanager cfile\n printCFile cfile \"\\nVariable groups\\n\"\n {#call unsafe cudd_printVarGroups#} ddmanager\n\n----------------------------------------\n-- Variable Reordering.\n----------------------------------------\n\n{#enum Cudd_ReorderingType as CUDDReorderingMethod {} deriving (Eq, Ord, Show)#}\n\ndecodeROM :: ReorderingMethod -> CInt\ndecodeROM rom = cFromEnum $ case rom of\n ReorderNone -> CUDD_REORDER_NONE\n ReorderSift -> CUDD_REORDER_SIFT\n ReorderSiftSym -> CUDD_REORDER_SYMM_SIFT\n ReorderStableWindow3 -> CUDD_REORDER_WINDOW3\n\n-- | Reorder the variables now.\nreorder :: ReorderingMethod -> IO ()\nreorder rom = {#call unsafe Cudd_ReduceHeap as _cudd_ReduceHeap#} ddmanager (decodeROM rom) 1 >> return ()\n\n-- | Set the dynamic variable ordering heuristic.\ndynamicReordering :: ReorderingMethod -> IO ()\ndynamicReordering rom = {#call unsafe Cudd_AutodynEnable as _cudd_AutodynEnable#} ddmanager (decodeROM rom) >> return ()\n\n----------------------------------------\n-- | Returns the relationship between BDD indices, BDD ids and\n-- variable names. This may be useful for discovering what the\n-- dynamic reordering is doing.\n--\n-- The intention of this function is to return\n-- @[(position in variable order, immutable variable id, label)]@\n-- so that the variable order can be saved.\n----------------------------------------\n\nvarIndices :: IO [(CInt, CInt, String)]\nvarIndices = do (toBDD, _fromBDD) <- readIORef bdd_vars\n mapM procVar $ Map.toList toBDD\n where -- procVar :: (String, BDD) -> IO (CUInt, CUInt, String)\n procVar (var, bdd) =\n do -- FIXME CUDD inconsistently uses signed and unsigned ints.\n vid <- fmap cToNum $\n withBDD bdd {#call unsafe Cudd_NodeReadIndex as _cudd_NodeReadIndex#}\n level <- {#call unsafe Cudd_ReadPerm as _cudd_ReadPerm#} ddmanager vid\n return (level, vid, var)\n{-# NOINLINE varIndices #-}\n\n----------------------------------------\n-- BDD Statistics.\n----------------------------------------\n\n-- | Determine the size of a BDD.\nbddSize :: BDD -> Int\nbddSize bdd = unsafePerformIO $\n do size <- withBDD bdd ({#call unsafe Cudd_DagSize as _cudd_DagSize#})\n return $ cToNum size\n\nprintInfo :: IO ()\nprintInfo = {#call unsafe print_stats#} ddmanager\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"710b2e2c4be988c9fea935f96eae832ac1be2fb5","subject":"[project @ 2003-11-11 12:07:43 by juhp]","message":"[project @ 2003-11-11 12:07:43 by juhp]\n\n(sourceTagSetStyle): Fix docu typo.\n\ndarcs-hash:20031111120743-f332a-4204102591aef0df07b793b11a3a9ae45f0407c7.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"sourceview\/SourceTag.chs","new_file":"sourceview\/SourceTag.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry SourceTag@\n--\n-- Author : Duncan Coutts\n-- derived from GtkTextView bindings by Axel Simon\n-- \n-- Created: 22 October 2003\n--\n-- This file is free software; you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation; either version 2 of the License, or\n-- (at your option) any later version.\n--\n-- This file is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n--\nmodule SourceTag (\n SourceTag,\n syntaxTagNew,\n patternTagNew,\n keywordListTagNew,\n blockCommentTagNew,\n lineCommentTagNew,\n stringTagNew,\n sourceTagGetStyle,\n sourceTagSetStyle\n ) where\n\nimport Monad\t(liftM)\nimport FFI\nimport GObject\t(makeNewGObject)\n{#import Hierarchy#}\n{#import SourceViewType#}\nimport SourceTagStyle\nimport GList (toGSList, fromGSList)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- @constructor syntaxTagNew@ Create a new @ref type SourceTag@\n--\nsyntaxTagNew :: String -> String -> String -> String -> IO SourceTag\nsyntaxTagNew id name patternStart patternEnd =\n makeNewGObject mkSourceTag $ liftM castPtr $\n withCString id $ \\strPtr1 -> \n withCString name $ \\strPtr2 -> \n withCString patternStart $ \\strPtr3 -> \n withCString patternEnd $ \\strPtr4 -> \n {#call syntax_tag_new#} strPtr1 strPtr2 strPtr3 strPtr4\n\n-- @constructor patternTagNew@ Create a new @ref type SourceTag@\n--\npatternTagNew :: String -> String -> String -> IO SourceTag\npatternTagNew id name pattern =\n makeNewGObject mkSourceTag $ liftM castPtr $\n withCString id $ \\strPtr1 -> \n withCString name $ \\strPtr2 -> \n withCString pattern $ \\strPtr3 -> \n {#call unsafe pattern_tag_new#} strPtr1 strPtr2 strPtr3\n\n\n-- @constructor keywordListTagNew@ Create a new @ref type SourceTag@.\n--\nkeywordListTagNew :: String -> String -> [String] -> Bool -> Bool -> Bool ->\n\t\t String -> String -> IO SourceTag\nkeywordListTagNew id name keywords\n caseSensitive\n matchEmptyStringAtBeginning\n matchEmptyStringAtEnd\n beginningRegex\n endRegex = do\n keywordPtrs <- mapM newUTFString keywords\n keywordList <- toGSList keywordPtrs\n obj <- makeNewGObject mkSourceTag $ liftM castPtr $\n\t withCString id $ \\strPtr1 -> \n\t withCString name $ \\strPtr2 -> \n\t withCString beginningRegex $ \\strPtr3 -> \n\t withCString endRegex $ \\strPtr4 -> {#call unsafe keyword_list_tag_new#}\n\t strPtr1 strPtr2 keywordList (fromBool caseSensitive)\n\t (fromBool matchEmptyStringAtBeginning) (fromBool matchEmptyStringAtEnd)\n\t strPtr3 strPtr4\n -- destory the list\n fromGSList keywordList\n -- destory the elements\n mapM_ free keywordPtrs\n return obj\n\n-- @constructor blockCommentTagNew@ Create a new @ref type SourceTag@\n--\nblockCommentTagNew :: String -> String -> String -> String -> IO SourceTag\nblockCommentTagNew = syntaxTagNew --in the C header this is just a macro\n\n-- @constructor lineCommentTagNew@ Create a new @ref type SourceTag@\n--\nlineCommentTagNew :: String -> String -> String -> IO SourceTag\nlineCommentTagNew id name pattern =\n makeNewGObject mkSourceTag $ liftM castPtr $\n withCString id $ \\strPtr1 ->\n withCString name $ \\strPtr2 ->\n withCString pattern $ \\strPtr3 ->\n {#call unsafe line_comment_tag_new#} strPtr1 strPtr2 strPtr3\n\n-- @constructor stringTagNew@ Create a new @ref type SourceTag@\n--\nstringTagNew :: String -> String -> String -> String -> Bool -> IO SourceTag\nstringTagNew id name patternStart patternEnd endAtLineEnd =\n makeNewGObject mkSourceTag $ liftM castPtr $\n withCString id $ \\strPtr1 -> \n withCString name $ \\strPtr2 -> \n withCString patternStart $ \\strPtr3 -> \n withCString patternEnd $ \\strPtr4 -> \n {#call unsafe string_tag_new#} strPtr1 strPtr2 strPtr3 strPtr4 (fromBool endAtLineEnd)\n\n\n-- @method sourceTagGetStyle@\n-- \nsourceTagGetStyle :: SourceTag -> IO SourceTagStyle\nsourceTagGetStyle tag = do\n tsPtr <- {#call unsafe source_tag_get_style#} tag\n ts <- peek (castPtr tsPtr)\n {#call unsafe g_free#} tsPtr\n return ts\n\n-- @method sourceTagSetStyle@\n-- \nsourceTagSetStyle :: SourceTag -> SourceTagStyle -> IO ()\nsourceTagSetStyle tag ts = alloca $ \\tsPtr -> do\n poke tsPtr ts\n {#call unsafe source_tag_set_style#} tag (castPtr tsPtr)\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry SourceTag@\n--\n-- Author : Duncan Coutts\n-- derived from GtkTextView bindings by Axel Simon\n-- \n-- Created: 22 October 2003\n--\n-- This file is free software; you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation; either version 2 of the License, or\n-- (at your option) any later version.\n--\n-- This file is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n--\n--\nmodule SourceTag (\n SourceTag,\n syntaxTagNew,\n patternTagNew,\n keywordListTagNew,\n blockCommentTagNew,\n lineCommentTagNew,\n stringTagNew,\n sourceTagGetStyle,\n sourceTagSetStyle\n ) where\n\nimport Monad\t(liftM)\nimport FFI\nimport GObject\t(makeNewGObject)\n{#import Hierarchy#}\n{#import SourceViewType#}\nimport SourceTagStyle\nimport GList (toGSList, fromGSList)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- @constructor syntaxTagNew@ Create a new @ref type SourceTag@\n--\nsyntaxTagNew :: String -> String -> String -> String -> IO SourceTag\nsyntaxTagNew id name patternStart patternEnd =\n makeNewGObject mkSourceTag $ liftM castPtr $\n withCString id $ \\strPtr1 -> \n withCString name $ \\strPtr2 -> \n withCString patternStart $ \\strPtr3 -> \n withCString patternEnd $ \\strPtr4 -> \n {#call syntax_tag_new#} strPtr1 strPtr2 strPtr3 strPtr4\n\n-- @constructor patternTagNew@ Create a new @ref type SourceTag@\n--\npatternTagNew :: String -> String -> String -> IO SourceTag\npatternTagNew id name pattern =\n makeNewGObject mkSourceTag $ liftM castPtr $\n withCString id $ \\strPtr1 -> \n withCString name $ \\strPtr2 -> \n withCString pattern $ \\strPtr3 -> \n {#call unsafe pattern_tag_new#} strPtr1 strPtr2 strPtr3\n\n\n-- @constructor keywordListTagNew@ Create a new @ref type SourceTag@.\n--\nkeywordListTagNew :: String -> String -> [String] -> Bool -> Bool -> Bool ->\n\t\t String -> String -> IO SourceTag\nkeywordListTagNew id name keywords\n caseSensitive\n matchEmptyStringAtBeginning\n matchEmptyStringAtEnd\n beginningRegex\n endRegex = do\n keywordPtrs <- mapM newUTFString keywords\n keywordList <- toGSList keywordPtrs\n obj <- makeNewGObject mkSourceTag $ liftM castPtr $\n\t withCString id $ \\strPtr1 -> \n\t withCString name $ \\strPtr2 -> \n\t withCString beginningRegex $ \\strPtr3 -> \n\t withCString endRegex $ \\strPtr4 -> {#call unsafe keyword_list_tag_new#}\n\t strPtr1 strPtr2 keywordList (fromBool caseSensitive)\n\t (fromBool matchEmptyStringAtBeginning) (fromBool matchEmptyStringAtEnd)\n\t strPtr3 strPtr4\n -- destory the list\n fromGSList keywordList\n -- destory the elements\n mapM_ free keywordPtrs\n return obj\n\n-- @constructor blockCommentTagNew@ Create a new @ref type SourceTag@\n--\nblockCommentTagNew :: String -> String -> String -> String -> IO SourceTag\nblockCommentTagNew = syntaxTagNew --in the C header this is just a macro\n\n-- @constructor lineCommentTagNew@ Create a new @ref type SourceTag@\n--\nlineCommentTagNew :: String -> String -> String -> IO SourceTag\nlineCommentTagNew id name pattern =\n makeNewGObject mkSourceTag $ liftM castPtr $\n withCString id $ \\strPtr1 ->\n withCString name $ \\strPtr2 ->\n withCString pattern $ \\strPtr3 ->\n {#call unsafe line_comment_tag_new#} strPtr1 strPtr2 strPtr3\n\n-- @constructor stringTagNew@ Create a new @ref type SourceTag@\n--\nstringTagNew :: String -> String -> String -> String -> Bool -> IO SourceTag\nstringTagNew id name patternStart patternEnd endAtLineEnd =\n makeNewGObject mkSourceTag $ liftM castPtr $\n withCString id $ \\strPtr1 -> \n withCString name $ \\strPtr2 -> \n withCString patternStart $ \\strPtr3 -> \n withCString patternEnd $ \\strPtr4 -> \n {#call unsafe string_tag_new#} strPtr1 strPtr2 strPtr3 strPtr4 (fromBool endAtLineEnd)\n\n\n-- @method sourceTagGetStyle@\n-- \nsourceTagGetStyle :: SourceTag -> IO SourceTagStyle\nsourceTagGetStyle tag = do\n tsPtr <- {#call unsafe source_tag_get_style#} tag\n ts <- peek (castPtr tsPtr)\n {#call unsafe g_free#} tsPtr\n return ts\n\n-- @method sourceTagGetStyle@\n-- \nsourceTagSetStyle :: SourceTag -> SourceTagStyle -> IO ()\nsourceTagSetStyle tag ts = alloca $ \\tsPtr -> do\n poke tsPtr ts\n {#call unsafe source_tag_set_style#} tag (castPtr tsPtr)\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"91950ff9968a0310c2cce881d9e96dbeda4aa89d","subject":"refs #8: add get image info functions","message":"refs #8: add get image info functions\n","repos":"Delan90\/opencl,Delan90\/opencl,IFCA\/opencl,IFCA\/opencl","old_file":"src\/Control\/Parallel\/OpenCL\/Memory.chs","new_file":"src\/Control\/Parallel\/OpenCL\/Memory.chs","new_contents":"{- Copyright (c) 2011 Luis Cabellos,\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided\n with the distribution.\n\n * Neither the name of nor the names of other\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables, CPP #-}\nmodule Control.Parallel.OpenCL.Memory(\n -- * Types\n CLMem, CLSampler, CLMemFlag(..), CLMemObjectType(..), CLAddressingMode(..), \n CLFilterMode(..), CLImageFormat(..),\n -- * Memory Functions\n clCreateBuffer, clRetainMemObject, clReleaseMemObject, clGetMemType, \n clGetMemFlags, clGetMemSize, clGetMemHostPtr, clGetMemMapCount, \n clGetMemReferenceCount, clGetMemContext,\n -- * Image Functions\n clCreateImage2D, clCreateImage3D, clGetSupportedImageFormats,\n clGetImageFormat, clGetImageElementSize, clGetImageRowPitch,\n clGetImageSlicePitch, clGetImageWidth, clGetImageHeight, clGetImageDepth,\n -- * Sampler Functions\n clCreateSampler, clRetainSampler, clReleaseSampler, clGetSamplerReferenceCount, \n clGetSamplerContext, clGetSamplerAddressingMode, clGetSamplerFilterMode, \n clGetSamplerNormalizedCoords\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Control.Applicative( (<$>), (<*>) )\nimport Control.Parallel.OpenCL.Types( \n CLMem, CLContext, CLSampler, CLint, CLuint, CLbool, CLMemFlags_,\n CLMemInfo_, CLAddressingMode_, CLFilterMode_, CLSamplerInfo_, CLImageInfo_,\n CLAddressingMode(..), CLFilterMode(..), CLMemFlag(..), CLMemObjectType_, \n CLMemObjectType(..), \n wrapPError, wrapCheckSuccess, wrapGetInfo, whenSuccess, getEnumCL, \n bitmaskFromFlags, bitmaskToMemFlags, getCLValue )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\nforeign import CALLCONV \"clCreateBuffer\" raw_clCreateBuffer :: \n CLContext -> CLMemFlags_ -> CSize -> Ptr () -> Ptr CLint -> IO CLMem\nforeign import CALLCONV \"clCreateImage2D\" raw_clCreateImage2D :: \n CLContext -> CLMemFlags_ -> CLImageFormat_p -> CSize -> CSize -> CSize \n -> Ptr () -> Ptr CLint -> IO CLMem\nforeign import CALLCONV \"clCreateImage3D\" raw_clCreateImage3D :: \n CLContext -> CLMemFlags_-> CLImageFormat_p -> CSize -> CSize -> CSize -> CSize \n -> CSize -> Ptr () -> Ptr CLint -> IO CLMem\nforeign import CALLCONV \"clRetainMemObject\" raw_clRetainMemObject :: \n CLMem -> IO CLint\nforeign import CALLCONV \"clReleaseMemObject\" raw_clReleaseMemObject :: \n CLMem -> IO CLint\nforeign import CALLCONV \"clGetSupportedImageFormats\" raw_clGetSupportedImageFormats :: \n CLContext -> CLMemFlags_ -> CLMemObjectType_ -> CLuint -> CLImageFormat_p \n -> Ptr CLuint -> IO CLint\nforeign import CALLCONV \"clGetMemObjectInfo\" raw_clGetMemObjectInfo :: \n CLMem -> CLMemInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clGetImageInfo\" raw_clGetImageInfo ::\n CLMem -> CLImageInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clCreateSampler\" raw_clCreateSampler :: \n CLContext -> CLbool -> CLAddressingMode_ -> CLFilterMode_ -> Ptr CLint -> IO CLSampler\nforeign import CALLCONV \"clRetainSampler\" raw_clRetainSampler :: \n CLSampler -> IO CLint\nforeign import CALLCONV \"clReleaseSampler\" raw_clReleaseSampler :: \n CLSampler -> IO CLint\nforeign import CALLCONV \"clGetSamplerInfo\" raw_clGetSamplerInfo :: \n CLSampler -> CLSamplerInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n{-| Creates a buffer object. Returns a valid non-zero buffer object if the\nbuffer object is created successfully. Otherwise, it throws the 'CLError': \n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_INVALID_VALUE' if values specified in flags are not valid.\n\n * 'CL_INVALID_BUFFER_SIZE' if size is 0 or is greater than\n'clDeviceMaxMemAllocSize' value for all devices in context.\n\n * 'CL_INVALID_HOST_PTR' if host_ptr is NULL and 'CL_MEM_USE_HOST_PTR' or\n'CL_MEM_COPY_HOST_PTR' are set in flags or if host_ptr is not NULL but\n'CL_MEM_COPY_HOST_PTR' or 'CL_MEM_USE_HOST_PTR' are not set in flags.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor buffer object.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n-}\nclCreateBuffer :: Integral a => CLContext -> [CLMemFlag] -> (a, Ptr ()) -> IO CLMem\nclCreateBuffer ctx xs (sbuff,buff) = wrapPError $ \\perr -> do\n raw_clCreateBuffer ctx flags (fromIntegral sbuff) buff perr\n where\n flags = bitmaskFromFlags xs\n \n-- | Increments the memory object reference count. returns 'True' if the\n-- function is executed successfully. After the memobj reference count becomes\n-- zero and commands queued for execution on a command-queue(s) that use memobj\n-- have finished, the memory object is deleted. It returns 'False' if memobj is\n-- not a valid memory object.\nclRetainMemObject :: CLMem -> IO Bool\nclRetainMemObject mem = wrapCheckSuccess $ raw_clRetainMemObject mem\n\n-- | Decrements the memory object reference count. After the memobj reference\n-- count becomes zero and commands queued for execution on a command-queue(s)\n-- that use memobj have finished, the memory object is deleted. Returns 'True'\n-- if the function is executed successfully. It returns 'False' if memobj is not\n-- a valid memory object.\nclReleaseMemObject :: CLMem -> IO Bool\nclReleaseMemObject mem = wrapCheckSuccess $ raw_clReleaseMemObject mem\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLChannelOrder {\n cL_R=CL_R,\n cL_A=CL_A,\n cL_INTENSITY=CL_INTENSITY,\n cL_LUMINANCE=CL_LUMINANCE,\n cL_RG=CL_RG,\n cL_RA=CL_RA,\n cL_RGB=CL_RGB,\n cL_RGBA=CL_RGBA,\n cL_ARGB=CL_ARGB,\n cL_BGRA=CL_BGRA,\n };\n#endc\n{-| Specifies the number of channels and the channel layout i.e. the memory\nlayout in which channels are stored in the image. Valid values are described in\nthe table below.\n \n * 'CL_R', 'CL_A'.\n\n * 'CL_INTENSITY', This format can only be used if channel data type =\n'CL_UNORM_INT8', 'CL_UNORM_INT16', 'CL_SNORM_INT8', 'CL_SNORM_INT16',\n'CL_HALF_FLOAT', or 'CL_FLOAT'.\n\n * 'CL_LUMINANCE', This format can only be used if channel data type =\n'CL_UNORM_INT8', 'CL_UNORM_INT16', 'CL_SNORM_INT8', 'CL_SNORM_INT16',\n'CL_HALF_FLOAT', or 'CL_FLOAT'.\n\n * 'CL_RG', 'CL_RA'.\n\n * 'CL_RGB', This format can only be used if channel data type =\n'CL_UNORM_SHORT_565', 'CL_UNORM_SHORT_555' or 'CL_UNORM_INT101010'.\n\n * 'CL_RGBA'.\n\n * 'CL_ARGB', 'CL_BGRA'. This format can only be used if channel data type =\n'CL_UNORM_INT8', 'CL_SNORM_INT8', 'CL_SIGNED_INT8' or 'CL_UNSIGNED_INT8'. \n-}\n{#enum CLChannelOrder {upcaseFirstLetter} deriving(Show)#}\n\n#c\nenum CLChannelType {\n cL_SNORM_INT8=CL_SNORM_INT8,\n cL_SNORM_INT16=CL_SNORM_INT16,\n cL_UNORM_INT8=CL_UNORM_INT8,\n cL_UNORM_INT16=CL_UNORM_INT16,\n cL_UNORM_SHORT_565=CL_UNORM_SHORT_565,\n cL_UNORM_SHORT_555=CL_UNORM_SHORT_555,\n cL_UNORM_INT_101010=CL_UNORM_INT_101010,\n cL_SIGNED_INT8=CL_SIGNED_INT8,\n cL_SIGNED_INT16=CL_SIGNED_INT16,\n cL_SIGNED_INT32=CL_SIGNED_INT32,\n cL_UNSIGNED_INT8=CL_UNSIGNED_INT8,\n cL_UNSIGNED_INT16=CL_UNSIGNED_INT16,\n cL_UNSIGNED_INT32=CL_UNSIGNED_INT32,\n cL_HALF_FLOAT=CL_HALF_FLOAT,\n cL_FLOAT=CL_FLOAT,\n };\n#endc\n{-| Describes the size of the channel data type. The number of bits per element\ndetermined by the image_channel_data_type and image_channel_order must be a\npower of two. The list of supported values is described in the table below.\n\n * 'CL_SNORM_INT8', Each channel component is a normalized signed 8-bit integer\nvalue.\n\n * 'CL_SNORM_INT16', Each channel component is a normalized signed 16-bit\ninteger value.\n\n * 'CL_UNORM_INT8', Each channel component is a normalized unsigned 8-bit\ninteger value.\n\n * 'CL_UNORM_INT16', Each channel component is a normalized unsigned 16-bit\ninteger value.\n\n * 'CL_UNORM_SHORT_565', Represents a normalized 5-6-5 3-channel RGB image. The\nchannel order must be 'CL_RGB'.\n\n * 'CL_UNORM_SHORT_555', Represents a normalized x-5-5-5 4-channel xRGB\nimage. The channel order must be 'CL_RGB'.\n\n * 'CL_UNORM_INT_101010', Represents a normalized x-10-10-10 4-channel xRGB\nimage. The channel order must be 'CL_RGB'.\n\n * 'CL_SIGNED_INT8', Each channel component is an unnormalized signed 8-bit\ninteger value.\n\n * 'CL_SIGNED_INT16', Each channel component is an unnormalized signed 16-bit\ninteger value.\n\n * 'CL_SIGNED_INT32', Each channel component is an unnormalized signed 32-bit\ninteger value.\n\n * 'CL_UNSIGNED_INT8', Each channel component is an unnormalized unsigned 8-bit\ninteger value.\n\n * 'CL_UNSIGNED_INT16', Each channel component is an unnormalized unsigned\n16-bit integer value.\n\n * 'CL_UNSIGNED_INT32', Each channel component is an unnormalized unsigned\n32-bit integer value.\n\n * 'CL_HALF_FLOAT', Each channel component is a 16-bit half-float value.\n\n * 'CL_FLOAT', Each channel component is a single precision floating-point\nvalue.\n-}\n{#enum CLChannelType {upcaseFirstLetter} deriving(Show)#}\n\ndata CLImageFormat = CLImageFormat\n { image_channel_order :: ! CLChannelOrder\n , image_channel_data_type :: ! CLChannelType }\n deriving( Show )\n{#pointer *cl_image_format as CLImageFormat_p -> CLImageFormat#}\ninstance Storable CLImageFormat where\n alignment _ = alignment (undefined :: CDouble)\n sizeOf _ = {#sizeof cl_image_format #}\n peek p =\n CLImageFormat <$> fmap getEnumCL ({#get cl_image_format.image_channel_order #} p)\n <*> fmap getEnumCL ({#get cl_image_format.image_channel_data_type #} p)\n poke p (CLImageFormat a b) = do\n {#set cl_image_format.image_channel_order #} p (getCLValue a)\n {#set cl_image_format.image_channel_data_type #} p (getCLValue b)\n\n-- -----------------------------------------------------------------------------\n{-| Creates a 2D image object.\n\n'clCreateImage2D' returns a valid non-zero image object created if the image\nobject is created successfully. Otherwise, it throws one of the following\n'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_INVALID_VALUE' if values specified in flags are not valid.\n\n * 'CL_INVALID_IMAGE_FORMAT_DESCRIPTOR' if values specified in image_format are\nnot valid.\n\n * 'CL_INVALID_IMAGE_SIZE' if image_width or image_height are 0 or if they\nexceed values specified in 'CL_DEVICE_IMAGE2D_MAX_WIDTH' or\n'CL_DEVICE_IMAGE2D_MAX_HEIGHT' respectively for all devices in context or if\nvalues specified by image_row_pitch do not follow rules described in the\nargument description above.\n\n * 'CL_INVALID_HOST_PTR' if host_ptr is 'nullPtr' and 'CL_MEM_USE_HOST_PTR' or\n'CL_MEM_COPY_HOST_PTR' are set in flags or if host_ptr is not 'nullPtr' but\n'CL_MEM_COPY_HOST_PTR' or 'CL_MEM_USE_HOST_PTR' are not set in flags.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED' if the image_format is not supported.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor image object.\n\n * 'CL_INVALID_OPERATION' if there are no devices in context that support images\n(i.e. 'CL_DEVICE_IMAGE_SUPPORT' (specified in the table of OpenCL Device Queries\nfor 'clGetDeviceInfo') is 'False').\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n\n-}\n\nclCreateImage2D :: Integral a => CLContext -- ^ A valid OpenCL context on which\n -- the image object is to be created.\n -> [CLMemFlag] -- ^ A list of flags that is used to specify\n -- allocation and usage information about the\n -- image memory object being created.\n -> CLImageFormat -- ^ Structure that describes format\n -- properties of the image to be allocated.\n -> a -- ^ The width of the image in pixels. It must be values\n -- greater than or equal to 1.\n -> a -- ^ The height of the image in pixels. It must be\n -- values greater than or equal to 1.\n -> a -- ^ The scan-line pitch in bytes. This must be 0 if\n -- host_ptr is 'nullPtr' and can be either 0 or greater\n -- than or equal to image_width * size of element in\n -- bytes if host_ptr is not 'nullPtr'. If host_ptr is\n -- not 'nullPtr' and image_row_pitch is equal to 0,\n -- image_row_pitch is calculated as image_width * size\n -- of element in bytes. If image_row_pitch is not 0, it\n -- must be a multiple of the image element size in\n -- bytes.\n -> Ptr () -- ^ A pointer to the image data that may already\n -- be allocated by the application. The size of the\n -- buffer that host_ptr points to must be greater\n -- than or equal to image_row_pitch *\n -- image_height. The size of each element in bytes\n -- must be a power of 2. The image data specified\n -- by host_ptr is stored as a linear sequence of\n -- adjacent scanlines. Each scanline is stored as a\n -- linear sequence of image elements.\n -> IO CLMem\nclCreateImage2D ctx xs fmt iw ih irp ptr = wrapPError $ \\perr -> with fmt $ \\pfmt -> do\n raw_clCreateImage2D ctx flags pfmt ciw cih cirp ptr perr\n where\n flags = bitmaskFromFlags xs\n ciw = fromIntegral iw\n cih = fromIntegral ih\n cirp = fromIntegral irp\n\n{-| Creates a 3D image object.\n\n'clCreateImage3D' returns a valid non-zero image object created if the image\nobject is created successfully. Otherwise, it throws one of the following\n'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_INVALID_VALUE' if values specified in flags are not valid.\n\n * 'CL_INVALID_IMAGE_FORMAT_DESCRIPTOR' if values specified in image_format are\nnot valid.\n\n * 'CL_INVALID_IMAGE_SIZE' if image_width, image_height are 0 or if image_depth\nless than or equal to 1 or if they exceed values specified in\n'CL_DEVICE_IMAGE3D_MAX_WIDTH', CL_DEVICE_IMAGE3D_MAX_HEIGHT' or\n'CL_DEVICE_IMAGE3D_MAX_DEPTH' respectively for all devices in context or if\nvalues specified by image_row_pitch and image_slice_pitch do not follow rules\ndescribed in the argument description above.\n\n * 'CL_INVALID_HOST_PTR' if host_ptr is 'nullPtr' and 'CL_MEM_USE_HOST_PTR' or\n'CL_MEM_COPY_HOST_PTR' are set in flags or if host_ptr is not 'nullPtr' but\n'CL_MEM_COPY_HOST_PTR' or 'CL_MEM_USE_HOST_PTR' are not set in flags.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED' if the image_format is not supported.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor image object.\n\n * 'CL_INVALID_OPERATION' if there are no devices in context that support images\n(i.e. 'CL_DEVICE_IMAGE_SUPPORT' (specified in the table of OpenCL Device Queries\nfor clGetDeviceInfo) is 'False').\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n\n-}\nclCreateImage3D :: Integral a => CLContext -- ^ A valid OpenCL context on which\n -- the image object is to be created.\n -> [CLMemFlag] -- ^ A list of flags that is used to specify\n -- allocation and usage information about the\n -- image memory object being created.\n -> CLImageFormat -- ^ Structure that describes format\n -- properties of the image to be allocated.\n -> a -- ^ The width of the image in pixels. It must be values\n -- greater than or equal to 1.\n -> a -- ^ The height of the image in pixels. It must be\n -- values greater than or equal to 1.\n -> a -- ^ The depth of the image in pixels. This must be a\n -- value greater than 1.\n -> a -- ^ The scan-line pitch in bytes. This must be 0 if\n -- host_ptr is 'nullPtr' and can be either 0 or greater\n -- than or equal to image_width * size of element in\n -- bytes if host_ptr is not 'nullPtr'. If host_ptr is\n -- not 'nullPtr' and image_row_pitch is equal to 0,\n -- image_row_pitch is calculated as image_width * size\n -- of element in bytes. If image_row_pitch is not 0, it\n -- must be a multiple of the image element size in\n -- bytes.\n -> a -- ^ The size in bytes of each 2D slice in the 3D\n -- image. This must be 0 if host_ptr is 'nullPtr' and\n -- can be either 0 or greater than or equal to\n -- image_row_pitch * image_height if host_ptr is not\n -- 'nullPtr'. If host_ptr is not 'nullPtr' and\n -- image_slice_pitch equal to 0, image_slice_pitch is\n -- calculated as image_row_pitch * image_height. If\n -- image_slice_pitch is not 0, it must be a multiple of\n -- the image_row_pitch.\n -> Ptr () -- ^ A pointer to the image data that may already\n -- be allocated by the application. The size of the\n -- buffer that host_ptr points to must be greater\n -- than or equal to image_slice_pitch *\n -- image_depth. The size of each element in bytes\n -- must be a power of 2. The image data specified\n -- by host_ptr is stored as a linear sequence of\n -- adjacent 2D slices. Each 2D slice is a linear\n -- sequence of adjacent scanlines. Each scanline is\n -- a linear sequence of image elements.\n -> IO CLMem\nclCreateImage3D ctx xs fmt iw ih idepth irp isp ptr = wrapPError $ \\perr -> with fmt $ \\pfmt -> do\n raw_clCreateImage3D ctx flags pfmt ciw cih cid cirp cisp ptr perr\n where\n flags = bitmaskFromFlags xs\n ciw = fromIntegral iw\n cih = fromIntegral ih\n cid = fromIntegral idepth\n cirp = fromIntegral irp\n cisp = fromIntegral isp \n \ngetNumSupportedImageFormats :: CLContext -> [CLMemFlag] -> CLMemObjectType -> IO CLuint\ngetNumSupportedImageFormats ctx xs mtype = alloca $ \\(value_size :: Ptr CLuint) -> do\n whenSuccess (raw_clGetSupportedImageFormats ctx flags (getCLValue mtype) 0 nullPtr value_size)\n $ peek value_size\n where\n flags = bitmaskFromFlags xs\n \n{-| Get the list of image formats supported by an OpenCL\nimplementation. 'clGetSupportedImageFormats' can be used to get the list of\nimage formats supported by an OpenCL implementation when the following\ninformation about an image memory object is specified:\n\n * Context\n * Image type - 2D or 3D image\n * Image object allocation information\n\nThrows 'CL_INVALID_CONTEXT' if context is not a valid context, throws\n'CL_INVALID_VALUE' if flags or image_type are not valid.\n\n-}\nclGetSupportedImageFormats :: CLContext -- ^ A valid OpenCL context on which the\n -- image object(s) will be created.\n -> [CLMemFlag] -- ^ A bit-field that is used to\n -- specify allocation and usage\n -- information about the image\n -- memory object.\n -> CLMemObjectType -- ^ Describes the image type\n -- and must be either\n -- 'CL_MEM_OBJECT_IMAGE2D' or\n -- 'CL_MEM_OBJECT_IMAGE3D'.\n -> IO [CLImageFormat]\nclGetSupportedImageFormats ctx xs mtype = do\n num <- getNumSupportedImageFormats ctx xs mtype\n allocaArray (fromIntegral num) $ \\(buff :: Ptr CLImageFormat) -> do\n whenSuccess (raw_clGetSupportedImageFormats ctx flags (getCLValue mtype) num (castPtr buff) nullPtr)\n $ peekArray (fromIntegral num) buff\n where\n flags = bitmaskFromFlags xs\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLImageInfo {\n cL_IMAGE_FORMAT=CL_IMAGE_FORMAT,\n cL_IMAGE_ELEMENT_SIZE=CL_IMAGE_ELEMENT_SIZE,\n cL_IMAGE_ROW_PITCH=CL_IMAGE_ROW_PITCH,\n cL_IMAGE_SLICE_PITCH=CL_IMAGE_SLICE_PITCH,\n cL_IMAGE_WIDTH=CL_IMAGE_WIDTH,\n cL_IMAGE_HEIGHT=CL_IMAGE_HEIGHT,\n cL_IMAGE_DEPTH=CL_IMAGE_DEPTH,\n };\n#endc\n{#enum CLImageInfo {upcaseFirstLetter} #}\n\n-- | Return image format descriptor specified when image is created with\n-- clCreateImage2D or clCreateImage3D.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_FORMAT'.\nclGetImageFormat :: CLMem -> IO CLImageFormat\nclGetImageFormat mem =\n wrapGetInfo (\\(dat :: Ptr CLImageFormat) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_FORMAT\n size = fromIntegral $ sizeOf (undefined :: CLImageFormat)\n \n-- | Return size of each element of the image memory object given by image. An\n-- element is made up of n channels. The value of n is given in 'CLImageFormat'\n-- descriptor.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_ELEMENT_SIZE'.\nclGetImageElementSize :: CLMem -> IO CSize \nclGetImageElementSize mem =\n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_ELEMENT_SIZE\n size = fromIntegral $ sizeOf (undefined :: CSize)\n \n-- | Return size in bytes of a row of elements of the image object given by\n-- image.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_ROW_PITCH'.\nclGetImageRowPitch :: CLMem -> IO CSize \nclGetImageRowPitch mem = \n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_ROW_PITCH\n size = fromIntegral $ sizeOf (undefined :: CSize)\n \n-- | Return size in bytes of a 2D slice for the 3D image object given by\n-- image. For a 2D image object this value will be 0.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_SLICE_PITCH'.\nclGetImageSlicePitch :: CLMem -> IO CSize \nclGetImageSlicePitch mem = \n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_SLICE_PITCH\n size = fromIntegral $ sizeOf (undefined :: CSize) \n \n-- | Return width of image in pixels.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_WIDTH'.\nclGetImageWidth :: CLMem -> IO CSize \nclGetImageWidth mem = \n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_WIDTH\n size = fromIntegral $ sizeOf (undefined :: CSize)\n \n-- | Return height of image in pixels.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_HEIGHT'.\nclGetImageHeight :: CLMem -> IO CSize \nclGetImageHeight mem = \n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_HEIGHT\n size = fromIntegral $ sizeOf (undefined :: CSize)\n\n-- | Return depth of the image in pixels. For a 2D image, depth equals 0.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_DEPTH'.\nclGetImageDepth :: CLMem -> IO CSize \nclGetImageDepth mem = \n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_DEPTH\n size = fromIntegral $ sizeOf (undefined :: CSize)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemInfo {\n cL_MEM_TYPE=CL_MEM_TYPE,\n cL_MEM_FLAGS=CL_MEM_FLAGS,\n cL_MEM_SIZE=CL_MEM_SIZE,\n cL_MEM_HOST_PTR=CL_MEM_HOST_PTR,\n cL_MEM_MAP_COUNT=CL_MEM_MAP_COUNT,\n cL_MEM_REFERENCE_COUNT=CL_MEM_REFERENCE_COUNT,\n cL_MEM_CONTEXT=CL_MEM_CONTEXT,\n };\n#endc\n{#enum CLMemInfo {upcaseFirstLetter} #}\n\n-- | Returns the mem object type.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_TYPE'.\nclGetMemType :: CLMem -> IO CLMemObjectType\nclGetMemType mem =\n wrapGetInfo (\\(dat :: Ptr CLMemObjectType_) ->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_MEM_TYPE\n size = fromIntegral $ sizeOf (0::CLMemObjectType_)\n\n-- | Return the flags argument value specified when memobj was created.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_FLAGS'.\nclGetMemFlags :: CLMem -> IO [CLMemFlag]\nclGetMemFlags mem =\n wrapGetInfo (\\(dat :: Ptr CLMemFlags_)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) bitmaskToMemFlags\n where \n infoid = getCLValue CL_MEM_FLAGS\n size = fromIntegral $ sizeOf (0::CLMemFlags_)\n\n-- | Return actual size of memobj in bytes.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_SIZE'.\nclGetMemSize :: CLMem -> IO CSize\nclGetMemSize mem =\n wrapGetInfo (\\(dat :: Ptr CSize)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_SIZE\n size = fromIntegral $ sizeOf (0::CSize)\n\n-- | Return the host_ptr argument value specified when memobj is created.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_HOST_PTR'.\nclGetMemHostPtr :: CLMem -> IO (Ptr ())\nclGetMemHostPtr mem =\n wrapGetInfo (\\(dat :: Ptr (Ptr ()))->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_HOST_PTR\n size = fromIntegral $ sizeOf (nullPtr::Ptr ())\n\n-- | Map count. The map count returned should be considered immediately\n-- stale. It is unsuitable for general use in applications. This feature is\n-- provided for debugging.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_MAP_COUNT'.\nclGetMemMapCount :: CLMem -> IO CLuint\nclGetMemMapCount mem =\n wrapGetInfo (\\(dat :: Ptr CLuint)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_MAP_COUNT\n size = fromIntegral $ sizeOf (0 :: CLuint)\n\n-- | Return memobj reference count. The reference count returned should be\n-- considered immediately stale. It is unsuitable for general use in\n-- applications. This feature is provided for identifying memory leaks.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_REFERENCE_COUNT'.\nclGetMemReferenceCount :: CLMem -> IO CLuint\nclGetMemReferenceCount mem =\n wrapGetInfo (\\(dat :: Ptr CLuint)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0 :: CLuint)\n\n-- | Return context specified when memory object is created.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_CONTEXT'.\nclGetMemContext :: CLMem -> IO CLContext\nclGetMemContext mem =\n wrapGetInfo (\\(dat :: Ptr CLContext)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_CONTEXT\n size = fromIntegral $ sizeOf (0 :: CLuint)\n\n-- -----------------------------------------------------------------------------\n{-| Creates a sampler object. A sampler object describes how to sample an image\nwhen the image is read in the kernel. The built-in functions to read from an\nimage in a kernel take a sampler as an argument. The sampler arguments to the\nimage read function can be sampler objects created using OpenCL functions and\npassed as argument values to the kernel or can be samplers declared inside a\nkernel. In this section we discuss how sampler objects are created using OpenCL\nfunctions.\n\nReturns a valid non-zero sampler object if the sampler object is created\nsuccessfully. Otherwise, it throws one of the following 'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_INVALID_VALUE' if addressing_mode, filter_mode, or normalized_coords or a\ncombination of these argument values are not valid.\n\n * 'CL_INVALID_OPERATION' if images are not supported by any device associated\nwith context (i.e. 'CL_DEVICE_IMAGE_SUPPORT' specified in the table of OpenCL\nDevice Queries for clGetDeviceInfo is 'False').\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n-}\nclCreateSampler :: CLContext -> Bool -> CLAddressingMode -> CLFilterMode \n -> IO CLSampler\nclCreateSampler ctx norm am fm = wrapPError $ \\perr -> do\n raw_clCreateSampler ctx (fromBool norm) (getCLValue am) (getCLValue fm) perr\n\n-- | Increments the sampler reference count. 'clCreateSampler' does an implicit\n-- retain. Returns 'True' if the function is executed successfully. It returns\n-- 'False' if sampler is not a valid sampler object.\nclRetainSampler :: CLSampler -> IO Bool\nclRetainSampler mem = wrapCheckSuccess $ raw_clRetainSampler mem\n\n-- | Decrements the sampler reference count. The sampler object is deleted after\n-- the reference count becomes zero and commands queued for execution on a\n-- command-queue(s) that use sampler have finished. 'clReleaseSampler' returns\n-- 'True' if the function is executed successfully. It returns 'False' if\n-- sampler is not a valid sampler object.\nclReleaseSampler :: CLSampler -> IO Bool\nclReleaseSampler mem = wrapCheckSuccess $ raw_clReleaseSampler mem\n\n#c\nenum CLSamplerInfo {\n cL_SAMPLER_REFERENCE_COUNT=CL_SAMPLER_REFERENCE_COUNT,\n cL_SAMPLER_CONTEXT=CL_SAMPLER_CONTEXT,\n cL_SAMPLER_ADDRESSING_MODE=CL_SAMPLER_ADDRESSING_MODE,\n cL_SAMPLER_FILTER_MODE=CL_SAMPLER_FILTER_MODE,\n cL_SAMPLER_NORMALIZED_COORDS=CL_SAMPLER_NORMALIZED_COORDS\n };\n#endc\n{#enum CLSamplerInfo {upcaseFirstLetter} #}\n\n-- | Return the sampler reference count. The reference count returned should be\n-- considered immediately stale. It is unsuitable for general use in\n-- applications. This feature is provided for identifying memory leaks.\n--\n-- This function execute OpenCL clGetSamplerInfo with\n-- 'CL_SAMPLER_REFERENCE_COUNT'.\nclGetSamplerReferenceCount :: CLSampler -> IO CLuint\nclGetSamplerReferenceCount sam =\n wrapGetInfo (\\(dat :: Ptr CLuint)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_SAMPLER_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0 :: CLuint)\n\n-- | Return the context specified when the sampler is created.\n--\n-- This function execute OpenCL clGetSamplerInfo with 'CL_SAMPLER_CONTEXT'.\nclGetSamplerContext :: CLSampler -> IO CLContext\nclGetSamplerContext sam =\n wrapGetInfo (\\(dat :: Ptr CLContext)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_SAMPLER_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr :: CLContext)\n\n-- | Return the value specified by addressing_mode argument to clCreateSampler.\n--\n-- This function execute OpenCL clGetSamplerInfo with\n-- 'CL_SAMPLER_ADDRESSING_MODE'.\nclGetSamplerAddressingMode :: CLSampler -> IO CLAddressingMode\nclGetSamplerAddressingMode sam =\n wrapGetInfo (\\(dat :: Ptr CLAddressingMode_)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_SAMPLER_ADDRESSING_MODE\n size = fromIntegral $ sizeOf (0 :: CLAddressingMode_)\n\n-- | Return the value specified by filter_mode argument to clCreateSampler.\n--\n-- This function execute OpenCL clGetSamplerInfo with 'CL_SAMPLER_FILTER_MODE'.\nclGetSamplerFilterMode :: CLSampler -> IO CLFilterMode\nclGetSamplerFilterMode sam =\n wrapGetInfo (\\(dat :: Ptr CLFilterMode_)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_SAMPLER_FILTER_MODE\n size = fromIntegral $ sizeOf (0 :: CLFilterMode_)\n\n-- | Return the value specified by normalized_coords argument to\n-- clCreateSampler.\n--\n-- This function execute OpenCL clGetSamplerInfo with\n-- 'CL_SAMPLER_NORMALIZED_COORDS'.\nclGetSamplerNormalizedCoords :: CLSampler -> IO Bool\nclGetSamplerNormalizedCoords sam =\n wrapGetInfo (\\(dat :: Ptr CLbool)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) (\/=0)\n where \n infoid = getCLValue CL_SAMPLER_NORMALIZED_COORDS\n size = fromIntegral $ sizeOf (0 :: CLbool)\n\n-- -----------------------------------------------------------------------------\n","old_contents":"{- Copyright (c) 2011 Luis Cabellos,\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided\n with the distribution.\n\n * Neither the name of nor the names of other\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables, CPP #-}\nmodule Control.Parallel.OpenCL.Memory(\n -- * Types\n CLMem, CLSampler, CLMemFlag(..), CLMemObjectType(..), CLAddressingMode(..), \n CLFilterMode(..), CLImageFormat(..),\n -- * Memory Functions\n clCreateBuffer, clRetainMemObject, clReleaseMemObject, clGetMemType, \n clGetMemFlags, clGetMemSize, clGetMemHostPtr, clGetMemMapCount, \n clGetMemReferenceCount, clGetMemContext,\n -- * Image Functions\n clCreateImage2D, clCreateImage3D, clGetSupportedImageFormats,\n -- * Sampler Functions\n clCreateSampler, clRetainSampler, clReleaseSampler, clGetSamplerReferenceCount, \n clGetSamplerContext, clGetSamplerAddressingMode, clGetSamplerFilterMode, \n clGetSamplerNormalizedCoords\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Control.Applicative( (<$>), (<*>) )\nimport Control.Parallel.OpenCL.Types( \n CLMem, CLContext, CLSampler, CLint, CLuint, CLbool, CLMemFlags_,\n CLMemInfo_, CLAddressingMode_, CLFilterMode_, CLSamplerInfo_,\n CLAddressingMode(..), CLFilterMode(..), CLMemFlag(..), CLMemObjectType_, \n CLMemObjectType(..), \n wrapPError, wrapCheckSuccess, wrapGetInfo, whenSuccess, getEnumCL, \n bitmaskFromFlags, bitmaskToMemFlags, getCLValue )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\nforeign import CALLCONV \"clCreateBuffer\" raw_clCreateBuffer :: \n CLContext -> CLMemFlags_ -> CSize -> Ptr () -> Ptr CLint -> IO CLMem\nforeign import CALLCONV \"clCreateImage2D\" raw_clCreateImage2D :: \n CLContext -> CLMemFlags_ -> CLImageFormat_p -> CSize -> CSize -> CSize \n -> Ptr () -> Ptr CLint -> IO CLMem\nforeign import CALLCONV \"clCreateImage3D\" raw_clCreateImage3D :: \n CLContext -> CLMemFlags_-> CLImageFormat_p -> CSize -> CSize -> CSize -> CSize \n -> CSize -> Ptr () -> Ptr CLint -> IO CLMem\nforeign import CALLCONV \"clRetainMemObject\" raw_clRetainMemObject :: \n CLMem -> IO CLint\nforeign import CALLCONV \"clReleaseMemObject\" raw_clReleaseMemObject :: \n CLMem -> IO CLint\nforeign import CALLCONV \"clGetSupportedImageFormats\" raw_clGetSupportedImageFormats :: \n CLContext -> CLMemFlags_ -> CLMemObjectType_ -> CLuint -> CLImageFormat_p \n -> Ptr CLuint -> IO CLint\nforeign import CALLCONV \"clGetMemObjectInfo\" raw_clGetMemObjectInfo :: \n CLMem -> CLMemInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n--foreign import CALLCONV \"clGetImageInfo\" raw_clGetImageInfo :: \n-- CLMem -> CLImageInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clCreateSampler\" raw_clCreateSampler :: \n CLContext -> CLbool -> CLAddressingMode_ -> CLFilterMode_ -> Ptr CLint -> IO CLSampler\nforeign import CALLCONV \"clRetainSampler\" raw_clRetainSampler :: \n CLSampler -> IO CLint\nforeign import CALLCONV \"clReleaseSampler\" raw_clReleaseSampler :: \n CLSampler -> IO CLint\nforeign import CALLCONV \"clGetSamplerInfo\" raw_clGetSamplerInfo :: \n CLSampler -> CLSamplerInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n{-| Creates a buffer object. Returns a valid non-zero buffer object if the\nbuffer object is created successfully. Otherwise, it throws the 'CLError': \n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_INVALID_VALUE' if values specified in flags are not valid.\n\n * 'CL_INVALID_BUFFER_SIZE' if size is 0 or is greater than\n'clDeviceMaxMemAllocSize' value for all devices in context.\n\n * 'CL_INVALID_HOST_PTR' if host_ptr is NULL and 'CL_MEM_USE_HOST_PTR' or\n'CL_MEM_COPY_HOST_PTR' are set in flags or if host_ptr is not NULL but\n'CL_MEM_COPY_HOST_PTR' or 'CL_MEM_USE_HOST_PTR' are not set in flags.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor buffer object.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n-}\nclCreateBuffer :: Integral a => CLContext -> [CLMemFlag] -> (a, Ptr ()) -> IO CLMem\nclCreateBuffer ctx xs (sbuff,buff) = wrapPError $ \\perr -> do\n raw_clCreateBuffer ctx flags (fromIntegral sbuff) buff perr\n where\n flags = bitmaskFromFlags xs\n \n-- | Increments the memory object reference count. returns 'True' if the\n-- function is executed successfully. After the memobj reference count becomes\n-- zero and commands queued for execution on a command-queue(s) that use memobj\n-- have finished, the memory object is deleted. It returns 'False' if memobj is\n-- not a valid memory object.\nclRetainMemObject :: CLMem -> IO Bool\nclRetainMemObject mem = wrapCheckSuccess $ raw_clRetainMemObject mem\n\n-- | Decrements the memory object reference count. After the memobj reference\n-- count becomes zero and commands queued for execution on a command-queue(s)\n-- that use memobj have finished, the memory object is deleted. Returns 'True'\n-- if the function is executed successfully. It returns 'False' if memobj is not\n-- a valid memory object.\nclReleaseMemObject :: CLMem -> IO Bool\nclReleaseMemObject mem = wrapCheckSuccess $ raw_clReleaseMemObject mem\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLChannelOrder {\n cL_R=CL_R,\n cL_A=CL_A,\n cL_INTENSITY=CL_INTENSITY,\n cL_LUMINANCE=CL_LUMINANCE,\n cL_RG=CL_RG,\n cL_RA=CL_RA,\n cL_RGB=CL_RGB,\n cL_RGBA=CL_RGBA,\n cL_ARGB=CL_ARGB,\n cL_BGRA=CL_BGRA,\n };\n#endc\n{-| Specifies the number of channels and the channel layout i.e. the memory\nlayout in which channels are stored in the image. Valid values are described in\nthe table below.\n \n * 'CL_R', 'CL_A'.\n\n * 'CL_INTENSITY', This format can only be used if channel data type =\n'CL_UNORM_INT8', 'CL_UNORM_INT16', 'CL_SNORM_INT8', 'CL_SNORM_INT16',\n'CL_HALF_FLOAT', or 'CL_FLOAT'.\n\n * 'CL_LUMINANCE', This format can only be used if channel data type =\n'CL_UNORM_INT8', 'CL_UNORM_INT16', 'CL_SNORM_INT8', 'CL_SNORM_INT16',\n'CL_HALF_FLOAT', or 'CL_FLOAT'.\n\n * 'CL_RG', 'CL_RA'.\n\n * 'CL_RGB', This format can only be used if channel data type =\n'CL_UNORM_SHORT_565', 'CL_UNORM_SHORT_555' or 'CL_UNORM_INT101010'.\n\n * 'CL_RGBA'.\n\n * 'CL_ARGB', 'CL_BGRA'. This format can only be used if channel data type =\n'CL_UNORM_INT8', 'CL_SNORM_INT8', 'CL_SIGNED_INT8' or 'CL_UNSIGNED_INT8'. \n-}\n{#enum CLChannelOrder {upcaseFirstLetter} deriving(Show)#}\n\n#c\nenum CLChannelType {\n cL_SNORM_INT8=CL_SNORM_INT8,\n cL_SNORM_INT16=CL_SNORM_INT16,\n cL_UNORM_INT8=CL_UNORM_INT8,\n cL_UNORM_INT16=CL_UNORM_INT16,\n cL_UNORM_SHORT_565=CL_UNORM_SHORT_565,\n cL_UNORM_SHORT_555=CL_UNORM_SHORT_555,\n cL_UNORM_INT_101010=CL_UNORM_INT_101010,\n cL_SIGNED_INT8=CL_SIGNED_INT8,\n cL_SIGNED_INT16=CL_SIGNED_INT16,\n cL_SIGNED_INT32=CL_SIGNED_INT32,\n cL_UNSIGNED_INT8=CL_UNSIGNED_INT8,\n cL_UNSIGNED_INT16=CL_UNSIGNED_INT16,\n cL_UNSIGNED_INT32=CL_UNSIGNED_INT32,\n cL_HALF_FLOAT=CL_HALF_FLOAT,\n cL_FLOAT=CL_FLOAT,\n };\n#endc\n{-| Describes the size of the channel data type. The number of bits per element\ndetermined by the image_channel_data_type and image_channel_order must be a\npower of two. The list of supported values is described in the table below.\n\n * 'CL_SNORM_INT8', Each channel component is a normalized signed 8-bit integer\nvalue.\n\n * 'CL_SNORM_INT16', Each channel component is a normalized signed 16-bit\ninteger value.\n\n * 'CL_UNORM_INT8', Each channel component is a normalized unsigned 8-bit\ninteger value.\n\n * 'CL_UNORM_INT16', Each channel component is a normalized unsigned 16-bit\ninteger value.\n\n * 'CL_UNORM_SHORT_565', Represents a normalized 5-6-5 3-channel RGB image. The\nchannel order must be 'CL_RGB'.\n\n * 'CL_UNORM_SHORT_555', Represents a normalized x-5-5-5 4-channel xRGB\nimage. The channel order must be 'CL_RGB'.\n\n * 'CL_UNORM_INT_101010', Represents a normalized x-10-10-10 4-channel xRGB\nimage. The channel order must be 'CL_RGB'.\n\n * 'CL_SIGNED_INT8', Each channel component is an unnormalized signed 8-bit\ninteger value.\n\n * 'CL_SIGNED_INT16', Each channel component is an unnormalized signed 16-bit\ninteger value.\n\n * 'CL_SIGNED_INT32', Each channel component is an unnormalized signed 32-bit\ninteger value.\n\n * 'CL_UNSIGNED_INT8', Each channel component is an unnormalized unsigned 8-bit\ninteger value.\n\n * 'CL_UNSIGNED_INT16', Each channel component is an unnormalized unsigned\n16-bit integer value.\n\n * 'CL_UNSIGNED_INT32', Each channel component is an unnormalized unsigned\n32-bit integer value.\n\n * 'CL_HALF_FLOAT', Each channel component is a 16-bit half-float value.\n\n * 'CL_FLOAT', Each channel component is a single precision floating-point\nvalue.\n-}\n{#enum CLChannelType {upcaseFirstLetter} deriving(Show)#}\n\ndata CLImageFormat = CLImageFormat\n { image_channel_order :: ! CLChannelOrder\n , image_channel_data_type :: ! CLChannelType }\n deriving( Show )\n{#pointer *cl_image_format as CLImageFormat_p -> CLImageFormat#}\ninstance Storable CLImageFormat where\n alignment _ = alignment (undefined :: CDouble)\n sizeOf _ = {#sizeof cl_image_format #}\n peek p =\n CLImageFormat <$> fmap getEnumCL ({#get cl_image_format.image_channel_order #} p)\n <*> fmap getEnumCL ({#get cl_image_format.image_channel_data_type #} p)\n poke p (CLImageFormat a b) = do\n {#set cl_image_format.image_channel_order #} p (getCLValue a)\n {#set cl_image_format.image_channel_data_type #} p (getCLValue b)\n\n-- -----------------------------------------------------------------------------\n{-| Creates a 2D image object.\n\n'clCreateImage2D' returns a valid non-zero image object created if the image\nobject is created successfully. Otherwise, it throws one of the following\n'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_INVALID_VALUE' if values specified in flags are not valid.\n\n * 'CL_INVALID_IMAGE_FORMAT_DESCRIPTOR' if values specified in image_format are\nnot valid.\n\n * 'CL_INVALID_IMAGE_SIZE' if image_width or image_height are 0 or if they\nexceed values specified in 'CL_DEVICE_IMAGE2D_MAX_WIDTH' or\n'CL_DEVICE_IMAGE2D_MAX_HEIGHT' respectively for all devices in context or if\nvalues specified by image_row_pitch do not follow rules described in the\nargument description above.\n\n * 'CL_INVALID_HOST_PTR' if host_ptr is 'nullPtr' and 'CL_MEM_USE_HOST_PTR' or\n'CL_MEM_COPY_HOST_PTR' are set in flags or if host_ptr is not 'nullPtr' but\n'CL_MEM_COPY_HOST_PTR' or 'CL_MEM_USE_HOST_PTR' are not set in flags.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED' if the image_format is not supported.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor image object.\n\n * 'CL_INVALID_OPERATION' if there are no devices in context that support images\n(i.e. 'CL_DEVICE_IMAGE_SUPPORT' (specified in the table of OpenCL Device Queries\nfor 'clGetDeviceInfo') is 'False').\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n\n-}\n\nclCreateImage2D :: Integral a => CLContext -- ^ A valid OpenCL context on which\n -- the image object is to be created.\n -> [CLMemFlag] -- ^ A list of flags that is used to specify\n -- allocation and usage information about the\n -- image memory object being created.\n -> CLImageFormat -- ^ Structure that describes format\n -- properties of the image to be allocated.\n -> a -- ^ The width of the image in pixels. It must be values\n -- greater than or equal to 1.\n -> a -- ^ The height of the image in pixels. It must be\n -- values greater than or equal to 1.\n -> a -- ^ The scan-line pitch in bytes. This must be 0 if\n -- host_ptr is 'nullPtr' and can be either 0 or greater\n -- than or equal to image_width * size of element in\n -- bytes if host_ptr is not 'nullPtr'. If host_ptr is\n -- not 'nullPtr' and image_row_pitch is equal to 0,\n -- image_row_pitch is calculated as image_width * size\n -- of element in bytes. If image_row_pitch is not 0, it\n -- must be a multiple of the image element size in\n -- bytes.\n -> Ptr () -- ^ A pointer to the image data that may already\n -- be allocated by the application. The size of the\n -- buffer that host_ptr points to must be greater\n -- than or equal to image_row_pitch *\n -- image_height. The size of each element in bytes\n -- must be a power of 2. The image data specified\n -- by host_ptr is stored as a linear sequence of\n -- adjacent scanlines. Each scanline is stored as a\n -- linear sequence of image elements.\n -> IO CLMem\nclCreateImage2D ctx xs fmt iw ih irp ptr = wrapPError $ \\perr -> with fmt $ \\pfmt -> do\n raw_clCreateImage2D ctx flags pfmt ciw cih cirp ptr perr\n where\n flags = bitmaskFromFlags xs\n ciw = fromIntegral iw\n cih = fromIntegral ih\n cirp = fromIntegral irp\n\n{-| Creates a 3D image object.\n\n'clCreateImage3D' returns a valid non-zero image object created if the image\nobject is created successfully. Otherwise, it throws one of the following\n'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_INVALID_VALUE' if values specified in flags are not valid.\n\n * 'CL_INVALID_IMAGE_FORMAT_DESCRIPTOR' if values specified in image_format are\nnot valid.\n\n * 'CL_INVALID_IMAGE_SIZE' if image_width, image_height are 0 or if image_depth\nless than or equal to 1 or if they exceed values specified in\n'CL_DEVICE_IMAGE3D_MAX_WIDTH', CL_DEVICE_IMAGE3D_MAX_HEIGHT' or\n'CL_DEVICE_IMAGE3D_MAX_DEPTH' respectively for all devices in context or if\nvalues specified by image_row_pitch and image_slice_pitch do not follow rules\ndescribed in the argument description above.\n\n * 'CL_INVALID_HOST_PTR' if host_ptr is 'nullPtr' and 'CL_MEM_USE_HOST_PTR' or\n'CL_MEM_COPY_HOST_PTR' are set in flags or if host_ptr is not 'nullPtr' but\n'CL_MEM_COPY_HOST_PTR' or 'CL_MEM_USE_HOST_PTR' are not set in flags.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED' if the image_format is not supported.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor image object.\n\n * 'CL_INVALID_OPERATION' if there are no devices in context that support images\n(i.e. 'CL_DEVICE_IMAGE_SUPPORT' (specified in the table of OpenCL Device Queries\nfor clGetDeviceInfo) is 'False').\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n\n-}\nclCreateImage3D :: Integral a => CLContext -- ^ A valid OpenCL context on which\n -- the image object is to be created.\n -> [CLMemFlag] -- ^ A list of flags that is used to specify\n -- allocation and usage information about the\n -- image memory object being created.\n -> CLImageFormat -- ^ Structure that describes format\n -- properties of the image to be allocated.\n -> a -- ^ The width of the image in pixels. It must be values\n -- greater than or equal to 1.\n -> a -- ^ The height of the image in pixels. It must be\n -- values greater than or equal to 1.\n -> a -- ^ The depth of the image in pixels. This must be a\n -- value greater than 1.\n -> a -- ^ The scan-line pitch in bytes. This must be 0 if\n -- host_ptr is 'nullPtr' and can be either 0 or greater\n -- than or equal to image_width * size of element in\n -- bytes if host_ptr is not 'nullPtr'. If host_ptr is\n -- not 'nullPtr' and image_row_pitch is equal to 0,\n -- image_row_pitch is calculated as image_width * size\n -- of element in bytes. If image_row_pitch is not 0, it\n -- must be a multiple of the image element size in\n -- bytes.\n -> a -- ^ The size in bytes of each 2D slice in the 3D\n -- image. This must be 0 if host_ptr is 'nullPtr' and\n -- can be either 0 or greater than or equal to\n -- image_row_pitch * image_height if host_ptr is not\n -- 'nullPtr'. If host_ptr is not 'nullPtr' and\n -- image_slice_pitch equal to 0, image_slice_pitch is\n -- calculated as image_row_pitch * image_height. If\n -- image_slice_pitch is not 0, it must be a multiple of\n -- the image_row_pitch.\n -> Ptr () -- ^ A pointer to the image data that may already\n -- be allocated by the application. The size of the\n -- buffer that host_ptr points to must be greater\n -- than or equal to image_slice_pitch *\n -- image_depth. The size of each element in bytes\n -- must be a power of 2. The image data specified\n -- by host_ptr is stored as a linear sequence of\n -- adjacent 2D slices. Each 2D slice is a linear\n -- sequence of adjacent scanlines. Each scanline is\n -- a linear sequence of image elements.\n -> IO CLMem\nclCreateImage3D ctx xs fmt iw ih idepth irp isp ptr = wrapPError $ \\perr -> with fmt $ \\pfmt -> do\n raw_clCreateImage3D ctx flags pfmt ciw cih cid cirp cisp ptr perr\n where\n flags = bitmaskFromFlags xs\n ciw = fromIntegral iw\n cih = fromIntegral ih\n cid = fromIntegral idepth\n cirp = fromIntegral irp\n cisp = fromIntegral isp \n \ngetNumSupportedImageFormats :: CLContext -> [CLMemFlag] -> CLMemObjectType -> IO CLuint\ngetNumSupportedImageFormats ctx xs mtype = alloca $ \\(value_size :: Ptr CLuint) -> do\n whenSuccess (raw_clGetSupportedImageFormats ctx flags (getCLValue mtype) 0 nullPtr value_size)\n $ peek value_size\n where\n flags = bitmaskFromFlags xs\n \n{-| Get the list of image formats supported by an OpenCL\nimplementation. 'clGetSupportedImageFormats' can be used to get the list of\nimage formats supported by an OpenCL implementation when the following\ninformation about an image memory object is specified:\n\n * Context\n * Image type - 2D or 3D image\n * Image object allocation information\n\nThrows 'CL_INVALID_CONTEXT' if context is not a valid context, throws\n'CL_INVALID_VALUE' if flags or image_type are not valid.\n\n-}\nclGetSupportedImageFormats :: CLContext -- ^ A valid OpenCL context on which the\n -- image object(s) will be created.\n -> [CLMemFlag] -- ^ A bit-field that is used to\n -- specify allocation and usage\n -- information about the image\n -- memory object.\n -> CLMemObjectType -- ^ Describes the image type\n -- and must be either\n -- 'CL_MEM_OBJECT_IMAGE2D' or\n -- 'CL_MEM_OBJECT_IMAGE3D'.\n -> IO [CLImageFormat]\nclGetSupportedImageFormats ctx xs mtype = do\n num <- getNumSupportedImageFormats ctx xs mtype\n allocaArray (fromIntegral num) $ \\(buff :: Ptr CLImageFormat) -> do\n whenSuccess (raw_clGetSupportedImageFormats ctx flags (getCLValue mtype) num (castPtr buff) nullPtr)\n $ peekArray (fromIntegral num) buff\n where\n flags = bitmaskFromFlags xs\n\n#c\nenum CLMemInfo {\n cL_MEM_TYPE=CL_MEM_TYPE,\n cL_MEM_FLAGS=CL_MEM_FLAGS,\n cL_MEM_SIZE=CL_MEM_SIZE,\n cL_MEM_HOST_PTR=CL_MEM_HOST_PTR,\n cL_MEM_MAP_COUNT=CL_MEM_MAP_COUNT,\n cL_MEM_REFERENCE_COUNT=CL_MEM_REFERENCE_COUNT,\n cL_MEM_CONTEXT=CL_MEM_CONTEXT,\n };\n#endc\n{#enum CLMemInfo {upcaseFirstLetter} #}\n\n-- | Returns the mem object type.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_TYPE'.\nclGetMemType :: CLMem -> IO CLMemObjectType\nclGetMemType mem =\n wrapGetInfo (\\(dat :: Ptr CLMemObjectType_) ->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_MEM_TYPE\n size = fromIntegral $ sizeOf (0::CLMemObjectType_)\n\n-- | Return the flags argument value specified when memobj was created.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_FLAGS'.\nclGetMemFlags :: CLMem -> IO [CLMemFlag]\nclGetMemFlags mem =\n wrapGetInfo (\\(dat :: Ptr CLMemFlags_)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) bitmaskToMemFlags\n where \n infoid = getCLValue CL_MEM_FLAGS\n size = fromIntegral $ sizeOf (0::CLMemFlags_)\n\n-- | Return actual size of memobj in bytes.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_SIZE'.\nclGetMemSize :: CLMem -> IO CSize\nclGetMemSize mem =\n wrapGetInfo (\\(dat :: Ptr CSize)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_SIZE\n size = fromIntegral $ sizeOf (0::CSize)\n\n-- | Return the host_ptr argument value specified when memobj is created.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_HOST_PTR'.\nclGetMemHostPtr :: CLMem -> IO (Ptr ())\nclGetMemHostPtr mem =\n wrapGetInfo (\\(dat :: Ptr (Ptr ()))->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_HOST_PTR\n size = fromIntegral $ sizeOf (nullPtr::Ptr ())\n\n-- | Map count. The map count returned should be considered immediately\n-- stale. It is unsuitable for general use in applications. This feature is\n-- provided for debugging.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_MAP_COUNT'.\nclGetMemMapCount :: CLMem -> IO CLuint\nclGetMemMapCount mem =\n wrapGetInfo (\\(dat :: Ptr CLuint)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_MAP_COUNT\n size = fromIntegral $ sizeOf (0 :: CLuint)\n\n-- | Return memobj reference count. The reference count returned should be\n-- considered immediately stale. It is unsuitable for general use in\n-- applications. This feature is provided for identifying memory leaks.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_REFERENCE_COUNT'.\nclGetMemReferenceCount :: CLMem -> IO CLuint\nclGetMemReferenceCount mem =\n wrapGetInfo (\\(dat :: Ptr CLuint)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0 :: CLuint)\n\n-- | Return context specified when memory object is created.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_CONTEXT'.\nclGetMemContext :: CLMem -> IO CLContext\nclGetMemContext mem =\n wrapGetInfo (\\(dat :: Ptr CLContext)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_CONTEXT\n size = fromIntegral $ sizeOf (0 :: CLuint)\n\n-- -----------------------------------------------------------------------------\n{-| Creates a sampler object. A sampler object describes how to sample an image\nwhen the image is read in the kernel. The built-in functions to read from an\nimage in a kernel take a sampler as an argument. The sampler arguments to the\nimage read function can be sampler objects created using OpenCL functions and\npassed as argument values to the kernel or can be samplers declared inside a\nkernel. In this section we discuss how sampler objects are created using OpenCL\nfunctions.\n\nReturns a valid non-zero sampler object if the sampler object is created\nsuccessfully. Otherwise, it throws one of the following 'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_INVALID_VALUE' if addressing_mode, filter_mode, or normalized_coords or a\ncombination of these argument values are not valid.\n\n * 'CL_INVALID_OPERATION' if images are not supported by any device associated\nwith context (i.e. 'CL_DEVICE_IMAGE_SUPPORT' specified in the table of OpenCL\nDevice Queries for clGetDeviceInfo is 'False').\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n-}\nclCreateSampler :: CLContext -> Bool -> CLAddressingMode -> CLFilterMode \n -> IO CLSampler\nclCreateSampler ctx norm am fm = wrapPError $ \\perr -> do\n raw_clCreateSampler ctx (fromBool norm) (getCLValue am) (getCLValue fm) perr\n\n-- | Increments the sampler reference count. 'clCreateSampler' does an implicit\n-- retain. Returns 'True' if the function is executed successfully. It returns\n-- 'False' if sampler is not a valid sampler object.\nclRetainSampler :: CLSampler -> IO Bool\nclRetainSampler mem = wrapCheckSuccess $ raw_clRetainSampler mem\n\n-- | Decrements the sampler reference count. The sampler object is deleted after\n-- the reference count becomes zero and commands queued for execution on a\n-- command-queue(s) that use sampler have finished. 'clReleaseSampler' returns\n-- 'True' if the function is executed successfully. It returns 'False' if\n-- sampler is not a valid sampler object.\nclReleaseSampler :: CLSampler -> IO Bool\nclReleaseSampler mem = wrapCheckSuccess $ raw_clReleaseSampler mem\n\n#c\nenum CLSamplerInfo {\n cL_SAMPLER_REFERENCE_COUNT=CL_SAMPLER_REFERENCE_COUNT,\n cL_SAMPLER_CONTEXT=CL_SAMPLER_CONTEXT,\n cL_SAMPLER_ADDRESSING_MODE=CL_SAMPLER_ADDRESSING_MODE,\n cL_SAMPLER_FILTER_MODE=CL_SAMPLER_FILTER_MODE,\n cL_SAMPLER_NORMALIZED_COORDS=CL_SAMPLER_NORMALIZED_COORDS\n };\n#endc\n{#enum CLSamplerInfo {upcaseFirstLetter} #}\n\n-- | Return the sampler reference count. The reference count returned should be\n-- considered immediately stale. It is unsuitable for general use in\n-- applications. This feature is provided for identifying memory leaks.\n--\n-- This function execute OpenCL clGetSamplerInfo with\n-- 'CL_SAMPLER_REFERENCE_COUNT'.\nclGetSamplerReferenceCount :: CLSampler -> IO CLuint\nclGetSamplerReferenceCount sam =\n wrapGetInfo (\\(dat :: Ptr CLuint)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_SAMPLER_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0 :: CLuint)\n\n-- | Return the context specified when the sampler is created.\n--\n-- This function execute OpenCL clGetSamplerInfo with 'CL_SAMPLER_CONTEXT'.\nclGetSamplerContext :: CLSampler -> IO CLContext\nclGetSamplerContext sam =\n wrapGetInfo (\\(dat :: Ptr CLContext)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_SAMPLER_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr :: CLContext)\n\n-- | Return the value specified by addressing_mode argument to clCreateSampler.\n--\n-- This function execute OpenCL clGetSamplerInfo with\n-- 'CL_SAMPLER_ADDRESSING_MODE'.\nclGetSamplerAddressingMode :: CLSampler -> IO CLAddressingMode\nclGetSamplerAddressingMode sam =\n wrapGetInfo (\\(dat :: Ptr CLAddressingMode_)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_SAMPLER_ADDRESSING_MODE\n size = fromIntegral $ sizeOf (0 :: CLAddressingMode_)\n\n-- | Return the value specified by filter_mode argument to clCreateSampler.\n--\n-- This function execute OpenCL clGetSamplerInfo with 'CL_SAMPLER_FILTER_MODE'.\nclGetSamplerFilterMode :: CLSampler -> IO CLFilterMode\nclGetSamplerFilterMode sam =\n wrapGetInfo (\\(dat :: Ptr CLFilterMode_)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_SAMPLER_FILTER_MODE\n size = fromIntegral $ sizeOf (0 :: CLFilterMode_)\n\n-- | Return the value specified by normalized_coords argument to\n-- clCreateSampler.\n--\n-- This function execute OpenCL clGetSamplerInfo with\n-- 'CL_SAMPLER_NORMALIZED_COORDS'.\nclGetSamplerNormalizedCoords :: CLSampler -> IO Bool\nclGetSamplerNormalizedCoords sam =\n wrapGetInfo (\\(dat :: Ptr CLbool)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) (\/=0)\n where \n infoid = getCLValue CL_SAMPLER_NORMALIZED_COORDS\n size = fromIntegral $ sizeOf (0 :: CLbool)\n\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"61af3a4f19e3f157abf2a0e5d691a5f8d352030b","subject":"Better returns on Context functions","message":"Better returns on Context functions\n","repos":"IFCA\/opencl,Delan90\/opencl,IFCA\/opencl,Delan90\/opencl","old_file":"src\/System\/GPU\/OpenCL\/CommandQueue.chs","new_file":"src\/System\/GPU\/OpenCL\/CommandQueue.chs","new_contents":"-- -----------------------------------------------------------------------------\n-- This file is part of Haskell-Opencl.\n\n-- Haskell-Opencl is free software: you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation, either version 3 of the License, or\n-- (at your option) any later version.\n\n-- Haskell-Opencl is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n\n-- You should have received a copy of the GNU General Public License\n-- along with Haskell-Opencl. If not, see .\n-- -----------------------------------------------------------------------------\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\nmodule System.GPU.OpenCL.CommandQueue(\n -- * Types\n CLCommandQueue, CLCommandQueueProperty(..), \n -- * Command Queue Functions\n clCreateCommandQueue, clRetainCommandQueue, clReleaseCommandQueue,\n clGetCommandQueueContext, clGetCommandQueueDevice, \n clGetCommandQueueReferenceCount, clGetCommandQueueProperties,\n clSetCommandQueueProperty,\n -- * Memory Commands\n clEnqueueReadBuffer, clEnqueueWriteBuffer,\n -- * Executing Kernels\n clEnqueueNDRangeKernel, clEnqueueTask, clEnqueueMarker, \n clEnqueueWaitForEvents, clEnqueueBarrier,\n -- * Flush and Finish\n clFlush, clFinish\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport System.GPU.OpenCL.Types( \n CLint, CLbool, CLuint, CLCommandQueueProperty_, CLCommandQueueInfo_, \n CLError(..), CLCommandQueue, CLDeviceID, CLContext, CLCommandQueueProperty(..), \n CLEvent, CLMem, CLKernel,\n wrapCheckSuccess, wrapPError, wrapGetInfo, getCLValue, getEnumCL,\n bitmaskToCommandQueueProperties, bitmaskFromFlags )\n\n#include \n\n-- -----------------------------------------------------------------------------\nforeign import ccall \"clCreateCommandQueue\" raw_clCreateCommandQueue :: \n CLContext -> CLDeviceID -> CLCommandQueueProperty_ -> Ptr CLint -> IO CLCommandQueue\nforeign import ccall \"clRetainCommandQueue\" raw_clRetainCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import ccall \"clReleaseCommandQueue\" raw_clReleaseCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import ccall \"clGetCommandQueueInfo\" raw_clGetCommandQueueInfo :: \n CLCommandQueue -> CLCommandQueueInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clSetCommandQueueProperty\" raw_clSetCommandQueueProperty :: \n CLCommandQueue -> CLCommandQueueProperty_ -> CLbool -> Ptr CLCommandQueueProperty_ -> IO CLint\nforeign import ccall \"clEnqueueReadBuffer\" raw_clEnqueueReadBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import ccall \"clEnqueueWriteBuffer\" raw_clEnqueueWriteBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import ccall \"clEnqueueNDRangeKernel\" raw_clEnqueueNDRangeKernel :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import ccall \"clEnqueueTask\" raw_clEnqueueTask :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import ccall \"clEnqueueMarker\" raw_clEnqueueMarker :: \n CLCommandQueue -> Ptr CLEvent -> IO CLint \nforeign import ccall \"clEnqueueWaitForEvents\" raw_clEnqueueWaitForEvents :: \n CLCommandQueue -> CLuint -> Ptr CLEvent -> IO CLint\nforeign import ccall \"clEnqueueBarrier\" raw_clEnqueueBarrier :: \n CLCommandQueue -> IO CLint \nforeign import ccall \"clFlush\" raw_clFlush ::\n CLCommandQueue -> IO CLint\nforeign import ccall \"clFinish\" raw_clFinish ::\n CLCommandQueue -> IO CLint\n\n-- -----------------------------------------------------------------------------\n{-| Create a command-queue on a specific device.\n\nThe OpenCL functions that are submitted to a command-queue are enqueued in the \norder the calls are made but can be configured to execute in-order or \nout-of-order. The properties argument in clCreateCommandQueue can be used to \nspecify the execution order.\n\nIf the 'CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE' property of a command-queue is \nnot set, the commands enqueued to a command-queue execute in order. For example, \nif an application calls 'clEnqueueNDRangeKernel' to execute kernel A followed by \na 'clEnqueueNDRangeKernel' to execute kernel B, the application can assume that \nkernel A finishes first and then kernel B is executed. If the memory objects \noutput by kernel A are inputs to kernel B then kernel B will see the correct \ndata in memory objects produced by execution of kernel A. If the \n'CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE' property of a commandqueue is set, then \nthere is no guarantee that kernel A will finish before kernel B starts execution.\n\nApplications can configure the commands enqueued to a command-queue to execute \nout-of-order by setting the 'CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE' property of \nthe command-queue. This can be specified when the command-queue is created or \ncan be changed dynamically using 'clCreateCommandQueue'. In out-of-order \nexecution mode there is no guarantee that the enqueued commands will finish \nexecution in the order they were queued. As there is no guarantee that kernels \nwill be executed in order, i.e. based on when the 'clEnqueueNDRangeKernel' calls \nare made within a command-queue, it is therefore possible that an earlier \n'clEnqueueNDRangeKernel' call to execute kernel A identified by event A may \nexecute and\/or finish later than a 'clEnqueueNDRangeKernel' call to execute \nkernel B which was called by the application at a later point in time. To \nguarantee a specific order of execution of kernels, a wait on a particular event \n(in this case event A) can be used. The wait for event A can be specified in the \nevent_wait_list argument to 'clEnqueueNDRangeKernel' for kernel B.\n\nIn addition, a wait for events or a barrier command can be enqueued to the \ncommand-queue. The wait for events command ensures that previously enqueued \ncommands identified by the list of events to wait for have finished before the \nnext batch of commands is executed. The barrier command ensures that all \npreviously enqueued commands in a command-queue have finished execution before \nthe next batch of commands is executed.\n\nSimilarly, commands to read, write, copy or map memory objects that are enqueued \nafter 'clEnqueueNDRangeKernel', 'clEnqueueTask' or 'clEnqueueNativeKernel' \ncommands are not guaranteed to wait for kernels scheduled for execution to have \ncompleted (if the 'CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE' property is set). To \nensure correct ordering of commands, the event object returned by \n'clEnqueueNDRangeKernel', 'clEnqueueTask' or 'clEnqueueNativeKernel' can be \nused to enqueue a wait for event or a barrier command can be enqueued that must \ncomplete before reads or writes to the memory object(s) occur.\n-}\nclCreateCommandQueue :: CLContext -> CLDeviceID -> [CLCommandQueueProperty] \n -> IO (Either CLError CLCommandQueue)\nclCreateCommandQueue ctx did xs = wrapPError $ \\perr -> do\n raw_clCreateCommandQueue ctx did props perr\n where\n props = bitmaskFromFlags xs\n\n{-| Increments the command_queue reference count. 'clCreateCommandQueue'\nperforms an implicit retain. This is very helpful for 3rd party libraries, which\ntypically get a command-queue passed to them by the application. However, it is\npossible that the application may delete the command-queue without informing the\nlibrary. Allowing functions to attach to (i.e. retain) and release a\ncommand-queue solves the problem of a command-queue being used by a library no\nlonger being valid. Returns 'True' if the function is executed successfully. It\nreturns 'False' if command_queue is not a valid command-queue. \n-}\nclRetainCommandQueue :: CLCommandQueue -> IO Bool\nclRetainCommandQueue = wrapCheckSuccess . raw_clRetainCommandQueue\n\n-- | Decrements the command_queue reference count.\n-- After the command_queue reference count becomes zero and all commands queued \n-- to command_queue have finished (e.g., kernel executions, memory object \n-- updates, etc.), the command-queue is deleted.\n-- Returns 'True' if the function is executed successfully. It returns 'False'\n-- if command_queue is not a valid command-queue.\nclReleaseCommandQueue :: CLCommandQueue -> IO Bool\nclReleaseCommandQueue = wrapCheckSuccess . raw_clReleaseCommandQueue\n\n#c\nenum CLCommandQueueInfo {\n cL_QUEUE_CONTEXT=CL_QUEUE_CONTEXT,\n cL_QUEUE_DEVICE=CL_QUEUE_DEVICE,\n cL_QUEUE_REFERENCE_COUNT=CL_QUEUE_REFERENCE_COUNT,\n cL_QUEUE_PROPERTIES=CL_QUEUE_PROPERTIES,\n };\n#endc\n{#enum CLCommandQueueInfo {upcaseFirstLetter} #}\n\n-- | Return the context specified when the command-queue is created.\nclGetCommandQueueContext :: CLCommandQueue -> IO (Either CLError CLContext)\nclGetCommandQueueContext cq = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetCommandQueueInfo cq infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_QUEUE_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the device specified when the command-queue is created.\nclGetCommandQueueDevice :: CLCommandQueue -> IO (Either CLError CLDeviceID)\nclGetCommandQueueDevice cq = wrapGetInfo (\\(dat :: Ptr CLDeviceID) \n -> raw_clGetCommandQueueInfo cq infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_QUEUE_DEVICE\n size = fromIntegral $ sizeOf (nullPtr::CLDeviceID)\n\n-- | Return the command-queue reference count.\n-- The reference count returned should be considered immediately stale. It is \n-- unsuitable for general use in applications. This feature is provided for \n-- identifying memory leaks.\nclGetCommandQueueReferenceCount :: CLCommandQueue -> IO (Either CLError CLuint)\nclGetCommandQueueReferenceCount cq = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetCommandQueueInfo cq infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_QUEUE_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n\n-- | Return the currently specified properties for the command-queue. These \n-- properties are specified by the properties argument in 'clCreateCommandQueue'\n-- , and can be changed by 'clSetCommandQueueProperty'.\nclGetCommandQueueProperties :: CLCommandQueue -> IO (Either CLError [CLCommandQueueProperty])\nclGetCommandQueueProperties cq = wrapGetInfo (\\(dat :: Ptr CLCommandQueueProperty_) \n -> raw_clGetCommandQueueInfo cq infoid size (castPtr dat)) bitmaskToCommandQueueProperties\n where \n infoid = getCLValue CL_QUEUE_PROPERTIES\n size = fromIntegral $ sizeOf (0::CLCommandQueueProperty_)\n\n{-| Enable or disable the properties of a command-queue. Returns the\ncommand-queue properties before they were changed by\n'clSetCommandQueueProperty'. As specified for 'clCreateCommandQueue', the\n'CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE' command-queue property determines\nwhether the commands in a command-queue are executed in-order or\nout-of-order. Changing this command-queue property will cause the OpenCL\nimplementation to block until all previously queued commands in command_queue\nhave completed. This can be an expensive operation and therefore changes to the\n'CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE' property should be only done when\nabsolutely necessary.\n\n It is possible that a device(s) becomes unavailable after a context and\ncommand-queues that use this device(s) have been created and commands have been\nqueued to command-queues. In this case the behavior of OpenCL API calls that use\nthis context (and command-queues) are considered to be\nimplementation-defined. The user callback function, if specified when the\ncontext is created, can be used to record appropriate information when the\ndevice becomes unavailable.\n-}\nclSetCommandQueueProperty :: CLCommandQueue -> [CLCommandQueueProperty] -> Bool \n -> IO (Either CLError [CLCommandQueueProperty])\nclSetCommandQueueProperty cq xs val = alloca $ \\(dat :: Ptr CLCommandQueueProperty_) -> do\n errcode <- raw_clSetCommandQueueProperty cq props (fromBool val) dat\n if errcode == getCLValue CL_SUCCESS\n then fmap (Right . bitmaskToCommandQueueProperties) $ peek dat\n else return . Left . getEnumCL $ errcode\n where\n props = bitmaskFromFlags xs\n\n-- -----------------------------------------------------------------------------\nclEnqueue :: (CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint) -> [CLEvent] \n -> IO (Either CLError CLEvent)\nclEnqueue f [] = alloca $ \\event -> do\n errcode <- f 0 nullPtr event\n if errcode == getCLValue CL_SUCCESS\n then fmap Right $ peek event\n else return . Left . getEnumCL $ errcode\nclEnqueue f events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> do\n errcode <- f cnevents pevents event\n if errcode == getCLValue CL_SUCCESS\n then fmap Right $ peek event\n else return . Left . getEnumCL $ errcode\n where\n nevents = length events\n cnevents = fromIntegral nevents\n\n-- -----------------------------------------------------------------------------\n{-| Enqueue commands to read from a buffer object to host memory. Calling\nclEnqueueReadBuffer to read a region of the buffer object with the ptr argument\nvalue set to host_ptr + offset, where host_ptr is a pointer to the memory region\nspecified when the buffer object being read is created with\n'CL_MEM_USE_HOST_PTR', must meet the following requirements in order to avoid\nundefined behavior:\n\n * All commands that use this buffer object have finished execution before the\nread command begins execution\n\n * The buffer object is not mapped\n\n * The buffer object is not used by any command-queue until the read command has\nfinished execution Errors\n\n'clEnqueueReadBuffer' returns the event if the function is executed\nsuccessfully. Otherwise, it returns one of the following errors:\n\n * 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue.\n\n * 'CL_INVALID_CONTEXT' if the context associated with command_queue and buffer\nare not the same or if the context associated with command_queue and events in\nevent_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT' if buffer is not a valid buffer object.\n\n * 'CL_INVALID_VALUE' if the region being read specified by (offset, cb) is out\nof bounds or if ptr is a NULL value.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event_wait_list is NULL and\nnum_events_in_wait_list greater than 0, or event_wait_list is not NULL and\nnum_events_in_wait_list is 0, or if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor data store associated with buffer.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n-}\nclEnqueueReadBuffer :: Integral a => CLCommandQueue -> CLMem -> Bool -> a -> a\n -> Ptr () -> [CLEvent] -> IO (Either CLError CLEvent)\nclEnqueueReadBuffer cq mem check off size dat = clEnqueue (raw_clEnqueueReadBuffer cq mem (fromBool check) (fromIntegral off) (fromIntegral size) dat)\n\n{-| Enqueue commands to write to a buffer object from host memory.Calling\nclEnqueueWriteBuffer to update the latest bits in a region of the buffer object\nwith the ptr argument value set to host_ptr + offset, where host_ptr is a\npointer to the memory region specified when the buffer object being written is\ncreated with 'CL_MEM_USE_HOST_PTR', must meet the following requirements in\norder to avoid undefined behavior:\n\n * The host memory region given by (host_ptr + offset, cb) contains the latest\nbits when the enqueued write command begins execution.\n\n * The buffer object is not mapped.\n\n * The buffer object is not used by any command-queue until the write command\nhas finished execution.\n\n'clEnqueueWriteBuffer' returns the Event if the function is executed\nsuccessfully. Otherwise, it returns one of the following errors:\n\n * 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue.\n\n * 'CL_INVALID_CONTEXT' if the context associated with command_queue and buffer\nare not the same or if the context associated with command_queue and events in\nevent_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT' if buffer is not a valid buffer object.\n\n * 'CL_INVALID_VALUE' if the region being written specified by (offset, cb) is\nout of bounds or if ptr is a NULL value.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event_wait_list is NULL and\nnum_events_in_wait_list greater than 0, or event_wait_list is not NULL and\nnum_events_in_wait_list is 0, or if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor data store associated with buffer.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n-}\nclEnqueueWriteBuffer :: Integral a => CLCommandQueue -> CLMem -> Bool -> a -> a\n -> Ptr () -> [CLEvent] -> IO (Either CLError CLEvent)\nclEnqueueWriteBuffer cq mem check off size dat = clEnqueue (raw_clEnqueueWriteBuffer cq mem (fromBool check) (fromIntegral off) (fromIntegral size) dat)\n\n-- -----------------------------------------------------------------------------\n{-| Enqueues a command to execute a kernel on a device. Each work-item is\nuniquely identified by a global identifier. The global ID, which can be read\ninside the kernel, is computed using the value given by global_work_size and\nglobal_work_offset. In OpenCL 1.0, the starting global ID is always (0, 0,\n... 0). In addition, a work-item is also identified within a work-group by a\nunique local ID. The local ID, which can also be read by the kernel, is computed\nusing the value given by local_work_size. The starting local ID is always (0, 0,\n... 0).\n\nReturns the event if the kernel execution was successfully queued. Otherwise, it\nreturns one of the following errors:\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no successfully built program\nexecutable available for device associated with command_queue.\n\n * 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue.\n\n * 'CL_INVALID_KERNEL' if kernel is not a valid kernel object.\n\n * 'CL_INVALID_CONTEXT' if context associated with command_queue and kernel is\nnot the same or if the context associated with command_queue and events in\nevent_wait_list are not the same.\n\n * 'CL_INVALID_KERNEL_ARGS' if the kernel argument values have not been\nspecified.\n\n * 'CL_INVALID_WORK_DIMENSION' if work_dim is not a valid value (i.e. a value\nbetween 1 and 3).\n\n * 'CL_INVALID_WORK_GROUP_SIZE' if local_work_size is specified and number of\nwork-items specified by global_work_size is not evenly divisable by size of\nwork-group given by local_work_size or does not match the work-group size\nspecified for kernel using the __attribute__((reqd_work_group_size(X, Y, Z)))\nqualifier in program source.\n\n * 'CL_INVALID_WORK_GROUP_SIZE' if local_work_size is specified and the total\nnumber of work-items in the work-group computed as local_work_size[0]\n*... local_work_size[work_dim - 1] is greater than the value specified by\n'CL_DEVICE_MAX_WORK_GROUP_SIZE' in the table of OpenCL Device Queries for\nclGetDeviceInfo.\n\n * 'CL_INVALID_WORK_GROUP_SIZE' if local_work_size is NULL and the\n__attribute__((reqd_work_group_size(X, Y, Z))) qualifier is used to declare the\nwork-group size for kernel in the program source.\n\n * 'CL_INVALID_WORK_ITEM_SIZE' if the number of work-items specified in any of\nlocal_work_size[0], ... local_work_size[work_dim - 1] is greater than the\ncorresponding values specified by 'CL_DEVICE_MAX_WORK_ITEM_SIZES'[0],\n.... 'CL_DEVICE_MAX_WORK_ITEM_SIZES'[work_dim - 1].\n\n * 'CL_OUT_OF_RESOURCES' if there is a failure to queue the execution instance\nof kernel on the command-queue because of insufficient resources needed to\nexecute the kernel. For example, the explicitly specified local_work_size causes\na failure to execute the kernel because of insufficient resources such as\nregisters or local memory. Another example would be the number of read-only\nimage args used in kernel exceed the 'CL_DEVICE_MAX_READ_IMAGE_ARGS' value for\ndevice or the number of write-only image args used in kernel exceed the\n'CL_DEVICE_MAX_WRITE_IMAGE_ARGS' value for device or the number of samplers used\nin kernel exceed 'CL_DEVICE_MAX_SAMPLERS' for device.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory for data store associated with image or buffer objects specified as arguments to kernel.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n-}\nclEnqueueNDRangeKernel :: Integral a => CLCommandQueue -> CLKernel -> [a] -> [a] -> [CLEvent] -> IO (Either CLError CLEvent)\nclEnqueueNDRangeKernel cq krn gws lws events = withArray (map fromIntegral gws) $ \\pgws -> withArray (map fromIntegral lws) $ \\plws -> do\n clEnqueue (raw_clEnqueueNDRangeKernel cq krn num nullPtr pgws plws) events\n where\n num = fromIntegral $ length gws\n \n{-| Enqueues a command to execute a kernel on a device. The kernel is executed\nusing a single work-item.\n\n'clEnqueueTask' is equivalent to calling 'clEnqueueNDRangeKernel' with work_dim\n= 1, global_work_offset = [], global_work_size[0] set to 1, and\nlocal_work_size[0] set to 1.\n\nReturns the evens if the kernel execution was successfully queued, or one of the\nerrors below:\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no successfully built program\nexecutable available for device associated with command_queue.\n\n * 'CL_INVALID_COMMAND_QUEUE if' command_queue is not a valid command-queue.\n\n * 'CL_INVALID_KERNEL' if kernel is not a valid kernel object.\n\n * 'CL_INVALID_CONTEXT' if context associated with command_queue and kernel is\nnot the same or if the context associated with command_queue and events in\nevent_wait_list are not the same.\n\n * 'CL_INVALID_KERNEL_ARGS' if the kernel argument values have not been specified.\n\n * 'CL_INVALID_WORK_GROUP_SIZE' if a work-group size is specified for kernel\nusing the __attribute__((reqd_work_group_size(X, Y, Z))) qualifier in program\nsource and is not (1, 1, 1).\n\n * 'CL_OUT_OF_RESOURCES' if there is a failure to queue the execution instance\nof kernel on the command-queue because of insufficient resources needed to\nexecute the kernel.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor data store associated with image or buffer objects specified as arguments to\nkernel.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n-}\nclEnqueueTask :: CLCommandQueue -> CLKernel -> [CLEvent] \n -> IO (Either CLError CLEvent)\nclEnqueueTask cq krn = clEnqueue (raw_clEnqueueTask cq krn)\n \n-- -----------------------------------------------------------------------------\n-- | Enqueues a marker command to command_queue. The marker command returns an\n-- event which can be used to queue a wait on this marker event i.e. wait for\n-- all commands queued before the marker command to complete. Returns the event\n-- if the function is successfully executed. It returns\n-- 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue and\n-- returns 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources\n-- required by the OpenCL implementation on the host.\nclEnqueueMarker :: CLCommandQueue -> IO (Either CLError CLEvent)\nclEnqueueMarker cq = alloca $ \\event -> do\n errcode <- raw_clEnqueueMarker cq event\n if errcode == getCLValue CL_SUCCESS\n then fmap Right $ peek event\n else return . Left . getEnumCL $ errcode\n \n{-| Enqueues a wait for a specific event or a list of events to complete before\nany future commands queued in the command-queue are executed. The context\nassociated with events in event_list and command_queue must be the same.\n\nReturns one of the errors below when fails:\n\n * 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue.\n\n * 'CL_INVALID_CONTEXT' if the context associated with command_queue and events\nin event_list are not the same.\n\n * 'CL_INVALID_VALUE' if num_events is zero.\n\n * 'CL_INVALID_EVENT' if event objects specified in event_list are not valid\nevents.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n-}\nclEnqueueWaitForEvents :: CLCommandQueue -> [CLEvent] -> IO (Either CLError ())\nclEnqueueWaitForEvents cq [] = do\n errcode <- raw_clEnqueueWaitForEvents cq 0 nullPtr\n if errcode == getCLValue CL_SUCCESS\n then return $ Right ()\n else return . Left . getEnumCL $ errcode\nclEnqueueWaitForEvents cq events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n errcode <- raw_clEnqueueWaitForEvents cq cnevents pevents\n if errcode == getCLValue CL_SUCCESS\n then return $ Right ()\n else return . Left . getEnumCL $ errcode\n where\n nevents = length events\n cnevents = fromIntegral nevents\n\n-- | 'clEnqueueBarrier' is a synchronization point that ensures that all queued\n-- commands in command_queue have finished execution before the next batch of\n-- commands can begin execution. It returns 'CL_INVALID_COMMAND_QUEUE' if\n-- command_queue is not a valid command-queue and returns\n-- 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\n-- by the OpenCL implementation on the host.\nclEnqueueBarrier :: CLCommandQueue -> IO (Either CLError ())\nclEnqueueBarrier cq = do\n errcode <- raw_clEnqueueBarrier cq\n if errcode == getCLValue CL_SUCCESS\n then return $ Right ()\n else return . Left . getEnumCL $ errcode\n \n-- -----------------------------------------------------------------------------\n{-| Issues all previously queued OpenCL commands in a command-queue to the\ndevice associated with the command-queue. 'clFlush' only guarantees that all\nqueued commands to command_queue get issued to the appropriate device. There is\nno guarantee that they will be complete after 'clFlush' returns.\n\n 'clFlush' returns 'True' if the function call was executed successfully. It\nreturns 'False' if command_queue is not a valid command-queue or if there is a\nfailure to allocate resources required by the OpenCL implementation on the host.\n\n Any blocking commands queued in a command-queue such as 'clEnqueueReadImage' or\n'clEnqueueReadBuffer' with blocking_read set to 'True', 'clEnqueueWriteImage' or\n'clEnqueueWriteBuffer' with blocking_write set to 'True', 'clEnqueueMapImage' or\n'clEnqueueMapBuffer' with blocking_map set to 'True' or 'clWaitForEvents'\nperform an implicit flush of the command-queue.\n\n To use event objects that refer to commands enqueued in a command-queue as\nevent objects to wait on by commands enqueued in a different command-queue, the\napplication must call a 'clFlush' or any blocking commands that perform an\nimplicit flush of the command-queue where the commands that refer to these event\nobjects are enqueued.\n-}\nclFlush :: CLCommandQueue -> IO Bool\nclFlush = wrapCheckSuccess . raw_clFlush\n \n-- | Blocks until all previously queued OpenCL commands in a command-queue are \n-- issued to the associated device and have completed.\n-- 'clFinish' does not return until all queued commands in command_queue have \n-- been processed and completed. 'clFinish' is also a synchronization point.\n--\n-- 'clFinish' returns 'True' if the function call was executed successfully. It \n-- returns 'False' if command_queue is not a valid command-queue or if there is \n-- a failure to allocate resources required by the OpenCL implementation on the \n-- host.\nclFinish :: CLCommandQueue -> IO Bool\nclFinish = wrapCheckSuccess . raw_clFinish\n \n-- -----------------------------------------------------------------------------\n","old_contents":"-- -----------------------------------------------------------------------------\n-- This file is part of Haskell-Opencl.\n\n-- Haskell-Opencl is free software: you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation, either version 3 of the License, or\n-- (at your option) any later version.\n\n-- Haskell-Opencl is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n\n-- You should have received a copy of the GNU General Public License\n-- along with Haskell-Opencl. If not, see .\n-- -----------------------------------------------------------------------------\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}\nmodule System.GPU.OpenCL.CommandQueue(\n -- * Types\n CLCommandQueue, CLCommandQueueProperty(..), \n -- * Command Queue Functions\n clCreateCommandQueue, clRetainCommandQueue, clReleaseCommandQueue,\n clGetCommandQueueContext, clGetCommandQueueDevice, \n clGetCommandQueueReferenceCount, clGetCommandQueueProperties,\n clSetCommandQueueProperty,\n -- * Memory Commands\n clEnqueueReadBuffer, clEnqueueWriteBuffer,\n -- * Executing Kernels\n clEnqueueNDRangeKernel, clEnqueueTask,\n -- * Flush and Finish\n clFlush, clFinish\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport System.GPU.OpenCL.Types( \n CLint, CLbool, CLuint, CLCommandQueueProperty_, CLCommandQueueInfo_, \n CLError(..), CLCommandQueue, CLDeviceID, CLContext, CLCommandQueueProperty(..), \n CLEvent, CLMem, ErrorCode(..), CLKernel,\n wrapCheckSuccess, wrapPError, wrapGetInfo, getCLValue,\n bitmaskToCommandQueueProperties, bitmaskFromFlags, clSuccess )\n\n#include \n\n-- -----------------------------------------------------------------------------\nforeign import ccall \"clCreateCommandQueue\" raw_clCreateCommandQueue :: \n CLContext -> CLDeviceID -> CLCommandQueueProperty_ -> Ptr CLint -> IO CLCommandQueue\nforeign import ccall \"clRetainCommandQueue\" raw_clRetainCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import ccall \"clReleaseCommandQueue\" raw_clReleaseCommandQueue :: \n CLCommandQueue -> IO CLint\nforeign import ccall \"clGetCommandQueueInfo\" raw_clGetCommandQueueInfo :: \n CLCommandQueue -> CLCommandQueueInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import ccall \"clSetCommandQueueProperty\" raw_clSetCommandQueueProperty :: \n CLCommandQueue -> CLCommandQueueProperty_ -> CLbool -> Ptr CLCommandQueueProperty_ -> IO CLint\nforeign import ccall \"clEnqueueReadBuffer\" raw_clEnqueueReadBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import ccall \"clEnqueueWriteBuffer\" raw_clEnqueueWriteBuffer ::\n CLCommandQueue -> CLMem -> CLbool -> CSize -> CSize -> Ptr () -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import ccall \"clEnqueueNDRangeKernel\" raw_clEnqueueNDRangeKernel :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CSize -> Ptr CSize -> Ptr CSize -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import ccall \"clEnqueueTask\" raw_clEnqueueTask :: \n CLCommandQueue -> CLKernel -> CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint\nforeign import ccall \"clFlush\" raw_clFlush ::\n CLCommandQueue -> IO CLint\nforeign import ccall \"clFinish\" raw_clFinish ::\n CLCommandQueue -> IO CLint\n\n-- -----------------------------------------------------------------------------\n{-| Create a command-queue on a specific device.\n\nThe OpenCL functions that are submitted to a command-queue are enqueued in the \norder the calls are made but can be configured to execute in-order or \nout-of-order. The properties argument in clCreateCommandQueue can be used to \nspecify the execution order.\n\nIf the 'CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE' property of a command-queue is \nnot set, the commands enqueued to a command-queue execute in order. For example, \nif an application calls 'clEnqueueNDRangeKernel' to execute kernel A followed by \na 'clEnqueueNDRangeKernel' to execute kernel B, the application can assume that \nkernel A finishes first and then kernel B is executed. If the memory objects \noutput by kernel A are inputs to kernel B then kernel B will see the correct \ndata in memory objects produced by execution of kernel A. If the \n'CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE' property of a commandqueue is set, then \nthere is no guarantee that kernel A will finish before kernel B starts execution.\n\nApplications can configure the commands enqueued to a command-queue to execute \nout-of-order by setting the 'CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE' property of \nthe command-queue. This can be specified when the command-queue is created or \ncan be changed dynamically using 'clCreateCommandQueue'. In out-of-order \nexecution mode there is no guarantee that the enqueued commands will finish \nexecution in the order they were queued. As there is no guarantee that kernels \nwill be executed in order, i.e. based on when the 'clEnqueueNDRangeKernel' calls \nare made within a command-queue, it is therefore possible that an earlier \n'clEnqueueNDRangeKernel' call to execute kernel A identified by event A may \nexecute and\/or finish later than a 'clEnqueueNDRangeKernel' call to execute \nkernel B which was called by the application at a later point in time. To \nguarantee a specific order of execution of kernels, a wait on a particular event \n(in this case event A) can be used. The wait for event A can be specified in the \nevent_wait_list argument to 'clEnqueueNDRangeKernel' for kernel B.\n\nIn addition, a wait for events or a barrier command can be enqueued to the \ncommand-queue. The wait for events command ensures that previously enqueued \ncommands identified by the list of events to wait for have finished before the \nnext batch of commands is executed. The barrier command ensures that all \npreviously enqueued commands in a command-queue have finished execution before \nthe next batch of commands is executed.\n\nSimilarly, commands to read, write, copy or map memory objects that are enqueued \nafter 'clEnqueueNDRangeKernel', 'clEnqueueTask' or 'clEnqueueNativeKernel' \ncommands are not guaranteed to wait for kernels scheduled for execution to have \ncompleted (if the 'CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE' property is set). To \nensure correct ordering of commands, the event object returned by \n'clEnqueueNDRangeKernel', 'clEnqueueTask' or 'clEnqueueNativeKernel' can be \nused to enqueue a wait for event or a barrier command can be enqueued that must \ncomplete before reads or writes to the memory object(s) occur.\n-}\nclCreateCommandQueue :: CLContext -> CLDeviceID -> [CLCommandQueueProperty] \n -> IO (Either CLError CLCommandQueue)\nclCreateCommandQueue ctx did xs = wrapPError $ \\perr -> do\n raw_clCreateCommandQueue ctx did props perr\n where\n props = bitmaskFromFlags xs\n\n-- | Increments the command_queue reference count.\n-- 'clCreateCommandQueue' performs an implicit retain. This is very helpful for \n-- 3rd party libraries, which typically get a command-queue passed to them by \n-- the application. However, it is possible that the application may delete the \n-- command-queue without informing the library. Allowing functions to attach to \n-- (i.e. retain) and release a command-queue solves the problem of a \n-- command-queue being used by a library no longer being valid.\n-- Returns 'True' if the function is executed successfully. It returns 'False'\n-- if command_queue is not a valid command-queue.\nclRetainCommandQueue :: CLCommandQueue -> IO Bool\nclRetainCommandQueue = wrapCheckSuccess . raw_clRetainCommandQueue\n\n-- | Decrements the command_queue reference count.\n-- After the command_queue reference count becomes zero and all commands queued \n-- to command_queue have finished (e.g., kernel executions, memory object \n-- updates, etc.), the command-queue is deleted.\n-- Returns 'True' if the function is executed successfully. It returns 'False'\n-- if command_queue is not a valid command-queue.\nclReleaseCommandQueue :: CLCommandQueue -> IO Bool\nclReleaseCommandQueue = wrapCheckSuccess . raw_clReleaseCommandQueue\n\n#c\nenum CLCommandQueueInfo {\n cL_QUEUE_CONTEXT=CL_QUEUE_CONTEXT,\n cL_QUEUE_DEVICE=CL_QUEUE_DEVICE,\n cL_QUEUE_REFERENCE_COUNT=CL_QUEUE_REFERENCE_COUNT,\n cL_QUEUE_PROPERTIES=CL_QUEUE_PROPERTIES,\n };\n#endc\n{#enum CLCommandQueueInfo {upcaseFirstLetter} #}\n\n-- | Return the context specified when the command-queue is created.\nclGetCommandQueueContext :: CLCommandQueue -> IO (Either CLError CLContext)\nclGetCommandQueueContext cq = wrapGetInfo (\\(dat :: Ptr CLContext) \n -> raw_clGetCommandQueueInfo cq infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_QUEUE_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr::CLContext)\n\n-- | Return the device specified when the command-queue is created.\nclGetCommandQueueDevice :: CLCommandQueue -> IO (Either CLError CLDeviceID)\nclGetCommandQueueDevice cq = wrapGetInfo (\\(dat :: Ptr CLDeviceID) \n -> raw_clGetCommandQueueInfo cq infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_QUEUE_DEVICE\n size = fromIntegral $ sizeOf (nullPtr::CLDeviceID)\n\n-- | Return the command-queue reference count.\n-- The reference count returned should be considered immediately stale. It is \n-- unsuitable for general use in applications. This feature is provided for \n-- identifying memory leaks.\nclGetCommandQueueReferenceCount :: CLCommandQueue -> IO (Either CLError CLuint)\nclGetCommandQueueReferenceCount cq = wrapGetInfo (\\(dat :: Ptr CLuint) \n -> raw_clGetCommandQueueInfo cq infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_QUEUE_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0::CLuint)\n\n\n-- | Return the currently specified properties for the command-queue. These \n-- properties are specified by the properties argument in 'clCreateCommandQueue'\n-- , and can be changed by 'clSetCommandQueueProperty'.\nclGetCommandQueueProperties :: CLCommandQueue -> IO (Either CLError [CLCommandQueueProperty])\nclGetCommandQueueProperties cq = wrapGetInfo (\\(dat :: Ptr CLCommandQueueProperty_) \n -> raw_clGetCommandQueueInfo cq infoid size (castPtr dat)) bitmaskToCommandQueueProperties\n where \n infoid = getCLValue CL_QUEUE_PROPERTIES\n size = fromIntegral $ sizeOf (0::CLCommandQueueProperty_)\n\n-- | Enable or disable the properties of a command-queue.\n-- Returns the command-queue properties before they were changed by \n-- 'clSetCommandQueueProperty'.\n-- As specified for 'clCreateCommandQueue', the \n-- 'CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE' command-queue property determines \n-- whether the commands in a command-queue are executed in-order or \n-- out-of-order. Changing this command-queue property will cause the OpenCL \n-- implementation to block until all previously queued commands in command_queue \n-- have completed. This can be an expensive operation and therefore changes to \n-- the 'CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE' property should be only done \n-- when absolutely necessary.\n-- \n-- It is possible that a device(s) becomes unavailable after a context and \n-- command-queues that use this device(s) have been created and commands have \n-- been queued to command-queues. In this case the behavior of OpenCL API calls \n-- that use this context (and command-queues) are considered to be \n-- implementation-defined. The user callback function, if specified when the \n-- context is created, can be used to record appropriate information \n-- when the device becomes unavailable.\nclSetCommandQueueProperty :: CLCommandQueue -> [CLCommandQueueProperty] -> Bool \n -> IO [CLCommandQueueProperty]\nclSetCommandQueueProperty cq xs val = alloca $ \\(dat :: Ptr CLCommandQueueProperty_) -> do\n errcode <- fmap ErrorCode $ raw_clSetCommandQueueProperty cq props (fromBool val) dat\n if errcode == clSuccess\n then fmap bitmaskToCommandQueueProperties $ peek dat\n else return []\n where\n props = bitmaskFromFlags xs\n\n-- -----------------------------------------------------------------------------\nclEnqueue :: (CLuint -> Ptr CLEvent -> Ptr CLEvent -> IO CLint) -> [CLEvent] -> IO (Either CLError CLEvent)\nclEnqueue f [] = alloca $ \\event -> do\n errcode <- f 0 nullPtr event\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS )\n then fmap Right $ peek event\n else return . Left . toEnum . fromIntegral $ errcode\nclEnqueue f events = allocaArray nevents $ \\pevents -> do\n pokeArray pevents events\n alloca $ \\event -> do\n errcode <- f cnevents pevents event\n if errcode == (fromIntegral . fromEnum $ CL_SUCCESS )\n then fmap Right $ peek event\n else return . Left . toEnum . fromIntegral $ errcode\n where\n nevents = length events\n cnevents = fromIntegral nevents\n\n-- -----------------------------------------------------------------------------\n{-| Enqueue commands to read from a buffer object to host memory. Calling\nclEnqueueReadBuffer to read a region of the buffer object with the ptr argument\nvalue set to host_ptr + offset, where host_ptr is a pointer to the memory region\nspecified when the buffer object being read is created with\n'CL_MEM_USE_HOST_PTR', must meet the following requirements in order to avoid\nundefined behavior:\n\n * All commands that use this buffer object have finished execution before the\nread command begins execution\n\n * The buffer object is not mapped\n\n * The buffer object is not used by any command-queue until the read command has\nfinished execution Errors\n\n'clEnqueueReadBuffer' returns the event if the function is executed\nsuccessfully. Otherwise, it returns one of the following errors:\n\n * 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue.\n\n * 'CL_INVALID_CONTEXT' if the context associated with command_queue and buffer\nare not the same or if the context associated with command_queue and events in\nevent_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT' if buffer is not a valid buffer object.\n\n * 'CL_INVALID_VALUE' if the region being read specified by (offset, cb) is out\nof bounds or if ptr is a NULL value.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event_wait_list is NULL and\nnum_events_in_wait_list greater than 0, or event_wait_list is not NULL and\nnum_events_in_wait_list is 0, or if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor data store associated with buffer.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n-}\nclEnqueueReadBuffer :: Integral a => CLCommandQueue -> CLMem -> Bool -> a -> a\n -> Ptr () -> [CLEvent] -> IO (Either CLError CLEvent)\nclEnqueueReadBuffer cq mem check off size dat = clEnqueue (raw_clEnqueueReadBuffer cq mem (fromBool check) (fromIntegral off) (fromIntegral size) dat)\n\n{-| Enqueue commands to write to a buffer object from host memory.Calling\nclEnqueueWriteBuffer to update the latest bits in a region of the buffer object\nwith the ptr argument value set to host_ptr + offset, where host_ptr is a\npointer to the memory region specified when the buffer object being written is\ncreated with 'CL_MEM_USE_HOST_PTR', must meet the following requirements in\norder to avoid undefined behavior:\n\n * The host memory region given by (host_ptr + offset, cb) contains the latest\nbits when the enqueued write command begins execution.\n\n * The buffer object is not mapped.\n\n * The buffer object is not used by any command-queue until the write command\nhas finished execution.\n\n'clEnqueueWriteBuffer' returns the Event if the function is executed\nsuccessfully. Otherwise, it returns one of the following errors:\n\n * 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue.\n\n * 'CL_INVALID_CONTEXT' if the context associated with command_queue and buffer\nare not the same or if the context associated with command_queue and events in\nevent_wait_list are not the same.\n\n * 'CL_INVALID_MEM_OBJECT' if buffer is not a valid buffer object.\n\n * 'CL_INVALID_VALUE' if the region being written specified by (offset, cb) is\nout of bounds or if ptr is a NULL value.\n\n * 'CL_INVALID_EVENT_WAIT_LIST' if event_wait_list is NULL and\nnum_events_in_wait_list greater than 0, or event_wait_list is not NULL and\nnum_events_in_wait_list is 0, or if event objects in event_wait_list are not\nvalid events.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor data store associated with buffer.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n-}\nclEnqueueWriteBuffer :: Integral a => CLCommandQueue -> CLMem -> Bool -> a -> a\n -> Ptr () -> [CLEvent] -> IO (Either CLError CLEvent)\nclEnqueueWriteBuffer cq mem check off size dat = clEnqueue (raw_clEnqueueWriteBuffer cq mem (fromBool check) (fromIntegral off) (fromIntegral size) dat)\n\n-- -----------------------------------------------------------------------------\n{-| Enqueues a command to execute a kernel on a device. Each work-item is\nuniquely identified by a global identifier. The global ID, which can be read\ninside the kernel, is computed using the value given by global_work_size and\nglobal_work_offset. In OpenCL 1.0, the starting global ID is always (0, 0,\n... 0). In addition, a work-item is also identified within a work-group by a\nunique local ID. The local ID, which can also be read by the kernel, is computed\nusing the value given by local_work_size. The starting local ID is always (0, 0,\n... 0).\n\nReturns the event if the kernel execution was successfully queued. Otherwise, it\nreturns one of the following errors:\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no successfully built program\nexecutable available for device associated with command_queue.\n\n * 'CL_INVALID_COMMAND_QUEUE' if command_queue is not a valid command-queue.\n\n * 'CL_INVALID_KERNEL' if kernel is not a valid kernel object.\n\n * 'CL_INVALID_CONTEXT' if context associated with command_queue and kernel is\nnot the same or if the context associated with command_queue and events in\nevent_wait_list are not the same.\n\n * 'CL_INVALID_KERNEL_ARGS' if the kernel argument values have not been\nspecified.\n\n * 'CL_INVALID_WORK_DIMENSION' if work_dim is not a valid value (i.e. a value\nbetween 1 and 3).\n\n * 'CL_INVALID_WORK_GROUP_SIZE' if local_work_size is specified and number of\nwork-items specified by global_work_size is not evenly divisable by size of\nwork-group given by local_work_size or does not match the work-group size\nspecified for kernel using the __attribute__((reqd_work_group_size(X, Y, Z)))\nqualifier in program source.\n\n * 'CL_INVALID_WORK_GROUP_SIZE' if local_work_size is specified and the total\nnumber of work-items in the work-group computed as local_work_size[0]\n*... local_work_size[work_dim - 1] is greater than the value specified by\n'CL_DEVICE_MAX_WORK_GROUP_SIZE' in the table of OpenCL Device Queries for\nclGetDeviceInfo.\n\n * 'CL_INVALID_WORK_GROUP_SIZE' if local_work_size is NULL and the\n__attribute__((reqd_work_group_size(X, Y, Z))) qualifier is used to declare the\nwork-group size for kernel in the program source.\n\n * 'CL_INVALID_WORK_ITEM_SIZE' if the number of work-items specified in any of\nlocal_work_size[0], ... local_work_size[work_dim - 1] is greater than the\ncorresponding values specified by 'CL_DEVICE_MAX_WORK_ITEM_SIZES'[0],\n.... 'CL_DEVICE_MAX_WORK_ITEM_SIZES'[work_dim - 1].\n\n * 'CL_OUT_OF_RESOURCES' if there is a failure to queue the execution instance\nof kernel on the command-queue because of insufficient resources needed to\nexecute the kernel. For example, the explicitly specified local_work_size causes\na failure to execute the kernel because of insufficient resources such as\nregisters or local memory. Another example would be the number of read-only\nimage args used in kernel exceed the 'CL_DEVICE_MAX_READ_IMAGE_ARGS' value for\ndevice or the number of write-only image args used in kernel exceed the\n'CL_DEVICE_MAX_WRITE_IMAGE_ARGS' value for device or the number of samplers used\nin kernel exceed 'CL_DEVICE_MAX_SAMPLERS' for device.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory for data store associated with image or buffer objects specified as arguments to kernel.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required by\nthe OpenCL implementation on the host.\n-}\nclEnqueueNDRangeKernel :: Integral a => CLCommandQueue -> CLKernel -> [a] -> [a] -> [CLEvent] -> IO (Either CLError CLEvent)\nclEnqueueNDRangeKernel cq krn gws lws events = withArray (map fromIntegral gws) $ \\pgws -> withArray (map fromIntegral lws) $ \\plws -> do\n clEnqueue (raw_clEnqueueNDRangeKernel cq krn num nullPtr pgws plws) events\n where\n num = fromIntegral $ length gws\n \n{-| Enqueues a command to execute a kernel on a device. The kernel is executed\nusing a single work-item.\n\n'clEnqueueTask' is equivalent to calling 'clEnqueueNDRangeKernel' with work_dim\n= 1, global_work_offset = [], global_work_size[0] set to 1, and\nlocal_work_size[0] set to 1.\n\nReturns the evens if the kernel execution was successfully queued, or one of the\nerrors below:\n\n * 'CL_INVALID_PROGRAM_EXECUTABLE' if there is no successfully built program\nexecutable available for device associated with command_queue.\n\n * 'CL_INVALID_COMMAND_QUEUE if' command_queue is not a valid command-queue.\n\n * 'CL_INVALID_KERNEL' if kernel is not a valid kernel object.\n\n * 'CL_INVALID_CONTEXT' if context associated with command_queue and kernel is\nnot the same or if the context associated with command_queue and events in\nevent_wait_list are not the same.\n\n * 'CL_INVALID_KERNEL_ARGS' if the kernel argument values have not been specified.\n\n * 'CL_INVALID_WORK_GROUP_SIZE' if a work-group size is specified for kernel\nusing the __attribute__((reqd_work_group_size(X, Y, Z))) qualifier in program\nsource and is not (1, 1, 1).\n\n * 'CL_OUT_OF_RESOURCES' if there is a failure to queue the execution instance\nof kernel on the command-queue because of insufficient resources needed to\nexecute the kernel.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor data store associated with image or buffer objects specified as arguments to\nkernel.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n-}\nclEnqueueTask :: CLCommandQueue -> CLKernel -> [CLEvent] -> IO (Either CLError CLEvent)\nclEnqueueTask cq krn = clEnqueue (raw_clEnqueueTask cq krn)\n \n-- -----------------------------------------------------------------------------\n-- | Issues all previously queued OpenCL commands in a command-queue to the \n-- device associated with the command-queue.\n-- 'clFlush' only guarantees that all queued commands to command_queue get \n-- issued to the appropriate device. There is no guarantee that they will be \n-- complete after 'clFlush' returns.\n-- \n-- 'clFlush' returns 'True' if the function call was executed successfully. It \n-- returns 'False' if command_queue is not a valid command-queue or if there is \n-- a failure to allocate resources required by the OpenCL implementation on the \n-- host.\n--\n-- Any blocking commands queued in a command-queue such as 'clEnqueueReadImage' \n-- or 'clEnqueueReadBuffer' with blocking_read set to 'True', \n-- 'clEnqueueWriteImage' or 'clEnqueueWriteBuffer' with blocking_write set to \n-- 'True', 'clEnqueueMapImage' or 'clEnqueueMapBuffer' with blocking_map set to \n-- 'True' or 'clWaitForEvents' perform an implicit flush of the command-queue.\n--\n-- To use event objects that refer to commands enqueued in a command-queue as \n-- event objects to wait on by commands enqueued in a different command-queue, \n-- the application must call a 'clFlush' or any blocking commands that perform \n-- an implicit flush of the command-queue where the commands that refer to these \n-- event objects are enqueued.\nclFlush :: CLCommandQueue -> IO Bool\nclFlush = wrapCheckSuccess . raw_clFlush\n \n-- | Blocks until all previously queued OpenCL commands in a command-queue are \n-- issued to the associated device and have completed.\n-- 'clFinish' does not return until all queued commands in command_queue have \n-- been processed and completed. 'clFinish' is also a synchronization point.\n--\n-- 'clFinish' returns 'True' if the function call was executed successfully. It \n-- returns 'False' if command_queue is not a valid command-queue or if there is \n-- a failure to allocate resources required by the OpenCL implementation on the \n-- host.\nclFinish :: CLCommandQueue -> IO Bool\nclFinish = wrapCheckSuccess . raw_clFinish\n \n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"d91394f57c20f9ff7e78e161a9ae6351c7bc4a51","subject":"[project @ 2005-10-30 11:56:30 by as49]","message":"[project @ 2005-10-30 11:56:30 by as49]\n\nFix wrong link.\n\ndarcs-hash:20051030115630-d90cf-3e254097a6b0aadbd76625011cbfe828c979edac.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"cairo\/Graphics\/Rendering\/Cairo\/Types.chs","new_file":"cairo\/Graphics\/Rendering\/Cairo\/Types.chs","new_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Types\n-- Copyright : (c) Paolo Martini 2005\n-- License : BSD-style (see cairo\/COPYRIGHT)\n--\n-- Maintainer : p.martini@neuralnoise.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Haskell bindings to the cairo types.\n-----------------------------------------------------------------------------\n\n-- #hide\nmodule Graphics.Rendering.Cairo.Types (\n Matrix(Matrix), MatrixPtr\n , Cairo(Cairo), unCairo\n , Surface(Surface), unSurface\n , Pattern(Pattern), unPattern\n , Status(..)\n , Operator(..)\n , Antialias(..)\n , FillRule(..)\n , LineCap(..)\n , LineJoin(..)\n , ScaledFont(..), unScaledFont\n , FontFace(..), unFontFace\n , Glyph, unGlyph\n , TextExtentsPtr\n , TextExtents(..)\n , FontExtentsPtr\n , FontExtents(..)\n , FontSlant(..)\n , FontWeight(..)\n , SubpixelOrder(..)\n , HintStyle(..)\n , HintMetrics(..)\n , FontOptions(..), withFontOptions, mkFontOptions\n , Path(..), unPath\n , Content(..)\n , Format(..)\n , Extend(..)\n , Filter(..)\n\n , cIntConv\n , cFloatConv\n , cFromBool\n , cToBool\n , cToEnum\n , cFromEnum\n , peekFloatConv\n , withFloatConv\n\n ) where\n\n{#import Graphics.Rendering.Cairo.Matrix#}\n\nimport Foreign hiding (rotate)\nimport CForeign\n\nimport Monad (liftM)\n\n{#context lib=\"cairo\" prefix=\"cairo\"#}\n\n-- not visible\n{#pointer *cairo_t as Cairo newtype#}\nunCairo (Cairo x) = x\n\n-- | The medium to draw on.\n{#pointer *surface_t as Surface newtype#}\nunSurface (Surface x) = x\n\n-- | Attributes for drawing operations.\n{#pointer *pattern_t as Pattern newtype#}\nunPattern (Pattern x) = x\n\n-- | Cairo status.\n--\n-- * 'Status' is used to indicate errors that can occur when using\n-- Cairo. In some cases it is returned directly by functions. When using\n-- 'Graphics.Rendering.Cairo.Render', the last error, if any, is stored\n-- in the monad and can be retrieved with 'Graphics.Rendering.Cairo.status'.\n--\n{#enum status_t as Status {underscoreToCase} deriving(Eq)#}\n\n-- | Composition operator for all drawing operations.\n--\n{#enum operator_t as Operator {underscoreToCase}#}\n\n-- | Specifies the type of antialiasing to do when rendering text or shapes\n--\n-- ['AntialiasDefault'] Use the default antialiasing for the subsystem\n-- and target device.\n--\n-- ['AntialiasNone'] Use a bilevel alpha mask.\n--\n-- ['AntialiasGray'] Perform single-color antialiasing (using shades of\n-- gray for black text on a white background, for example).\n--\n-- ['AntialiasSubpixel'] Perform antialiasing by taking advantage of\n-- the order of subpixel elements on devices such as LCD panels.\n--\n{#enum antialias_t as Antialias {underscoreToCase}#}\n\n-- | Specify how paths are filled.\n--\n-- * For both fill rules, whether or not a point is included in the fill is\n-- determined by taking a ray from that point to infinity and looking at\n-- intersections with the path. The ray can be in any direction, as long\n-- as it doesn't pass through the end point of a segment or have a tricky\n-- intersection such as intersecting tangent to the path. (Note that\n-- filling is not actually implemented in this way. This is just a\n-- description of the rule that is applied.)\n--\n-- ['FillRuleWinding'] If the path crosses the ray from left-to-right,\n-- counts +1. If the path crosses the ray from right to left, counts -1.\n-- (Left and right are determined from the perspective of looking along\n-- the ray from the starting point.) If the total count is non-zero, the\n-- point will be filled.\n--\n-- ['FillRuleEvenOdd'] Counts the total number of intersections,\n-- without regard to the orientation of the contour. If the total number\n-- of intersections is odd, the point will be filled.\n--\n{#enum fill_rule_t as FillRule {underscoreToCase}#}\n\n-- | Specify line endings.\n--\n-- ['LineCapButt'] Start(stop) the line exactly at the start(end) point.\n--\n-- ['LineCapRound'] Use a round ending, the center of the circle is the\n-- end point.\n--\n-- ['LineCapSquare'] Use squared ending, the center of the square is the\n-- end point\n--\n{#enum line_cap_t as LineCap {underscoreToCase}#}\n\n-- | Specify how lines join.\n--\n{#enum line_join_t as LineJoin {underscoreToCase}#}\n\n{#pointer *scaled_font_t as ScaledFont newtype#}\nunScaledFont (ScaledFont x) = x\n\n{#pointer *font_face_t as FontFace newtype#}\nunFontFace (FontFace x) = x\n\n{#pointer *glyph_t as Glyph newtype#}\nunGlyph (Glyph x) = x\n\n{#pointer *text_extents_t as TextExtentsPtr -> TextExtents#}\n\n-- | Specify the extents of a text.\ndata TextExtents = TextExtents {\n textExtentsXbearing :: Double\n , textExtentsYbearing :: Double\n , textExtentsWidth :: Double\n , textExtentsHeight :: Double\n , textExtentsXadvance :: Double\n , textExtentsYadvance :: Double\n }\n\ninstance Storable TextExtents where\n sizeOf _ = {#sizeof text_extents_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n x_bearing <- {#get text_extents_t->x_bearing#} p\n y_bearing <- {#get text_extents_t->y_bearing#} p\n width <- {#get text_extents_t->width#} p\n height <- {#get text_extents_t->height#} p\n x_advance <- {#get text_extents_t->x_advance#} p\n y_advance <- {#get text_extents_t->y_advance#} p\n return $ TextExtents (cFloatConv x_bearing) (cFloatConv y_bearing)\n (cFloatConv width) (cFloatConv height)\n (cFloatConv x_advance) (cFloatConv y_advance)\n poke p (TextExtents x_bearing y_bearing width height x_advance y_advance) = do\n {#set text_extents_t->x_bearing#} p (cFloatConv x_bearing)\n {#set text_extents_t->y_bearing#} p (cFloatConv y_bearing)\n {#set text_extents_t->width#} p (cFloatConv width)\n {#set text_extents_t->height#} p (cFloatConv height)\n {#set text_extents_t->x_advance#} p (cFloatConv x_advance)\n {#set text_extents_t->y_advance#} p (cFloatConv y_advance)\n return ()\n\n{#pointer *font_extents_t as FontExtentsPtr -> FontExtents#}\n\n-- | Result of querying the font extents.\ndata FontExtents = FontExtents {\n fontExtentsAscent :: Double\n , fontExtentsDescent :: Double\n , fontExtentsHeight :: Double\n , fontExtentsMaxXadvance :: Double\n , fontExtentsMaxYadvance :: Double\n }\n\ninstance Storable FontExtents where\n sizeOf _ = {#sizeof font_extents_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n ascent <- {#get font_extents_t->ascent#} p\n descent <- {#get font_extents_t->descent#} p\n height <- {#get font_extents_t->height#} p\n max_x_advance <- {#get font_extents_t->max_x_advance#} p\n max_y_advance <- {#get font_extents_t->max_y_advance#} p\n return $ FontExtents (cFloatConv ascent) (cFloatConv descent) (cFloatConv height)\n (cFloatConv max_x_advance) (cFloatConv max_y_advance)\n poke p (FontExtents ascent descent height max_x_advance max_y_advance) = do\n {#set font_extents_t->ascent#} p (cFloatConv ascent)\n {#set font_extents_t->descent#} p (cFloatConv descent)\n {#set font_extents_t->height#} p (cFloatConv height)\n {#set font_extents_t->max_x_advance#} p (cFloatConv max_x_advance)\n {#set font_extents_t->max_y_advance#} p (cFloatConv max_y_advance)\n return ()\n\n-- | Specify font slant.\n{#enum font_slant_t as FontSlant {underscoreToCase}#}\n\n-- | Specify font weight.\n{#enum font_weight_t as FontWeight {underscoreToCase}#}\n\n-- | Specify subpixel order.\n{#enum subpixel_order_t as SubpixelOrder {underscoreToCase}#}\n\n-- | FIXME: Document.\n{#enum hint_style_t as HintStyle {underscoreToCase}#}\n\n-- | FIXME: Document.\n{#enum hint_metrics_t as HintMetrics {underscoreToCase}#}\n\n-- | Specifies how to render text.\n{#pointer *font_options_t as FontOptions foreign newtype#}\n\nwithFontOptions (FontOptions fptr) = withForeignPtr fptr\n\nmkFontOptions :: Ptr FontOptions -> IO FontOptions\nmkFontOptions fontOptionsPtr = do\n fontOptionsForeignPtr <- newForeignPtr fontOptionsDestroy fontOptionsPtr\n return (FontOptions fontOptionsForeignPtr)\n\nforeign import ccall unsafe \"&cairo_font_options_destroy\"\n fontOptionsDestroy :: FinalizerPtr FontOptions\n\n-- XXX: pathToList :: Path -> [PathData]\n-- \n-- http:\/\/cairographics.org\/manual\/bindings-path.html\n-- \n-- {#enum path_data_type_t as PathDataType {underscoreToCase}#}\n-- \n-- type Point = (Double, Double)\n-- data PathData = PathMoveTo Point\n-- | PathLineTo Point\n-- | PathCurveTo Point Point Point\n-- | PathClose\n\n-- | A Cairo path.\n--\n-- * A path is a sequence of drawing operations that are accumulated until\n-- 'Graphics.Rendering.Cairo.stroke' is called. Using a path is particularly\n-- useful when drawing lines with special join styles and\n-- 'Graphics.Rendering.Cairo.closePath'.\n--\n{#pointer *path_t as Path newtype#}\nunPath (Path x) = x\n\n{#enum content_t as Content {underscoreToCase}#}\n\ndata Format = FormatARGB32\n | FormatRGB24\n | FormatA8\n | FormatA1\n deriving (Enum)\n\n-- | FIX ME: We should find out about this.\n{#enum extend_t as Extend {underscoreToCase}#}\n\n-- | Specify how filtering is done.\n{#enum filter_t as Filter {underscoreToCase}#}\n\n-- Marshalling functions\n\ncIntConv :: (Integral a, Integral b) => a -> b\ncIntConv = fromIntegral\n\ncFloatConv :: (RealFloat a, RealFloat b) => a -> b\ncFloatConv = realToFrac\n\ncFromBool :: Num a => Bool -> a\ncFromBool = fromBool\n\ncToBool :: Num a => a -> Bool\ncToBool = toBool\n\ncToEnum :: (Integral i, Enum e) => i -> e\ncToEnum = toEnum . cIntConv\n\ncFromEnum :: (Enum e, Integral i) => e -> i\ncFromEnum = cIntConv . fromEnum\n\npeekFloatConv :: (Storable a, RealFloat a, RealFloat b) => Ptr a -> IO b\npeekFloatConv = liftM cFloatConv . peek\n\nwithFloatConv :: (Storable b, RealFloat a, RealFloat b) => a -> (Ptr b -> IO c) -> IO c\nwithFloatConv = with . cFloatConv\n\nwithArrayFloatConv :: (Storable b, RealFloat a, RealFloat b) => [a] -> (Ptr b -> IO b1) -> IO b1\nwithArrayFloatConv = withArray . map (cFloatConv)\n","old_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.Types\n-- Copyright : (c) Paolo Martini 2005\n-- License : BSD-style (see cairo\/COPYRIGHT)\n--\n-- Maintainer : p.martini@neuralnoise.com\n-- Stability : experimental\n-- Portability : portable\n--\n-- Haskell bindings to the cairo types.\n-----------------------------------------------------------------------------\n\n-- #hide\nmodule Graphics.Rendering.Cairo.Types (\n Matrix(Matrix), MatrixPtr\n , Cairo(Cairo), unCairo\n , Surface(Surface), unSurface\n , Pattern(Pattern), unPattern\n , Status(..)\n , Operator(..)\n , Antialias(..)\n , FillRule(..)\n , LineCap(..)\n , LineJoin(..)\n , ScaledFont(..), unScaledFont\n , FontFace(..), unFontFace\n , Glyph, unGlyph\n , TextExtentsPtr\n , TextExtents(..)\n , FontExtentsPtr\n , FontExtents(..)\n , FontSlant(..)\n , FontWeight(..)\n , SubpixelOrder(..)\n , HintStyle(..)\n , HintMetrics(..)\n , FontOptions(..), withFontOptions, mkFontOptions\n , Path(..), unPath\n , Content(..)\n , Format(..)\n , Extend(..)\n , Filter(..)\n\n , cIntConv\n , cFloatConv\n , cFromBool\n , cToBool\n , cToEnum\n , cFromEnum\n , peekFloatConv\n , withFloatConv\n\n ) where\n\n{#import Graphics.Rendering.Cairo.Matrix#}\n\nimport Foreign hiding (rotate)\nimport CForeign\n\nimport Monad (liftM)\n\n{#context lib=\"cairo\" prefix=\"cairo\"#}\n\n-- not visible\n{#pointer *cairo_t as Cairo newtype#}\nunCairo (Cairo x) = x\n\n-- | The medium to draw on.\n{#pointer *surface_t as Surface newtype#}\nunSurface (Surface x) = x\n\n-- | Attributes for drawing operations.\n{#pointer *pattern_t as Pattern newtype#}\nunPattern (Pattern x) = x\n\n-- | Cairo status.\n--\n-- * 'Status' is used to indicate errors that can occur when using\n-- Cairo. In some cases it is returned directly by functions. When using\n-- 'Graphics.Rendering.Cairo.Render', the last error, if any, is stored\n-- in the monad and can be retrieved with 'Graphics.Rendering.Cairo.status'.\n--\n{#enum status_t as Status {underscoreToCase} deriving(Eq)#}\n\n-- | Composition operator for all drawing operations.\n--\n{#enum operator_t as Operator {underscoreToCase}#}\n\n-- | Specifies the type of antialiasing to do when rendering text or shapes\n--\n-- ['AntialiasDefault'] Use the default antialiasing for the subsystem\n-- and target device.\n--\n-- ['AntialiasNone'] Use a bilevel alpha mask.\n--\n-- ['AntialiasGray'] Perform single-color antialiasing (using shades of\n-- gray for black text on a white background, for example).\n--\n-- ['AntialiasSubpixel'] Perform antialiasing by taking advantage of\n-- the order of subpixel elements on devices such as LCD panels.\n--\n{#enum antialias_t as Antialias {underscoreToCase}#}\n\n-- | Specify how paths are filled.\n--\n-- * For both fill rules, whether or not a point is included in the fill is\n-- determined by taking a ray from that point to infinity and looking at\n-- intersections with the path. The ray can be in any direction, as long\n-- as it doesn't pass through the end point of a segment or have a tricky\n-- intersection such as intersecting tangent to the path. (Note that\n-- filling is not actually implemented in this way. This is just a\n-- description of the rule that is applied.)\n--\n-- ['FillRuleWinding'] If the path crosses the ray from left-to-right,\n-- counts +1. If the path crosses the ray from right to left, counts -1.\n-- (Left and right are determined from the perspective of looking along\n-- the ray from the starting point.) If the total count is non-zero, the\n-- point will be filled.\n--\n-- ['FillRuleEvenOdd'] Counts the total number of intersections,\n-- without regard to the orientation of the contour. If the total number\n-- of intersections is odd, the point will be filled.\n--\n{#enum fill_rule_t as FillRule {underscoreToCase}#}\n\n-- | Specify line endings.\n--\n-- ['LineCapButt'] Start(stop) the line exactly at the start(end) point.\n--\n-- ['LineCapRound'] Use a round ending, the center of the circle is the\n-- end point.\n--\n-- ['LineCapSquare'] Use squared ending, the center of the square is the\n-- end point\n--\n{#enum line_cap_t as LineCap {underscoreToCase}#}\n\n-- | Specify how lines join.\n--\n{#enum line_join_t as LineJoin {underscoreToCase}#}\n\n{#pointer *scaled_font_t as ScaledFont newtype#}\nunScaledFont (ScaledFont x) = x\n\n{#pointer *font_face_t as FontFace newtype#}\nunFontFace (FontFace x) = x\n\n{#pointer *glyph_t as Glyph newtype#}\nunGlyph (Glyph x) = x\n\n{#pointer *text_extents_t as TextExtentsPtr -> TextExtents#}\n\n-- | Specify the extents of a text.\ndata TextExtents = TextExtents {\n textExtentsXbearing :: Double\n , textExtentsYbearing :: Double\n , textExtentsWidth :: Double\n , textExtentsHeight :: Double\n , textExtentsXadvance :: Double\n , textExtentsYadvance :: Double\n }\n\ninstance Storable TextExtents where\n sizeOf _ = {#sizeof text_extents_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n x_bearing <- {#get text_extents_t->x_bearing#} p\n y_bearing <- {#get text_extents_t->y_bearing#} p\n width <- {#get text_extents_t->width#} p\n height <- {#get text_extents_t->height#} p\n x_advance <- {#get text_extents_t->x_advance#} p\n y_advance <- {#get text_extents_t->y_advance#} p\n return $ TextExtents (cFloatConv x_bearing) (cFloatConv y_bearing)\n (cFloatConv width) (cFloatConv height)\n (cFloatConv x_advance) (cFloatConv y_advance)\n poke p (TextExtents x_bearing y_bearing width height x_advance y_advance) = do\n {#set text_extents_t->x_bearing#} p (cFloatConv x_bearing)\n {#set text_extents_t->y_bearing#} p (cFloatConv y_bearing)\n {#set text_extents_t->width#} p (cFloatConv width)\n {#set text_extents_t->height#} p (cFloatConv height)\n {#set text_extents_t->x_advance#} p (cFloatConv x_advance)\n {#set text_extents_t->y_advance#} p (cFloatConv y_advance)\n return ()\n\n{#pointer *font_extents_t as FontExtentsPtr -> FontExtents#}\n\n-- | Result of querying the font extents.\ndata FontExtents = FontExtents {\n fontExtentsAscent :: Double\n , fontExtentsDescent :: Double\n , fontExtentsHeight :: Double\n , fontExtentsMaxXadvance :: Double\n , fontExtentsMaxYadvance :: Double\n }\n\ninstance Storable FontExtents where\n sizeOf _ = {#sizeof font_extents_t#}\n alignment _ = alignment (undefined :: CDouble)\n peek p = do\n ascent <- {#get font_extents_t->ascent#} p\n descent <- {#get font_extents_t->descent#} p\n height <- {#get font_extents_t->height#} p\n max_x_advance <- {#get font_extents_t->max_x_advance#} p\n max_y_advance <- {#get font_extents_t->max_y_advance#} p\n return $ FontExtents (cFloatConv ascent) (cFloatConv descent) (cFloatConv height)\n (cFloatConv max_x_advance) (cFloatConv max_y_advance)\n poke p (FontExtents ascent descent height max_x_advance max_y_advance) = do\n {#set font_extents_t->ascent#} p (cFloatConv ascent)\n {#set font_extents_t->descent#} p (cFloatConv descent)\n {#set font_extents_t->height#} p (cFloatConv height)\n {#set font_extents_t->max_x_advance#} p (cFloatConv max_x_advance)\n {#set font_extents_t->max_y_advance#} p (cFloatConv max_y_advance)\n return ()\n\n-- | Specify font slant.\n{#enum font_slant_t as FontSlant {underscoreToCase}#}\n\n-- | Specify font weight.\n{#enum font_weight_t as FontWeight {underscoreToCase}#}\n\n-- | Specify subpixel order.\n{#enum subpixel_order_t as SubpixelOrder {underscoreToCase}#}\n\n-- | FIXME: Document.\n{#enum hint_style_t as HintStyle {underscoreToCase}#}\n\n-- | FIXME: Document.\n{#enum hint_metrics_t as HintMetrics {underscoreToCase}#}\n\n-- | Specifies how to render text.\n{#pointer *font_options_t as FontOptions foreign newtype#}\n\nwithFontOptions (FontOptions fptr) = withForeignPtr fptr\n\nmkFontOptions :: Ptr FontOptions -> IO FontOptions\nmkFontOptions fontOptionsPtr = do\n fontOptionsForeignPtr <- newForeignPtr fontOptionsDestroy fontOptionsPtr\n return (FontOptions fontOptionsForeignPtr)\n\nforeign import ccall unsafe \"&cairo_font_options_destroy\"\n fontOptionsDestroy :: FinalizerPtr FontOptions\n\n-- XXX: pathToList :: Path -> [PathData]\n-- \n-- http:\/\/cairographics.org\/manual\/bindings-path.html\n-- \n-- {#enum path_data_type_t as PathDataType {underscoreToCase}#}\n-- \n-- type Point = (Double, Double)\n-- data PathData = PathMoveTo Point\n-- | PathLineTo Point\n-- | PathCurveTo Point Point Point\n-- | PathClose\n\n-- | A Cairo path.\n--\n-- * A path is a sequence of drawing operations that are accumulated until\n-- 'Graphics.Render.Cairo.stroke' is called. Using a path is particularly\n-- useful when drawing lines with special join styles and\n-- 'Graphics.Render.Cairo.closePath'.\n--\n{#pointer *path_t as Path newtype#}\nunPath (Path x) = x\n\n{#enum content_t as Content {underscoreToCase}#}\n\ndata Format = FormatARGB32\n | FormatRGB24\n | FormatA8\n | FormatA1\n deriving (Enum)\n\n-- | FIX ME: We should find out about this.\n{#enum extend_t as Extend {underscoreToCase}#}\n\n-- | Specify how filtering is done.\n{#enum filter_t as Filter {underscoreToCase}#}\n\n-- Marshalling functions\n\ncIntConv :: (Integral a, Integral b) => a -> b\ncIntConv = fromIntegral\n\ncFloatConv :: (RealFloat a, RealFloat b) => a -> b\ncFloatConv = realToFrac\n\ncFromBool :: Num a => Bool -> a\ncFromBool = fromBool\n\ncToBool :: Num a => a -> Bool\ncToBool = toBool\n\ncToEnum :: (Integral i, Enum e) => i -> e\ncToEnum = toEnum . cIntConv\n\ncFromEnum :: (Enum e, Integral i) => e -> i\ncFromEnum = cIntConv . fromEnum\n\npeekFloatConv :: (Storable a, RealFloat a, RealFloat b) => Ptr a -> IO b\npeekFloatConv = liftM cFloatConv . peek\n\nwithFloatConv :: (Storable b, RealFloat a, RealFloat b) => a -> (Ptr b -> IO c) -> IO c\nwithFloatConv = with . cFloatConv\n\nwithArrayFloatConv :: (Storable b, RealFloat a, RealFloat b) => [a] -> (Ptr b -> IO b1) -> IO b1\nwithArrayFloatConv = withArray . map (cFloatConv)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"ad0e3ec63b33345efb87bdab29b248f135f5b925","subject":"Fix font functions.","message":"Fix font functions.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/FL.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/FL.chs","new_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n\nmodule Graphics.UI.FLTK.LowLevel.FL\n (\n Option(..),\n ClipboardContents(..),\n PasteSource(..),\n scrollbarSize,\n setScrollbarSize,\n selectionOwner,\n setSelectionOwner,\n run,\n replRun,\n check,\n ready,\n option,\n setOption,\n addAwakeHandler,\n getAwakeHandler_,\n display,\n ownColormap,\n getSystemColors,\n foreground,\n background,\n background2,\n setScheme,\n getScheme,\n reloadScheme,\n isScheme,\n setFirstWindow,\n nextWindow,\n setGrab,\n getMouse,\n eventStates,\n extract,\n extractEventStates,\n handle,\n handle_,\n belowmouse,\n setBelowmouse,\n setPushed,\n setFocus,\n setHandler,\n paste,\n toRectangle,\n fromRectangle,\n screenBounds,\n screenDPI,\n screenWorkArea,\n setColorRgb,\n toAttribute,\n release,\n setVisibleFocus,\n visibleFocus,\n setDndTextOps,\n dndTextOps,\n deleteWidget,\n doWidgetDeletion,\n watchWidgetPointer,\n releaseWidgetPointer,\n clearWidgetPointer,\n version,\n help,\n visual,\n#if !defined(__APPLE__) && defined(GLSUPPORT)\n glVisual,\n glVisualWithAlist,\n#endif\n wait,\n setWait,\n waitFor,\n readqueue,\n addTimeout,\n repeatTimeout,\n hasTimeout,\n removeTimeout,\n addCheck,\n hasCheck,\n removeCheck,\n addIdle,\n hasIdle,\n removeIdle,\n damage,\n redraw,\n flush,\n firstWindow,\n modal,\n grab,\n getKey,\n compose,\n composeReset,\n testShortcut,\n enableIm,\n disableIm,\n pushed,\n focus,\n copy,\n copyWithDestination,\n pasteWithSource,\n dnd,\n x,\n y,\n w,\n h,\n screenCount,\n setColor,\n getColor,\n getColorRgb,\n#if !defined(__APPLE__)\n removeFromColormap,\n#endif\n -- * Box\n BoxtypeSpec,\n getBoxtype,\n setBoxtype,\n boxDx,\n boxDy,\n boxDw,\n boxDh,\n drawBoxActive,\n -- * Fonts\n getFontName,\n getFont,\n getFontSizes,\n setFontToString,\n setFontToFont,\n setFonts,\n -- * File Descriptor Callbacks\n addFd,\n addFdWhen,\n removeFd,\n removeFdWhen,\n -- * Events\n event,\n eventShift,\n eventCtrl,\n eventCommand,\n eventAlt,\n eventButtons,\n eventButton1,\n eventButton2,\n eventButton3,\n eventX,\n eventY,\n eventXRoot,\n eventYRoot,\n eventDx,\n eventDy,\n eventClicks,\n setEventClicks,\n eventIsClick,\n setEventIsClick,\n eventButton,\n eventState,\n containsEventState,\n eventKey,\n eventOriginalKey,\n eventKeyPressed,\n eventInsideRegion,\n eventInsideWidget,\n eventDispatch,\n setEventDispatch,\n eventText,\n eventLength,\n eventClipboardContents,\n#if FLTK_API_VERSION >= 10304\n setBoxColor,\n boxColor,\n abiVersion,\n apiVersion,\n abiCheck,\n localCtrl,\n localMeta,\n localAlt,\n localShift\n#ifdef GLSUPPORT\n , useHighResGL\n , setUseHighResGL\n#endif\n#endif\n )\nwhere\n#include \"Fl_C.h\"\nimport C2HS hiding (cFromEnum, cToBool,cToEnum,cFromBool)\nimport Data.IORef\n\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Hierarchy hiding (\n setVisibleFocus,\n handle,\n redraw,\n flush,\n testShortcut,\n copy,\n setColor,\n getColor,\n focus,\n display,\n setScrollbarSize\n )\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\nimport qualified Data.Text.Foreign as TF\nimport qualified System.IO.Unsafe as Unsafe (unsafePerformIO)\nimport Control.Exception(catch, throw, AsyncException(UserInterrupt))\n#c\n enum Option {\n OptionArrowFocus = OPTION_ARROW_FOCUS,\n OptionVisibleFocus = OPTION_VISIBLE_FOCUS,\n OptionDndText = OPTION_DND_TEXT,\n OptionShowTooltips = OPTION_SHOW_TOOLTIPS,\n OptionLast = OPTION_LAST\n };\n#endc\n\n{#enum Option {} deriving (Show) #}\n\nptrToGlobalEventHandler :: IORef (FunPtr GlobalEventHandlerPrim)\nptrToGlobalEventHandler = Unsafe.unsafePerformIO $ do\n initialHandler <- toGlobalEventHandlerPrim (\\_ -> return (-1))\n newIORef initialHandler\n\n-- | Contents of the clipboard following a copy or cut. Can be either an <.\/Graphics-UI-FLTK-LowLevel-Image.html Image> or plain 'T.Text'.\ndata ClipboardContents =\n ClipboardContentsImage (Maybe (Ref Image))\n | ClipboardContentsPlainText (Maybe T.Text)\n\ndata PasteSource =\n PasteSourceSelectionBuffer\n | PasteSourceClipboardPlainText\n | PasteSourceClipboardImage\n\ntype EventDispatchPrim = (CInt ->\n Ptr () ->\n IO CInt)\nforeign import ccall \"wrapper\"\n wrapEventDispatchPrim :: EventDispatchPrim ->\n IO (FunPtr EventDispatchPrim)\nforeign import ccall \"dynamic\"\n unwrapEventDispatchPrim :: FunPtr EventDispatchPrim -> EventDispatchPrim\n\nrun :: IO Int\nrun = {#call Fl_run as fl_run #} >>= return . fromIntegral\n\ncheck :: IO Int\ncheck = {#call Fl_check as fl_check #} >>= return . fromIntegral\n\nready :: IO Int\nready = {#call Fl_ready as fl_ready #} >>= return . fromIntegral\n\n\noption :: Option -> IO Bool\noption o = {#call Fl_option as fl_option #} (cFromEnum o) >>= \\(c::CInt) -> return $ cToBool $ ((fromIntegral c) :: Int)\n\nsetOption :: Option -> Bool -> IO ()\nsetOption o t = {#call Fl_set_option as fl_set_option #} (cFromEnum o) (Graphics.UI.FLTK.LowLevel.Utils.cFromBool t)\n\nunsafeToCallbackPrim :: GlobalCallback -> FunPtr CallbackPrim\nunsafeToCallbackPrim = (Unsafe.unsafePerformIO) . toGlobalCallbackPrim\n\n{# fun Fl_add_awake_handler_ as addAwakeHandler'\n {id `FunPtr CallbackPrim', id `(Ptr ())'} -> `Int' #}\naddAwakeHandler :: GlobalCallback -> IO Int\naddAwakeHandler awakeHandler =\n do\n callbackPtr <- toGlobalCallbackPrim awakeHandler\n addAwakeHandler' callbackPtr nullPtr\n\n{# fun Fl_get_awake_handler_ as getAwakeHandler_'\n {id `Ptr (FunPtr CallbackPrim)', id `Ptr (Ptr ())'} -> `Int' #}\ngetAwakeHandler_ :: IO GlobalCallback\ngetAwakeHandler_ =\n alloca $ \\ptrToFunPtr ->\n alloca $ \\ptrToUD -> do\n _ <- getAwakeHandler_' ptrToFunPtr ptrToUD\n funPtr <- peek ptrToFunPtr\n return $ unwrapGlobalCallbackPtr $ castFunPtr funPtr\n\n{# fun Fl_version as version\n {} -> `Double' #}\n{# fun Fl_help as help\n {} -> `T.Text' unsafeFromCString #}\n\ndisplay :: T.Text -> IO ()\ndisplay text = TF.withCStringLen text $ \\(str,_) -> {#call Fl_display as fl_display #} str\n{# fun Fl_visual as visual\n {cFromEnum `Mode'} -> `Bool' cToBool #}\n#if !defined(__APPLE__) && defined(GLSUPPORT)\n-- | Only available if on a non OSX platform and if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{# fun Fl_gl_visual as glVisual\n {cFromEnum `Mode'} -> `Bool' cToBool #}\n-- | Only available if on a non OSX platform and if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{# fun Fl_gl_visual_with_alist as glVisualWithAlist\n {cFromEnum `Mode', id `Ptr CInt'} -> `Bool' cToBool #}\n#endif\n\nownColormap :: IO ()\nownColormap = {#call Fl_own_colormap as fl_own_colormap #}\n\ngetSystemColors :: IO ()\ngetSystemColors = {#call Fl_get_system_colors as fl_get_system_colors #}\n\nforeground :: RGB -> IO ()\nforeground (r,g,b) = {#call Fl_foreground as fl_foreground #}\n (fromIntegral r)\n (fromIntegral g)\n (fromIntegral b)\nbackground :: RGB -> IO ()\nbackground (r,g,b) = {#call Fl_background as fl_background #}\n (fromIntegral r)\n (fromIntegral g)\n (fromIntegral b)\nbackground2 :: RGB -> IO ()\nbackground2 (r,g,b) = {#call Fl_background2 as fl_background2 #}\n (fromIntegral r)\n (fromIntegral g)\n (fromIntegral b)\n{# fun pure Fl_scheme as getScheme\n {} -> `T.Text' unsafeFromCString #}\nsetScheme :: T.Text -> IO Int\nsetScheme sch = TF.withCStringLen sch $ \\(str,_) -> {#call Fl_set_scheme as fl_set_scheme #} str >>= return . fromIntegral\n{# fun pure Fl_reload_scheme as reloadScheme {} -> `Int' #}\nisScheme :: T.Text -> IO Bool\nisScheme sch = TF.withCStringLen sch $ \\(str,_) -> {#call Fl_is_scheme as fl_is_scheme #} str >>= return . toBool\n{# fun Fl_wait as wait\n { } -> `Int' #}\n{# fun Fl_set_wait as waitFor\n { `Double' } -> `Double' #}\n\nsetWait :: Double -> IO Double\nsetWait = waitFor\n{# fun Fl_scrollbar_size as scrollbarSize\n { } -> `Int' #}\n{# fun Fl_set_scrollbar_size as setScrollbarSize\n { `Int' } -> `()' #}\n\n{# fun Fl_readqueue as readqueue\n { } -> `Maybe (Ref Widget)' unsafeToMaybeRef #}\n{# fun Fl_add_timeout as addTimeout\n { `Double', unsafeToCallbackPrim `GlobalCallback' } -> `()' supressWarningAboutRes #}\n{# fun Fl_repeat_timeout as repeatTimeout\n { `Double',unsafeToCallbackPrim `GlobalCallback' } -> `()' supressWarningAboutRes #}\n{# fun Fl_has_timeout as hasTimeout\n { unsafeToCallbackPrim `GlobalCallback' } -> `Int' #}\n{# fun Fl_remove_timeout as removeTimeout\n { unsafeToCallbackPrim `GlobalCallback' } -> `()' supressWarningAboutRes #}\n{# fun Fl_add_check as addCheck\n { unsafeToCallbackPrim `GlobalCallback' } -> `()' supressWarningAboutRes #}\n{# fun Fl_has_check as hasCheck\n { unsafeToCallbackPrim `GlobalCallback' } -> `Int' #}\n{# fun Fl_remove_check as removeCheck\n { unsafeToCallbackPrim `GlobalCallback' } -> `()' supressWarningAboutRes #}\n{# fun Fl_add_idle as addIdle\n { unsafeToCallbackPrim `GlobalCallback' } -> `()' supressWarningAboutRes #}\n{# fun Fl_has_idle as hasIdle\n { unsafeToCallbackPrim `GlobalCallback' } -> `Int' #}\n{# fun Fl_remove_idle as removeIdle\n { unsafeToCallbackPrim `GlobalCallback' } -> `()' supressWarningAboutRes #}\n{# fun Fl_damage as damage\n { } -> `Int' #}\n{# fun Fl_redraw as redraw\n { } -> `()' supressWarningAboutRes #}\n{# fun Fl_flush as flush\n { } -> `()' supressWarningAboutRes #}\n{# fun Fl_first_window as firstWindow\n { } -> `Maybe (Ref Window)' unsafeToMaybeRef #}\n{# fun Fl_set_first_window as setFirstWindow'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetFirstWindow :: (Parent a Window) => Ref a -> IO ()\nsetFirstWindow wp =\n withRef wp setFirstWindow'\n{# fun Fl_next_window as nextWindow'\n { id `Ptr ()' } -> `Maybe (Ref Window)' unsafeToMaybeRef #}\nnextWindow :: (Parent a Window) => Ref a -> IO (Maybe (Ref Window))\nnextWindow currWindow =\n withRef currWindow nextWindow'\n{# fun Fl_modal as modal\n { } -> `Maybe (Ref Window)' unsafeToMaybeRef #}\n{# fun Fl_grab as grab\n { } -> `Maybe (Ref Window)' unsafeToMaybeRef #}\n{# fun Fl_set_grab as setGrab'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetGrab :: (Parent a Window) => Ref a -> IO ()\nsetGrab wp = withRef wp setGrab'\n{# fun Fl_event as event\n { } -> `Event' cToEnum #}\n{# fun Fl_event_x as eventX\n { } -> `Int'#}\n{# fun Fl_event_y as eventY\n { } -> `Int'#}\n{# fun Fl_event_x_root as eventXRoot\n { } -> `Int' #}\n{# fun Fl_event_y_root as eventYRoot\n { } -> `Int' #}\n{# fun Fl_event_dx as eventDx\n { } -> `Int' #}\n{# fun Fl_event_dy as eventDy\n { } -> `Int' #}\n{# fun Fl_get_mouse as getMouse'\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv*\n } -> `()' #}\ngetMouse :: IO Position\ngetMouse = do\n (x_pos,y_pos) <- getMouse'\n return $ (Position (X x_pos) (Y y_pos))\n{# fun Fl_event_clicks as eventClicks\n { } -> `Int'#}\n{# fun Fl_set_event_clicks as setEventClicks\n { `Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_event_is_click as eventIsClick\n { } -> `Bool' toBool #}\n{# fun Fl_set_event_is_click as setEventIsClick\n { `Int' } -> `()' supressWarningAboutRes #}\n\n{# fun Fl_event_button as eventButton'\n { } -> `Int' #}\neventButton :: IO (Maybe MouseButton)\neventButton = do\n mb <- eventButton'\n case mb of\n mb' | mb' == (fromEnum Mouse_Left) -> return (Just Mouse_Left)\n mb' | mb' == (fromEnum Mouse_Middle) -> return (Just Mouse_Right)\n mb' | mb' == (fromEnum Mouse_Right) -> return (Just Mouse_Middle)\n _ -> return Nothing\n\neventStates :: [EventState]\neventStates = [\n Kb_ShiftState,\n Kb_CapsLockState,\n Kb_CtrlState,\n Kb_AltState,\n Kb_NumLockState,\n Kb_MetaState,\n Kb_ScrollLockState,\n Mouse_Button1State,\n Mouse_Button2State,\n Mouse_Button3State\n ]\nextractEventStates :: CInt -> [EventState]\nextractEventStates = extract eventStates\n\n{# fun Fl_event_state as eventState\n { } -> `[EventState]' extractEventStates #}\n{# fun Fl_contains_event_state as containsEventState\n {cFromEnum `EventState' } -> `Bool' toBool #}\n{# fun Fl_event_key as eventKey\n { } -> `KeyType' cToKeyType #}\n{# fun Fl_event_original_key as eventOriginalKey\n { } -> `KeyType' cToKeyType #}\n{# fun Fl_event_key_pressed as eventKeyPressed\n {cFromKeyType `KeyType' } -> `Bool' toBool #}\n{# fun Fl_get_key as getKey\n {cFromKeyType `KeyType' } -> `Bool' toBool #}\n{# fun Fl_event_text as eventText\n { } -> `T.Text' unsafeFromCString #}\n{# fun Fl_event_length as eventLength\n { } -> `Int' #}\n\n{# fun Fl_event_clipboard as flEventClipboard' { } -> `Ptr ()' #}\n{# fun Fl_event_clipboard_type as flEventClipboardType' { } -> `T.Text' unsafeFromCString #}\neventClipboardContents :: IO (Maybe ClipboardContents)\neventClipboardContents = do\n typeString <- flEventClipboardType'\n if (T.length typeString == 0)\n then return Nothing\n else case typeString of\n s | (T.unpack s == \"Fl::clipboard_image\") -> do\n stringContents <- flEventClipboard' >>= cStringToText . castPtr\n return (if (T.length stringContents == 0)\n then (Just (ClipboardContentsPlainText Nothing))\n else (Just (ClipboardContentsPlainText (Just stringContents))))\n s | (T.unpack s == \"Fl::clipboard_plain_text\") -> do\n imageRef <- flEventClipboard' >>= toMaybeRef\n return (Just (ClipboardContentsImage imageRef))\n _ -> error \"eventClipboardContents :: The type of the clipboard contents must be either the string \\\"Fl::clipboard_image\\\" or \\\"Fl::clipboard_plain_image\\\".\"\n\n{# fun Fl_compose as compose\n { alloca- `Int' peekIntConv* } -> `Bool' toBool #}\n{# fun Fl_compose_reset as composeReset\n { } -> `()' supressWarningAboutRes #}\n{# fun Fl_event_inside_region as eventInsideRegion'\n { `Int',`Int',`Int',`Int' } -> `Int' #}\neventInsideRegion :: Rectangle -> IO Event\neventInsideRegion (Rectangle\n (Position\n (X x_pos)\n (Y y_pos))\n (Size\n (Width width)\n (Height height))) =\n do\n eventNum <- eventInsideRegion' x_pos y_pos width height\n return $ toEnum eventNum\n{# fun Fl_event_inside_widget as eventInsideWidget'\n { id `Ptr ()' } -> `Int' #}\neventInsideWidget :: (Parent a Widget) => Ref a -> IO Event\neventInsideWidget wp =\n withRef wp (\\ptr -> do\n eventNum <- eventInsideWidget' (castPtr ptr)\n return $ toEnum eventNum)\n{# fun Fl_test_shortcut as testShortcut\n { id `FlShortcut' } -> `Bool' toBool #}\n{# fun Fl_enable_im as enableIm\n {} -> `()' supressWarningAboutRes #}\n{# fun Fl_disable_im as disableIm\n {} -> `()' supressWarningAboutRes #}\n{# fun Fl_handle as handle'\n { `Int',id `Ptr ()' } -> `Int' #}\nhandle :: (Parent a Window) => Event -> Ref a -> IO Int\nhandle e wp =\n withRef wp (handle' (cFromEnum e))\n{# fun Fl_handle_ as handle_'\n { `Int',id `Ptr ()' } -> `Int' #}\nhandle_ :: (Parent a Window) => Event -> Ref a -> IO Int\nhandle_ e wp =\n withRef wp (handle_' (cFromEnum e))\n{# fun Fl_belowmouse as belowmouse\n { } -> `Maybe (Ref Widget)' unsafeToMaybeRef #}\n{# fun Fl_set_belowmouse as setBelowmouse'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetBelowmouse :: (Parent a Widget) => Ref a -> IO ()\nsetBelowmouse wp = withRef wp setBelowmouse'\n{# fun Fl_pushed as pushed'\n { } -> `Ptr ()' #}\npushed :: IO (Maybe (Ref Widget))\npushed = pushed' >>= toMaybeRef\n{# fun Fl_set_pushed as setPushed'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetPushed :: (Parent a Widget) => Ref a -> IO ()\nsetPushed wp = withRef wp setPushed'\n{# fun Fl_focus as focus\n { } -> `Maybe (Ref Widget)' unsafeToMaybeRef #}\n{# fun Fl_set_focus as setFocus'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetFocus :: (Parent a Widget) => Ref a -> IO ()\nsetFocus wp = withRef wp setFocus'\n{# fun Fl_selection_owner as selectionOwner\n { } -> `Maybe (Ref Widget)' unsafeToMaybeRef #}\n{# fun Fl_set_selection_owner as setSelection_Owner'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetSelectionOwner :: (Parent a Widget) => Ref a -> IO ()\nsetSelectionOwner wp = withRef wp setSelection_Owner'\n{# fun Fl_add_handler as addHandler'\n { id `FunPtr GlobalEventHandlerPrim' } -> `()' supressWarningAboutRes #}\n{# fun Fl_remove_handler as removeHandler'\n { id `FunPtr GlobalEventHandlerPrim' } -> `()' supressWarningAboutRes #}\nsetHandler :: GlobalEventHandlerF -> IO ()\nsetHandler eh = do\n newGlobalEventHandler <- toGlobalEventHandlerPrim eh\n curr <- do\n old <- readIORef ptrToGlobalEventHandler\n writeIORef ptrToGlobalEventHandler newGlobalEventHandler\n return old\n removeHandler' curr\n addHandler' newGlobalEventHandler\n\n{# fun Fl_set_event_dispatch as setEventDispatch'\n { id `Ptr (FunPtr EventDispatchPrim)' } -> `()' supressWarningAboutRes #}\n{# fun Fl_event_dispatch as eventDispatch'\n { } -> `FunPtr EventDispatchPrim' id #}\neventDispatch :: (Parent a Widget) => IO (Event -> Ref a -> IO (Int))\neventDispatch =\n do\n funPtr <- eventDispatch'\n return (\\e window ->\n withRef\n window\n (\\ptr ->\n let eventNum = fromIntegral (fromEnum e)\n fun = unwrapEventDispatchPrim funPtr\n in fun eventNum (castPtr ptr) >>=\n return . fromIntegral\n )\n )\n\nsetEventDispatch :: (Parent a Widget) => (Event -> Ref a -> IO Int) -> IO ()\nsetEventDispatch ed = do\n do\n let toPrim = (\\e ptr ->\n let eventEnum = toEnum $ fromIntegral e\n in do\n obj <- toRef ptr\n result <- ed eventEnum obj\n return $ fromIntegral result\n )\n callbackPtr <- wrapEventDispatchPrim toPrim\n ptrToCallbackPtr <- new callbackPtr\n poke ptrToCallbackPtr callbackPtr\n setEventDispatch' ptrToCallbackPtr\n{# fun Fl_copy as copy\n { unsafeToCString `T.Text',`Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_copy_with_destination as copyWithDestination\n { unsafeToCString `T.Text',`Int',`Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_paste_with_source as pasteWithSource\n { id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_paste_with_source_type as pasteWithSourceType\n { id `Ptr ()',`Int', unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\npaste :: (Parent a Widget) => Ref a -> PasteSource -> IO ()\npaste widget PasteSourceSelectionBuffer = withRef widget (\\widgetPtr -> pasteWithSource widgetPtr 0)\npaste widget PasteSourceClipboardPlainText =\n withRef widget (\\widgetPtr -> pasteWithSourceType widgetPtr 1 (T.pack \"Fl::clipboard_plain_text\"))\npaste widget PasteSourceClipboardImage =\n withRef widget (\\widgetPtr -> pasteWithSourceType widgetPtr 1 (T.pack \"Fl::clipboard_image\"))\n\n{# fun Fl_dnd as dnd\n { } -> `Int' #}\n{# fun Fl_x as x\n { } -> `Int' #}\n{# fun Fl_y as y\n { } -> `Int' #}\n{# fun Fl_w as w\n { } -> `Int' #}\n{# fun Fl_h as h\n { } -> `Int' #}\n{# fun Fl_screen_count as screenCount\n { } -> `Int' #}\n\n{# fun Fl_screen_xywh as screenXYWH\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv*\n } -> `()' #}\n\n{# fun Fl_screen_xywh_with_mxmy as screenXYWYWithMXMY\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int',\n `Int'\n } -> `()' #}\n\n{# fun Fl_screen_xywh_with_n as screenXYWNWithN\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int'\n } -> `()' #}\n\n{# fun Fl_screen_xywh_with_mxmymwmh as screenXYWHWithNMXMYMWMH\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int',\n `Int',\n `Int',\n `Int'\n } -> `()' #}\n\nscreenBounds :: Maybe ScreenLocation -> IO Rectangle\nscreenBounds location =\n case location of\n (Just (Intersect (Rectangle (Position (X x_pos) (Y y_pos)) (Size (Width width) (Height height))))) ->\n screenXYWHWithNMXMYMWMH x_pos y_pos width height >>= return . toRectangle\n (Just (ScreenPosition (Position (X x_pos) (Y y_pos)))) ->\n screenXYWYWithMXMY x_pos y_pos >>= return . toRectangle\n (Just (ScreenNumber n)) ->\n screenXYWNWithN n >>= return . toRectangle\n Nothing ->\n screenXYWH >>= return . toRectangle\n\n{# fun Fl_screen_dpi as screenDpi'\n { alloca- `Float' peekFloatConv*,\n alloca- `Float' peekFloatConv* }\n -> `()' #}\n{# fun Fl_screen_dpi_with_n as screenDpiWithN'\n { alloca- `Float' peekFloatConv*,\n alloca- `Float' peekFloatConv*,\n `Int' }\n -> `()' #}\n\nscreenDPI :: Maybe Int -> IO DPI\nscreenDPI (Just n) = do\n (dpiX, dpiY) <- screenDpiWithN' n\n return $ DPI dpiX dpiY\nscreenDPI Nothing = do\n (dpiX, dpiY) <- screenDpi'\n return $ DPI dpiX dpiY\n\n{# fun Fl_screen_work_area_with_mx_my as screenWorkAreaWithMXMY'\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int',\n `Int'\n }\n -> `()' #}\n{# fun Fl_screen_work_area_with_n as screenWorkAreaWithN'\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int'\n }\n -> `()' #}\n{# fun Fl_screen_work_area as screenWorkArea'\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv*\n }\n -> `()' id- #}\nscreenWorkArea :: Maybe ScreenLocation -> IO Rectangle\nscreenWorkArea location =\n case location of\n (Just (Intersect (Rectangle (Position (X x_pos) (Y y_pos)) _))) ->\n screenWorkAreaWithMXMY' x_pos y_pos >>= return . toRectangle\n (Just (ScreenPosition (Position (X x_pos) (Y y_pos)))) ->\n screenWorkAreaWithMXMY' x_pos y_pos >>= return . toRectangle\n (Just (ScreenNumber n)) ->\n screenWorkAreaWithN' n >>= return . toRectangle\n Nothing ->\n screenWorkArea' >>= return . toRectangle\n\nsetColorRgb :: Color -> Word8 -> Word8 -> Word8 -> IO ()\nsetColorRgb c r g b = {#call Fl_set_color_rgb as fl_set_color_rgb #}\n (cFromColor c)\n (fromIntegral r)\n (fromIntegral g)\n (fromIntegral b)\n{# fun Fl_set_color as setColor\n { cFromColor `Color',`Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_get_color as getColor\n { cFromColor `Color' } -> `Int' #}\n{# fun Fl_get_color_rgb as getColorRgb'\n {\n cFromColor `Color',\n alloca- `CUChar' peekIntConv*,\n alloca- `CUChar' peekIntConv*,\n alloca- `CUChar' peekIntConv*\n } -> `()' supressWarningAboutRes #}\ngetColorRgb :: Color -> IO RGB\ngetColorRgb c = do\n (_,r,g,b) <- getColorRgb' c\n return (r,g,b)\n\n#if !defined(__APPLE__)\n{# fun Fl_free_color as freeColor'\n { cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_free_color_with_overlay as freeColorWithOverlay'\n { cFromColor `Color', `Int' } -> `()' supressWarningAboutRes #}\nremoveFromColormap :: Maybe Int -> Color -> IO ()\nremoveFromColormap (Just overlay) c = freeColorWithOverlay' c overlay\nremoveFromColormap Nothing c = freeColor' c\n#endif\n{# fun Fl_get_font as getFont\n { cFromFont `Font' } -> `T.Text' unsafeFromCString #}\n{# fun Fl_get_font_name_with_attributes as getFontNameWithAttributes'\n { cFromFont `Font', alloca- `Maybe FontAttribute' toAttribute* } -> `T.Text' unsafeFromCString #}\ntoAttribute :: Ptr CInt -> IO (Maybe FontAttribute)\ntoAttribute ptr =\n do\n attributeCode <- peekIntConv ptr\n return $ cToFontAttribute attributeCode\ngetFontName :: Font -> IO (T.Text, Maybe FontAttribute)\ngetFontName f = getFontNameWithAttributes' f\n{# fun Fl_get_font_sizes as getFontSizes\n { cFromFont `Font', alloca- `Int' peekIntConv* } -> `Int' #}\n{# fun Fl_set_font_by_string as setFontToString\n { cFromFont `Font', unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\n{# fun Fl_set_font_by_font as setFontToFont\n { cFromFont `Font',cFromFont `Font' } -> `()' supressWarningAboutRes #}\n{# fun Fl_set_fonts as setFonts'\n { } -> `Int' #}\n{# fun Fl_set_fonts_with_string as setFontsWithString'\n { id `Ptr CChar' } -> `Int' #}\nsetFonts :: Maybe T.Text -> IO Int\nsetFonts (Just xstarName) = withText xstarName (\\starNamePtr -> setFontsWithString' starNamePtr)\nsetFonts Nothing = setFonts'\n\n{# fun Fl_add_fd_with_when as addFdWhen'\n {\n `CInt',\n `CInt',\n id `FunPtr FDHandlerPrim'\n } -> `()' #}\n\naddFdWhen :: CInt -> [FdWhen] -> FDHandler -> IO ()\naddFdWhen fd fdWhens handler = do\n fPtr <- toFDHandlerPrim handler\n addFdWhen' fd (fromIntegral . combine $ fdWhens) fPtr\n\n{# fun Fl_add_fd as addFd'\n {\n `CInt',\n id `FunPtr FDHandlerPrim'\n } -> `()' #}\n\naddFd :: CInt -> FDHandler -> IO ()\naddFd fd handler = do\n fPtr <- toFDHandlerPrim handler\n addFd' fd fPtr\n\n{# fun Fl_remove_fd_with_when as removeFdWhen' { `CInt', `CInt'} -> `()' #}\nremoveFdWhen :: CInt -> [FdWhen] -> IO ()\nremoveFdWhen fd fdWhens =\n removeFdWhen' fd (fromIntegral . combine $ fdWhens)\n\n{# fun Fl_remove_fd as removeFd' { `CInt' } -> `()' #}\nremoveFd :: CInt -> IO ()\nremoveFd fd = removeFd' fd\n\n{# fun Fl_get_boxtype as getBoxtype'\n { cFromEnum `Boxtype' } -> `FunPtr BoxDrawFPrim' id #}\ngetBoxtype :: Boxtype -> IO BoxDrawF\ngetBoxtype bt = do\n wrappedFunPtr <- getBoxtype' bt\n let boxDrawPrim = unwrapBoxDrawFPrim wrappedFunPtr\n return $ toBoxDrawF boxDrawPrim\n\n{# fun Fl_set_boxtype as setBoxtype'\n {\n cFromEnum `Boxtype',\n id `FunPtr BoxDrawFPrim',\n `Word8',\n `Word8',\n `Word8',\n `Word8'\n } -> `()' supressWarningAboutRes #}\n{# fun Fl_set_boxtype_by_boxtype as setBoxtypeByBoxtype'\n {\n cFromEnum `Boxtype',\n cFromEnum `Boxtype'\n } -> `()' supressWarningAboutRes #}\n\ndata BoxtypeSpec = FromSpec BoxDrawF Word8 Word8 Word8 Word8\n | FromBoxtype Boxtype\nsetBoxtype :: Boxtype -> BoxtypeSpec -> IO ()\nsetBoxtype bt (FromSpec f dx dy dw dh) =\n do\n funPtr <- wrapBoxDrawFPrim (toBoxDrawFPrim f)\n setBoxtype' bt funPtr dx dy dw dh\nsetBoxtype bt (FromBoxtype template) =\n setBoxtypeByBoxtype' bt template\n\n{# fun Fl_box_dx as boxDx\n { cFromEnum `Boxtype' } -> `Int' #}\n{# fun Fl_box_dy as boxDy\n { cFromEnum `Boxtype' } -> `Int' #}\n{# fun Fl_box_dw as boxDw\n { cFromEnum `Boxtype' } -> `Int' #}\n{# fun Fl_box_dh as boxDh\n { cFromEnum `Boxtype' } -> `Int' #}\n{# fun Fl_draw_box_active as drawBoxActive\n { } -> `Bool' toBool #}\n{# fun Fl_event_shift as eventShift\n { } -> `Bool' toBool #}\n{# fun Fl_event_ctrl as eventCtrl\n { } -> `Bool' toBool #}\n{# fun Fl_event_command as eventCommand\n { } -> `Bool' toBool #}\n{# fun Fl_event_alt as eventAlt\n { } -> `Bool' toBool #}\n{# fun Fl_event_buttons as eventButtons\n { } -> `Bool' toBool #}\n{# fun Fl_event_button1 as eventButton1\n { } -> `Bool' toBool #}\n{# fun Fl_event_button2 as eventButton2\n { } -> `Bool' toBool #}\n{# fun Fl_event_button3 as eventButton3\n { } -> `Bool' toBool #}\nrelease :: IO ()\nrelease = {#call Fl_release as fl_release #}\nsetVisibleFocus :: Int -> IO ()\nsetVisibleFocus = {#call Fl_set_visible_focus as fl_set_visible_focus #} . fromIntegral\nvisibleFocus :: IO Int\nvisibleFocus = {#call Fl_visible_focus as fl_visible_focus #} >>= return . fromIntegral\nsetDndTextOps :: Bool -> IO ()\nsetDndTextOps = {#call Fl_set_dnd_text_ops as fl_set_dnd_text_ops #} . fromBool\ndndTextOps :: IO Option\ndndTextOps = {#call Fl_dnd_text_ops as fl_dnd_text_ops #} >>= return . cToEnum\ndeleteWidget :: (Parent a Widget) => Ref a -> IO ()\ndeleteWidget wptr =\n swapRef wptr $ \\ptr -> do\n {#call Fl_delete_widget as fl_delete_widget #} ptr\n return nullPtr\ndoWidgetDeletion :: IO ()\ndoWidgetDeletion = {#call Fl_do_widget_deletion as fl_do_widget_deletion #}\nwatchWidgetPointer :: (Parent a Widget) => Ref a -> IO ()\nwatchWidgetPointer wp = withRef wp {#call Fl_watch_widget_pointer as fl_Watch_widget_Pointer #}\nreleaseWidgetPointer :: (Parent a Widget) => Ref a -> IO ()\nreleaseWidgetPointer wp = withRef wp {#call Fl_release_widget_pointer as fl_release_widget_pointer #}\nclearWidgetPointer :: (Parent a Widget) => Ref a -> IO ()\nclearWidgetPointer wp = withRef wp {#call Fl_clear_widget_pointer as fl_Clear_Widget_Pointer #}\n#if FLTK_API_VERSION >= 10304\n-- | Only available on FLTK version 1.3.4 and above.\nsetBoxColor :: Color -> IO ()\nsetBoxColor c = {#call Fl_set_box_color as fl_set_box_color #} (cFromColor c)\n-- | Only available on FLTK version 1.3.4 and above.\nboxColor :: Color -> IO Color\nboxColor c = {#call Fl_box_color as fl_box_color #} (cFromColor c) >>= return . cToColor\n-- | Only available on FLTK version 1.3.4 and above.\nabiVersion :: IO Int\nabiVersion = {#call Fl_abi_version as fl_abi_version #} >>= return . fromIntegral\n-- | Only available on FLTK version 1.3.4 and above.\nabiCheck :: Int -> IO Int\nabiCheck v = {#call Fl_abi_check as fl_abi_check #} (fromIntegral v) >>= return . fromIntegral\n-- | Only available on FLTK version 1.3.4 and above.\napiVersion :: IO Int\napiVersion = {#call Fl_abi_version as fl_abi_version #} >>= return . fromIntegral\n-- | Only available on FLTK version 1.3.4 and above.\nlocalCtrl :: IO T.Text\nlocalCtrl = {#call Fl_local_ctrl as fl_local_ctrl #} >>= cStringToText\n-- | Only available on FLTK version 1.3.4 and above.\nlocalAlt :: IO T.Text\nlocalAlt = {#call Fl_local_alt as fl_local_alt #} >>= cStringToText\n-- | Only available on FLTK version 1.3.4 and above.\nlocalMeta :: IO T.Text\nlocalMeta = {#call Fl_local_meta as fl_local_meta #} >>= cStringToText\n-- | Only available on FLTK version 1.3.4 and above.\nlocalShift :: IO T.Text\nlocalShift = {#call Fl_local_shift as fl_local_shift #} >>= cStringToText\n#ifdef GLSUPPORT\n-- | Only available on FLTK version 1.3.4 and above if GL is enabled with 'stack build --flag fltkhs:opengl'\nuseHighResGL :: IO Bool\nuseHighResGL = {#call Fl_use_high_res_GL as fl_use_high_res_GL #} >>= return . cToBool\n-- | Only available on FLTK version 1.3.4 and above if GL is enabled with 'stack build --flag fltkhs:opengl'\nsetUseHighResGL :: Bool -> IO ()\nsetUseHighResGL use' = {#call Fl_set_use_high_res_GL as fl_set_use_high_res_GL #} (cFromBool use')\n#endif\n#endif\n\n\n-- | Use this function to run a GUI in GHCi.\nreplRun :: IO ()\nreplRun = do\n flush\n w <- firstWindow\n case w of\n Just w' ->\n catch (waitFor 0 >> replRun)\n (\\e -> if (e == UserInterrupt)\n then do\n allToplevelWindows [] (Just w') >>= mapM_ deleteWidget\n flush\n else throw e)\n Nothing -> return ()\n where\n allToplevelWindows :: [Ref Window] -> Maybe (Ref Window) -> IO [Ref Window]\n allToplevelWindows ws (Just w) = nextWindow w >>= allToplevelWindows (w:ws)\n allToplevelWindows ws Nothing = return ws\n","old_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n\nmodule Graphics.UI.FLTK.LowLevel.FL\n (\n Option(..),\n ClipboardContents(..),\n PasteSource(..),\n scrollbarSize,\n setScrollbarSize,\n selectionOwner,\n setSelectionOwner,\n run,\n replRun,\n check,\n ready,\n option,\n setOption,\n addAwakeHandler,\n getAwakeHandler_,\n display,\n ownColormap,\n getSystemColors,\n foreground,\n background,\n background2,\n setScheme,\n getScheme,\n reloadScheme,\n isScheme,\n setFirstWindow,\n nextWindow,\n setGrab,\n getMouse,\n eventStates,\n extract,\n extractEventStates,\n handle,\n handle_,\n belowmouse,\n setBelowmouse,\n setPushed,\n setFocus,\n setHandler,\n paste,\n toRectangle,\n fromRectangle,\n screenBounds,\n screenDPI,\n screenWorkArea,\n setColorRgb,\n toAttribute,\n release,\n setVisibleFocus,\n visibleFocus,\n setDndTextOps,\n dndTextOps,\n deleteWidget,\n doWidgetDeletion,\n watchWidgetPointer,\n releaseWidgetPointer,\n clearWidgetPointer,\n version,\n help,\n visual,\n#if !defined(__APPLE__) && defined(GLSUPPORT)\n glVisual,\n glVisualWithAlist,\n#endif\n wait,\n setWait,\n waitFor,\n readqueue,\n addTimeout,\n repeatTimeout,\n hasTimeout,\n removeTimeout,\n addCheck,\n hasCheck,\n removeCheck,\n addIdle,\n hasIdle,\n removeIdle,\n damage,\n redraw,\n flush,\n firstWindow,\n modal,\n grab,\n getKey,\n compose,\n composeReset,\n testShortcut,\n enableIm,\n disableIm,\n pushed,\n focus,\n copy,\n copyWithDestination,\n pasteWithSource,\n dnd,\n x,\n y,\n w,\n h,\n screenCount,\n setColor,\n getColor,\n getColorRgb,\n#if !defined(__APPLE__)\n removeFromColormap,\n#endif\n -- * Box\n BoxtypeSpec,\n getBoxtype,\n setBoxtype,\n boxDx,\n boxDy,\n boxDw,\n boxDh,\n drawBoxActive,\n -- * Fonts\n getFontName,\n getFont,\n getFontSizes,\n setFontByString,\n setFontByFont,\n setFonts,\n setFontsWithString,\n -- * File Descriptor Callbacks\n addFd,\n addFdWhen,\n removeFd,\n removeFdWhen,\n -- * Events\n event,\n eventShift,\n eventCtrl,\n eventCommand,\n eventAlt,\n eventButtons,\n eventButton1,\n eventButton2,\n eventButton3,\n eventX,\n eventY,\n eventXRoot,\n eventYRoot,\n eventDx,\n eventDy,\n eventClicks,\n setEventClicks,\n eventIsClick,\n setEventIsClick,\n eventButton,\n eventState,\n containsEventState,\n eventKey,\n eventOriginalKey,\n eventKeyPressed,\n eventInsideRegion,\n eventInsideWidget,\n eventDispatch,\n setEventDispatch,\n eventText,\n eventLength,\n eventClipboardContents,\n#if FLTK_API_VERSION >= 10304\n setBoxColor,\n boxColor,\n abiVersion,\n apiVersion,\n abiCheck,\n localCtrl,\n localMeta,\n localAlt,\n localShift\n#ifdef GLSUPPORT\n , useHighResGL\n , setUseHighResGL\n#endif\n#endif\n )\nwhere\n#include \"Fl_C.h\"\nimport C2HS hiding (cFromEnum, cToBool,cToEnum,cFromBool)\nimport Data.IORef\n\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Hierarchy hiding (\n setVisibleFocus,\n handle,\n redraw,\n flush,\n testShortcut,\n copy,\n setColor,\n getColor,\n focus,\n display,\n setScrollbarSize\n )\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\nimport qualified Data.Text.Foreign as TF\nimport qualified System.IO.Unsafe as Unsafe (unsafePerformIO)\nimport Control.Exception(catch, throw, AsyncException(UserInterrupt))\n#c\n enum Option {\n OptionArrowFocus = OPTION_ARROW_FOCUS,\n OptionVisibleFocus = OPTION_VISIBLE_FOCUS,\n OptionDndText = OPTION_DND_TEXT,\n OptionShowTooltips = OPTION_SHOW_TOOLTIPS,\n OptionLast = OPTION_LAST\n };\n#endc\n\n{#enum Option {} deriving (Show) #}\n\nptrToGlobalEventHandler :: IORef (FunPtr GlobalEventHandlerPrim)\nptrToGlobalEventHandler = Unsafe.unsafePerformIO $ do\n initialHandler <- toGlobalEventHandlerPrim (\\_ -> return (-1))\n newIORef initialHandler\n\n-- | Contents of the clipboard following a copy or cut. Can be either an <.\/Graphics-UI-FLTK-LowLevel-Image.html Image> or plain 'T.Text'.\ndata ClipboardContents =\n ClipboardContentsImage (Maybe (Ref Image))\n | ClipboardContentsPlainText (Maybe T.Text)\n\ndata PasteSource =\n PasteSourceSelectionBuffer\n | PasteSourceClipboardPlainText\n | PasteSourceClipboardImage\n\ntype EventDispatchPrim = (CInt ->\n Ptr () ->\n IO CInt)\nforeign import ccall \"wrapper\"\n wrapEventDispatchPrim :: EventDispatchPrim ->\n IO (FunPtr EventDispatchPrim)\nforeign import ccall \"dynamic\"\n unwrapEventDispatchPrim :: FunPtr EventDispatchPrim -> EventDispatchPrim\n\nrun :: IO Int\nrun = {#call Fl_run as fl_run #} >>= return . fromIntegral\n\ncheck :: IO Int\ncheck = {#call Fl_check as fl_check #} >>= return . fromIntegral\n\nready :: IO Int\nready = {#call Fl_ready as fl_ready #} >>= return . fromIntegral\n\n\noption :: Option -> IO Bool\noption o = {#call Fl_option as fl_option #} (cFromEnum o) >>= \\(c::CInt) -> return $ cToBool $ ((fromIntegral c) :: Int)\n\nsetOption :: Option -> Bool -> IO ()\nsetOption o t = {#call Fl_set_option as fl_set_option #} (cFromEnum o) (Graphics.UI.FLTK.LowLevel.Utils.cFromBool t)\n\nunsafeToCallbackPrim :: GlobalCallback -> FunPtr CallbackPrim\nunsafeToCallbackPrim = (Unsafe.unsafePerformIO) . toGlobalCallbackPrim\n\n{# fun Fl_add_awake_handler_ as addAwakeHandler'\n {id `FunPtr CallbackPrim', id `(Ptr ())'} -> `Int' #}\naddAwakeHandler :: GlobalCallback -> IO Int\naddAwakeHandler awakeHandler =\n do\n callbackPtr <- toGlobalCallbackPrim awakeHandler\n addAwakeHandler' callbackPtr nullPtr\n\n{# fun Fl_get_awake_handler_ as getAwakeHandler_'\n {id `Ptr (FunPtr CallbackPrim)', id `Ptr (Ptr ())'} -> `Int' #}\ngetAwakeHandler_ :: IO GlobalCallback\ngetAwakeHandler_ =\n alloca $ \\ptrToFunPtr ->\n alloca $ \\ptrToUD -> do\n _ <- getAwakeHandler_' ptrToFunPtr ptrToUD\n funPtr <- peek ptrToFunPtr\n return $ unwrapGlobalCallbackPtr $ castFunPtr funPtr\n\n{# fun Fl_version as version\n {} -> `Double' #}\n{# fun Fl_help as help\n {} -> `T.Text' unsafeFromCString #}\n\ndisplay :: T.Text -> IO ()\ndisplay text = TF.withCStringLen text $ \\(str,_) -> {#call Fl_display as fl_display #} str\n{# fun Fl_visual as visual\n {cFromEnum `Mode'} -> `Bool' cToBool #}\n#if !defined(__APPLE__) && defined(GLSUPPORT)\n-- | Only available if on a non OSX platform and if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{# fun Fl_gl_visual as glVisual\n {cFromEnum `Mode'} -> `Bool' cToBool #}\n-- | Only available if on a non OSX platform and if the 'opengl' flag is set (stack build --flag fltkhs:opengl).\n{# fun Fl_gl_visual_with_alist as glVisualWithAlist\n {cFromEnum `Mode', id `Ptr CInt'} -> `Bool' cToBool #}\n#endif\n\nownColormap :: IO ()\nownColormap = {#call Fl_own_colormap as fl_own_colormap #}\n\ngetSystemColors :: IO ()\ngetSystemColors = {#call Fl_get_system_colors as fl_get_system_colors #}\n\nforeground :: RGB -> IO ()\nforeground (r,g,b) = {#call Fl_foreground as fl_foreground #}\n (fromIntegral r)\n (fromIntegral g)\n (fromIntegral b)\nbackground :: RGB -> IO ()\nbackground (r,g,b) = {#call Fl_background as fl_background #}\n (fromIntegral r)\n (fromIntegral g)\n (fromIntegral b)\nbackground2 :: RGB -> IO ()\nbackground2 (r,g,b) = {#call Fl_background2 as fl_background2 #}\n (fromIntegral r)\n (fromIntegral g)\n (fromIntegral b)\n{# fun pure Fl_scheme as getScheme\n {} -> `T.Text' unsafeFromCString #}\nsetScheme :: T.Text -> IO Int\nsetScheme sch = TF.withCStringLen sch $ \\(str,_) -> {#call Fl_set_scheme as fl_set_scheme #} str >>= return . fromIntegral\n{# fun pure Fl_reload_scheme as reloadScheme {} -> `Int' #}\nisScheme :: T.Text -> IO Bool\nisScheme sch = TF.withCStringLen sch $ \\(str,_) -> {#call Fl_is_scheme as fl_is_scheme #} str >>= return . toBool\n{# fun Fl_wait as wait\n { } -> `Int' #}\n{# fun Fl_set_wait as waitFor\n { `Double' } -> `Double' #}\n\nsetWait :: Double -> IO Double\nsetWait = waitFor\n{# fun Fl_scrollbar_size as scrollbarSize\n { } -> `Int' #}\n{# fun Fl_set_scrollbar_size as setScrollbarSize\n { `Int' } -> `()' #}\n\n{# fun Fl_readqueue as readqueue\n { } -> `Maybe (Ref Widget)' unsafeToMaybeRef #}\n{# fun Fl_add_timeout as addTimeout\n { `Double', unsafeToCallbackPrim `GlobalCallback' } -> `()' supressWarningAboutRes #}\n{# fun Fl_repeat_timeout as repeatTimeout\n { `Double',unsafeToCallbackPrim `GlobalCallback' } -> `()' supressWarningAboutRes #}\n{# fun Fl_has_timeout as hasTimeout\n { unsafeToCallbackPrim `GlobalCallback' } -> `Int' #}\n{# fun Fl_remove_timeout as removeTimeout\n { unsafeToCallbackPrim `GlobalCallback' } -> `()' supressWarningAboutRes #}\n{# fun Fl_add_check as addCheck\n { unsafeToCallbackPrim `GlobalCallback' } -> `()' supressWarningAboutRes #}\n{# fun Fl_has_check as hasCheck\n { unsafeToCallbackPrim `GlobalCallback' } -> `Int' #}\n{# fun Fl_remove_check as removeCheck\n { unsafeToCallbackPrim `GlobalCallback' } -> `()' supressWarningAboutRes #}\n{# fun Fl_add_idle as addIdle\n { unsafeToCallbackPrim `GlobalCallback' } -> `()' supressWarningAboutRes #}\n{# fun Fl_has_idle as hasIdle\n { unsafeToCallbackPrim `GlobalCallback' } -> `Int' #}\n{# fun Fl_remove_idle as removeIdle\n { unsafeToCallbackPrim `GlobalCallback' } -> `()' supressWarningAboutRes #}\n{# fun Fl_damage as damage\n { } -> `Int' #}\n{# fun Fl_redraw as redraw\n { } -> `()' supressWarningAboutRes #}\n{# fun Fl_flush as flush\n { } -> `()' supressWarningAboutRes #}\n{# fun Fl_first_window as firstWindow\n { } -> `Maybe (Ref Window)' unsafeToMaybeRef #}\n{# fun Fl_set_first_window as setFirstWindow'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetFirstWindow :: (Parent a Window) => Ref a -> IO ()\nsetFirstWindow wp =\n withRef wp setFirstWindow'\n{# fun Fl_next_window as nextWindow'\n { id `Ptr ()' } -> `Maybe (Ref Window)' unsafeToMaybeRef #}\nnextWindow :: (Parent a Window) => Ref a -> IO (Maybe (Ref Window))\nnextWindow currWindow =\n withRef currWindow nextWindow'\n{# fun Fl_modal as modal\n { } -> `Maybe (Ref Window)' unsafeToMaybeRef #}\n{# fun Fl_grab as grab\n { } -> `Maybe (Ref Window)' unsafeToMaybeRef #}\n{# fun Fl_set_grab as setGrab'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetGrab :: (Parent a Window) => Ref a -> IO ()\nsetGrab wp = withRef wp setGrab'\n{# fun Fl_event as event\n { } -> `Event' cToEnum #}\n{# fun Fl_event_x as eventX\n { } -> `Int'#}\n{# fun Fl_event_y as eventY\n { } -> `Int'#}\n{# fun Fl_event_x_root as eventXRoot\n { } -> `Int' #}\n{# fun Fl_event_y_root as eventYRoot\n { } -> `Int' #}\n{# fun Fl_event_dx as eventDx\n { } -> `Int' #}\n{# fun Fl_event_dy as eventDy\n { } -> `Int' #}\n{# fun Fl_get_mouse as getMouse'\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv*\n } -> `()' #}\ngetMouse :: IO Position\ngetMouse = do\n (x_pos,y_pos) <- getMouse'\n return $ (Position (X x_pos) (Y y_pos))\n{# fun Fl_event_clicks as eventClicks\n { } -> `Int'#}\n{# fun Fl_set_event_clicks as setEventClicks\n { `Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_event_is_click as eventIsClick\n { } -> `Bool' toBool #}\n{# fun Fl_set_event_is_click as setEventIsClick\n { `Int' } -> `()' supressWarningAboutRes #}\n\n{# fun Fl_event_button as eventButton'\n { } -> `Int' #}\neventButton :: IO (Maybe MouseButton)\neventButton = do\n mb <- eventButton'\n case mb of\n mb' | mb' == (fromEnum Mouse_Left) -> return (Just Mouse_Left)\n mb' | mb' == (fromEnum Mouse_Middle) -> return (Just Mouse_Right)\n mb' | mb' == (fromEnum Mouse_Right) -> return (Just Mouse_Middle)\n _ -> return Nothing\n\neventStates :: [EventState]\neventStates = [\n Kb_ShiftState,\n Kb_CapsLockState,\n Kb_CtrlState,\n Kb_AltState,\n Kb_NumLockState,\n Kb_MetaState,\n Kb_ScrollLockState,\n Mouse_Button1State,\n Mouse_Button2State,\n Mouse_Button3State\n ]\nextractEventStates :: CInt -> [EventState]\nextractEventStates = extract eventStates\n\n{# fun Fl_event_state as eventState\n { } -> `[EventState]' extractEventStates #}\n{# fun Fl_contains_event_state as containsEventState\n {cFromEnum `EventState' } -> `Bool' toBool #}\n{# fun Fl_event_key as eventKey\n { } -> `KeyType' cToKeyType #}\n{# fun Fl_event_original_key as eventOriginalKey\n { } -> `KeyType' cToKeyType #}\n{# fun Fl_event_key_pressed as eventKeyPressed\n {cFromKeyType `KeyType' } -> `Bool' toBool #}\n{# fun Fl_get_key as getKey\n {cFromKeyType `KeyType' } -> `Bool' toBool #}\n{# fun Fl_event_text as eventText\n { } -> `T.Text' unsafeFromCString #}\n{# fun Fl_event_length as eventLength\n { } -> `Int' #}\n\n{# fun Fl_event_clipboard as flEventClipboard' { } -> `Ptr ()' #}\n{# fun Fl_event_clipboard_type as flEventClipboardType' { } -> `T.Text' unsafeFromCString #}\neventClipboardContents :: IO (Maybe ClipboardContents)\neventClipboardContents = do\n typeString <- flEventClipboardType'\n if (T.length typeString == 0)\n then return Nothing\n else case typeString of\n s | (T.unpack s == \"Fl::clipboard_image\") -> do\n stringContents <- flEventClipboard' >>= cStringToText . castPtr\n return (if (T.length stringContents == 0)\n then (Just (ClipboardContentsPlainText Nothing))\n else (Just (ClipboardContentsPlainText (Just stringContents))))\n s | (T.unpack s == \"Fl::clipboard_plain_text\") -> do\n imageRef <- flEventClipboard' >>= toMaybeRef\n return (Just (ClipboardContentsImage imageRef))\n _ -> error \"eventClipboardContents :: The type of the clipboard contents must be either the string \\\"Fl::clipboard_image\\\" or \\\"Fl::clipboard_plain_image\\\".\"\n\n{# fun Fl_compose as compose\n { alloca- `Int' peekIntConv* } -> `Bool' toBool #}\n{# fun Fl_compose_reset as composeReset\n { } -> `()' supressWarningAboutRes #}\n{# fun Fl_event_inside_region as eventInsideRegion'\n { `Int',`Int',`Int',`Int' } -> `Int' #}\neventInsideRegion :: Rectangle -> IO Event\neventInsideRegion (Rectangle\n (Position\n (X x_pos)\n (Y y_pos))\n (Size\n (Width width)\n (Height height))) =\n do\n eventNum <- eventInsideRegion' x_pos y_pos width height\n return $ toEnum eventNum\n{# fun Fl_event_inside_widget as eventInsideWidget'\n { id `Ptr ()' } -> `Int' #}\neventInsideWidget :: (Parent a Widget) => Ref a -> IO Event\neventInsideWidget wp =\n withRef wp (\\ptr -> do\n eventNum <- eventInsideWidget' (castPtr ptr)\n return $ toEnum eventNum)\n{# fun Fl_test_shortcut as testShortcut\n { id `FlShortcut' } -> `Bool' toBool #}\n{# fun Fl_enable_im as enableIm\n {} -> `()' supressWarningAboutRes #}\n{# fun Fl_disable_im as disableIm\n {} -> `()' supressWarningAboutRes #}\n{# fun Fl_handle as handle'\n { `Int',id `Ptr ()' } -> `Int' #}\nhandle :: (Parent a Window) => Event -> Ref a -> IO Int\nhandle e wp =\n withRef wp (handle' (cFromEnum e))\n{# fun Fl_handle_ as handle_'\n { `Int',id `Ptr ()' } -> `Int' #}\nhandle_ :: (Parent a Window) => Event -> Ref a -> IO Int\nhandle_ e wp =\n withRef wp (handle_' (cFromEnum e))\n{# fun Fl_belowmouse as belowmouse\n { } -> `Maybe (Ref Widget)' unsafeToMaybeRef #}\n{# fun Fl_set_belowmouse as setBelowmouse'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetBelowmouse :: (Parent a Widget) => Ref a -> IO ()\nsetBelowmouse wp = withRef wp setBelowmouse'\n{# fun Fl_pushed as pushed'\n { } -> `Ptr ()' #}\npushed :: IO (Maybe (Ref Widget))\npushed = pushed' >>= toMaybeRef\n{# fun Fl_set_pushed as setPushed'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetPushed :: (Parent a Widget) => Ref a -> IO ()\nsetPushed wp = withRef wp setPushed'\n{# fun Fl_focus as focus\n { } -> `Maybe (Ref Widget)' unsafeToMaybeRef #}\n{# fun Fl_set_focus as setFocus'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetFocus :: (Parent a Widget) => Ref a -> IO ()\nsetFocus wp = withRef wp setFocus'\n{# fun Fl_selection_owner as selectionOwner\n { } -> `Maybe (Ref Widget)' unsafeToMaybeRef #}\n{# fun Fl_set_selection_owner as setSelection_Owner'\n { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nsetSelectionOwner :: (Parent a Widget) => Ref a -> IO ()\nsetSelectionOwner wp = withRef wp setSelection_Owner'\n{# fun Fl_add_handler as addHandler'\n { id `FunPtr GlobalEventHandlerPrim' } -> `()' supressWarningAboutRes #}\n{# fun Fl_remove_handler as removeHandler'\n { id `FunPtr GlobalEventHandlerPrim' } -> `()' supressWarningAboutRes #}\nsetHandler :: GlobalEventHandlerF -> IO ()\nsetHandler eh = do\n newGlobalEventHandler <- toGlobalEventHandlerPrim eh\n curr <- do\n old <- readIORef ptrToGlobalEventHandler\n writeIORef ptrToGlobalEventHandler newGlobalEventHandler\n return old\n removeHandler' curr\n addHandler' newGlobalEventHandler\n\n{# fun Fl_set_event_dispatch as setEventDispatch'\n { id `Ptr (FunPtr EventDispatchPrim)' } -> `()' supressWarningAboutRes #}\n{# fun Fl_event_dispatch as eventDispatch'\n { } -> `FunPtr EventDispatchPrim' id #}\neventDispatch :: (Parent a Widget) => IO (Event -> Ref a -> IO (Int))\neventDispatch =\n do\n funPtr <- eventDispatch'\n return (\\e window ->\n withRef\n window\n (\\ptr ->\n let eventNum = fromIntegral (fromEnum e)\n fun = unwrapEventDispatchPrim funPtr\n in fun eventNum (castPtr ptr) >>=\n return . fromIntegral\n )\n )\n\nsetEventDispatch :: (Parent a Widget) => (Event -> Ref a -> IO Int) -> IO ()\nsetEventDispatch ed = do\n do\n let toPrim = (\\e ptr ->\n let eventEnum = toEnum $ fromIntegral e\n in do\n obj <- toRef ptr\n result <- ed eventEnum obj\n return $ fromIntegral result\n )\n callbackPtr <- wrapEventDispatchPrim toPrim\n ptrToCallbackPtr <- new callbackPtr\n poke ptrToCallbackPtr callbackPtr\n setEventDispatch' ptrToCallbackPtr\n{# fun Fl_copy as copy\n { unsafeToCString `T.Text',`Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_copy_with_destination as copyWithDestination\n { unsafeToCString `T.Text',`Int',`Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_paste_with_source as pasteWithSource\n { id `Ptr ()',`Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_paste_with_source_type as pasteWithSourceType\n { id `Ptr ()',`Int', unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\npaste :: (Parent a Widget) => Ref a -> PasteSource -> IO ()\npaste widget PasteSourceSelectionBuffer = withRef widget (\\widgetPtr -> pasteWithSource widgetPtr 0)\npaste widget PasteSourceClipboardPlainText =\n withRef widget (\\widgetPtr -> pasteWithSourceType widgetPtr 1 (T.pack \"Fl::clipboard_plain_text\"))\npaste widget PasteSourceClipboardImage =\n withRef widget (\\widgetPtr -> pasteWithSourceType widgetPtr 1 (T.pack \"Fl::clipboard_image\"))\n\n{# fun Fl_dnd as dnd\n { } -> `Int' #}\n{# fun Fl_x as x\n { } -> `Int' #}\n{# fun Fl_y as y\n { } -> `Int' #}\n{# fun Fl_w as w\n { } -> `Int' #}\n{# fun Fl_h as h\n { } -> `Int' #}\n{# fun Fl_screen_count as screenCount\n { } -> `Int' #}\n\n{# fun Fl_screen_xywh as screenXYWH\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv*\n } -> `()' #}\n\n{# fun Fl_screen_xywh_with_mxmy as screenXYWYWithMXMY\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int',\n `Int'\n } -> `()' #}\n\n{# fun Fl_screen_xywh_with_n as screenXYWNWithN\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int'\n } -> `()' #}\n\n{# fun Fl_screen_xywh_with_mxmymwmh as screenXYWHWithNMXMYMWMH\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int',\n `Int',\n `Int',\n `Int'\n } -> `()' #}\n\nscreenBounds :: Maybe ScreenLocation -> IO Rectangle\nscreenBounds location =\n case location of\n (Just (Intersect (Rectangle (Position (X x_pos) (Y y_pos)) (Size (Width width) (Height height))))) ->\n screenXYWHWithNMXMYMWMH x_pos y_pos width height >>= return . toRectangle\n (Just (ScreenPosition (Position (X x_pos) (Y y_pos)))) ->\n screenXYWYWithMXMY x_pos y_pos >>= return . toRectangle\n (Just (ScreenNumber n)) ->\n screenXYWNWithN n >>= return . toRectangle\n Nothing ->\n screenXYWH >>= return . toRectangle\n\n{# fun Fl_screen_dpi as screenDpi'\n { alloca- `Float' peekFloatConv*,\n alloca- `Float' peekFloatConv* }\n -> `()' #}\n{# fun Fl_screen_dpi_with_n as screenDpiWithN'\n { alloca- `Float' peekFloatConv*,\n alloca- `Float' peekFloatConv*,\n `Int' }\n -> `()' #}\n\nscreenDPI :: Maybe Int -> IO DPI\nscreenDPI (Just n) = do\n (dpiX, dpiY) <- screenDpiWithN' n\n return $ DPI dpiX dpiY\nscreenDPI Nothing = do\n (dpiX, dpiY) <- screenDpi'\n return $ DPI dpiX dpiY\n\n{# fun Fl_screen_work_area_with_mx_my as screenWorkAreaWithMXMY'\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int',\n `Int'\n }\n -> `()' #}\n{# fun Fl_screen_work_area_with_n as screenWorkAreaWithN'\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n `Int'\n }\n -> `()' #}\n{# fun Fl_screen_work_area as screenWorkArea'\n {\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv* ,\n alloca- `Int' peekIntConv*\n }\n -> `()' id- #}\nscreenWorkArea :: Maybe ScreenLocation -> IO Rectangle\nscreenWorkArea location =\n case location of\n (Just (Intersect (Rectangle (Position (X x_pos) (Y y_pos)) _))) ->\n screenWorkAreaWithMXMY' x_pos y_pos >>= return . toRectangle\n (Just (ScreenPosition (Position (X x_pos) (Y y_pos)))) ->\n screenWorkAreaWithMXMY' x_pos y_pos >>= return . toRectangle\n (Just (ScreenNumber n)) ->\n screenWorkAreaWithN' n >>= return . toRectangle\n Nothing ->\n screenWorkArea' >>= return . toRectangle\n\nsetColorRgb :: Color -> Word8 -> Word8 -> Word8 -> IO ()\nsetColorRgb c r g b = {#call Fl_set_color_rgb as fl_set_color_rgb #}\n (cFromColor c)\n (fromIntegral r)\n (fromIntegral g)\n (fromIntegral b)\n{# fun Fl_set_color as setColor\n { cFromColor `Color',`Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_get_color as getColor\n { cFromColor `Color' } -> `Int' #}\n{# fun Fl_get_color_rgb as getColorRgb'\n {\n cFromColor `Color',\n alloca- `CUChar' peekIntConv*,\n alloca- `CUChar' peekIntConv*,\n alloca- `CUChar' peekIntConv*\n } -> `()' supressWarningAboutRes #}\ngetColorRgb :: Color -> IO RGB\ngetColorRgb c = do\n (_,r,g,b) <- getColorRgb' c\n return (r,g,b)\n\n#if !defined(__APPLE__)\n{# fun Fl_free_color as freeColor'\n { cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_free_color_with_overlay as freeColorWithOverlay'\n { cFromColor `Color', `Int' } -> `()' supressWarningAboutRes #}\nremoveFromColormap :: Maybe Int -> Color -> IO ()\nremoveFromColormap (Just overlay) c = freeColorWithOverlay' c overlay\nremoveFromColormap Nothing c = freeColor' c\n#endif\n{# fun Fl_get_font as getFont\n { cFromFont `Font' } -> `T.Text' unsafeFromCString #}\n{# fun Fl_get_font_name_with_attributes as getFontNameWithAttributes'\n { cFromFont `Font', alloca- `Maybe FontAttribute' toAttribute* } -> `T.Text' unsafeFromCString #}\ntoAttribute :: Ptr CInt -> IO (Maybe FontAttribute)\ntoAttribute ptr =\n do\n attributeCode <- peekIntConv ptr\n return $ cToFontAttribute attributeCode\ngetFontName :: Font -> IO (T.Text, Maybe FontAttribute)\ngetFontName f = getFontNameWithAttributes' f\n{# fun Fl_get_font_sizes as getFontSizes\n { cFromFont `Font', alloca- `Int' peekIntConv* } -> `Int' #}\n{# fun Fl_set_font_by_string as setFontByString\n { cFromFont `Font', unsafeToCString `T.Text' } -> `()' supressWarningAboutRes #}\n{# fun Fl_set_font_by_font as setFontByFont\n { cFromFont `Font',cFromFont `Font' } -> `()' supressWarningAboutRes #}\n{# fun Fl_set_fonts as setFonts\n { } -> `Font' cToFont #}\n{# fun Fl_set_fonts_with_string as setFontsWithString\n { unsafeToCString `T.Text' } -> `Font' cToFont #}\n\n{# fun Fl_add_fd_with_when as addFdWhen'\n {\n `CInt',\n `CInt',\n id `FunPtr FDHandlerPrim'\n } -> `()' #}\n\naddFdWhen :: CInt -> [FdWhen] -> FDHandler -> IO ()\naddFdWhen fd fdWhens handler = do\n fPtr <- toFDHandlerPrim handler\n addFdWhen' fd (fromIntegral . combine $ fdWhens) fPtr\n\n{# fun Fl_add_fd as addFd'\n {\n `CInt',\n id `FunPtr FDHandlerPrim'\n } -> `()' #}\n\naddFd :: CInt -> FDHandler -> IO ()\naddFd fd handler = do\n fPtr <- toFDHandlerPrim handler\n addFd' fd fPtr\n\n{# fun Fl_remove_fd_with_when as removeFdWhen' { `CInt', `CInt'} -> `()' #}\nremoveFdWhen :: CInt -> [FdWhen] -> IO ()\nremoveFdWhen fd fdWhens =\n removeFdWhen' fd (fromIntegral . combine $ fdWhens)\n\n{# fun Fl_remove_fd as removeFd' { `CInt' } -> `()' #}\nremoveFd :: CInt -> IO ()\nremoveFd fd = removeFd' fd\n\n{# fun Fl_get_boxtype as getBoxtype'\n { cFromEnum `Boxtype' } -> `FunPtr BoxDrawFPrim' id #}\ngetBoxtype :: Boxtype -> IO BoxDrawF\ngetBoxtype bt = do\n wrappedFunPtr <- getBoxtype' bt\n let boxDrawPrim = unwrapBoxDrawFPrim wrappedFunPtr\n return $ toBoxDrawF boxDrawPrim\n\n{# fun Fl_set_boxtype as setBoxtype'\n {\n cFromEnum `Boxtype',\n id `FunPtr BoxDrawFPrim',\n `Word8',\n `Word8',\n `Word8',\n `Word8'\n } -> `()' supressWarningAboutRes #}\n{# fun Fl_set_boxtype_by_boxtype as setBoxtypeByBoxtype'\n {\n cFromEnum `Boxtype',\n cFromEnum `Boxtype'\n } -> `()' supressWarningAboutRes #}\n\ndata BoxtypeSpec = FromSpec BoxDrawF Word8 Word8 Word8 Word8\n | FromBoxtype Boxtype\nsetBoxtype :: Boxtype -> BoxtypeSpec -> IO ()\nsetBoxtype bt (FromSpec f dx dy dw dh) =\n do\n funPtr <- wrapBoxDrawFPrim (toBoxDrawFPrim f)\n setBoxtype' bt funPtr dx dy dw dh\nsetBoxtype bt (FromBoxtype template) =\n setBoxtypeByBoxtype' bt template\n\n{# fun Fl_box_dx as boxDx\n { cFromEnum `Boxtype' } -> `Int' #}\n{# fun Fl_box_dy as boxDy\n { cFromEnum `Boxtype' } -> `Int' #}\n{# fun Fl_box_dw as boxDw\n { cFromEnum `Boxtype' } -> `Int' #}\n{# fun Fl_box_dh as boxDh\n { cFromEnum `Boxtype' } -> `Int' #}\n{# fun Fl_draw_box_active as drawBoxActive\n { } -> `Bool' toBool #}\n{# fun Fl_event_shift as eventShift\n { } -> `Bool' toBool #}\n{# fun Fl_event_ctrl as eventCtrl\n { } -> `Bool' toBool #}\n{# fun Fl_event_command as eventCommand\n { } -> `Bool' toBool #}\n{# fun Fl_event_alt as eventAlt\n { } -> `Bool' toBool #}\n{# fun Fl_event_buttons as eventButtons\n { } -> `Bool' toBool #}\n{# fun Fl_event_button1 as eventButton1\n { } -> `Bool' toBool #}\n{# fun Fl_event_button2 as eventButton2\n { } -> `Bool' toBool #}\n{# fun Fl_event_button3 as eventButton3\n { } -> `Bool' toBool #}\nrelease :: IO ()\nrelease = {#call Fl_release as fl_release #}\nsetVisibleFocus :: Int -> IO ()\nsetVisibleFocus = {#call Fl_set_visible_focus as fl_set_visible_focus #} . fromIntegral\nvisibleFocus :: IO Int\nvisibleFocus = {#call Fl_visible_focus as fl_visible_focus #} >>= return . fromIntegral\nsetDndTextOps :: Bool -> IO ()\nsetDndTextOps = {#call Fl_set_dnd_text_ops as fl_set_dnd_text_ops #} . fromBool\ndndTextOps :: IO Option\ndndTextOps = {#call Fl_dnd_text_ops as fl_dnd_text_ops #} >>= return . cToEnum\ndeleteWidget :: (Parent a Widget) => Ref a -> IO ()\ndeleteWidget wptr =\n swapRef wptr $ \\ptr -> do\n {#call Fl_delete_widget as fl_delete_widget #} ptr\n return nullPtr\ndoWidgetDeletion :: IO ()\ndoWidgetDeletion = {#call Fl_do_widget_deletion as fl_do_widget_deletion #}\nwatchWidgetPointer :: (Parent a Widget) => Ref a -> IO ()\nwatchWidgetPointer wp = withRef wp {#call Fl_watch_widget_pointer as fl_Watch_widget_Pointer #}\nreleaseWidgetPointer :: (Parent a Widget) => Ref a -> IO ()\nreleaseWidgetPointer wp = withRef wp {#call Fl_release_widget_pointer as fl_release_widget_pointer #}\nclearWidgetPointer :: (Parent a Widget) => Ref a -> IO ()\nclearWidgetPointer wp = withRef wp {#call Fl_clear_widget_pointer as fl_Clear_Widget_Pointer #}\n#if FLTK_API_VERSION >= 10304\n-- | Only available on FLTK version 1.3.4 and above.\nsetBoxColor :: Color -> IO ()\nsetBoxColor c = {#call Fl_set_box_color as fl_set_box_color #} (cFromColor c)\n-- | Only available on FLTK version 1.3.4 and above.\nboxColor :: Color -> IO Color\nboxColor c = {#call Fl_box_color as fl_box_color #} (cFromColor c) >>= return . cToColor\n-- | Only available on FLTK version 1.3.4 and above.\nabiVersion :: IO Int\nabiVersion = {#call Fl_abi_version as fl_abi_version #} >>= return . fromIntegral\n-- | Only available on FLTK version 1.3.4 and above.\nabiCheck :: Int -> IO Int\nabiCheck v = {#call Fl_abi_check as fl_abi_check #} (fromIntegral v) >>= return . fromIntegral\n-- | Only available on FLTK version 1.3.4 and above.\napiVersion :: IO Int\napiVersion = {#call Fl_abi_version as fl_abi_version #} >>= return . fromIntegral\n-- | Only available on FLTK version 1.3.4 and above.\nlocalCtrl :: IO T.Text\nlocalCtrl = {#call Fl_local_ctrl as fl_local_ctrl #} >>= cStringToText\n-- | Only available on FLTK version 1.3.4 and above.\nlocalAlt :: IO T.Text\nlocalAlt = {#call Fl_local_alt as fl_local_alt #} >>= cStringToText\n-- | Only available on FLTK version 1.3.4 and above.\nlocalMeta :: IO T.Text\nlocalMeta = {#call Fl_local_meta as fl_local_meta #} >>= cStringToText\n-- | Only available on FLTK version 1.3.4 and above.\nlocalShift :: IO T.Text\nlocalShift = {#call Fl_local_shift as fl_local_shift #} >>= cStringToText\n#ifdef GLSUPPORT\n-- | Only available on FLTK version 1.3.4 and above if GL is enabled with 'stack build --flag fltkhs:opengl'\nuseHighResGL :: IO Bool\nuseHighResGL = {#call Fl_use_high_res_GL as fl_use_high_res_GL #} >>= return . cToBool\n-- | Only available on FLTK version 1.3.4 and above if GL is enabled with 'stack build --flag fltkhs:opengl'\nsetUseHighResGL :: Bool -> IO ()\nsetUseHighResGL use' = {#call Fl_set_use_high_res_GL as fl_set_use_high_res_GL #} (cFromBool use')\n#endif\n#endif\n\n\n-- | Use this function to run a GUI in GHCi.\nreplRun :: IO ()\nreplRun = do\n flush\n w <- firstWindow\n case w of\n Just w' ->\n catch (waitFor 0 >> replRun)\n (\\e -> if (e == UserInterrupt)\n then do\n allToplevelWindows [] (Just w') >>= mapM_ deleteWidget\n flush\n else throw e)\n Nothing -> return ()\n where\n allToplevelWindows :: [Ref Window] -> Maybe (Ref Window) -> IO [Ref Window]\n allToplevelWindows ws (Just w) = nextWindow w >>= allToplevelWindows (w:ws)\n allToplevelWindows ws Nothing = return ws\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"}
{"commit":"1b9c8133a04a32caf769cc61f26943d38f13f038","subject":"Stub out the knot tying function","message":"Stub out the knot tying function\n","repos":"wangxiayang\/llvm-analysis,travitch\/llvm-analysis,wangxiayang\/llvm-analysis,travitch\/llvm-analysis","old_file":"src\/Data\/LLVM\/Private\/Unmarshal.chs","new_file":"src\/Data\/LLVM\/Private\/Unmarshal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, RankNTypes #-}\nmodule Data.LLVM.Private.Unmarshal where\n\n#include \"c++\/marshal.h\"\n\nimport Control.Applicative\nimport Control.Monad.State\nimport Data.Array.Storable\nimport Data.HashMap.Strict ( HashMap )\nimport qualified Data.HashMap.Strict as M\nimport Foreign.C\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Data.LLVM.Private.C2HS\n\n{#enum CmpPredicate {underscoreToCase} deriving (Show, Eq) #}\n{#enum CallingConvention {} deriving (Show, Eq) #}\n{#enum TypeTag {} deriving (Show, Eq) #}\n{#enum ValueTag {underscoreToCase} deriving (Show, Eq) #}\n{#enum LinkageType {} deriving (Show, Eq) #}\n{#enum VisibilityType {} deriving (Show, Eq) #}\n\ndata CModule\n{#pointer *CModule as ModulePtr -> CModule #}\n\ncModuleIdentifier :: ModulePtr -> IO String\ncModuleIdentifier m = ({#get CModule->moduleIdentifier#} m) >>= peekCString\n\ncModuleDataLayout :: ModulePtr -> IO String\ncModuleDataLayout m = ({#get CModule->moduleDataLayout#} m) >>= peekCString\n\ncModuleTargetTriple :: ModulePtr -> IO String\ncModuleTargetTriple m = ({#get CModule->targetTriple#} m) >>= peekCString\n\ncModuleInlineAsm :: ModulePtr -> IO String\ncModuleInlineAsm m = ({#get CModule->moduleInlineAsm#} m) >>= peekCString\n\ncModuleHasError :: ModulePtr -> IO Bool\ncModuleHasError m = cToBool <$> ({#get CModule->hasError#} m)\n\ncModuleErrorMessage :: ModulePtr -> IO String\ncModuleErrorMessage m = ({#get CModule->errMsg#} m) >>= peekCString\n\ncModuleLittleEndian :: ModulePtr -> IO Bool\ncModuleLittleEndian m = cToBool <$> ({#get CModule->littleEndian#} m)\n\ncModulePointerSize :: ModulePtr -> IO Int\ncModulePointerSize m = cIntConv <$> ({#get CModule->pointerSize#} m)\n\ncModuleGlobalVariables :: ModulePtr -> IO (StorableArray Int ValuePtr)\ncModuleGlobalVariables m =\n peekArray m {#get CModule->globalVariables#} {#get CModule->numGlobalVariables#}\n\ncModuleGlobalAliases :: ModulePtr -> IO (StorableArray Int ValuePtr)\ncModuleGlobalAliases m =\n peekArray m ({#get CModule->globalAliases#}) ({#get CModule->numGlobalAliases#})\n\ncModuleFunctions :: ModulePtr -> IO (StorableArray Int ValuePtr)\ncModuleFunctions m =\n peekArray m ({#get CModule->functions#}) ({#get CModule->numFunctions#})\n\npeekArray :: forall a b c i e . (Ix i, Integral i, Integral c) =>\n a -> (a -> IO (Ptr b)) -> (a -> IO c) -> IO (StorableArray i e)\npeekArray obj arrAccessor sizeAccessor = do\n nElts <- sizeAccessor obj\n arrPtr <- arrAccessor obj\n fArrPtr <- newForeignPtr_ (castPtr arrPtr)\n unsafeForeignPtrToStorableArray fArrPtr (1, cIntConv nElts)\n\ndata CType = CType TypeTag Int Bool Bool (Ptr TypePtr) Int TypePtr String\n{#pointer *CType as TypePtr -> CType #}\n\ndata CValue = CValue ValueTag TypePtr String (Ptr ()) (Ptr ())\n{#pointer *CValue as ValuePtr -> CValue #}\n\n{#fun marshalLLVM { `String' } -> `ModulePtr' id #}\n{#fun disposeCModule { id `ModulePtr' } -> `()' #}\n\ndata KnotState = KnotState { valueMap :: HashMap Int Int }\n\ntranslate bitcodefile = do\n m <- marshalLLVM bitcodefile\n\n let initialState = KnotState { valueMap = M.empty }\n (ir, finalState) <- evalStateT (mfix (tieKnot m)) initialState\n\n disposeCModule m\n return ir\n\ntieKnot m (_, finalState) = return (undefined, finalState)","old_contents":"{-# LANGUAGE ForeignFunctionInterface, RankNTypes #-}\nmodule Data.LLVM.Private.Unmarshal where\n\n#include \"c++\/marshal.h\"\n\nimport Control.Applicative\nimport Data.Array.Storable\nimport Foreign.C\nimport Foreign.C.String\nimport Foreign.C.Types\nimport Foreign.ForeignPtr\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Data.LLVM.Private.C2HS\n\n{#enum CmpPredicate {underscoreToCase} deriving (Show, Eq) #}\n{#enum CallingConvention {} deriving (Show, Eq) #}\n{#enum TypeTag {} deriving (Show, Eq) #}\n{#enum ValueTag {underscoreToCase} deriving (Show, Eq) #}\n{#enum LinkageType {} deriving (Show, Eq) #}\n{#enum VisibilityType {} deriving (Show, Eq) #}\n\ndata CModule\n{#pointer *CModule as ModulePtr -> CModule #}\n\ncModuleIdentifier :: ModulePtr -> IO String\ncModuleIdentifier m = ({#get CModule->moduleIdentifier#} m) >>= peekCString\n\ncModuleDataLayout :: ModulePtr -> IO String\ncModuleDataLayout m = ({#get CModule->moduleDataLayout#} m) >>= peekCString\n\ncModuleTargetTriple :: ModulePtr -> IO String\ncModuleTargetTriple m = ({#get CModule->targetTriple#} m) >>= peekCString\n\ncModuleInlineAsm :: ModulePtr -> IO String\ncModuleInlineAsm m = ({#get CModule->moduleInlineAsm#} m) >>= peekCString\n\ncModuleHasError :: ModulePtr -> IO Bool\ncModuleHasError m = cToBool <$> ({#get CModule->hasError#} m)\n\ncModuleErrorMessage :: ModulePtr -> IO String\ncModuleErrorMessage m = ({#get CModule->errMsg#} m) >>= peekCString\n\ncModuleLittleEndian :: ModulePtr -> IO Bool\ncModuleLittleEndian m = cToBool <$> ({#get CModule->littleEndian#} m)\n\ncModulePointerSize :: ModulePtr -> IO Int\ncModulePointerSize m = cIntConv <$> ({#get CModule->pointerSize#} m)\n\ncModuleGlobalVariables :: ModulePtr -> IO (StorableArray Int ValuePtr)\ncModuleGlobalVariables m =\n peekArray m {#get CModule->globalVariables#} {#get CModule->numGlobalVariables#}\n\ncModuleGlobalAliases :: ModulePtr -> IO (StorableArray Int ValuePtr)\ncModuleGlobalAliases m =\n peekArray m ({#get CModule->globalAliases#}) ({#get CModule->numGlobalAliases#})\n\ncModuleFunctions :: ModulePtr -> IO (StorableArray Int ValuePtr)\ncModuleFunctions m =\n peekArray m ({#get CModule->functions#}) ({#get CModule->numFunctions#})\n\npeekArray :: forall a b c i e . (Ix i, Integral i, Integral c) =>\n a -> (a -> IO (Ptr b)) -> (a -> IO c) -> IO (StorableArray i e)\npeekArray obj arrAccessor sizeAccessor = do\n nElts <- sizeAccessor obj\n arrPtr <- arrAccessor obj\n fArrPtr <- newForeignPtr_ (castPtr arrPtr)\n unsafeForeignPtrToStorableArray fArrPtr (1, cIntConv nElts)\n\ndata CType = CType TypeTag Int Bool Bool (Ptr TypePtr) Int TypePtr String\n{#pointer *CType as TypePtr -> CType #}\n\ndata CValue = CValue ValueTag TypePtr String (Ptr ()) (Ptr ())\n{#pointer *CValue as ValuePtr -> CValue #}\n\n{#fun marshalLLVM { `String' } -> `ModulePtr' id #}\n{#fun disposeCModule { id `ModulePtr' } -> `()' #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"9ca62b3ef4c638da032effaa584d5bdbd0aa76b2","subject":"improve error messages for \"not found\"","message":"improve error messages for \"not found\"\n\nIgnore-this: 4e801d782c33634cde834611ff76e716\n\ndarcs-hash:20101025222612-dcabc-9baef97eab33e0da4bc9f6270f139f07248c1a82.gz\n","repos":"phaazon\/cuda,mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Module.chs","new_file":"Foreign\/CUDA\/Driver\/Module.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : (c) [2009..2010] Trevor L. McDonell\n-- License : BSD\n--\n-- Module management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Module\n (\n Module,\n JITOption(..), JITTarget(..), JITResult(..),\n getFun, getPtr, getTex,\n loadFile, loadData, loadDataEx, unload\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Ptr\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Exec\nimport Foreign.CUDA.Driver.Marshal (peekDeviceHandle)\nimport Foreign.CUDA.Driver.Texture\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Unsafe.Coerce\n\nimport Control.Monad (liftM)\nimport Control.Exception.Extensible (throwIO)\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as B\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A reference to a Module object, containing collections of device functions\n--\nnewtype Module = Module { useModule :: {# type CUmodule #}}\n\n\n-- |\n-- Just-in-time compilation options\n--\ndata JITOption\n = MaxRegisters Int -- ^ maximum number of registers per thread\n | ThreadsPerBlock Int -- ^ number of threads per block to target for\n | OptimisationLevel Int -- ^ level of optimisation to apply (1-4, default 4)\n | Target JITTarget -- ^ compilation target, otherwise determined from context\n-- | FallbackStrategy JITFallback\n deriving (Show)\n\n-- |\n-- Results of online compilation\n--\ndata JITResult = JITResult\n {\n jitTime :: Float, -- ^ milliseconds spent compiling PTX\n jitInfoLog :: ByteString, -- ^ information about PTX asembly\n jitErrorLog :: ByteString -- ^ compilation errors\n }\n deriving (Show)\n\n\n{# enum CUjit_option as JITOptionInternal\n { }\n with prefix=\"CU\" deriving (Eq, Show) #}\n\n{# enum CUjit_target as JITTarget\n { underscoreToCase }\n with prefix=\"CU_TARGET\" deriving (Eq, Show) #}\n\n{# enum CUjit_fallback as JITFallback\n { underscoreToCase }\n with prefix=\"CU_PREFER\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Module management\n--------------------------------------------------------------------------------\n\n-- |\n-- Returns a function handle\n--\ngetFun :: Module -> String -> IO Fun\ngetFun mdl fn = resultIfFound \"function\" fn =<< cuModuleGetFunction mdl fn\n\n{# fun unsafe cuModuleGetFunction\n { alloca- `Fun' peekFun*\n , useModule `Module'\n , withCString* `String' } -> `Status' cToEnum #}\n where peekFun = liftM Fun . peek\n\n\n-- |\n-- Return a global pointer, and size of the global (in bytes)\n--\ngetPtr :: Module -> String -> IO (DevicePtr a, Int)\ngetPtr mdl name = do\n (status,dptr,bytes) <- cuModuleGetGlobal mdl name\n resultIfFound \"global\" name (status,(dptr,bytes))\n\n{# fun unsafe cuModuleGetGlobal\n { alloca- `DevicePtr a' peekDeviceHandle*\n , alloca- `Int' peekIntConv*\n , useModule `Module'\n , withCString* `String' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return a handle to a texture reference\n--\ngetTex :: Module -> String -> IO Texture\ngetTex mdl name = resultIfFound \"texture\" name =<< cuModuleGetTexRef mdl name\n\n{# fun unsafe cuModuleGetTexRef\n { alloca- `Texture' peekTex*\n , useModule `Module'\n , withCString* `String' } -> `Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the specified file (either a ptx or cubin file) to\n-- create a new module, and load that module into the current context\n--\nloadFile :: FilePath -> IO Module\nloadFile ptx = resultIfOk =<< cuModuleLoad ptx\n\n{# fun unsafe cuModuleLoad\n { alloca- `Module' peekMod*\n , withCString* `FilePath' } -> `Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a new module, and load that module\n-- into the current context. The image (typically) is the contents of a cubin or\n-- ptx file as a NULL-terminated string.\n--\nloadData :: ByteString -> IO Module\nloadData img = resultIfOk =<< cuModuleLoadData img\n\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , useByteString* `ByteString' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load a module with online compiler options. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\nloadDataEx :: ByteString -> [JITOption] -> IO (Module, JITResult)\nloadDataEx img options =\n allocaArray logSize $ \\p_ilog ->\n allocaArray logSize $ \\p_elog ->\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first\n , (JIT_INFO_LOG_BUFFER_SIZE_BYTES, logSize)\n , (JIT_ERROR_LOG_BUFFER_SIZE_BYTES, logSize)\n , (JIT_INFO_LOG_BUFFER, unsafeCoerce (p_ilog :: CString))\n , (JIT_ERROR_LOG_BUFFER, unsafeCoerce (p_elog :: CString)) ] ++ map unpack options in\n\n withArray (map cFromEnum opt) $ \\p_opts ->\n withArray (map unsafeCoerce val) $ \\p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img (length opt) p_opts p_vals\n infoLog <- B.packCString p_ilog\n errLog <- B.packCString p_elog\n time <- peek (castPtr p_vals)\n resultIfOk (s, (mdl, JITResult time infoLog errLog))\n\n where\n logSize = 2048\n\n unpack (MaxRegisters x) = (JIT_MAX_REGISTERS, x)\n unpack (ThreadsPerBlock x) = (JIT_THREADS_PER_BLOCK, x)\n unpack (OptimisationLevel x) = (JIT_OPTIMIZATION_LEVEL, x)\n unpack (Target x) = (JIT_TARGET, fromEnum x)\n\n\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , useByteString* `ByteString'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context\n--\nunload :: Module -> IO ()\nunload m = nothingIfOk =<< cuModuleUnload m\n\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\nresultIfFound :: String -> String -> (Status, a) -> IO a\nresultIfFound kind name (status,result) =\n case status of\n Success -> return result\n NotFound -> cudaError (kind ++ ' ' : describe status ++ \": \" ++ name)\n _ -> throwIO (ExitCode status)\n\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\nuseByteString :: ByteString -> (Ptr a -> IO b) -> IO b\nuseByteString bs act = B.useAsCString bs $ \\p -> act (castPtr p)\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Module\n-- Copyright : (c) [2009..2010] Trevor L. McDonell\n-- License : BSD\n--\n-- Module management for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Module\n (\n Module,\n JITOption(..), JITTarget(..), JITResult(..),\n getFun, getPtr, getTex,\n loadFile, loadData, loadDataEx, unload\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Ptr\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Exec\nimport Foreign.CUDA.Driver.Marshal (peekDeviceHandle)\nimport Foreign.CUDA.Driver.Texture\nimport Foreign.CUDA.Internal.C2HS\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Unsafe.Coerce\n\nimport Control.Monad (liftM)\nimport Data.ByteString.Char8 (ByteString)\nimport qualified Data.ByteString.Char8 as B\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A reference to a Module object, containing collections of device functions\n--\nnewtype Module = Module { useModule :: {# type CUmodule #}}\n\n\n-- |\n-- Just-in-time compilation options\n--\ndata JITOption\n = MaxRegisters Int -- ^ maximum number of registers per thread\n | ThreadsPerBlock Int -- ^ number of threads per block to target for\n | OptimisationLevel Int -- ^ level of optimisation to apply (1-4, default 4)\n | Target JITTarget -- ^ compilation target, otherwise determined from context\n-- | FallbackStrategy JITFallback\n deriving (Show)\n\n-- |\n-- Results of online compilation\n--\ndata JITResult = JITResult\n {\n jitTime :: Float, -- ^ milliseconds spent compiling PTX\n jitInfoLog :: ByteString, -- ^ information about PTX asembly\n jitErrorLog :: ByteString -- ^ compilation errors\n }\n deriving (Show)\n\n\n{# enum CUjit_option as JITOptionInternal\n { }\n with prefix=\"CU\" deriving (Eq, Show) #}\n\n{# enum CUjit_target as JITTarget\n { underscoreToCase }\n with prefix=\"CU_TARGET\" deriving (Eq, Show) #}\n\n{# enum CUjit_fallback as JITFallback\n { underscoreToCase }\n with prefix=\"CU_PREFER\" deriving (Eq, Show) #}\n\n\n--------------------------------------------------------------------------------\n-- Module management\n--------------------------------------------------------------------------------\n\n-- |\n-- Returns a function handle\n--\ngetFun :: Module -> String -> IO Fun\ngetFun mdl fn = resultIfOk =<< cuModuleGetFunction mdl fn\n\n{# fun unsafe cuModuleGetFunction\n { alloca- `Fun' peekFun*\n , useModule `Module'\n , withCString* `String' } -> `Status' cToEnum #}\n where peekFun = liftM Fun . peek\n\n\n-- |\n-- Return a global pointer, and size of the global (in bytes)\n--\ngetPtr :: Module -> String -> IO (DevicePtr a, Int)\ngetPtr mdl name = do\n (status,dptr,bytes) <- cuModuleGetGlobal mdl name\n resultIfOk (status,(dptr,bytes))\n\n{# fun unsafe cuModuleGetGlobal\n { alloca- `DevicePtr a' peekDeviceHandle*\n , alloca- `Int' peekIntConv*\n , useModule `Module'\n , withCString* `String' } -> `Status' cToEnum #}\n\n\n-- |\n-- Return a handle to a texture reference\n--\ngetTex :: Module -> String -> IO Texture\ngetTex mdl name = resultIfOk =<< cuModuleGetTexRef mdl name\n\n{# fun unsafe cuModuleGetTexRef\n { alloca- `Texture' peekTex*\n , useModule `Module'\n , withCString* `String' } -> `Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the specified file (either a ptx or cubin file) to\n-- create a new module, and load that module into the current context\n--\nloadFile :: FilePath -> IO Module\nloadFile ptx = resultIfOk =<< cuModuleLoad ptx\n\n{# fun unsafe cuModuleLoad\n { alloca- `Module' peekMod*\n , withCString* `FilePath' } -> `Status' cToEnum #}\n\n\n-- |\n-- Load the contents of the given image into a new module, and load that module\n-- into the current context. The image (typically) is the contents of a cubin or\n-- ptx file as a NULL-terminated string.\n--\nloadData :: ByteString -> IO Module\nloadData img = resultIfOk =<< cuModuleLoadData img\n\n{# fun unsafe cuModuleLoadData\n { alloca- `Module' peekMod*\n , useByteString* `ByteString' } -> ` Status' cToEnum #}\n\n\n-- |\n-- Load a module with online compiler options. The actual attributes of the\n-- compiled kernel can be probed using 'requires'.\n--\nloadDataEx :: ByteString -> [JITOption] -> IO (Module, JITResult)\nloadDataEx img options =\n allocaArray logSize $ \\p_ilog ->\n allocaArray logSize $ \\p_elog ->\n let (opt,val) = unzip $\n [ (JIT_WALL_TIME, 0) -- must be first\n , (JIT_INFO_LOG_BUFFER_SIZE_BYTES, logSize)\n , (JIT_ERROR_LOG_BUFFER_SIZE_BYTES, logSize)\n , (JIT_INFO_LOG_BUFFER, unsafeCoerce (p_ilog :: CString))\n , (JIT_ERROR_LOG_BUFFER, unsafeCoerce (p_elog :: CString)) ] ++ map unpack options in\n\n withArray (map cFromEnum opt) $ \\p_opts ->\n withArray (map unsafeCoerce val) $ \\p_vals -> do\n\n (s,mdl) <- cuModuleLoadDataEx img (length opt) p_opts p_vals\n infoLog <- B.packCString p_ilog\n errLog <- B.packCString p_elog\n time <- peek (castPtr p_vals)\n resultIfOk (s, (mdl, JITResult time infoLog errLog))\n\n where\n logSize = 2048\n\n unpack (MaxRegisters x) = (JIT_MAX_REGISTERS, x)\n unpack (ThreadsPerBlock x) = (JIT_THREADS_PER_BLOCK, x)\n unpack (OptimisationLevel x) = (JIT_OPTIMIZATION_LEVEL, x)\n unpack (Target x) = (JIT_TARGET, fromEnum x)\n\n\n{# fun unsafe cuModuleLoadDataEx\n { alloca- `Module' peekMod*\n , useByteString* `ByteString'\n , `Int'\n , id `Ptr CInt'\n , id `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n\n-- |\n-- Unload a module from the current context\n--\nunload :: Module -> IO ()\nunload m = nothingIfOk =<< cuModuleUnload m\n\n{# fun unsafe cuModuleUnload\n { useModule `Module' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Internal\n--------------------------------------------------------------------------------\n\npeekMod :: Ptr {# type CUmodule #} -> IO Module\npeekMod = liftM Module . peek\n\nuseByteString :: ByteString -> (Ptr a -> IO b) -> IO b\nuseByteString bs act = B.useAsCString bs $ \\p -> act (castPtr p)\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"cbd8f2c5639ffa1e0c43349ec34e88386d08cff6","subject":"Document the Cairo.SVG module.","message":"Document the Cairo.SVG module.","repos":"vincenthz\/webkit","old_file":"svgcairo\/Graphics\/Rendering\/Cairo\/SVG.chs","new_file":"svgcairo\/Graphics\/Rendering\/Cairo\/SVG.chs","new_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.SVG\n-- Copyright : (c) 2005 Duncan Coutts, Paolo Martini \n-- License : BSD-style (see cairo\/COPYRIGHT)\n--\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : experimental\n-- Portability : portable\n--\n-- The SVG extension to the Cairo 2D graphics library.\n--\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.SVG (\n -- * Convenience API\n\n -- | These operations render an SVG image directly in the current 'Render'\n -- contect. Because they operate in the cairo 'Render' monad they are\n -- affected by the current transformation matrix. So it is possible, for\n -- example, to scale or rotate an SVG image.\n --\n -- In the following example we scale an SVG image to a unit square:\n --\n -- > let (width, height) = svgGetSize in\n -- > do scale (1\/width) (1\/height)\n -- > svgRender svg\n\n svgRenderFromFile,\n svgRenderFromHandle,\n svgRenderFromString,\n\n -- * Standard API\n\n -- | With this API there are seperate functions for loading the SVG and\n -- rendering it. This allows us to be more effecient in the case that an SVG\n -- image is used many times - since it can be loaded just once and rendered\n -- many times. With the convenience API above the SVG would be parsed and\n -- processed each time it is drawn.\n\n SVG,\n svgRender,\n svgGetSize,\n\n -- ** Block scoped versions\n\n -- | These versions of the SVG loading operations give temporary access\n -- to the 'SVG' object within the scope of the handler function. These\n -- operations guarantee that the resources for the SVG object are deallocated\n -- at the end of the handler block. If this form of resource allocation is\n -- too restrictive you can use the GC-managed versions below.\n --\n -- These versions are ofen used in the following style:\n --\n -- > withSvgFromFile \"foo.svg\" $ \\svg -> do\n -- > ...\n -- > svgRender svg\n -- > ...\n\n withSvgFromFile,\n withSvgFromHandle,\n withSvgFromString,\n\n -- ** GC-managed versions\n\n -- | These versions of the SVG loading operations use the standard Haskell\n -- garbage collector to manage the resources associated with the 'SVG' object.\n -- As such they are more convenient to use but the GC cannot give\n -- strong guarantees about when the resources associated with the 'SVG' object\n -- will be released. In most circumstances this is not a problem, especially\n -- if the SVG files being used are not very big.\n\n svgNewFromFile,\n svgNewFromHandle,\n svgNewFromString,\n ) where\n\nimport Control.Monad (liftM, when)\nimport Foreign hiding (rotate)\nimport CForeign\nimport Control.Exception (bracket)\nimport Control.Monad.Reader (ReaderT(..), runReaderT, ask, MonadIO, liftIO)\nimport System.IO\n\nimport Graphics.Rendering.Cairo.Internal hiding (Status(..))\n{# import Graphics.Rendering.Cairo.Types #} hiding (Status(..))\n\n{# context lib=\"svg-cairo\" prefix=\"svg_cairo\" #}\n\n---------------------\n-- Types\n-- \n\n{# pointer *svg_cairo_t as SVG foreign newtype #}\n\n{# enum status_t as Status {underscoreToCase} deriving(Eq, Show) #}\n\n---------------------\n-- Basic API\n-- \n\n-- block scoped versions\n\nwithSvgFromFile :: FilePath -> (SVG -> Render a) -> Render a\nwithSvgFromFile file action =\n withSVG $ \\svg -> do \n liftIO $ svgParseFromFile file svg\n action svg\n\nwithSvgFromHandle :: Handle -> (SVG -> Render a) -> Render a\nwithSvgFromHandle hnd action =\n withSVG $ \\svg -> do \n liftIO $ svgParseFromHandle hnd svg\n action svg\n\nwithSvgFromString :: String -> (SVG -> Render a) -> Render a\nwithSvgFromString str action =\n withSVG $ \\svg -> do\n liftIO $ svgParseFromString str svg\n action svg\n\nwithSVG :: (SVG -> Render a) -> Render a\nwithSVG =\n bracketR (alloca $ \\svgPtrPtr -> do\n {# call unsafe create #} (castPtr svgPtrPtr)\n svgPtr <- peek (svgPtrPtr :: Ptr (Ptr SVG))\n svgPtr' <- newForeignPtr_ svgPtr\n return (SVG svgPtr'))\n \n {# call unsafe destroy #}\n\n-- GC managed versions\n\nsvgNewFromFile :: FilePath -> IO SVG\nsvgNewFromFile file = do\n svg <- svgNew\n svgParseFromFile file svg\n return svg\n\nsvgNewFromHandle :: Handle -> IO SVG\nsvgNewFromHandle hnd = do\n svg <- svgNew\n svgParseFromHandle hnd svg\n return svg\n\nsvgNewFromString :: String -> IO SVG\nsvgNewFromString str = do\n svg <- svgNew\n svgParseFromString str svg\n return svg\n\nsvgNew :: IO SVG\nsvgNew =\n alloca $ \\svgPtrPtr -> do\n {# call unsafe create #} (castPtr svgPtrPtr)\n svgPtr <- peek (svgPtrPtr :: Ptr (Ptr SVG))\n svgPtr' <- newForeignPtr svg_cairo_destroy_ptr svgPtr\n return (SVG svgPtr')\n\nforeign import ccall unsafe \"&svg_cairo_destroy\"\n svg_cairo_destroy_ptr :: FinalizerPtr SVG\n\n-- internal implementation\n\nsvgParseFromFile :: FilePath -> SVG -> IO ()\nsvgParseFromFile file svg =\n checkStatus $\n withCString file $ \\filePtr -> \n {# call parse #} svg filePtr\n\nsvgParseFromHandle :: Handle -> SVG -> IO ()\nsvgParseFromHandle hnd svg =\n allocaBytes 4096 $ \\bufferPtr -> do\n checkStatus $ {# call parse_chunk_begin #} svg\n let loop = do\n count <- hGetBuf hnd bufferPtr 4096\n when (count > 0)\n (checkStatus $ {# call parse_chunk #}\n svg bufferPtr (fromIntegral count))\n when (count == 4096) loop\n loop\n checkStatus $ {# call parse_chunk_end #} svg\n\nsvgParseFromString :: String -> SVG -> IO ()\nsvgParseFromString str svg = do\n checkStatus $ {# call parse_chunk_begin #} svg\n let loop \"\" = return ()\n loop str =\n case splitAt 4096 str of\n (chunk, str') -> do\n withCStringLen chunk $ \\(chunkPtr, len) ->\n checkStatus $ {# call parse_chunk #}\n svg chunkPtr (fromIntegral len)\n loop str'\n loop str\n checkStatus $ {# call parse_chunk_end #} svg\n\n-- actually render it\n\nsvgRender :: SVG -> Render ()\nsvgRender svg = do\n cr <- ask\n liftIO $ checkStatus $ {# call render #} svg cr\n\n-- | Get the width and height of the SVG image.\n--\nsvgGetSize :: \n SVG\n -> (Int, Int) -- ^ @(width, height)@\nsvgGetSize svg = unsafePerformIO $\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call unsafe get_size #} svg widthPtr heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n---------------------\n-- Convenience API\n-- \n\nsvgRenderFromFile :: FilePath -> Render ()\nsvgRenderFromFile file = withSvgFromFile file svgRender\n\nsvgRenderFromHandle :: Handle -> Render ()\nsvgRenderFromHandle hnd = withSvgFromHandle hnd svgRender\n\nsvgRenderFromString :: String -> Render ()\nsvgRenderFromString str = withSvgFromString str svgRender\n\n---------------------\n-- Utils\n-- \n\ncheckStatus :: IO CInt -> IO ()\ncheckStatus action = do\n status <- liftM (toEnum . fromIntegral) action\n if status == StatusSuccess\n then return ()\n else fail (\"svg-cairo error: \" ++ show status)\n","old_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.SVG\n-- Copyright : (c) 2005 Duncan Coutts, Paolo Martini \n-- License : BSD-style (see cairo\/COPYRIGHT)\n--\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : experimental\n-- Portability : portable\n--\n-- The SVG extension to the Cairo 2D graphics library.\n--\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.SVG (\n -- * Convenience API\n svgRenderFromFile,\n svgRenderFromHandle,\n svgRenderFromString,\n \n -- * Basic API\n SVG,\n svgRender,\n svgGetSize,\n\n -- ** Block scoped versions\n withSvgFromFile,\n withSvgFromHandle,\n withSvgFromString,\n\n -- ** GC-managed versions\n svgNewFromFile,\n svgNewFromHandle,\n svgNewFromString,\n ) where\n\nimport Control.Monad (liftM, when)\nimport Foreign hiding (rotate)\nimport CForeign\nimport Control.Exception (bracket)\nimport Control.Monad.Reader (ReaderT(..), runReaderT, ask, MonadIO, liftIO)\nimport System.IO\n\nimport Graphics.Rendering.Cairo.Internal hiding (Status(..))\n{# import Graphics.Rendering.Cairo.Types #} hiding (Status(..))\n\n{# context lib=\"svg-cairo\" prefix=\"svg_cairo\" #}\n\n---------------------\n-- Types\n-- \n\n{# pointer *svg_cairo_t as SVG foreign newtype #}\n\n{# enum status_t as Status {underscoreToCase} deriving(Eq, Show) #}\n\n---------------------\n-- Basic API\n-- \n\n-- block scoped versions\n\nwithSvgFromFile :: FilePath -> (SVG -> Render a) -> Render a\nwithSvgFromFile file action =\n withSVG $ \\svg -> do \n liftIO $ svgParseFromFile file svg\n action svg\n\nwithSvgFromHandle :: Handle -> (SVG -> Render a) -> Render a\nwithSvgFromHandle hnd action =\n withSVG $ \\svg -> do \n liftIO $ svgParseFromHandle hnd svg\n action svg\n\nwithSvgFromString :: String -> (SVG -> Render a) -> Render a\nwithSvgFromString str action =\n withSVG $ \\svg -> do\n liftIO $ svgParseFromString str svg\n action svg\n\nwithSVG :: (SVG -> Render a) -> Render a\nwithSVG =\n bracketR (alloca $ \\svgPtrPtr -> do\n {# call unsafe create #} (castPtr svgPtrPtr)\n svgPtr <- peek (svgPtrPtr :: Ptr (Ptr SVG))\n svgPtr' <- newForeignPtr_ svgPtr\n return (SVG svgPtr'))\n \n {# call unsafe destroy #}\n\n-- GC managed versions\n\nsvgNewFromFile :: FilePath -> IO SVG\nsvgNewFromFile file = do\n svg <- svgNew\n svgParseFromFile file svg\n return svg\n\nsvgNewFromHandle :: Handle -> IO SVG\nsvgNewFromHandle hnd = do\n svg <- svgNew\n svgParseFromHandle hnd svg\n return svg\n\nsvgNewFromString :: String -> IO SVG\nsvgNewFromString str = do\n svg <- svgNew\n svgParseFromString str svg\n return svg\n\nsvgNew :: IO SVG\nsvgNew =\n alloca $ \\svgPtrPtr -> do\n {# call unsafe create #} (castPtr svgPtrPtr)\n svgPtr <- peek (svgPtrPtr :: Ptr (Ptr SVG))\n svgPtr' <- newForeignPtr svg_cairo_destroy_ptr svgPtr\n return (SVG svgPtr')\n\nforeign import ccall unsafe \"&svg_cairo_destroy\"\n svg_cairo_destroy_ptr :: FinalizerPtr SVG\n\n-- internal implementation\n\nsvgParseFromFile :: FilePath -> SVG -> IO ()\nsvgParseFromFile file svg =\n checkStatus $\n withCString file $ \\filePtr -> \n {# call parse #} svg filePtr\n\nsvgParseFromHandle :: Handle -> SVG -> IO ()\nsvgParseFromHandle hnd svg =\n allocaBytes 4096 $ \\bufferPtr -> do\n checkStatus $ {# call parse_chunk_begin #} svg\n let loop = do\n count <- hGetBuf hnd bufferPtr 4096\n when (count > 0)\n (checkStatus $ {# call parse_chunk #}\n svg bufferPtr (fromIntegral count))\n when (count == 4096) loop\n loop\n checkStatus $ {# call parse_chunk_end #} svg\n\nsvgParseFromString :: String -> SVG -> IO ()\nsvgParseFromString str svg = do\n checkStatus $ {# call parse_chunk_begin #} svg\n let loop \"\" = return ()\n loop str =\n case splitAt 4096 str of\n (chunk, str') -> do\n withCStringLen chunk $ \\(chunkPtr, len) ->\n checkStatus $ {# call parse_chunk #}\n svg chunkPtr (fromIntegral len)\n loop str'\n loop str\n checkStatus $ {# call parse_chunk_end #} svg\n\n-- actually render it\n\nsvgRender :: SVG -> Render ()\nsvgRender svg = do\n cr <- ask\n liftIO $ checkStatus $ {# call render #} svg cr\n\n-- find out how big the thing is supposed to be.\nsvgGetSize :: SVG -> (Int, Int)\nsvgGetSize svg = unsafePerformIO $\n alloca $ \\widthPtr ->\n alloca $ \\heightPtr -> do\n {# call unsafe get_size #} svg widthPtr heightPtr\n width <- peek widthPtr\n height <- peek heightPtr\n return (fromIntegral width, fromIntegral height)\n\n---------------------\n-- Convenience API\n-- \n\nsvgRenderFromFile :: FilePath -> Render ()\nsvgRenderFromFile file = withSvgFromFile file svgRender\n\nsvgRenderFromHandle :: Handle -> Render ()\nsvgRenderFromHandle hnd = withSvgFromHandle hnd svgRender\n\nsvgRenderFromString :: String -> Render ()\nsvgRenderFromString str = withSvgFromString str svgRender\n\n---------------------\n-- Utils\n-- \n\ncheckStatus :: IO CInt -> IO ()\ncheckStatus action = do\n status <- liftM (toEnum . fromIntegral) action\n if status == StatusSuccess\n then return ()\n else fail (\"svg-cairo error: \" ++ show status)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"de26a542d45ac3257cae5cdc27a9c4014855e583","subject":"Fix build failure with lens-4.2","message":"Fix build failure with lens-4.2\n\nSince lens-4.2 export the `deep`, turn CV.Image.deep into local\nfunction to avoid \"ambiguous symbol\" build error.\n","repos":"aleator\/CV,BeautifulDestinations\/CV,TomMD\/CV,aleator\/CV","old_file":"CV\/Image.chs","new_file":"CV\/Image.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns,ParallelListComp, FlexibleInstances, FlexibleContexts, TypeFamilies, EmptyDataDecls, ScopedTypeVariables, StandaloneDeriving, DeriveDataTypeable, UndecidableInstances, MultiParamTypeClasses #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, MutableImage(..)\n, Mask\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\n, withMask\n, withMutableClone\n, withCloneValue\n, CreateImage\n, Save(..)\n\n-- * Colour spaces\n, ChannelOf\n, GrayScale\n, Complex\n, BGR\n, RGB\n, RGBA\n, RGB_Channel(..)\n, LAB\n, LAB_Channel(..)\n, D32\n, D64\n, D8\n, Tag\n, lab\n, rgba\n, rgb\n, compose\n, composeMultichannelImage\n\n-- * IO operations\n, Loadable(..)\n, saveImage\n, loadColorImage\n, loadImage\n\n-- * Pixel level access\n, GetPixel(..)\n, SetPixel(..)\n, safeGetPixel\n, getAllPixels\n, getAllPixelsRowMajor\n, mapImageInplace\n\n-- * Image information\n, ImageDepth\n, Sized(..)\n, biggerThan\n, getArea\n, getChannel\n, getImageChannels\n, getImageDepth\n, getImageInfo\n\n-- * ROI's, COI's and subregions\n, setCOI\n, setROI\n, resetROI\n, getRegion\n, withIOROI\n--, withROI\n\n-- * Blitting\n, blendBlit\n, blit\n, blitM\n, subPixelBlit\n, safeBlit\n, montage\n, tileImages\n\n-- * Conversions\n, convertTo\n, rgbToGray\n, rgbToGray8\n, grayToRGB\n, rgbToLab\n, bgrToRgb\n, rgbToBgr\n, cloneTo64F\n, unsafeImageTo32F \n, unsafeImageTo64F \n, unsafeImageTo8Bit \n\n-- * Low level access operations\n, BareImage(..)\n, creatingImage\n, unImage\n, unS\n, withGenBareImage\n, withBareImage\n, creatingBareImage\n, withGenImage\n, withImage\n, withMutableImage\n, withRawImageData\n, imageFPTR\n, ensure32F\n\n-- * Extended error handling\n, setCatch\n, CvException\n, CvSizeError(..)\n, CvIOError(..)\n) where\n\nimport System.Mem\nimport System.Directory\nimport System.FilePath\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Utils\nimport Foreign.ForeignPtr hiding (newForeignPtr,unsafeForeignPtrToPtr)\nimport Foreign.Concurrent\nimport Foreign.Ptr\nimport Control.Parallel.Strategies\nimport Control.DeepSeq\nimport Control.Lens\n\nimport CV.Bindings.Error\n\nimport Data.Maybe(catMaybes)\nimport Data.List(genericLength)\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)\nimport Foreign.Storable\nimport System.IO.Unsafe\nimport Data.Word\nimport qualified Data.Complex as C\nimport Control.Monad\nimport Control.Exception\nimport Data.Data\nimport Data.Typeable\n\nimport Utils.GeometryClass\nimport Control.Applicative hiding (empty)\n\n\n\n\n-- Colorspaces\n\n-- | Single channel grayscale image\ndata GrayScale\ndata Complex\ndata RGB\ndata RGB_Channel = Red |\u00a0Green |\u00a0Blue deriving (Eq,Ord,Enum)\n\ndata BGR\n\ndata LAB\ndata YUV\ndata RGBA\ndata LAB_Channel = LAB_L |\u00a0LAB_A |\u00a0LAB_B deriving (Eq,Ord,Enum)\ndata YUV_Channel = YUV_Y |\u00a0YUV_U |\u00a0YUV_V deriving (Eq,Ord,Enum)\n\n-- | Type family for expressing which channels a colorspace contains. This needs to be fixed wrt. the BGR color space.\ntype family ChannelOf a :: *\ntype instance ChannelOf RGB_Channel = RGB\ntype instance ChannelOf LAB_Channel = LAB\ntype instance ChannelOf YUV_Channel = YUV\n\n-- Bit Depths\ntype D8 = Word8\ntype D32 = Float\ntype D64 = Double\n\n-- | The type for Images\nnewtype Image channels depth = S BareImage\nnewtype MutableImage channels depth = Mutable (Image channels depth)\n\n-- | Alias for images used as masks\ntype Mask = Maybe (Image GrayScale D8)\n\n-- |\u00a0Remove typing info from an image\nunS (S i) = i -- Unsafe and ugly\n\nimageFPTR :: Image c d -> ForeignPtr BareImage\nimageFPTR (S (BareImage fptr)) = fptr\n\nwithImage :: Image c d -> (Ptr BareImage ->IO a) -> IO a\nwithImage (S i) op = withBareImage i op\n--withGenNewImage (S i) op = withGenImage i op\n\nwithRawImageData :: Image c d -> (Int -> Ptr Word8 -> IO a) -> IO a\nwithRawImageData (S i) op = withBareImage i $ \\pp-> do\n d <- {#get IplImage->imageData#} pp \n wd <- {#get IplImage->widthStep#} pp\n op (fromIntegral wd) (castPtr d)\n\n-- Ok. this is just the example why I need image types\nwithUniPtr with x fun = with x $ \\y ->\n fun (castPtr y)\n\nwithGenImage :: Image c d -> (Ptr b -> IO a) -> IO a\nwithGenImage = withUniPtr withImage\n\n-- |\u00a0This function converts masks to pointers. Masks which are nothing are converted\n-- to null pointers.\nwithMask :: Mask -> (Ptr b -> IO a) -> IO a\nwithMask (Just i) op = withUniPtr withImage i op\nwithMask Nothing op = op nullPtr\n\nwithMutableImage :: MutableImage c d -> (Ptr b -> IO a) -> IO a\nwithMutableImage (Mutable i) o = withGenImage i o\n\nwithGenBareImage :: BareImage -> (Ptr b -> IO a) -> IO a\nwithGenBareImage = withUniPtr withBareImage\n\n{#pointer *IplImage as BareImage foreign newtype#}\n\nfreeBareImage ptr = with ptr {#call cvReleaseImage#}\n\n--foreign import ccall \"& wrapReleaseImage\" releaseImage :: FinalizerPtr BareImage\n\ninstance NFData (Image a b) where\n rnf a@(S (BareImage fptr)) = (unsafeForeignPtrToPtr) fptr `seq` a `seq` ()-- This might also need peek?\n\n\ncreatingImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . S . BareImage $ fptr\n\ncreatingBareImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . BareImage $ fptr\n\nunImage (S (BareImage fptr)) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\nrgba = undefined :: Tag RGBA\nlab = undefined :: Tag LAB\n\n-- | Typeclass for elements that are build from component elements. For example,\n-- RGB images can be constructed from three grayscale images.\nclass Composes a where\n type Source a :: *\n compose :: Source a -> a\n\ninstance (CreateImage (Image RGBA a)) => Composes (Image RGBA a) where\n type Source (Image RGBA a) = (Image GrayScale a, Image GrayScale a\n ,Image GrayScale a, Image GrayScale a)\n compose (r,g,b,a) = composeMultichannelImage (Just b) (Just g) (Just r) (Just a) rgba\n\ninstance (CreateImage (Image RGB a)) => Composes (Image RGB a) where\n type Source (Image RGB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (r,g,b) = composeMultichannelImage (Just b) (Just g) (Just r) Nothing rgb\n\ninstance (CreateImage (Image LAB a)) => Composes (Image LAB a) where\n type Source (Image LAB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (l,a,b) = composeMultichannelImage (Just l) (Just a) (Just b) Nothing lab\n\n{-# DEPRECATED composeMultichannelImage \"This is unsafe. Use compose instead\" #-}\ncomposeMultichannelImage :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannelImage = composeMultichannel\n\ncomposeMultichannel :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannel (c2)\n (c1)\n (c3)\n (c4)\n totag\n = unsafePerformIO $\u00a0do\n res <- create (size) -- TODO: Check channel count -- This is NOT correct\n withMaybe c1 $ \\cc1 ->\n withMaybe c2 $ \\cc2 ->\n withMaybe c3 $ \\cc3 ->\n withMaybe c4 $ \\cc4 ->\n withGenImage res $ \\cres -> {#call cvMerge#} cc1 cc2 cc3 cc4 cres\n return res\n where\n withMaybe (Just i) op = withGenImage i op\n withMaybe (Nothing) op = op nullPtr\n size = getSize . head . catMaybes $ [c1,c2,c3,c4]\n\n\n-- | Typeclass for CV items that can be read from file. Mainly images at this point.\nclass Loadable a where\n readFromFile :: FilePath -> IO a\n\n\ninstance Loadable ((Image GrayScale D32)) where\n readFromFile fp = do\n e <- loadImage fp\n case e of\n Just i -> return i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D32)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ unsafeImageTo32F $ bgrToRgb i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D8)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ bgrToRgb i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image GrayScale D8)) where\n readFromFile fp = do\n e <- loadImage8 fp\n case e of\n Just i -> return i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\n\n-- | This function loads and converts image to an arbitrary format. Notice that it is\n-- polymorphic enough to cause run time errors if the declared and actual types of the\n-- images do not match. Use with care.\nunsafeloadUsing x p n = do\n exists <- doesFileExist n\n if not exists then return Nothing\n else do\n i <- withCString n $ \\name ->\n creatingBareImage ({#call cvLoadImage #} name p)\n bw <- x i\n return . Just .\u00a0S $ bw\n\nloadImage :: FilePath -> IO (Maybe (Image GrayScale D32))\nloadImage = unsafeloadUsing imageTo32F 0\nloadImage8 :: FilePath -> IO (Maybe (Image GrayScale D8))\nloadImage8 = unsafeloadUsing imageTo8Bit 0\nloadColorImage :: FilePath -> IO (Maybe (Image BGR D32))\nloadColorImage = unsafeloadUsing imageTo32F 1\nloadColorImage8 :: FilePath -> IO (Maybe (Image BGR D8))\nloadColorImage8 = unsafeloadUsing imageTo8Bit 1\n\n\ninstance Sized (MutableImage a b) where\n type Size (MutableImage a b) = IO (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize (Mutable i) = evaluate (deep (getSize i))\n where\n deep a = a `deepseq` a\n\ninstance Sized BareImage where\n type Size BareImage = (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize image = unsafePerformIO $ withBareImage image $ \\i -> do\n w <- {#call getImageWidth#} i\n h <- {#call getImageHeight#} i\n return (fromIntegral w,fromIntegral h)\n\ninstance Sized (Image c d) where\n type Size (Image c d) = (Int,Int)\n getSize = getSize . unS\n\n\n#c\nenum CvtFlags {\n CvtFlip = CV_CVTIMG_FLIP,\n CvtSwapRB = CV_CVTIMG_SWAP_RB\n };\n#endc\n\n#c\nenum CvtCodes {\n BGR2BGRA =0,\n RGB2RGBA =BGR2BGRA,\n\n BGRA2BGR =1,\n RGBA2RGB =BGRA2BGR,\n\n BGR2RGBA =2,\n RGB2BGRA =BGR2RGBA,\n\n RGBA2BGR =3,\n BGRA2RGB =RGBA2BGR,\n\n BGR2RGB =4,\n RGB2BGR =BGR2RGB,\n\n BGRA2RGBA =5,\n RGBA2BGRA =BGRA2RGBA,\n\n BGR2GRAY =6,\n RGB2GRAY =7,\n GRAY2BGR =8,\n GRAY2RGB =GRAY2BGR,\n GRAY2BGRA =9,\n GRAY2RGBA =GRAY2BGRA,\n BGRA2GRAY =10,\n RGBA2GRAY =11,\n\n BGR2BGR565 =12,\n RGB2BGR565 =13,\n BGR5652BGR =14,\n BGR5652RGB =15,\n BGRA2BGR565 =16,\n RGBA2BGR565 =17,\n BGR5652BGRA =18,\n BGR5652RGBA =19,\n\n GRAY2BGR565 =20,\n BGR5652GRAY =21,\n\n BGR2BGR555 =22,\n RGB2BGR555 =23,\n BGR5552BGR =24,\n BGR5552RGB =25,\n BGRA2BGR555 =26,\n RGBA2BGR555 =27,\n BGR5552BGRA =28,\n BGR5552RGBA =29,\n\n GRAY2BGR555 =30,\n BGR5552GRAY =31,\n\n BGR2XYZ =32,\n RGB2XYZ =33,\n XYZ2BGR =34,\n XYZ2RGB =35,\n\n BGR2YCrCb =36,\n RGB2YCrCb =37,\n YCrCb2BGR =38,\n YCrCb2RGB =39,\n\n BGR2HSV =40,\n RGB2HSV =41,\n\n BGR2Lab =44,\n RGB2Lab =45,\n\n BayerBG2BGR =46,\n BayerGB2BGR =47,\n BayerRG2BGR =48,\n BayerGR2BGR =49,\n\n BayerBG2RGB =BayerRG2BGR,\n BayerGB2RGB =BayerGR2BGR,\n BayerRG2RGB =BayerBG2BGR,\n BayerGR2RGB =BayerGB2BGR,\n\n BGR2Luv =50,\n RGB2Luv =51,\n BGR2HLS =52,\n RGB2HLS =53,\n\n HSV2BGR =54,\n HSV2RGB =55,\n\n Lab2BGR =56,\n Lab2RGB =57,\n Luv2BGR =58,\n Luv2RGB =59,\n HLS2BGR =60,\n HLS2RGB =61,\n\n BayerBG2BGR_VNG =62,\n BayerGB2BGR_VNG =63,\n BayerRG2BGR_VNG =64,\n BayerGR2BGR_VNG =65,\n\n BayerBG2RGB_VNG =BayerRG2BGR_VNG,\n BayerGB2RGB_VNG =BayerGR2BGR_VNG,\n BayerRG2RGB_VNG =BayerBG2BGR_VNG,\n BayerGR2RGB_VNG =BayerGB2BGR_VNG,\n\n BGR2HSV_FULL = 66,\n RGB2HSV_FULL = 67,\n BGR2HLS_FULL = 68,\n RGB2HLS_FULL = 69,\n\n HSV2BGR_FULL = 70,\n HSV2RGB_FULL = 71,\n HLS2BGR_FULL = 72,\n HLS2RGB_FULL = 73,\n\n LBGR2Lab = 74,\n LRGB2Lab = 75,\n LBGR2Luv = 76,\n LRGB2Luv = 77,\n\n Lab2LBGR = 78,\n Lab2LRGB = 79,\n Luv2LBGR = 80,\n Luv2LRGB = 81,\n\n BGR2YUV = 82,\n RGB2YUV = 83,\n YUV2BGR = 84,\n YUV2RGB = 85,\n\n COLORCVT_MAX =100\n};\n#endc\n\n{#enum CvtCodes {}#}\n\n{#enum CvtFlags {}#}\n\nrgbToLab :: Image RGB D32 -> Image LAB D32\nrgbToLab = S . convertTo RGB2Lab 3 . unS\n\nrgbToYUV :: Image RGB D32 -> Image YUV D32\nrgbToYUV = S . convertTo RGB2YUV 3 . unS\n\nrgbToGray :: Image RGB D32 -> Image GrayScale D32\nrgbToGray = S . convertTo RGB2GRAY 1 . unS\n\nrgbToGray8 :: Image RGB D8 -> Image GrayScale D8\nrgbToGray8 = S . convert8UTo RGB2GRAY 1 . unS\n\ngrayToRGB :: Image GrayScale D32 -> Image RGB D32\ngrayToRGB = S . convertTo GRAY2BGR 3 . unS\n\nbgrToRgb :: Image BGR D8 -> Image RGB D8\nbgrToRgb = S . swapRB . unS\n\nrgbToBgr :: Image RGB D8 -> Image BGR D8\nrgbToBgr = S . swapRB . unS\n\nswapRB :: BareImage -> BareImage\nswapRB img = unsafePerformIO $ do\n res <- cloneBareImage img\n withBareImage img $ \\cimg ->\n withBareImage res $ \\cres ->\n {#call cvConvertImage#} (castPtr cimg) (castPtr cres) (fromIntegral . fromEnum $ CvtSwapRB)\n return res\n\n\nsafeGetPixel :: (Sized image, Size image ~ (Int,Int), GetPixel image) => (P image) -> (Int,Int) -> image -> P image\nsafeGetPixel def (x,y) i |\u00a0x<0 || x>= w || y<0 || y>=h = def\n | otherwise = getPixel (x,y) i\n where\n (w,h) = getSize i\n -- (x',y') = (clamp (0,w-1) x, clamp (0,h-1) y)\n\nclamp :: Ord a => (a, a) -> a -> a\nclamp (a,b) x = max a (min b x)\n\ninstance (NFData (P (Image a b)), GetPixel (Image a b)) => GetPixel (MutableImage a b) where\n type P (MutableImage a b) = IO (P (Image a b))\n getPixel xy (Mutable i) = let p = getPixel xy i\n in p `deepseq` return p\n\nclass GetPixel a where\n type P a :: *\n getPixel :: (Int,Int) -> a -> P a\n\n-- #define FGET(img,x,y) (((float *)((img)->imageData + (y)*(img)->widthStep))[(x)])\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Float))):: Ptr Float)\n\ninstance GetPixel (Image GrayScale D8) where\n type P (Image GrayScale D8) = D8\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Word8))):: Ptr Word8)\n\ninstance GetPixel (Image Complex D32) where\n type P (Image Complex D32) = C.Complex D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n re <- peek (castPtr (d`plusPtr` (y*cs + x*2*fs)))\n im <- peek (castPtr (d`plusPtr` (y*cs +(x*2+1)*fs)))\n return (re C.:+ im)\n\n-- #define UGETC(img,color,x,y) (((uint8_t *)((img)->imageData + (y)*(img)->widthStep))[(x)*3+(color)])\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\ninstance GetPixel (Image BGR D32) where\n type P (Image BGR D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\ninstance GetPixel (Image BGR D8) where\n type P (Image BGR D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image RGB D8) where\n type P (Image RGB D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image LAB D32) where\n type P (Image LAB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n l <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n a <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n b <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (l,a,b)\n\n-- | Perform (a destructive) inplace map of the image. This should be wrapped inside\n-- withClone or an image operation\nmapImageInplace :: (P (Image GrayScale D32) -> P (Image GrayScale D32))\n -> MutableImage GrayScale D32\n -> IO ()\nmapImageInplace f image = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n (w,h) <- getSize image\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n forM_ [(x,y) | x<-[0..w-1], y <- [0..h-1]] $ \\(x,y) ->\u00a0do\n v <- peek (castPtr (d `plusPtr` (y*cs+x*fs)))\n poke (castPtr (d `plusPtr` (y*cs+x*fs))) (f v)\n\n\n\nconvert8UTo :: CvtCodes -> CInt -> BareImage -> BareImage\nconvert8UTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage8U#} w h channels\n withBareImage img $ \\cimg ->\n {#call cvCvtColor#} (castPtr cimg) (castPtr res) (fromIntegral . fromEnum $ code)\n return res\n where\n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\nconvertTo :: CvtCodes -> CInt -> BareImage -> BareImage\nconvertTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage32F#} w h channels\n withBareImage img $ \\cimg ->\n {#call cvCvtColor#} (castPtr cimg) (castPtr res) (fromIntegral . fromEnum $ code)\n return res\n where\n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\n-- |\u00a0Class for images that exist.\nclass CreateImage a where\n -- | Create an image from size\n create :: (Int,Int) -> IO a\n\ncreateWith :: CreateImage (Image c d) => (Int,Int) -> (MutableImage c d -> IO (MutableImage c d)) -> IO (Image c d)\ncreateWith s f = do\n c <- create s\n Mutable r <- f (Mutable c)\n return r\n\n\n\n\ninstance CreateImage (Image GrayScale D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image Complex D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 2\ninstance CreateImage (Image LAB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image c d) => CreateImage (MutableImage c d) where\n create s = Mutable <$> create s\n\n\n-- | Allocate a new empty image\nempty :: (CreateImage (Image a b)) => (Int,Int) -> (Image a b)\nempty size = unsafePerformIO $ create size\n\n-- |\u00a0Allocate a new image that of the same size and type as the exemplar image given.\nemptyCopy :: (CreateImage (Image a b)) => Image a b -> (Image a b)\nemptyCopy img = unsafePerformIO $ create (getSize img)\n\nemptyCopy' :: (CreateImage (Image a b)) => Image a b -> IO (Image a b)\nemptyCopy' img = create (getSize img)\n\n-- | Save image. This will convert the image to 8 bit one before saving\nclass Save a where\n save :: FilePath -> a -> IO ()\n\ninstance Save (Image BGR D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image)\n\ninstance Save (Image RGB D32) where\n save filename image = primitiveSave filename (swapRB . unS . unsafeImageTo8Bit $ image)\n\ninstance Save (Image RGB D8) where\n save filename image = primitiveSave filename (swapRB . unS $ image)\n\ninstance Save (Image GrayScale D8) where\n save filename image = primitiveSave filename (unS $ image)\n\ninstance Save (Image GrayScale D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image)\n\nprimitiveSave :: FilePath -> BareImage -> IO ()\nprimitiveSave filename fpi = do\n exists <- doesDirectoryExist (takeDirectory filename)\n when (not exists) $\u00a0throw (CvIOError $ \"Directory does not exist: \" ++ (takeDirectory filename))\n withCString filename $ \\name ->\n withGenBareImage fpi $ \\cvArr ->\n alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\n-- |Save an image as 8 bit gray scale\nsaveImage :: (Save (Image c d)) => FilePath -> Image c d -> IO ()\nsaveImage = save\n\ngetArea :: (Sized a,Num b, Size a ~ (b,b)) => a -> b\ngetArea = uncurry (*).getSize\n\ngetRegion :: (Int,Int) -> (Int,Int) -> Image c d -> Image c d\ngetRegion (fromIntegral -> x,fromIntegral -> y) (fromIntegral -> w,fromIntegral -> h) image\n | x+w <= width && y+h <= height = S . getRegion' (x,y) (w,h) $ unS image\n | otherwise = error $ \"Region outside image:\"\n ++ show (getSize image) ++\n \"\/\"++show (x+w,y+h)\n where\n (fromIntegral -> width,fromIntegral -> height) = getSize image\n\ngetRegion' (x,y) (w,h) image = unsafePerformIO $\n withBareImage image $ \\i ->\n creatingBareImage ({#call getSubImage#}\n i x y w h)\n\n\n-- | Tile images by overlapping them on a black canvas.\ntileImages image1 image2 (x,y) = unsafePerformIO $\n withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n creatingImage ({#call simpleMergeImages#}\n i1 i2 x y)\n-- | Blit image2 onto image1.\nclass Blittable channels depth \ninstance Blittable GrayScale D32\ninstance Blittable RGB D32\n\nblit :: Blittable c d => MutableImage c d -> Image c d -> (Int,Int) -> IO ()\nblit image1 image2 (x,y) = do\n (w1,h1) <- getSize image1\n let ((w2,h2)) = getSize image2\n if x+w2>w1 || y+h2>h1 || x<0 || y<0\n then error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n else withMutableImage image1 $ \\i1 ->\n withImage image2 $ \\i2 -> \n ({#call plainBlit#} i1 i2 (fromIntegral y) (fromIntegral x))\n\n-- | Create an image by blitting multiple images onto an empty image.\nblitM :: (CreateImage (MutableImage GrayScale D32)) => \n (Int,Int) -> [((Int,Int),Image GrayScale D32)] -> Image GrayScale D32\nblitM (rw,rh) imgs = unsafePerformIO $ resultPic >>= fromMutable \n where\n resultPic = do\n r <- create (fromIntegral rw,fromIntegral rh)\n sequence_ [blit r i (fromIntegral x, fromIntegral y)\n | ((x,y),i) <- imgs ]\n return r\n\n\nsubPixelBlit :: MutableImage c d -> Image c d -> (CDouble, CDouble) -> IO ()\nsubPixelBlit (image1) (image2) (x,y) = do\n (w1,h1) <- getSize image1\n let ((w2,h2)) = getSize image2\n if ceiling x+w2>w1 || ceiling y+h2>h1 ||\u00a0x<0 || y<0\n then error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n else withMutableImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call subpixel_blit#} i1 i2 y x)\n\nsafeBlit i1 i2 (x,y) = unsafePerformIO $ do\n res <- toMutable i1-- createImage32F (getSize i1) 1\n blit res i2 (x,y)\n return res\n\n-- | Blit image2 onto image1.\n-- This uses an alpha channel bitmap for determining the regions where the image should be \"blended\" with\n-- the base image.\nblendBlit :: MutableImage c d -> Image c1 d1 -> Image c3 d3 -> Image c2 d2\n -> (CInt, CInt) -> IO ()\nblendBlit image1 image1Alpha image2 image2Alpha (x,y) =\n withMutableImage image1 $ \\i1 ->\n withImage image1Alpha $ \\i1a ->\n withImage image2Alpha $ \\i2a ->\n withImage image2 $ \\i2 ->\n ({#call alphaBlit#} i1 i1a i2 i2a y x)\n\n\n-- | Create a copy of an image\ncloneImage :: Image a b -> IO (Image a b)\ncloneImage img = withGenImage img $ \\image ->\n creatingImage ({#call cvCloneImage #} image)\n\ntoMutable :: Image a b -> IO (MutableImage a b)\ntoMutable img = withGenImage img $ \\image ->\n Mutable <$>\u00a0creatingImage ({#call cvCloneImage #} image)\n\nfromMutable :: MutableImage a b -> IO (Image a b)\nfromMutable (Mutable img) = cloneImage img \n\n-- | Create a copy of a non-types image\ncloneBareImage :: BareImage -> IO BareImage\ncloneBareImage img = withGenBareImage img $ \\image ->\n creatingBareImage ({#call cvCloneImage #} image)\n\nwithMutableClone\n :: Image channels depth\n -> (MutableImage channels depth -> IO a)\n -> IO a\nwithMutableClone img fun = do\n result <- toMutable img\n fun result\n\nwithClone\n :: Image channels depth\n -> (Image channels depth -> IO ())\n -> IO (Image channels depth)\nwithClone img fun = do\n result <- cloneImage img\n fun result\n return result\n\nwithCloneValue\n :: Image channels depth\n -> (Image channels depth -> IO a)\n -> IO a\nwithCloneValue img fun = do\n result <- cloneImage img\n r <- fun result\n return r\n\ncloneTo64F :: Image c d -> IO (Image c D64)\ncloneTo64F img = withGenImage img $ \\image ->\n creatingImage\n ({#call ensure64F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 64 bit, floating point, image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image. \nunsafeImageTo64F :: Image c d -> Image c D64\nunsafeImageTo64F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure64F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 32 bit, floating point, image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image. \nunsafeImageTo32F :: Image c d -> Image c D32\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure32F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 8 bit image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image. \nunsafeImageTo8Bit :: Image cspace a -> Image cspace D8\nunsafeImageTo8Bit img =\n unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage ({#call ensure8U #} image)\n\n--toD32 :: Image c d -> Image c D32\n--toD32 i =\n-- unsafePerformIO $\n-- withImage i $ \\i_ptr ->\n-- creatingImage\n\n\nimageTo32F img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure32F #} image)\n\nimageTo8Bit img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure8U #} image)\n#c\nenum ImageDepth {\n Depth32F = IPL_DEPTH_32F,\n Depth64F = IPL_DEPTH_64F,\n Depth8U = IPL_DEPTH_8U,\n Depth8S = IPL_DEPTH_8S,\n Depth16U = IPL_DEPTH_16U,\n Depth16S = IPL_DEPTH_16S,\n Depth32S = IPL_DEPTH_32S\n };\n#endc\n\n{#enum ImageDepth {}#}\n\nderiving instance Show ImageDepth\n\ngetImageDepth :: Image c d -> IO ImageDepth\ngetImageDepth i = withImage i $ \\c_img -> {#get IplImage->depth #} c_img >>= return.toEnum.fromIntegral\ngetImageChannels i = withImage i $ \\c_img -> {#get IplImage->nChannels #} c_img\n\ngetImageInfo x = do\n let s = getSize x\n d <- getImageDepth x\n c <- getImageChannels x\n return (s,d,c)\n\n\n-- | Set the region of interest for a mutable image\nsetROI :: (Integral a) => (a,a) -> (a,a) -> MutableImage c d -> IO ()\nsetROI (fromIntegral -> x,fromIntegral -> y)\n (fromIntegral -> w,fromIntegral -> h)\n image = withMutableImage image $ \\i ->\n {#call wrapSetImageROI#} i x y w h\n\n-- | Set the region of interest to cover the entire image.\nresetROI :: MutableImage c d -> IO ()\nresetROI image = withMutableImage image $ \\i ->\n {#call cvResetImageROI#} i\n\nsetCOI :: (Enum a) => a -> MutableImage (ChannelOf a) d -> IO ()\nsetCOI chnl image = withMutableImage image $ \\i ->\n {#call cvSetImageCOI#} i (fromIntegral . (+1) . fromEnum $ chnl) \n -- CV numbers channels starting from 1. 0 means all channels\n\nresetCOI :: MutableImage a d -> IO ()\nresetCOI image = withMutableImage image $ \\i ->\n {#call cvSetImageCOI#} i 0\n\n\ngetChannel :: (Enum a) => a -> Image (ChannelOf a) d -> Image GrayScale d\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n mut <- toMutable image\n setCOI no mut\n cres <- {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\n withMutableImage mut $ \\cimage ->\n {#call cvCopy#} cimage (castPtr cres) (nullPtr)\n resetCOI mut\n return cres\n\nwithIOROI :: (Int,Int) -> (Int,Int) -> MutableImage c d -> IO a -> IO a\nwithIOROI pos size image op = do\n setROI pos size image\n x <- op\n resetROI image\n return x\n\n--withROI :: (Int, Int) -> (Int, Int) -> Image c d -> (MutableImage c d -> a) -> a\n--withROI pos size image op = unsafePerformIO $ do\n-- setROI pos size image\n-- let x = op image -- BUG\n-- resetROI image\n-- return x\n\nclass SetPixel a where\n type SP a :: *\n setPixel :: (Int,Int) -> SP a -> a -> IO ()\n\ninstance SetPixel (MutableImage GrayScale D32) where\n type SP (MutableImage GrayScale D32) = D32\n {-#INLINE setPixel#-}\n setPixel (x,y) v (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Float))):: Ptr Float)\n v\n\ninstance SetPixel (MutableImage GrayScale D8) where\n type SP (MutableImage GrayScale D8) = D8\n {-#INLINE setPixel#-}\n setPixel (x,y) v (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Word8))):: Ptr Word8)\n v\n\ninstance SetPixel (MutableImage RGB D8) where\n type SP (MutableImage RGB D8) = (D8,D8,D8)\n {-#INLINE setPixel#-}\n setPixel (x,y) (r,g,b) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n poke (castPtr (d`plusPtr` (y*cs +x*3*fs))) b\n poke (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs))) g\n poke (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs))) r\n\ninstance SetPixel (MutableImage RGB D32) where\n type SP (MutableImage RGB D32) = (D32,D32,D32)\n {-#INLINE setPixel#-}\n setPixel (x,y) (r,g,b) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs +x*3*fs))) b\n poke (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs))) g\n poke (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs))) r\n\ninstance SetPixel (MutableImage Complex D32) where\n type SP (MutableImage Complex D32) = C.Complex D32\n {-#INLINE setPixel#-}\n setPixel (x,y) (re C.:+ im) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs + x*2*fs))) re\n poke (castPtr (d`plusPtr` (y*cs + (x*2+1)*fs))) im\n\n\n\ngetAllPixels image = [getPixel (i,j) image\n | i <- [0..width-1 ]\n , j <- [0..height-1]]\n where\n (width,height) = getSize image\n\ngetAllPixelsRowMajor image = [getPixel (i,j) image\n | j <- [0..height-1]\n , i <- [0..width-1]\n ]\n where\n (width,height) = getSize image\n\n-- |Create a montage form given images (u,v) determines the layout and space the spacing\n-- between images. Images are assumed to be the same size (determined by the first image)\nmontage :: (Blittable c d) => (CreateImage (MutableImage c d)) => (Int,Int) -> Int -> [Image c d] -> Image c d\nmontage (u',v') space' imgs\n | u'*v' < (length imgs) = error (\"Montage mismatch: \"++show (u,v, length imgs))\n | otherwise = resultPic\n where\n space = fromIntegral space'\n (u,v) = (fromIntegral u', fromIntegral v')\n (rw,rh) = (u*xstep,v*ystep)\n (w,h) = foldl (\\(mx,my) (x,y) -> (max mx x, max my y)) (0,0) $ map getSize imgs\n (xstep,ystep) = (fromIntegral space + w,fromIntegral space + h)\n edge = space`div`2\n resultPic = unsafePerformIO $ do\n r <- create (rw,rh)\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep)\n | y <- [0..v-1] , x <- [0..u-1]\n | i <- imgs ]\n let (Mutable i) = r \n i `seq` return i\n\ndata CvException = CvException Int String String String Int\n deriving (Show, Typeable)\n\ndata CvIOError = CvIOError String deriving (Show,Typeable)\ndata CvSizeError = CvSizeError String deriving (Show,Typeable)\n\ninstance Exception CvException\ninstance Exception CvIOError\ninstance Exception CvSizeError\n\nsetCatch = do\n let catch i cstr1 cstr2 cstr3 j = do\n func <- peekCString cstr1\n msg <- peekCString cstr2\n file <- peekCString cstr3\n throw (CvException (fromIntegral i) func msg file (fromIntegral j))\n return 0\n cb <- mk'CvErrorCallback catch\n c'cvRedirectError cb nullPtr nullPtr\n c'cvSetErrMode c'CV_ErrModeSilent\n\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns,ParallelListComp, FlexibleInstances, FlexibleContexts, TypeFamilies, EmptyDataDecls, ScopedTypeVariables, StandaloneDeriving, DeriveDataTypeable, UndecidableInstances, MultiParamTypeClasses #-}\n#include \"cvWrapLEO.h\"\nmodule CV.Image (\n-- * Basic types\n Image(..)\n, MutableImage(..)\n, Mask\n, create\n, createWith\n, empty\n, toMutable\n, fromMutable\n, emptyCopy\n, emptyCopy'\n, cloneImage\n, withClone\n, withMask\n, withMutableClone\n, withCloneValue\n, CreateImage\n, Save(..)\n\n-- * Colour spaces\n, ChannelOf\n, GrayScale\n, Complex\n, BGR\n, RGB\n, RGBA\n, RGB_Channel(..)\n, LAB\n, LAB_Channel(..)\n, D32\n, D64\n, D8\n, Tag\n, lab\n, rgba\n, rgb\n, compose\n, composeMultichannelImage\n\n-- * IO operations\n, Loadable(..)\n, saveImage\n, loadColorImage\n, loadImage\n\n-- * Pixel level access\n, GetPixel(..)\n, SetPixel(..)\n, safeGetPixel\n, getAllPixels\n, getAllPixelsRowMajor\n, mapImageInplace\n\n-- * Image information\n, ImageDepth\n, Sized(..)\n, biggerThan\n, getArea\n, getChannel\n, getImageChannels\n, getImageDepth\n, getImageInfo\n\n-- * ROI's, COI's and subregions\n, setCOI\n, setROI\n, resetROI\n, getRegion\n, withIOROI\n--, withROI\n\n-- * Blitting\n, blendBlit\n, blit\n, blitM\n, subPixelBlit\n, safeBlit\n, montage\n, tileImages\n\n-- * Conversions\n, convertTo\n, rgbToGray\n, rgbToGray8\n, grayToRGB\n, rgbToLab\n, bgrToRgb\n, rgbToBgr\n, cloneTo64F\n, unsafeImageTo32F \n, unsafeImageTo64F \n, unsafeImageTo8Bit \n\n-- * Low level access operations\n, BareImage(..)\n, creatingImage\n, unImage\n, unS\n, withGenBareImage\n, withBareImage\n, creatingBareImage\n, withGenImage\n, withImage\n, withMutableImage\n, withRawImageData\n, imageFPTR\n, ensure32F\n\n-- * Extended error handling\n, setCatch\n, CvException\n, CvSizeError(..)\n, CvIOError(..)\n) where\n\nimport System.Mem\nimport System.Directory\nimport System.FilePath\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Utils\nimport Foreign.ForeignPtr hiding (newForeignPtr,unsafeForeignPtrToPtr)\nimport Foreign.Concurrent\nimport Foreign.Ptr\nimport Control.Parallel.Strategies\nimport Control.DeepSeq\nimport Control.Lens\n\nimport CV.Bindings.Error\n\nimport Data.Maybe(catMaybes)\nimport Data.List(genericLength)\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr)\nimport Foreign.Storable\nimport System.IO.Unsafe\nimport Data.Word\nimport qualified Data.Complex as C\nimport Control.Monad\nimport Control.Exception\nimport Data.Data\nimport Data.Typeable\n\nimport Utils.GeometryClass\nimport Control.Applicative hiding (empty)\n\n\n\n\n-- Colorspaces\n\n-- | Single channel grayscale image\ndata GrayScale\ndata Complex\ndata RGB\ndata RGB_Channel = Red |\u00a0Green |\u00a0Blue deriving (Eq,Ord,Enum)\n\ndata BGR\n\ndata LAB\ndata YUV\ndata RGBA\ndata LAB_Channel = LAB_L |\u00a0LAB_A |\u00a0LAB_B deriving (Eq,Ord,Enum)\ndata YUV_Channel = YUV_Y |\u00a0YUV_U |\u00a0YUV_V deriving (Eq,Ord,Enum)\n\n-- | Type family for expressing which channels a colorspace contains. This needs to be fixed wrt. the BGR color space.\ntype family ChannelOf a :: *\ntype instance ChannelOf RGB_Channel = RGB\ntype instance ChannelOf LAB_Channel = LAB\ntype instance ChannelOf YUV_Channel = YUV\n\n-- Bit Depths\ntype D8 = Word8\ntype D32 = Float\ntype D64 = Double\n\n-- | The type for Images\nnewtype Image channels depth = S BareImage\nnewtype MutableImage channels depth = Mutable (Image channels depth)\n\n-- | Alias for images used as masks\ntype Mask = Maybe (Image GrayScale D8)\n\n-- |\u00a0Remove typing info from an image\nunS (S i) = i -- Unsafe and ugly\n\nimageFPTR :: Image c d -> ForeignPtr BareImage\nimageFPTR (S (BareImage fptr)) = fptr\n\nwithImage :: Image c d -> (Ptr BareImage ->IO a) -> IO a\nwithImage (S i) op = withBareImage i op\n--withGenNewImage (S i) op = withGenImage i op\n\nwithRawImageData :: Image c d -> (Int -> Ptr Word8 -> IO a) -> IO a\nwithRawImageData (S i) op = withBareImage i $ \\pp-> do\n d <- {#get IplImage->imageData#} pp \n wd <- {#get IplImage->widthStep#} pp\n op (fromIntegral wd) (castPtr d)\n\n-- Ok. this is just the example why I need image types\nwithUniPtr with x fun = with x $ \\y ->\n fun (castPtr y)\n\nwithGenImage :: Image c d -> (Ptr b -> IO a) -> IO a\nwithGenImage = withUniPtr withImage\n\n-- |\u00a0This function converts masks to pointers. Masks which are nothing are converted\n-- to null pointers.\nwithMask :: Mask -> (Ptr b -> IO a) -> IO a\nwithMask (Just i) op = withUniPtr withImage i op\nwithMask Nothing op = op nullPtr\n\nwithMutableImage :: MutableImage c d -> (Ptr b -> IO a) -> IO a\nwithMutableImage (Mutable i) o = withGenImage i o\n\nwithGenBareImage :: BareImage -> (Ptr b -> IO a) -> IO a\nwithGenBareImage = withUniPtr withBareImage\n\n{#pointer *IplImage as BareImage foreign newtype#}\n\nfreeBareImage ptr = with ptr {#call cvReleaseImage#}\n\n--foreign import ccall \"& wrapReleaseImage\" releaseImage :: FinalizerPtr BareImage\n\ninstance NFData (Image a b) where\n rnf a@(S (BareImage fptr)) = (unsafeForeignPtrToPtr) fptr `seq` a `seq` ()-- This might also need peek?\n\n\ncreatingImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . S . BareImage $ fptr\n\ncreatingBareImage fun = do\n iptr <- fun\n-- {#call incrImageC#} -- Uncomment this line to get statistics of number of images allocated by ghc\n fptr <- newForeignPtr iptr (freeBareImage iptr)\n return . BareImage $ fptr\n\nunImage (S (BareImage fptr)) = fptr\n\ndata Tag tp;\nrgb = undefined :: Tag RGB\nrgba = undefined :: Tag RGBA\nlab = undefined :: Tag LAB\n\n-- | Typeclass for elements that are build from component elements. For example,\n-- RGB images can be constructed from three grayscale images.\nclass Composes a where\n type Source a :: *\n compose :: Source a -> a\n\ninstance (CreateImage (Image RGBA a)) => Composes (Image RGBA a) where\n type Source (Image RGBA a) = (Image GrayScale a, Image GrayScale a\n ,Image GrayScale a, Image GrayScale a)\n compose (r,g,b,a) = composeMultichannelImage (Just b) (Just g) (Just r) (Just a) rgba\n\ninstance (CreateImage (Image RGB a)) => Composes (Image RGB a) where\n type Source (Image RGB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (r,g,b) = composeMultichannelImage (Just b) (Just g) (Just r) Nothing rgb\n\ninstance (CreateImage (Image LAB a)) => Composes (Image LAB a) where\n type Source (Image LAB a) = (Image GrayScale a, Image GrayScale a, Image GrayScale a)\n compose (l,a,b) = composeMultichannelImage (Just l) (Just a) (Just b) Nothing lab\n\n{-# DEPRECATED composeMultichannelImage \"This is unsafe. Use compose instead\" #-}\ncomposeMultichannelImage :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannelImage = composeMultichannel\n\ncomposeMultichannel :: (CreateImage (Image tp a)) => Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Maybe (Image GrayScale a) -> Tag tp -> Image tp a\ncomposeMultichannel (c2)\n (c1)\n (c3)\n (c4)\n totag\n = unsafePerformIO $\u00a0do\n res <- create (size) -- TODO: Check channel count -- This is NOT correct\n withMaybe c1 $ \\cc1 ->\n withMaybe c2 $ \\cc2 ->\n withMaybe c3 $ \\cc3 ->\n withMaybe c4 $ \\cc4 ->\n withGenImage res $ \\cres -> {#call cvMerge#} cc1 cc2 cc3 cc4 cres\n return res\n where\n withMaybe (Just i) op = withGenImage i op\n withMaybe (Nothing) op = op nullPtr\n size = getSize . head . catMaybes $ [c1,c2,c3,c4]\n\n\n-- | Typeclass for CV items that can be read from file. Mainly images at this point.\nclass Loadable a where\n readFromFile :: FilePath -> IO a\n\n\ninstance Loadable ((Image GrayScale D32)) where\n readFromFile fp = do\n e <- loadImage fp\n case e of\n Just i -> return i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D32)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ unsafeImageTo32F $ bgrToRgb i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image RGB D8)) where\n readFromFile fp = do\n e <- loadColorImage8 fp\n case e of\n Just i -> return $ bgrToRgb i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\ninstance Loadable ((Image GrayScale D8)) where\n readFromFile fp = do\n e <- loadImage8 fp\n case e of\n Just i -> return i\n Nothing -> throw $ CvIOError $ \"Could not load \"++fp\n\n\n-- | This function loads and converts image to an arbitrary format. Notice that it is\n-- polymorphic enough to cause run time errors if the declared and actual types of the\n-- images do not match. Use with care.\nunsafeloadUsing x p n = do\n exists <- doesFileExist n\n if not exists then return Nothing\n else do\n i <- withCString n $ \\name ->\n creatingBareImage ({#call cvLoadImage #} name p)\n bw <- x i\n return . Just .\u00a0S $ bw\n\nloadImage :: FilePath -> IO (Maybe (Image GrayScale D32))\nloadImage = unsafeloadUsing imageTo32F 0\nloadImage8 :: FilePath -> IO (Maybe (Image GrayScale D8))\nloadImage8 = unsafeloadUsing imageTo8Bit 0\nloadColorImage :: FilePath -> IO (Maybe (Image BGR D32))\nloadColorImage = unsafeloadUsing imageTo32F 1\nloadColorImage8 :: FilePath -> IO (Maybe (Image BGR D8))\nloadColorImage8 = unsafeloadUsing imageTo8Bit 1\n\n\ninstance Sized (MutableImage a b) where\n type Size (MutableImage a b) = IO (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize (Mutable i) = evaluate (deep (getSize i))\n\ndeep a = a `deepseq` a\n\ninstance Sized BareImage where\n type Size BareImage = (Int,Int)\n -- getSize :: (Integral a, Integral b) => Image c d -> (a,b)\n getSize image = unsafePerformIO $ withBareImage image $ \\i -> do\n w <- {#call getImageWidth#} i\n h <- {#call getImageHeight#} i\n return (fromIntegral w,fromIntegral h)\n\ninstance Sized (Image c d) where\n type Size (Image c d) = (Int,Int)\n getSize = getSize . unS\n\n\n#c\nenum CvtFlags {\n CvtFlip = CV_CVTIMG_FLIP,\n CvtSwapRB = CV_CVTIMG_SWAP_RB\n };\n#endc\n\n#c\nenum CvtCodes {\n BGR2BGRA =0,\n RGB2RGBA =BGR2BGRA,\n\n BGRA2BGR =1,\n RGBA2RGB =BGRA2BGR,\n\n BGR2RGBA =2,\n RGB2BGRA =BGR2RGBA,\n\n RGBA2BGR =3,\n BGRA2RGB =RGBA2BGR,\n\n BGR2RGB =4,\n RGB2BGR =BGR2RGB,\n\n BGRA2RGBA =5,\n RGBA2BGRA =BGRA2RGBA,\n\n BGR2GRAY =6,\n RGB2GRAY =7,\n GRAY2BGR =8,\n GRAY2RGB =GRAY2BGR,\n GRAY2BGRA =9,\n GRAY2RGBA =GRAY2BGRA,\n BGRA2GRAY =10,\n RGBA2GRAY =11,\n\n BGR2BGR565 =12,\n RGB2BGR565 =13,\n BGR5652BGR =14,\n BGR5652RGB =15,\n BGRA2BGR565 =16,\n RGBA2BGR565 =17,\n BGR5652BGRA =18,\n BGR5652RGBA =19,\n\n GRAY2BGR565 =20,\n BGR5652GRAY =21,\n\n BGR2BGR555 =22,\n RGB2BGR555 =23,\n BGR5552BGR =24,\n BGR5552RGB =25,\n BGRA2BGR555 =26,\n RGBA2BGR555 =27,\n BGR5552BGRA =28,\n BGR5552RGBA =29,\n\n GRAY2BGR555 =30,\n BGR5552GRAY =31,\n\n BGR2XYZ =32,\n RGB2XYZ =33,\n XYZ2BGR =34,\n XYZ2RGB =35,\n\n BGR2YCrCb =36,\n RGB2YCrCb =37,\n YCrCb2BGR =38,\n YCrCb2RGB =39,\n\n BGR2HSV =40,\n RGB2HSV =41,\n\n BGR2Lab =44,\n RGB2Lab =45,\n\n BayerBG2BGR =46,\n BayerGB2BGR =47,\n BayerRG2BGR =48,\n BayerGR2BGR =49,\n\n BayerBG2RGB =BayerRG2BGR,\n BayerGB2RGB =BayerGR2BGR,\n BayerRG2RGB =BayerBG2BGR,\n BayerGR2RGB =BayerGB2BGR,\n\n BGR2Luv =50,\n RGB2Luv =51,\n BGR2HLS =52,\n RGB2HLS =53,\n\n HSV2BGR =54,\n HSV2RGB =55,\n\n Lab2BGR =56,\n Lab2RGB =57,\n Luv2BGR =58,\n Luv2RGB =59,\n HLS2BGR =60,\n HLS2RGB =61,\n\n BayerBG2BGR_VNG =62,\n BayerGB2BGR_VNG =63,\n BayerRG2BGR_VNG =64,\n BayerGR2BGR_VNG =65,\n\n BayerBG2RGB_VNG =BayerRG2BGR_VNG,\n BayerGB2RGB_VNG =BayerGR2BGR_VNG,\n BayerRG2RGB_VNG =BayerBG2BGR_VNG,\n BayerGR2RGB_VNG =BayerGB2BGR_VNG,\n\n BGR2HSV_FULL = 66,\n RGB2HSV_FULL = 67,\n BGR2HLS_FULL = 68,\n RGB2HLS_FULL = 69,\n\n HSV2BGR_FULL = 70,\n HSV2RGB_FULL = 71,\n HLS2BGR_FULL = 72,\n HLS2RGB_FULL = 73,\n\n LBGR2Lab = 74,\n LRGB2Lab = 75,\n LBGR2Luv = 76,\n LRGB2Luv = 77,\n\n Lab2LBGR = 78,\n Lab2LRGB = 79,\n Luv2LBGR = 80,\n Luv2LRGB = 81,\n\n BGR2YUV = 82,\n RGB2YUV = 83,\n YUV2BGR = 84,\n YUV2RGB = 85,\n\n COLORCVT_MAX =100\n};\n#endc\n\n{#enum CvtCodes {}#}\n\n{#enum CvtFlags {}#}\n\nrgbToLab :: Image RGB D32 -> Image LAB D32\nrgbToLab = S . convertTo RGB2Lab 3 . unS\n\nrgbToYUV :: Image RGB D32 -> Image YUV D32\nrgbToYUV = S . convertTo RGB2YUV 3 . unS\n\nrgbToGray :: Image RGB D32 -> Image GrayScale D32\nrgbToGray = S . convertTo RGB2GRAY 1 . unS\n\nrgbToGray8 :: Image RGB D8 -> Image GrayScale D8\nrgbToGray8 = S . convert8UTo RGB2GRAY 1 . unS\n\ngrayToRGB :: Image GrayScale D32 -> Image RGB D32\ngrayToRGB = S . convertTo GRAY2BGR 3 . unS\n\nbgrToRgb :: Image BGR D8 -> Image RGB D8\nbgrToRgb = S . swapRB . unS\n\nrgbToBgr :: Image RGB D8 -> Image BGR D8\nrgbToBgr = S . swapRB . unS\n\nswapRB :: BareImage -> BareImage\nswapRB img = unsafePerformIO $ do\n res <- cloneBareImage img\n withBareImage img $ \\cimg ->\n withBareImage res $ \\cres ->\n {#call cvConvertImage#} (castPtr cimg) (castPtr cres) (fromIntegral . fromEnum $ CvtSwapRB)\n return res\n\n\nsafeGetPixel :: (Sized image, Size image ~ (Int,Int), GetPixel image) => (P image) -> (Int,Int) -> image -> P image\nsafeGetPixel def (x,y) i |\u00a0x<0 || x>= w || y<0 || y>=h = def\n | otherwise = getPixel (x,y) i\n where\n (w,h) = getSize i\n -- (x',y') = (clamp (0,w-1) x, clamp (0,h-1) y)\n\nclamp :: Ord a => (a, a) -> a -> a\nclamp (a,b) x = max a (min b x)\n\ninstance (NFData (P (Image a b)), GetPixel (Image a b)) => GetPixel (MutableImage a b) where\n type P (MutableImage a b) = IO (P (Image a b))\n getPixel xy (Mutable i) = let p = getPixel xy i\n in p `deepseq` return p\n\nclass GetPixel a where\n type P a :: *\n getPixel :: (Int,Int) -> a -> P a\n\n-- #define FGET(img,x,y) (((float *)((img)->imageData + (y)*(img)->widthStep))[(x)])\ninstance GetPixel (Image GrayScale D32) where\n type P (Image GrayScale D32) = D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Float))):: Ptr Float)\n\ninstance GetPixel (Image GrayScale D8) where\n type P (Image GrayScale D8) = D8\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n peek (castPtr (d`plusPtr` (y*(fromIntegral s) +x*sizeOf (0::Word8))):: Ptr Word8)\n\ninstance GetPixel (Image Complex D32) where\n type P (Image Complex D32) = C.Complex D32\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n re <- peek (castPtr (d`plusPtr` (y*cs + x*2*fs)))\n im <- peek (castPtr (d`plusPtr` (y*cs +(x*2+1)*fs)))\n return (re C.:+ im)\n\n-- #define UGETC(img,color,x,y) (((uint8_t *)((img)->imageData + (y)*(img)->widthStep))[(x)*3+(color)])\ninstance GetPixel (Image RGB D32) where\n type P (Image RGB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\ninstance GetPixel (Image BGR D32) where\n type P (Image BGR D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\ninstance GetPixel (Image BGR D8) where\n type P (Image BGR D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image RGB D8) where\n type P (Image RGB D8) = (D8,D8,D8)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n b <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n g <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n r <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (r,g,b)\n\ninstance GetPixel (Image LAB D32) where\n type P (Image LAB D32) = (D32,D32,D32)\n {-#INLINE getPixel#-}\n getPixel (x,y) i = unsafePerformIO $\n withGenImage i $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n l <- peek (castPtr (d`plusPtr` (y*cs +x*3*fs)))\n a <- peek (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs)))\n b <- peek (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs)))\n return (l,a,b)\n\n-- | Perform (a destructive) inplace map of the image. This should be wrapped inside\n-- withClone or an image operation\nmapImageInplace :: (P (Image GrayScale D32) -> P (Image GrayScale D32))\n -> MutableImage GrayScale D32\n -> IO ()\nmapImageInplace f image = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n (w,h) <- getSize image\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n forM_ [(x,y) | x<-[0..w-1], y <- [0..h-1]] $ \\(x,y) ->\u00a0do\n v <- peek (castPtr (d `plusPtr` (y*cs+x*fs)))\n poke (castPtr (d `plusPtr` (y*cs+x*fs))) (f v)\n\n\n\nconvert8UTo :: CvtCodes -> CInt -> BareImage -> BareImage\nconvert8UTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage8U#} w h channels\n withBareImage img $ \\cimg ->\n {#call cvCvtColor#} (castPtr cimg) (castPtr res) (fromIntegral . fromEnum $ code)\n return res\n where\n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\nconvertTo :: CvtCodes -> CInt -> BareImage -> BareImage\nconvertTo code channels img = unsafePerformIO $\u00a0creatingBareImage $ do\n res <- {#call wrapCreateImage32F#} w h channels\n withBareImage img $ \\cimg ->\n {#call cvCvtColor#} (castPtr cimg) (castPtr res) (fromIntegral . fromEnum $ code)\n return res\n where\n (fromIntegral -> w,fromIntegral -> h) = getSize img\n\n-- |\u00a0Class for images that exist.\nclass CreateImage a where\n -- | Create an image from size\n create :: (Int,Int) -> IO a\n\ncreateWith :: CreateImage (Image c d) => (Int,Int) -> (MutableImage c d -> IO (MutableImage c d)) -> IO (Image c d)\ncreateWith s f = do\n c <- create s\n Mutable r <- f (Mutable c)\n return r\n\n\n\n\ninstance CreateImage (Image GrayScale D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image Complex D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 2\ninstance CreateImage (Image LAB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D32) where\n create (w,h) = creatingImage $ {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D64) where\n create (w,h) = creatingImage $ {#call wrapCreateImage64F#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image GrayScale D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 1\ninstance CreateImage (Image LAB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGB D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 3\ninstance CreateImage (Image RGBA D8) where\n create (w,h) = creatingImage $ {#call wrapCreateImage8U#} (fromIntegral w) (fromIntegral h) 4\n\ninstance CreateImage (Image c d) => CreateImage (MutableImage c d) where\n create s = Mutable <$> create s\n\n\n-- | Allocate a new empty image\nempty :: (CreateImage (Image a b)) => (Int,Int) -> (Image a b)\nempty size = unsafePerformIO $ create size\n\n-- |\u00a0Allocate a new image that of the same size and type as the exemplar image given.\nemptyCopy :: (CreateImage (Image a b)) => Image a b -> (Image a b)\nemptyCopy img = unsafePerformIO $ create (getSize img)\n\nemptyCopy' :: (CreateImage (Image a b)) => Image a b -> IO (Image a b)\nemptyCopy' img = create (getSize img)\n\n-- | Save image. This will convert the image to 8 bit one before saving\nclass Save a where\n save :: FilePath -> a -> IO ()\n\ninstance Save (Image BGR D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image)\n\ninstance Save (Image RGB D32) where\n save filename image = primitiveSave filename (swapRB . unS . unsafeImageTo8Bit $ image)\n\ninstance Save (Image RGB D8) where\n save filename image = primitiveSave filename (swapRB . unS $ image)\n\ninstance Save (Image GrayScale D8) where\n save filename image = primitiveSave filename (unS $ image)\n\ninstance Save (Image GrayScale D32) where\n save filename image = primitiveSave filename (unS . unsafeImageTo8Bit $ image)\n\nprimitiveSave :: FilePath -> BareImage -> IO ()\nprimitiveSave filename fpi = do\n exists <- doesDirectoryExist (takeDirectory filename)\n when (not exists) $\u00a0throw (CvIOError $ \"Directory does not exist: \" ++ (takeDirectory filename))\n withCString filename $ \\name ->\n withGenBareImage fpi $ \\cvArr ->\n alloca (\\defs -> poke defs 0 >> {#call cvSaveImage #} name cvArr defs >> return ())\n\n-- |Save an image as 8 bit gray scale\nsaveImage :: (Save (Image c d)) => FilePath -> Image c d -> IO ()\nsaveImage = save\n\ngetArea :: (Sized a,Num b, Size a ~ (b,b)) => a -> b\ngetArea = uncurry (*).getSize\n\ngetRegion :: (Int,Int) -> (Int,Int) -> Image c d -> Image c d\ngetRegion (fromIntegral -> x,fromIntegral -> y) (fromIntegral -> w,fromIntegral -> h) image\n | x+w <= width && y+h <= height = S . getRegion' (x,y) (w,h) $ unS image\n | otherwise = error $ \"Region outside image:\"\n ++ show (getSize image) ++\n \"\/\"++show (x+w,y+h)\n where\n (fromIntegral -> width,fromIntegral -> height) = getSize image\n\ngetRegion' (x,y) (w,h) image = unsafePerformIO $\n withBareImage image $ \\i ->\n creatingBareImage ({#call getSubImage#}\n i x y w h)\n\n\n-- | Tile images by overlapping them on a black canvas.\ntileImages image1 image2 (x,y) = unsafePerformIO $\n withImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n creatingImage ({#call simpleMergeImages#}\n i1 i2 x y)\n-- | Blit image2 onto image1.\nclass Blittable channels depth \ninstance Blittable GrayScale D32\ninstance Blittable RGB D32\n\nblit :: Blittable c d => MutableImage c d -> Image c d -> (Int,Int) -> IO ()\nblit image1 image2 (x,y) = do\n (w1,h1) <- getSize image1\n let ((w2,h2)) = getSize image2\n if x+w2>w1 || y+h2>h1 || x<0 || y<0\n then error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n else withMutableImage image1 $ \\i1 ->\n withImage image2 $ \\i2 -> \n ({#call plainBlit#} i1 i2 (fromIntegral y) (fromIntegral x))\n\n-- | Create an image by blitting multiple images onto an empty image.\nblitM :: (CreateImage (MutableImage GrayScale D32)) => \n (Int,Int) -> [((Int,Int),Image GrayScale D32)] -> Image GrayScale D32\nblitM (rw,rh) imgs = unsafePerformIO $ resultPic >>= fromMutable \n where\n resultPic = do\n r <- create (fromIntegral rw,fromIntegral rh)\n sequence_ [blit r i (fromIntegral x, fromIntegral y)\n | ((x,y),i) <- imgs ]\n return r\n\n\nsubPixelBlit :: MutableImage c d -> Image c d -> (CDouble, CDouble) -> IO ()\nsubPixelBlit (image1) (image2) (x,y) = do\n (w1,h1) <- getSize image1\n let ((w2,h2)) = getSize image2\n if ceiling x+w2>w1 || ceiling y+h2>h1 ||\u00a0x<0 || y<0\n then error $ \"Bad blit sizes: \" ++ show [(w1,h1),(w2,h2)]++\"<-\"++show (x,y)\n else withMutableImage image1 $ \\i1 ->\n withImage image2 $ \\i2 ->\n ({#call subpixel_blit#} i1 i2 y x)\n\nsafeBlit i1 i2 (x,y) = unsafePerformIO $ do\n res <- toMutable i1-- createImage32F (getSize i1) 1\n blit res i2 (x,y)\n return res\n\n-- | Blit image2 onto image1.\n-- This uses an alpha channel bitmap for determining the regions where the image should be \"blended\" with\n-- the base image.\nblendBlit :: MutableImage c d -> Image c1 d1 -> Image c3 d3 -> Image c2 d2\n -> (CInt, CInt) -> IO ()\nblendBlit image1 image1Alpha image2 image2Alpha (x,y) =\n withMutableImage image1 $ \\i1 ->\n withImage image1Alpha $ \\i1a ->\n withImage image2Alpha $ \\i2a ->\n withImage image2 $ \\i2 ->\n ({#call alphaBlit#} i1 i1a i2 i2a y x)\n\n\n-- | Create a copy of an image\ncloneImage :: Image a b -> IO (Image a b)\ncloneImage img = withGenImage img $ \\image ->\n creatingImage ({#call cvCloneImage #} image)\n\ntoMutable :: Image a b -> IO (MutableImage a b)\ntoMutable img = withGenImage img $ \\image ->\n Mutable <$>\u00a0creatingImage ({#call cvCloneImage #} image)\n\nfromMutable :: MutableImage a b -> IO (Image a b)\nfromMutable (Mutable img) = cloneImage img \n\n-- | Create a copy of a non-types image\ncloneBareImage :: BareImage -> IO BareImage\ncloneBareImage img = withGenBareImage img $ \\image ->\n creatingBareImage ({#call cvCloneImage #} image)\n\nwithMutableClone\n :: Image channels depth\n -> (MutableImage channels depth -> IO a)\n -> IO a\nwithMutableClone img fun = do\n result <- toMutable img\n fun result\n\nwithClone\n :: Image channels depth\n -> (Image channels depth -> IO ())\n -> IO (Image channels depth)\nwithClone img fun = do\n result <- cloneImage img\n fun result\n return result\n\nwithCloneValue\n :: Image channels depth\n -> (Image channels depth -> IO a)\n -> IO a\nwithCloneValue img fun = do\n result <- cloneImage img\n r <- fun result\n return r\n\ncloneTo64F :: Image c d -> IO (Image c D64)\ncloneTo64F img = withGenImage img $ \\image ->\n creatingImage\n ({#call ensure64F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 64 bit, floating point, image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image. \nunsafeImageTo64F :: Image c d -> Image c D64\nunsafeImageTo64F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure64F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 32 bit, floating point, image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image. \nunsafeImageTo32F :: Image c d -> Image c D32\nunsafeImageTo32F img = unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage\n ({#call ensure32F #} image)\n\n-- | Convert an image to from arbitrary bit depth into 8 bit image.\n-- This conversion does preserve the color space.\n-- Note: this function is named unsafe because it will lose information\n-- from the image. \nunsafeImageTo8Bit :: Image cspace a -> Image cspace D8\nunsafeImageTo8Bit img =\n unsafePerformIO $ withGenImage img $ \\image ->\n creatingImage ({#call ensure8U #} image)\n\n--toD32 :: Image c d -> Image c D32\n--toD32 i =\n-- unsafePerformIO $\n-- withImage i $ \\i_ptr ->\n-- creatingImage\n\n\nimageTo32F img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure32F #} image)\n\nimageTo8Bit img = withGenBareImage img $ \\image ->\n creatingBareImage\n ({#call ensure8U #} image)\n#c\nenum ImageDepth {\n Depth32F = IPL_DEPTH_32F,\n Depth64F = IPL_DEPTH_64F,\n Depth8U = IPL_DEPTH_8U,\n Depth8S = IPL_DEPTH_8S,\n Depth16U = IPL_DEPTH_16U,\n Depth16S = IPL_DEPTH_16S,\n Depth32S = IPL_DEPTH_32S\n };\n#endc\n\n{#enum ImageDepth {}#}\n\nderiving instance Show ImageDepth\n\ngetImageDepth :: Image c d -> IO ImageDepth\ngetImageDepth i = withImage i $ \\c_img -> {#get IplImage->depth #} c_img >>= return.toEnum.fromIntegral\ngetImageChannels i = withImage i $ \\c_img -> {#get IplImage->nChannels #} c_img\n\ngetImageInfo x = do\n let s = getSize x\n d <- getImageDepth x\n c <- getImageChannels x\n return (s,d,c)\n\n\n-- | Set the region of interest for a mutable image\nsetROI :: (Integral a) => (a,a) -> (a,a) -> MutableImage c d -> IO ()\nsetROI (fromIntegral -> x,fromIntegral -> y)\n (fromIntegral -> w,fromIntegral -> h)\n image = withMutableImage image $ \\i ->\n {#call wrapSetImageROI#} i x y w h\n\n-- | Set the region of interest to cover the entire image.\nresetROI :: MutableImage c d -> IO ()\nresetROI image = withMutableImage image $ \\i ->\n {#call cvResetImageROI#} i\n\nsetCOI :: (Enum a) => a -> MutableImage (ChannelOf a) d -> IO ()\nsetCOI chnl image = withMutableImage image $ \\i ->\n {#call cvSetImageCOI#} i (fromIntegral . (+1) . fromEnum $ chnl) \n -- CV numbers channels starting from 1. 0 means all channels\n\nresetCOI :: MutableImage a d -> IO ()\nresetCOI image = withMutableImage image $ \\i ->\n {#call cvSetImageCOI#} i 0\n\n\ngetChannel :: (Enum a) => a -> Image (ChannelOf a) d -> Image GrayScale d\ngetChannel no image = unsafePerformIO $ creatingImage $ do\n let (w,h) = getSize image\n mut <- toMutable image\n setCOI no mut\n cres <- {#call wrapCreateImage32F#} (fromIntegral w) (fromIntegral h) 1\n withMutableImage mut $ \\cimage ->\n {#call cvCopy#} cimage (castPtr cres) (nullPtr)\n resetCOI mut\n return cres\n\nwithIOROI :: (Int,Int) -> (Int,Int) -> MutableImage c d -> IO a -> IO a\nwithIOROI pos size image op = do\n setROI pos size image\n x <- op\n resetROI image\n return x\n\n--withROI :: (Int, Int) -> (Int, Int) -> Image c d -> (MutableImage c d -> a) -> a\n--withROI pos size image op = unsafePerformIO $ do\n-- setROI pos size image\n-- let x = op image -- BUG\n-- resetROI image\n-- return x\n\nclass SetPixel a where\n type SP a :: *\n setPixel :: (Int,Int) -> SP a -> a -> IO ()\n\ninstance SetPixel (MutableImage GrayScale D32) where\n type SP (MutableImage GrayScale D32) = D32\n {-#INLINE setPixel#-}\n setPixel (x,y) v (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Float))):: Ptr Float)\n v\n\ninstance SetPixel (MutableImage GrayScale D8) where\n type SP (MutableImage GrayScale D8) = D8\n {-#INLINE setPixel#-}\n setPixel (x,y) v (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n poke (castPtr (d`plusPtr` (y*(fromIntegral s)\n + x*sizeOf (0::Word8))):: Ptr Word8)\n v\n\ninstance SetPixel (MutableImage RGB D8) where\n type SP (MutableImage RGB D8) = (D8,D8,D8)\n {-#INLINE setPixel#-}\n setPixel (x,y) (r,g,b) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: D8)\n poke (castPtr (d`plusPtr` (y*cs +x*3*fs))) b\n poke (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs))) g\n poke (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs))) r\n\ninstance SetPixel (MutableImage RGB D32) where\n type SP (MutableImage RGB D32) = (D32,D32,D32)\n {-#INLINE setPixel#-}\n setPixel (x,y) (r,g,b) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs +x*3*fs))) b\n poke (castPtr (d`plusPtr` (y*cs +(x*3+1)*fs))) g\n poke (castPtr (d`plusPtr` (y*cs +(x*3+2)*fs))) r\n\ninstance SetPixel (MutableImage Complex D32) where\n type SP (MutableImage Complex D32) = C.Complex D32\n {-#INLINE setPixel#-}\n setPixel (x,y) (re C.:+ im) (image) = withMutableImage image $ \\c_i -> do\n d <- {#get IplImage->imageData#} c_i\n s <- {#get IplImage->widthStep#} c_i\n let cs = fromIntegral s\n fs = sizeOf (undefined :: Float)\n poke (castPtr (d`plusPtr` (y*cs + x*2*fs))) re\n poke (castPtr (d`plusPtr` (y*cs + (x*2+1)*fs))) im\n\n\n\ngetAllPixels image = [getPixel (i,j) image\n | i <- [0..width-1 ]\n , j <- [0..height-1]]\n where\n (width,height) = getSize image\n\ngetAllPixelsRowMajor image = [getPixel (i,j) image\n | j <- [0..height-1]\n , i <- [0..width-1]\n ]\n where\n (width,height) = getSize image\n\n-- |Create a montage form given images (u,v) determines the layout and space the spacing\n-- between images. Images are assumed to be the same size (determined by the first image)\nmontage :: (Blittable c d) => (CreateImage (MutableImage c d)) => (Int,Int) -> Int -> [Image c d] -> Image c d\nmontage (u',v') space' imgs\n | u'*v' < (length imgs) = error (\"Montage mismatch: \"++show (u,v, length imgs))\n | otherwise = resultPic\n where\n space = fromIntegral space'\n (u,v) = (fromIntegral u', fromIntegral v')\n (rw,rh) = (u*xstep,v*ystep)\n (w,h) = foldl (\\(mx,my) (x,y) -> (max mx x, max my y)) (0,0) $ map getSize imgs\n (xstep,ystep) = (fromIntegral space + w,fromIntegral space + h)\n edge = space`div`2\n resultPic = unsafePerformIO $ do\n r <- create (rw,rh)\n sequence_ [blit r i (edge + x*xstep, edge + y*ystep)\n | y <- [0..v-1] , x <- [0..u-1]\n | i <- imgs ]\n let (Mutable i) = r \n i `seq` return i\n\ndata CvException = CvException Int String String String Int\n deriving (Show, Typeable)\n\ndata CvIOError = CvIOError String deriving (Show,Typeable)\ndata CvSizeError = CvSizeError String deriving (Show,Typeable)\n\ninstance Exception CvException\ninstance Exception CvIOError\ninstance Exception CvSizeError\n\nsetCatch = do\n let catch i cstr1 cstr2 cstr3 j = do\n func <- peekCString cstr1\n msg <- peekCString cstr2\n file <- peekCString cstr3\n throw (CvException (fromIntegral i) func msg file (fromIntegral j))\n return 0\n cb <- mk'CvErrorCallback catch\n c'cvRedirectError cb nullPtr nullPtr\n c'cvSetErrMode c'CV_ErrModeSilent\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"50113adb9402c5c399310ceaa7cd24b62e78bec9","subject":"Added all cv camera properties","message":"Added all cv camera properties","repos":"BeautifulDestinations\/CV,aleator\/CV,aleator\/CV,TomMD\/CV","old_file":"CV\/Video.chs","new_file":"CV\/Video.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns#-}\n#include \"cvWrapLeo.h\"\nmodule CV.Video where\n{#import CV.Image#}\n\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.ForeignPtr\nimport Foreign.Storable\nimport Foreign.C.Types\nimport Foreign.C.String\nimport System.IO.Unsafe\n\n{#pointer *CvCapture as Capture foreign newtype#}\n\nforeign import ccall \"& wrapReleaseCapture\" releaseCapture :: FinalizerPtr Capture\n\n{#pointer *CvVideoWriter as VideoWriter foreign newtype#}\n\nforeign import ccall \"& wrapReleaseVideoWriter\" releaseVideoWriter :: FinalizerPtr VideoWriter\n-- NOTE: This use of foreignPtr is quite likely to cause trouble by retaining\n-- videos longer than necessary.\n\ncaptureFromFile fn = withCString fn $ \\cfn -> do\n ptr <- {#call cvCreateFileCapture#} cfn\n fptr <- newForeignPtr releaseCapture ptr\n return . Capture $ fptr\n\ncaptureFromCam int = do\n ptr <- {#call cvCreateCameraCapture#} (fromIntegral int)\n fptr <- newForeignPtr releaseCapture ptr\n return . Capture $ fptr\n\ndropFrame cap = withCapture cap $ \\ccap -> {#call cvGrabFrame#} ccap >> return ()\n\ngetFrame cap = withCapture cap $\u00a0\\ccap -> do\n p_frame <- {#call cvQueryFrame#} ccap \n creatingImage $ ensure32F p_frame -- NOTE: This works because Image module has generated wrappers for ensure32F\n\n-- These are likely to break..\ncvCAP_PROP_POS_MSEC =0 :: CInt\ncvCAP_PROP_POS_FRAMES =1 :: CInt\ncvCAP_PROP_POS_AVI_RATIO =2 :: CInt\ncvCAP_PROP_FRAME_WIDTH =3 :: CInt\ncvCAP_PROP_FRAME_HEIGHT =4 :: CInt\ncvCAP_PROP_FPS =5 :: CInt\ncvCAP_PROP_FOURCC =6 :: CInt\ncvCAP_PROP_FRAME_COUNT =7 :: CInt\ncvCAP_PROP_FORMAT =8 :: CInt\ncvCAP_PROP_MODE =9 :: CInt\ncvCAP_PROP_BRIGHTNESS =10 :: CInt\ncvCAP_PROP_CONTRAST =11 :: CInt\ncvCAP_PROP_SATURATION =12 :: CInt\ncvCAP_PROP_HUE =13 :: CInt\ncvCAP_PROP_GAIN =14 :: CInt\ncvCAP_PROP_EXPOSURE =15 :: CInt\ncvCAP_PROP_CONVERT_RGB =16 :: CInt\ncvCAP_PROP_WHITE_BALANCE =17 :: CInt\ncvCAP_PROP_RECTIFICATION =18 :: CInt \ncvCAP_PROP_MONOCROME =19 :: CInt\n\n\ngetFrameRate cap = unsafePerformIO $\n withCapture cap $\u00a0\\ccap ->\n {#call cvGetCaptureProperty#} \n ccap cvCAP_PROP_FPS >>= return . realToFrac\n\ngetFrameSize cap = unsafePerformIO $\n withCapture cap $\u00a0\\ccap -> do\n w <- {#call cvGetCaptureProperty#} ccap cvCAP_PROP_FRAME_WIDTH >>= return . round\n h <- {#call cvGetCaptureProperty#} ccap cvCAP_PROP_FRAME_HEIGHT >>= return . round\n return (w,h)\n\n\nsetCapProp cap prop val = withCapture cap $\u00a0\\ccap ->\n {#call cvSetCaptureProperty#} \n ccap prop (realToFrac val)\n\ngetNumberOfFrames cap = unsafePerformIO $\n withCapture cap $\u00a0\\ccap ->\n {#call cvGetCaptureProperty#} \n ccap cvCAP_PROP_FRAME_COUNT\n >>= return . floor\n\ngetFrameNumber cap = unsafePerformIO $\n withCapture cap $\u00a0\\ccap ->\n {#call cvGetCaptureProperty#} \n ccap cvCAP_PROP_POS_FRAMES >>= return . floor\n\n-- Video Writing\n\ndata Codec = MPG4 deriving (Eq,Show)\n\ncreateVideoWriter filename codec framerate frameSize isColor = \n withCString filename $ \\cfilename -> do\n ptr <- {#call wrapCreateVideoWriter#} cfilename fourcc \n framerate w h ccolor\n if ptr == nullPtr then error \"Could not create video writer\" else return ()\n fptr <- newForeignPtr releaseVideoWriter ptr\n return . VideoWriter $ fptr\n where\n (w,h) = frameSize\n ccolor | isColor = 1\n | otherwise = 0\n fourcc | codec == MPG4 = 0x4d504734 -- This is so wrong..\n\nwriteFrame writer img = withVideoWriter writer $\u00a0\\cwriter ->\n withImage img $ \\cimg -> \n {#call cvWriteFrame #} cwriter cimg\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ViewPatterns#-}\n#include \"cvWrapLeo.h\"\nmodule CV.Video where\n{#import CV.Image#}\n\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.ForeignPtr\nimport Foreign.Storable\nimport Foreign.C.Types\nimport Foreign.C.String\nimport System.IO.Unsafe\n\n{#pointer *CvCapture as Capture foreign newtype#}\n\nforeign import ccall \"& wrapReleaseCapture\" releaseCapture :: FinalizerPtr Capture\n\n{#pointer *CvVideoWriter as VideoWriter foreign newtype#}\n\nforeign import ccall \"& wrapReleaseVideoWriter\" releaseVideoWriter :: FinalizerPtr VideoWriter\n-- NOTE: This use of foreignPtr is quite likely to cause trouble by retaining\n-- videos longer than necessary.\n\ncaptureFromFile fn = withCString fn $ \\cfn -> do\n ptr <- {#call cvCreateFileCapture#} cfn\n fptr <- newForeignPtr releaseCapture ptr\n return . Capture $ fptr\n\ncaptureFromCam int = do\n ptr <- {#call cvCreateCameraCapture#} (fromIntegral int)\n fptr <- newForeignPtr releaseCapture ptr\n return . Capture $ fptr\n\ndropFrame cap = withCapture cap $ \\ccap -> {#call cvGrabFrame#} ccap >> return ()\n\ngetFrame cap = withCapture cap $\u00a0\\ccap -> do\n p_frame <- {#call cvQueryFrame#} ccap \n creatingImage $ ensure32F p_frame -- NOTE: This works because Image module has generated wrappers for ensure32F\n\ncvCAP_PROP_FRAME_COUNT = 7 -- These are likely to break..\ncvCAP_PROP_FPS = 5\ncvCAP_PROP_FRAME_WIDTH = 3\ncvCAP_PROP_FRAME_HEIGHT = 4\ncvCAP_POS_FRAMES = 1\n\ngetFrameRate cap = unsafePerformIO $\n withCapture cap $\u00a0\\ccap ->\n {#call cvGetCaptureProperty#} \n ccap cvCAP_PROP_FPS >>= return . realToFrac\n\ngetFrameSize cap = unsafePerformIO $\n withCapture cap $\u00a0\\ccap -> do\n w <- {#call cvGetCaptureProperty#} ccap cvCAP_PROP_FRAME_WIDTH >>= return . round\n h <- {#call cvGetCaptureProperty#} ccap cvCAP_PROP_FRAME_HEIGHT >>= return . round\n return (w,h)\n\n\ngetNumberOfFrames cap = unsafePerformIO $\n withCapture cap $\u00a0\\ccap ->\n {#call cvGetCaptureProperty#} \n ccap cvCAP_PROP_FRAME_COUNT\n >>= return . floor\n\ngetFrameNumber cap = unsafePerformIO $\n withCapture cap $\u00a0\\ccap ->\n {#call cvGetCaptureProperty#} \n ccap cvCAP_POS_FRAMES >>= return . floor\n\n-- Video Writing\n\ndata Codec = MPG4 deriving (Eq,Show)\n\ncreateVideoWriter filename codec framerate frameSize isColor = \n withCString filename $ \\cfilename -> do\n ptr <- {#call wrapCreateVideoWriter#} cfilename fourcc \n framerate w h ccolor\n if ptr == nullPtr then error \"Could not create video writer\" else return ()\n fptr <- newForeignPtr releaseVideoWriter ptr\n return . VideoWriter $ fptr\n where\n (w,h) = frameSize\n ccolor | isColor = 1\n | otherwise = 0\n fourcc | codec == MPG4 = 0x4d504734 -- This is so wrong..\n\nwriteFrame writer img = withVideoWriter writer $\u00a0\\cwriter ->\n withImage img $ \\cimg -> \n {#call cvWriteFrame #} cwriter cimg\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"57cf90ce640ba0bf64282e598c3a41257913eaf5","subject":"Add the tree view notification functions.","message":"Add the tree view notification functions.\n\nThese are needed by any custom TreeModel implementation that allows changes in\nthe model. They are to tell any watcing views of changes in the model so the\nviews can update themselves appropriately.\n\ndarcs-hash:20060117113329-b4c10-df3229caaeb907e6aaa6e4fc3970f5460fa8cc74.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gtk\/Graphics\/UI\/Gtk\/TreeList\/CustomStore.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/TreeList\/CustomStore.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) CustomStore TreeModel\n--\n-- Author : Duncan Coutts\n--\n-- Created: 19 Sep 2005\n--\n-- Version $Revision: 1.1 $ from $Date: 2005\/12\/08 18:12:43 $\n--\n-- Copyright (C) 2005 Duncan Coutts\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : custom-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Allows a custom data structure to be used with the 'TreeView'\n--\nmodule Graphics.UI.Gtk.TreeList.CustomStore (\n CustomStore(..),\n customStoreNew,\n\n -- * View notifcation functions\n treeModelRowChanged,\n treeModelRowInserted,\n treeModelRowHasChildToggled,\n treeModelRowDeleted,\n treeModelRowsReordered,\n ) where\n\nimport Monad\t(liftM, when)\n\nimport System.Glib.FFI\t\t\thiding\t(maybeNull)\nimport System.Glib.Flags\nimport System.Glib.GObject\t\t\t(makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.TreeList.TreeModel#}\n{#import Graphics.UI.Gtk.TreeList.TreeIter#}\n{#import Graphics.UI.Gtk.TreeList.TreePath#}\nimport System.Glib.StoreValue\t\t\t(TMType(..), GenericValue(..)\n\t\t\t\t\t\t,valueSetGenericValue)\n{#import System.Glib.GValue#}\t\t\t(GValue(GValue), allocaGValue)\n{#import System.Glib.GType#}\t\t\t(GType)\nimport System.Glib.GValueTypes (valueSetString)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\ndata CustomStore = CustomStore {\n customStoreGetFlags :: IO [TreeModelFlags],\n customStoreGetNColumns :: IO Int,\n customStoreGetColumnType :: Int -> IO GType,\n customStoreGetIter :: TreePath -> IO (Maybe TreeIter), -- convert a path to an iterator\n customStoreGetPath :: TreeIter -> IO TreePath, -- convert an interator to a path\n customStoreGetValue :: TreeIter -> Int -> GValue -> IO (), -- get the value at an iter and column\n customStoreIterNext :: TreeIter -> IO (Maybe TreeIter), -- following row (if any)\n customStoreIterChildren :: Maybe TreeIter -> IO (Maybe TreeIter), -- first child row (if any)\n customStoreIterHasChild :: TreeIter -> IO Bool, -- row has any children at all\n customStoreIterNChildren :: Maybe TreeIter -> IO Int, -- number of children of a row\n customStoreIterNthChild :: Maybe TreeIter -> Int -> IO (Maybe TreeIter), -- nth child row of a given row\n customStoreIterParent :: TreeIter -> IO (Maybe TreeIter), -- parent row of a row\n customStoreRefNode :: TreeIter -> IO (), -- caching hint\n customStoreUnrefNode :: TreeIter -> IO () -- caching hint\n }\n\ncustomStoreGetFlags_static :: StablePtr CustomStore -> IO CInt\ncustomStoreGetFlags_static storePtr = do\n store <- deRefStablePtr storePtr\n liftM (fromIntegral . fromFlags) $ customStoreGetFlags store\n\nforeign export ccall \"gtk2hs_store_get_flags_impl\"\n customStoreGetFlags_static :: StablePtr CustomStore -> IO CInt\n\n\ncustomStoreGetNColumns_static :: StablePtr CustomStore -> IO CInt\ncustomStoreGetNColumns_static storePtr = do\n store <- deRefStablePtr storePtr\n liftM fromIntegral $ customStoreGetNColumns store\n\nforeign export ccall \"gtk2hs_store_get_n_columns_impl\"\n customStoreGetNColumns_static :: StablePtr CustomStore -> IO CInt\n\n\ncustomStoreGetColumnType_static :: StablePtr CustomStore -> CInt -> IO GType\ncustomStoreGetColumnType_static storePtr column = do\n store <- deRefStablePtr storePtr\n customStoreGetColumnType store (fromIntegral column)\n\nforeign export ccall \"gtk2hs_store_get_column_type_impl\"\n customStoreGetColumnType_static :: StablePtr CustomStore -> CInt -> IO GType\n\n\ncustomStoreGetIter_static :: StablePtr CustomStore -> Ptr TreeIter -> Ptr NativeTreePath -> IO CInt\ncustomStoreGetIter_static storePtr iterPtr pathPtr = do\n store <- deRefStablePtr storePtr\n path <- peekTreePath pathPtr\n iter <- customStoreGetIter store path\n case iter of\n Nothing -> return (fromBool False)\n Just iter -> do poke iterPtr iter\n return (fromBool True)\n\nforeign export ccall \"gtk2hs_store_get_iter_impl\"\n customStoreGetIter_static :: StablePtr CustomStore -> Ptr TreeIter -> Ptr NativeTreePath -> IO CInt\n\n\ncustomStoreGetPath_static :: StablePtr CustomStore -> Ptr TreeIter -> IO (Ptr NativeTreePath)\ncustomStoreGetPath_static storePtr iterPtr = do\n store <- deRefStablePtr storePtr\n iter <- peek iterPtr\n path <- customStoreGetPath store iter\n NativeTreePath pathPtr <- newTreePath path\n return pathPtr\n\nforeign export ccall \"gtk2hs_store_get_path_impl\"\n customStoreGetPath_static :: StablePtr CustomStore -> Ptr TreeIter -> IO (Ptr NativeTreePath)\n\n\ncustomStoreGetValue_static :: StablePtr CustomStore -> Ptr TreeIter -> CInt -> Ptr GValue -> IO ()\ncustomStoreGetValue_static storePtr iterPtr column gvaluePtr = do\n store <- deRefStablePtr storePtr\n iter <- peek iterPtr\n customStoreGetValue store iter (fromIntegral column) (GValue gvaluePtr)\n\nforeign export ccall \"gtk2hs_store_get_value_impl\"\n customStoreGetValue_static :: StablePtr CustomStore -> Ptr TreeIter -> CInt -> Ptr GValue -> IO ()\n\n\ncustomStoreIterNext_static :: StablePtr CustomStore -> Ptr TreeIter -> IO CInt\ncustomStoreIterNext_static storePtr iterPtr = do\n store <- deRefStablePtr storePtr\n iter <- peek iterPtr\n iter' <- customStoreIterNext store iter\n case iter' of\n Nothing -> return (fromBool False)\n Just iter' -> do poke iterPtr iter'\n return (fromBool True)\n\nforeign export ccall \"gtk2hs_store_iter_next_impl\"\n customStoreIterNext_static :: StablePtr CustomStore -> Ptr TreeIter -> IO CInt\n\n\ncustomStoreIterChildren_static :: StablePtr CustomStore -> Ptr TreeIter -> Ptr TreeIter -> IO CInt\ncustomStoreIterChildren_static storePtr iterPtr parentIterPtr = do\n store <- deRefStablePtr storePtr\n parentIter <- maybeNull peek parentIterPtr\n iter <- customStoreIterChildren store parentIter\n case iter of\n Nothing -> return (fromBool False)\n Just iter -> do poke iterPtr iter\n return (fromBool True)\n\nforeign export ccall \"gtk2hs_store_iter_children_impl\"\n customStoreIterChildren_static :: StablePtr CustomStore -> Ptr TreeIter -> Ptr TreeIter -> IO CInt\n\n\ncustomStoreIterHasChild_static :: StablePtr CustomStore -> Ptr TreeIter -> IO CInt\ncustomStoreIterHasChild_static storePtr iterPtr = do\n store <- deRefStablePtr storePtr\n iter <- peek iterPtr\n liftM fromBool $ customStoreIterHasChild store iter\n\nforeign export ccall \"gtk2hs_store_iter_has_child_impl\"\n customStoreIterHasChild_static :: StablePtr CustomStore -> Ptr TreeIter -> IO CInt\n\n\ncustomStoreIterNChildren_static :: StablePtr CustomStore -> Ptr TreeIter -> IO CInt\ncustomStoreIterNChildren_static storePtr iterPtr = do\n store <- deRefStablePtr storePtr\n iter <- maybeNull peek iterPtr\n liftM fromIntegral $ customStoreIterNChildren store iter\n\nforeign export ccall \"gtk2hs_store_iter_n_children_impl\"\n customStoreIterNChildren_static :: StablePtr CustomStore -> Ptr TreeIter -> IO CInt\n\n\ncustomStoreIterNthChild_static :: StablePtr CustomStore -> Ptr TreeIter -> Ptr TreeIter -> CInt -> IO CInt\ncustomStoreIterNthChild_static storePtr iterPtr parentIterPtr n = do\n store <- deRefStablePtr storePtr\n parentIter <- maybeNull peek parentIterPtr\n iter <- customStoreIterNthChild store parentIter (fromIntegral n)\n case iter of\n Nothing -> return (fromBool False)\n Just iter -> do poke iterPtr iter\n return (fromBool True)\n\nforeign export ccall \"gtk2hs_store_iter_nth_child_impl\"\n customStoreIterNthChild_static :: StablePtr CustomStore -> Ptr TreeIter -> Ptr TreeIter -> CInt -> IO CInt\n\n\ncustomStoreIterParent_static :: StablePtr CustomStore -> Ptr TreeIter -> Ptr TreeIter -> IO CInt\ncustomStoreIterParent_static storePtr iterPtr childIterPtr = do\n store <- deRefStablePtr storePtr\n childIter <- peek childIterPtr\n iter <- customStoreIterParent store childIter\n case iter of\n Nothing -> return (fromBool False)\n Just iter -> do poke iterPtr iter\n return (fromBool True)\n\nforeign export ccall \"gtk2hs_store_iter_parent_impl\"\n customStoreIterParent_static :: StablePtr CustomStore -> Ptr TreeIter -> Ptr TreeIter -> IO CInt\n\n\ncustomStoreRefNode_static :: StablePtr CustomStore -> Ptr TreeIter -> IO ()\ncustomStoreRefNode_static storePtr iterPtr = do\n store <- deRefStablePtr storePtr\n iter <- peek iterPtr\n customStoreRefNode store iter\n\nforeign export ccall \"gtk2hs_store_ref_node_impl\"\n customStoreRefNode_static :: StablePtr CustomStore -> Ptr TreeIter -> IO ()\n\n\ncustomStoreUnrefNode_static :: StablePtr CustomStore -> Ptr TreeIter -> IO ()\ncustomStoreUnrefNode_static storePtr iterPtr = do\n store <- deRefStablePtr storePtr\n iter <- peek iterPtr\n customStoreUnrefNode store iter\n\nforeign export ccall \"gtk2hs_store_unref_node_impl\"\n customStoreUnrefNode_static :: StablePtr CustomStore -> Ptr TreeIter -> IO ()\n\nforeign import ccall unsafe \"gtk2hs_store_new\"\n gtk2hs_store_new :: StablePtr CustomStore -> IO (Ptr TreeModel)\n\ncustomStoreNew :: CustomStore -> IO TreeModel\ncustomStoreNew impl = do\n implPtr <- newStablePtr impl\n makeNewGObject mkTreeModel $\n gtk2hs_store_new implPtr\n\nmaybeNull :: (Ptr a -> IO b) -> Ptr a -> IO (Maybe b)\nmaybeNull marshal ptr\n | ptr == nullPtr = return Nothing\n | otherwise = liftM Just (marshal ptr)\n\n\n-- | Emits the \\\"row_changed\\\" signal on the 'TreeModel'.\n--\ntreeModelRowChanged :: TreeModelClass self => self\n -> TreePath -- ^ @path@ - A 'TreePath' pointing to the changed row\n -> TreeIter -- ^ @iter@ - A valid 'TreeIter' pointing to the changed row\n -> IO ()\ntreeModelRowChanged self path iter =\n withTreePath path $ \\pathPtr ->\n with iter $ \\iterPtr ->\n {# call gtk_tree_model_row_changed #}\n (toTreeModel self)\n pathPtr\n iterPtr\n\n-- | Emits the \\\"row_inserted\\\" signal on the 'TreeModel'\n--\ntreeModelRowInserted :: TreeModelClass self => self\n -> TreePath -- ^ @path@ - A 'TreePath' pointing to the inserted row\n -> TreeIter -- ^ @iter@ - A valid 'TreeIter' pointing to the inserted row\n -> IO ()\ntreeModelRowInserted self path iter =\n withTreePath path $ \\pathPtr ->\n with iter $ \\iterPtr ->\n {# call gtk_tree_model_row_inserted #}\n (toTreeModel self)\n pathPtr\n iterPtr\n\n-- | Emits the \\\"row_has_child_toggled\\\" signal on the 'TreeModel'. This should\n-- be called by models after the child state of a node changes.\n--\ntreeModelRowHasChildToggled :: TreeModelClass self => self\n -> TreePath -- ^ @path@ - A 'TreePath' pointing to the changed row\n -> TreeIter -- ^ @iter@ - A valid 'TreeIter' pointing to the changed row\n -> IO ()\ntreeModelRowHasChildToggled self path iter =\n withTreePath path $ \\pathPtr ->\n with iter $ \\iterPtr ->\n {# call gtk_tree_model_row_has_child_toggled #}\n (toTreeModel self)\n pathPtr\n iterPtr\n\n-- | Emits the \\\"row_deleted\\\" signal the 'TreeModel'. This should be called by\n-- models after a row has been removed. The location pointed to by @path@\n-- should be the location that the row previously was at. It may not be a valid\n-- location anymore.\n--\ntreeModelRowDeleted :: TreeModelClass self => self\n -> TreePath -- ^ @path@ - A 'TreePath' pointing to the previous location of\n -- the deleted row.\n -> IO ()\ntreeModelRowDeleted self path =\n withTreePath path $ \\pathPtr ->\n {# call gtk_tree_model_row_deleted #}\n (toTreeModel self)\n pathPtr\n\n-- | Emits the \\\"rows_reordered\\\" signal on the 'TreeModel'. This should be\n-- called by models when their rows have been reordered.\n--\ntreeModelRowsReordered :: TreeModelClass self => self\n -> TreePath -- ^ @path@ - A 'TreePath' pointing to the tree node whose\n -- children have been reordered\n -> TreeIter -- ^ @iter@ - A valid 'TreeIter' pointing to the node whose\n -- children have been reordered, or {@NULL@, FIXME: this should\n -- probably be converted to a Maybe data type} if the depth of\n -- @path@ is 0.\n -> [Int] -- ^ @newOrder@ - an array of integers mapping the current\n -- position of each child to its old position before the\n -- re-ordering, i.e. @newOrder@@[newpos] = oldpos@.\n -> IO ()\ntreeModelRowsReordered self path iter newOrder =\n withTreePath path $ \\pathPtr ->\n with iter $ \\iterPtr ->\n withArrayLen (map fromIntegral newOrder) $ \\newLength newOrderArrPtr -> do\n --check newOrder is the right length or it'll overrun\n curLength <- treeModelIterNChildren self (Just iter)\n when (curLength \/= newLength)\n (fail \"treeModelRowsReordered: mapping wrong length for store\")\n {# call gtk_tree_model_rows_reordered #}\n (toTreeModel self)\n pathPtr\n iterPtr\n newOrderArrPtr\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) CustomStore TreeModel\n--\n-- Author : Duncan Coutts\n--\n-- Created: 19 Sep 2005\n--\n-- Version $Revision: 1.1 $ from $Date: 2005\/12\/08 18:12:43 $\n--\n-- Copyright (C) 2005 Duncan Coutts\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : custom-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Allows a custom data structure to be used with the 'TreeView'\n--\nmodule Graphics.UI.Gtk.TreeList.CustomStore (\n CustomStore(..),\n customStoreNew,\n ) where\n\nimport Monad\t(liftM, when)\n\nimport System.Glib.FFI\t\t\thiding\t(maybeNull)\nimport System.Glib.Flags\nimport System.Glib.GObject\t\t\t(makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.TreeList.TreeModel#}\n{#import Graphics.UI.Gtk.TreeList.TreeIter#}\n{#import Graphics.UI.Gtk.TreeList.TreePath#}\nimport System.Glib.StoreValue\t\t\t(TMType(..), GenericValue(..)\n\t\t\t\t\t\t,valueSetGenericValue)\n{#import System.Glib.GValue#}\t\t\t(GValue(GValue), allocaGValue)\n{#import System.Glib.GType#}\t\t\t(GType)\nimport System.Glib.GValueTypes (valueSetString)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\ndata CustomStore = CustomStore {\n customStoreGetFlags :: IO [TreeModelFlags],\n customStoreGetNColumns :: IO Int,\n customStoreGetColumnType :: Int -> IO GType,\n customStoreGetIter :: TreePath -> IO (Maybe TreeIter), -- convert a path to an iterator\n customStoreGetPath :: TreeIter -> IO TreePath, -- convert an interator to a path\n customStoreGetValue :: TreeIter -> Int -> GValue -> IO (), -- get the value at an iter and column\n customStoreIterNext :: TreeIter -> IO (Maybe TreeIter), -- following row (if any)\n customStoreIterChildren :: Maybe TreeIter -> IO (Maybe TreeIter), -- first child row (if any)\n customStoreIterHasChild :: TreeIter -> IO Bool, -- row has any children at all\n customStoreIterNChildren :: Maybe TreeIter -> IO Int, -- number of children of a row\n customStoreIterNthChild :: Maybe TreeIter -> Int -> IO (Maybe TreeIter), -- nth child row of a given row\n customStoreIterParent :: TreeIter -> IO (Maybe TreeIter), -- parent row of a row\n customStoreRefNode :: TreeIter -> IO (), -- caching hint\n customStoreUnrefNode :: TreeIter -> IO () -- caching hint\n }\n\ncustomStoreGetFlags_static :: StablePtr CustomStore -> IO CInt\ncustomStoreGetFlags_static storePtr = do\n store <- deRefStablePtr storePtr\n liftM (fromIntegral . fromFlags) $ customStoreGetFlags store\n\nforeign export ccall \"gtk2hs_store_get_flags_impl\"\n customStoreGetFlags_static :: StablePtr CustomStore -> IO CInt\n\n\ncustomStoreGetNColumns_static :: StablePtr CustomStore -> IO CInt\ncustomStoreGetNColumns_static storePtr = do\n store <- deRefStablePtr storePtr\n liftM fromIntegral $ customStoreGetNColumns store\n\nforeign export ccall \"gtk2hs_store_get_n_columns_impl\"\n customStoreGetNColumns_static :: StablePtr CustomStore -> IO CInt\n\n\ncustomStoreGetColumnType_static :: StablePtr CustomStore -> CInt -> IO GType\ncustomStoreGetColumnType_static storePtr column = do\n store <- deRefStablePtr storePtr\n customStoreGetColumnType store (fromIntegral column)\n\nforeign export ccall \"gtk2hs_store_get_column_type_impl\"\n customStoreGetColumnType_static :: StablePtr CustomStore -> CInt -> IO GType\n\n\ncustomStoreGetIter_static :: StablePtr CustomStore -> Ptr TreeIter -> Ptr NativeTreePath -> IO CInt\ncustomStoreGetIter_static storePtr iterPtr pathPtr = do\n store <- deRefStablePtr storePtr\n path <- peekTreePath pathPtr\n iter <- customStoreGetIter store path\n case iter of\n Nothing -> return (fromBool False)\n Just iter -> do poke iterPtr iter\n return (fromBool True)\n\nforeign export ccall \"gtk2hs_store_get_iter_impl\"\n customStoreGetIter_static :: StablePtr CustomStore -> Ptr TreeIter -> Ptr NativeTreePath -> IO CInt\n\n\ncustomStoreGetPath_static :: StablePtr CustomStore -> Ptr TreeIter -> IO (Ptr NativeTreePath)\ncustomStoreGetPath_static storePtr iterPtr = do\n store <- deRefStablePtr storePtr\n iter <- peek iterPtr\n path <- customStoreGetPath store iter\n NativeTreePath pathPtr <- newTreePath path\n return pathPtr\n\nforeign export ccall \"gtk2hs_store_get_path_impl\"\n customStoreGetPath_static :: StablePtr CustomStore -> Ptr TreeIter -> IO (Ptr NativeTreePath)\n\n\ncustomStoreGetValue_static :: StablePtr CustomStore -> Ptr TreeIter -> CInt -> Ptr GValue -> IO ()\ncustomStoreGetValue_static storePtr iterPtr column gvaluePtr = do\n store <- deRefStablePtr storePtr\n iter <- peek iterPtr\n customStoreGetValue store iter (fromIntegral column) (GValue gvaluePtr)\n\nforeign export ccall \"gtk2hs_store_get_value_impl\"\n customStoreGetValue_static :: StablePtr CustomStore -> Ptr TreeIter -> CInt -> Ptr GValue -> IO ()\n\n\ncustomStoreIterNext_static :: StablePtr CustomStore -> Ptr TreeIter -> IO CInt\ncustomStoreIterNext_static storePtr iterPtr = do\n store <- deRefStablePtr storePtr\n iter <- peek iterPtr\n iter' <- customStoreIterNext store iter\n case iter' of\n Nothing -> return (fromBool False)\n Just iter' -> do poke iterPtr iter'\n return (fromBool True)\n\nforeign export ccall \"gtk2hs_store_iter_next_impl\"\n customStoreIterNext_static :: StablePtr CustomStore -> Ptr TreeIter -> IO CInt\n\n\ncustomStoreIterChildren_static :: StablePtr CustomStore -> Ptr TreeIter -> Ptr TreeIter -> IO CInt\ncustomStoreIterChildren_static storePtr iterPtr parentIterPtr = do\n store <- deRefStablePtr storePtr\n parentIter <- maybeNull peek parentIterPtr\n iter <- customStoreIterChildren store parentIter\n case iter of\n Nothing -> return (fromBool False)\n Just iter -> do poke iterPtr iter\n return (fromBool True)\n\nforeign export ccall \"gtk2hs_store_iter_children_impl\"\n customStoreIterChildren_static :: StablePtr CustomStore -> Ptr TreeIter -> Ptr TreeIter -> IO CInt\n\n\ncustomStoreIterHasChild_static :: StablePtr CustomStore -> Ptr TreeIter -> IO CInt\ncustomStoreIterHasChild_static storePtr iterPtr = do\n store <- deRefStablePtr storePtr\n iter <- peek iterPtr\n liftM fromBool $ customStoreIterHasChild store iter\n\nforeign export ccall \"gtk2hs_store_iter_has_child_impl\"\n customStoreIterHasChild_static :: StablePtr CustomStore -> Ptr TreeIter -> IO CInt\n\n\ncustomStoreIterNChildren_static :: StablePtr CustomStore -> Ptr TreeIter -> IO CInt\ncustomStoreIterNChildren_static storePtr iterPtr = do\n store <- deRefStablePtr storePtr\n iter <- maybeNull peek iterPtr\n liftM fromIntegral $ customStoreIterNChildren store iter\n\nforeign export ccall \"gtk2hs_store_iter_n_children_impl\"\n customStoreIterNChildren_static :: StablePtr CustomStore -> Ptr TreeIter -> IO CInt\n\n\ncustomStoreIterNthChild_static :: StablePtr CustomStore -> Ptr TreeIter -> Ptr TreeIter -> CInt -> IO CInt\ncustomStoreIterNthChild_static storePtr iterPtr parentIterPtr n = do\n store <- deRefStablePtr storePtr\n parentIter <- maybeNull peek parentIterPtr\n iter <- customStoreIterNthChild store parentIter (fromIntegral n)\n case iter of\n Nothing -> return (fromBool False)\n Just iter -> do poke iterPtr iter\n return (fromBool True)\n\nforeign export ccall \"gtk2hs_store_iter_nth_child_impl\"\n customStoreIterNthChild_static :: StablePtr CustomStore -> Ptr TreeIter -> Ptr TreeIter -> CInt -> IO CInt\n\n\ncustomStoreIterParent_static :: StablePtr CustomStore -> Ptr TreeIter -> Ptr TreeIter -> IO CInt\ncustomStoreIterParent_static storePtr iterPtr childIterPtr = do\n store <- deRefStablePtr storePtr\n childIter <- peek childIterPtr\n iter <- customStoreIterParent store childIter\n case iter of\n Nothing -> return (fromBool False)\n Just iter -> do poke iterPtr iter\n return (fromBool True)\n\nforeign export ccall \"gtk2hs_store_iter_parent_impl\"\n customStoreIterParent_static :: StablePtr CustomStore -> Ptr TreeIter -> Ptr TreeIter -> IO CInt\n\n\ncustomStoreRefNode_static :: StablePtr CustomStore -> Ptr TreeIter -> IO ()\ncustomStoreRefNode_static storePtr iterPtr = do\n store <- deRefStablePtr storePtr\n iter <- peek iterPtr\n customStoreRefNode store iter\n\nforeign export ccall \"gtk2hs_store_ref_node_impl\"\n customStoreRefNode_static :: StablePtr CustomStore -> Ptr TreeIter -> IO ()\n\n\ncustomStoreUnrefNode_static :: StablePtr CustomStore -> Ptr TreeIter -> IO ()\ncustomStoreUnrefNode_static storePtr iterPtr = do\n store <- deRefStablePtr storePtr\n iter <- peek iterPtr\n customStoreUnrefNode store iter\n\nforeign export ccall \"gtk2hs_store_unref_node_impl\"\n customStoreUnrefNode_static :: StablePtr CustomStore -> Ptr TreeIter -> IO ()\n\nforeign import ccall unsafe \"gtk2hs_store_new\"\n gtk2hs_store_new :: StablePtr CustomStore -> IO (Ptr TreeModel)\n\ncustomStoreNew :: CustomStore -> IO TreeModel\ncustomStoreNew impl = do\n implPtr <- newStablePtr impl\n makeNewGObject mkTreeModel $\n gtk2hs_store_new implPtr\n\nmaybeNull :: (Ptr a -> IO b) -> Ptr a -> IO (Maybe b)\nmaybeNull marshal ptr\n | ptr == nullPtr = return Nothing\n | otherwise = liftM Just (marshal ptr)\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"35ae9a87ea19c2e2d2d53990096342917914bbae","subject":"Fix webSettingsFantasyFontFamily attr","message":"Fix webSettingsFantasyFontFamily attr","repos":"vincenthz\/webkit","old_file":"Graphics\/UI\/Gtk\/WebKit\/WebSettings.chs","new_file":"Graphics\/UI\/Gtk\/WebKit\/WebSettings.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebSettings\n-- Author : Cjacker Huang\n-- Copyright : (c) 2009 Cjacker Huang \n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Control the behaviour of a 'WebView'\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebSettings (\n-- * Types\n WebSettings,\n WebSettingsClass,\n EditingBehavior,\n\n-- * Constructors\n webSettingsNew,\n\n-- * Methods\n webSettingsCopy,\n webSettingsGetUserAgent,\n\n-- * Attributes\n webSettingsAutoLoadImages,\n webSettingsAutoShrinkImages,\n webSettingsCursiveFontFamily,\n webSettingsDefaultEncoding,\n webSettingsDefaultFontFamily,\n webSettingsDefaultFontSize,\n webSettingsDefaultMonospaceFontSize,\n webSettingsEditingBehavior,\n webSettingsEnableCaretBrowsing,\n webSettingsEnableDeveloperExtras,\n#if WEBKIT_CHECK_VERSION (1,1,16)\n webSettingsEnableDomPaste,\n#endif\n webSettingsEnableHtml5Database,\n webSettingsEnableHtml5LocalStorage,\n webSettingsEnableOfflineWebApplicationCache,\n webSettingsEnablePlugins,\n webSettingsEnablePrivateBrowsing,\n webSettingsEnableScripts,\n webSettingsEnableSpellChecking,\n webSettingsEnableUniversalAccessFromFileUris,\n webSettingsEnableXssAuditor,\n webSettingsEnforce96Dpi,\n webSettingsFantasyFontFamily,\n webSettingsJSCanOpenWindowAuto,\n webSettingsMinimumFontSize,\n webSettingsMinimumLogicalFontSize,\n webSettingsMonospaceFontFamily,\n webSettingsPrintBackgrounds,\n webSettingsResizableTextAreas,\n webSettingsSansFontFamily,\n webSettingsSerifFontFamily,\n webSettingsSpellCheckingLang,\n#if WEBKIT_CHECK_VERSION (1,1,17)\n webSettingsTabKeyCyclesThroughElements,\n#endif\n#if WEBKIT_CHECK_VERSION (1,1,18)\n webSettingsEnableDefaultContextMenu,\n webSettingsEnablePageCache,\n#endif\n webSettingsUserAgent,\n webSettingsUserStylesheetUri,\n webSettingsZoomStep,\n webSettingsEnableSiteSpecificQuirks,\n#if WEBKIT_CHECK_VERSION (1,1,23)\n webSettingsEnableSpatialNavigation,\n#endif\n) where\n\nimport Control.Monad\t\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GList\nimport System.Glib.GError \nimport System.Glib.Properties\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Gdk.Events\n\n{#import Graphics.UI.Gtk.Abstract.Object#}\t(makeNewObject)\n{#import Graphics.UI.Gtk.WebKit.Types#}\n{#import System.Glib.GObject#}\n\n{#context lib=\"webkit\" prefix =\"webkit\"#}\n\n{#enum EditingBehavior {underscoreToCase}#}\n------------------\n-- Constructors\n\n\n-- | Create a new 'WebSettings' instance.\n-- \n-- A 'WebSettings' can be applied to a 'WebView'\n-- to control the to be used text encoding, color, font size, \n-- printing mode,script support, loading of images and various other things.\nwebSettingsNew :: IO WebSettings\nwebSettingsNew = \n constructNewGObject mkWebSettings $ {#call web_settings_new#}\n\n\n-- | Copy an existing 'WebSettings' instance.\nwebSettingsCopy :: \n WebSettingsClass self => self\n -> IO WebSettings\nwebSettingsCopy websettings = \n constructNewGObject mkWebSettings $ {#call web_settings_copy#} (toWebSettings websettings)\n\n-- | Return the User-Agent string currently used.\nwebSettingsGetUserAgent :: \n WebSettingsClass self => self\n -> IO (Maybe String) -- ^ User-Agent string or @Nothing@ in case failed.\nwebSettingsGetUserAgent websettings = \n {#call web_settings_get_user_agent#} (toWebSettings websettings) >>= maybePeek peekCString\n\n-- | Load images automatically\n--\n-- Default value: True\nwebSettingsAutoLoadImages :: (WebSettingsClass self) => Attr self Bool\nwebSettingsAutoLoadImages = newAttrFromBoolProperty \"auto-load-images\"\n\n-- | Automatically shrink standalone images to fit\n--\n-- Default value: True\nwebSettingsAutoShrinkImages :: (WebSettingsClass self) => Attr self Bool\nwebSettingsAutoShrinkImages = newAttrFromBoolProperty \"auto-shrink-images\"\n\n-- | The default Cursive font family used to display text\n--\n-- Default value \"serif\"\nwebSettingsCursiveFontFamily :: (WebSettingsClass self) => Attr self String\nwebSettingsCursiveFontFamily = newAttrFromStringProperty \"cursive-font-family\"\n\n-- | The default encoding used to display text\n--\n-- Default value \"iso-8859-1\"\n\nwebSettingsDefaultEncoding :: (WebSettingsClass self) => Attr self String\nwebSettingsDefaultEncoding = newAttrFromStringProperty \"default-encoding\"\n\n-- | The default font family used to display text\n--\n-- Default value: \"sans-serif\"\n\nwebSettingsDefaultFontFamily :: (WebSettingsClass self) => Attr self String\nwebSettingsDefaultFontFamily = newAttrFromStringProperty \"default-font-family\"\n\n-- | The default font size used to display text\n--\n-- Default value: >=5\n\nwebSettingsDefaultFontSize :: (WebSettingsClass self) => Attr self Int\nwebSettingsDefaultFontSize = newAttrFromIntProperty \"default-font-size\"\n\n-- | The default font size used to display monospace text\n--\n-- Allowed values: >= 5\n-- \n-- Default value: 10\n\nwebSettingsDefaultMonospaceFontSize :: (WebSettingsClass self) => Attr self Int\nwebSettingsDefaultMonospaceFontSize = newAttrFromIntProperty \"default-monospace-font-size\"\n\n-- | This settings controls various editing behaviors\nwebSettingsEditingBehavior :: (WebSettingsClass self) => Attr self EditingBehavior\nwebSettingsEditingBehavior = newAttrFromEnumProperty \"editing-behavior\"\n {#call pure unsafe webkit_editing_behavior_get_type#}\n-- | Whether to enable caret browsing mode.\nwebSettingsEnableCaretBrowsing :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableCaretBrowsing = newAttrFromBoolProperty \"enable-caret-browsing\"\n\n-- | Whether developer extensions should be enabled.\n--\n-- This enables, for now, the 'WebInspector'\nwebSettingsEnableDeveloperExtras :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableDeveloperExtras = newAttrFromBoolProperty \"enable-developer-extras\"\n\n#if WEBKIT_CHECK_VERSION (1,1,16)\n-- | Whether to enable DOM paste. If set to 'True', document.execCommand(\"Paste\") will correctly execute\n-- and paste content of the clipboard.\n-- \n-- Default value: 'False'\n--\n-- * Since 1.1.16\nwebSettingsEnableDomPaste :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableDomPaste = newAttrFromBoolProperty \"enable-dom-paste\"\n#endif\n\n-- | Whether to enable HTML5 client-side SQL database support.\nwebSettingsEnableHtml5Database :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableHtml5Database = newAttrFromBoolProperty \"enable-html5-database\"\n\n-- | Whether to enable HTML5 localStorage support.\nwebSettingsEnableHtml5LocalStorage :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableHtml5LocalStorage = newAttrFromBoolProperty \"enable-html5-local-storage\"\n\n-- | Whether to enable HTML5 offline web application cache support.\nwebSettingsEnableOfflineWebApplicationCache :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableOfflineWebApplicationCache = newAttrFromBoolProperty \"enable-offline-web-application-cache\"\n\n-- | Enable embedded plugin objects.\nwebSettingsEnablePlugins :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnablePlugins = newAttrFromBoolProperty \"enable-plugins\"\n\n-- | Whether to enable private browsing mode.\nwebSettingsEnablePrivateBrowsing :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnablePrivateBrowsing = newAttrFromBoolProperty \"enable-private-browsing\"\n\n-- | Enable embedded scripting languages\nwebSettingsEnableScripts :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableScripts = newAttrFromBoolProperty \"enable-scripts\"\n\n-- | Whether to enable speel checking while typing.\nwebSettingsEnableSpellChecking :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableSpellChecking = newAttrFromBoolProperty \"enable-spell-checking\"\n\n-- | Whether to allow files loaded through file:\/\/ URLs universal access to all pages.\nwebSettingsEnableUniversalAccessFromFileUris :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableUniversalAccessFromFileUris = newAttrFromBoolProperty \"enable-universal-access-from-file-uris\"\n\n-- | Whether to enable the XSS Auditor.\n--\n-- This feature filters some kinds of reflective XSS attacks on vulnerable web sites.\nwebSettingsEnableXssAuditor :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableXssAuditor = newAttrFromBoolProperty \"enable-xss-auditor\"\n\n-- | Enforce a resolution of 96 DPI.\nwebSettingsEnforce96Dpi :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnforce96Dpi = newAttrFromBoolProperty \"enforce-96-dpi\"\n\n-- | The default Fantasy font family used to display text\nwebSettingsFantasyFontFamily :: (WebSettingsClass self) => Attr self String\nwebSettingsFantasyFontFamily = newAttrFromStringProperty \"fantasy-font-family\"\n\n-- | Whether JavaScript can open popup windows automatically without user intervention.\nwebSettingsJSCanOpenWindowAuto :: (WebSettingsClass self) => Attr self Bool\nwebSettingsJSCanOpenWindowAuto = newAttrFromBoolProperty \"javascript-can-open-windows-automatically\"\n\n-- | The minimum font size used to display text.\n-- \n-- Allowed values: >=1\n--\n-- Default value: 5\nwebSettingsMinimumFontSize :: (WebSettingsClass self) => Attr self Int\nwebSettingsMinimumFontSize = newAttrFromIntProperty \"minimum-font-size\"\n\n-- | The minimum logical font size used to display text\n--\n-- Allowed values: >=1\n--\n-- Default value: 5\nwebSettingsMinimumLogicalFontSize :: (WebSettingsClass self) => Attr self Int\nwebSettingsMinimumLogicalFontSize = newAttrFromIntProperty \"minimum-logical-font-size\"\n\n\n-- | The default font family used to display monospace text.\n-- \n-- Default value: \"monospace\"\nwebSettingsMonospaceFontFamily :: (WebSettingsClass self) => Attr self String\nwebSettingsMonospaceFontFamily = newAttrFromStringProperty \"monospace-font-family\"\n\n-- | Whether background images should be printed\n--\n-- Default value: True\nwebSettingsPrintBackgrounds :: (WebSettingsClass self) => Attr self Bool\nwebSettingsPrintBackgrounds = newAttrFromBoolProperty \"print-backgrounds\"\n\n-- | Whether text areas are resizable\n--\n-- Default value : True\nwebSettingsResizableTextAreas :: (WebSettingsClass self) => Attr self Bool\nwebSettingsResizableTextAreas = newAttrFromBoolProperty \"resizable-text-areas\"\n\n-- | The default Sans Serif font family used to display text\n-- \n-- Default value \"sans-serif\"\nwebSettingsSansFontFamily :: (WebSettingsClass self) => Attr self String\nwebSettingsSansFontFamily = newAttrFromStringProperty \"sans-serif-font-family\"\n\n\n-- | The default Serif font family used to display text\n--\n-- Default value: \"serif\"\nwebSettingsSerifFontFamily :: (WebSettingsClass self) => Attr self String\nwebSettingsSerifFontFamily = newAttrFromStringProperty \"serif-font-family\"\n\n\n-- | The languages to be used for spell checking, separated by commas\n-- \n-- The locale string typically is in the form lang_COUNTRY,\n-- where lang is an ISO-639 language code, and COUNTRY is an ISO-3166 country code. \n-- For instance, sv_FI for Swedish as written in Finland or pt_BR for Portuguese as written in Brazil.\n--\n-- If no value is specified then the value returned by gtk_get_default_language will be used.\n--\n-- Default value: @Nothing@\nwebSettingsSpellCheckingLang :: (WebSettingsClass self) => Attr self (Maybe String)\nwebSettingsSpellCheckingLang = newAttrFromMaybeStringProperty \"spell-checking-languages\"\n\n#if WEBKIT_CHECK_VERSION (1,1,17)\n-- | Whether the tab key cycles through elements on the page.\n-- \n-- If flag is 'True', pressing the tab key will focus the next element in the @webView@. If flag is 'False',\n-- the @webView@ will interpret tab key presses as normal key presses. If the selected element is\n-- editable, the tab key will cause the insertion of a tab character.\n-- \n-- Default value: 'True'\n--\n-- * Since 1.1.17\nwebSettingsTabKeyCyclesThroughElements :: (WebSettingsClass self) => Attr self Bool\nwebSettingsTabKeyCyclesThroughElements = newAttrFromBoolProperty \"tab-key-cycles-through-elements\"\n#endif\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n-- | Whether right-clicks should be handled automatically to create, and display the context\n-- menu. Turning this off will make WebKitGTK+ not emit the populate-popup signal. Notice that the\n-- default button press event handler may still handle right clicks for other reasons, such as in-page\n-- context menus, or right-clicks that are handled by the page itself.\n-- \n-- Default value: 'True'\n-- \n-- * Since 1.1.18\nwebSettingsEnableDefaultContextMenu :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableDefaultContextMenu = newAttrFromBoolProperty \"enable-default-context-menu\"\n\n-- | Enable or disable the page cache. Disabling the page cache is generally only useful for special\n-- circumstances like low-memory scenarios or special purpose applications like static HTML\n-- viewers. This setting only controls the Page Cache, this cache is different than the disk-based or\n-- memory-based traditional resource caches, its point is to make going back and forth between pages\n-- much faster. For details about the different types of caches and their purposes see:\n-- http:\/\/webkit.org\/ blog\/427\/webkit-page-cache-i-the-basics\/\n-- \n-- Default value: 'False'\n-- \n-- * Since 1.1.18\nwebSettingsEnablePageCache :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnablePageCache = newAttrFromBoolProperty \"enable-page-cache\"\n#endif\n\n-- | The User-Agent string used by WebKit\n-- \n-- This will return a default User-Agent string if a custom string wasn't provided by the application. \n-- Setting this property to a NULL value or an empty string will result in \n-- the User-Agent string being reset to the default value.\n--\n-- Default value: \\\"Mozilla\/5.0 (X11; U; Linux x86_64; c) AppleWebKit\/531.2+ (KHTML, like Gecko) Safari\/531.2+\\\"\n\nwebSettingsUserAgent :: (WebSettingsClass self) => Attr self String\nwebSettingsUserAgent = newAttrFromStringProperty \"user-agent\"\n\n-- | The URI of a stylesheet that is applied to every page.\n--\n-- Default value: @Nothing@\n\nwebSettingsUserStylesheetUri :: (WebSettingsClass self) => Attr self (Maybe String)\nwebSettingsUserStylesheetUri = newAttrFromMaybeStringProperty \"user-stylesheet-uri\"\n\n-- | The value by which the zoom level is changed when zooming in or out\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0.1\nwebSettingsZoomStep :: (WebSettingsClass self) => Attr self Float\nwebSettingsZoomStep = newAttrFromFloatProperty \"zoom-step\"\n \n-- | Enables the site-specific compatibility workarounds.\n--\n-- Default value: False\nwebSettingsEnableSiteSpecificQuirks :: WebSettingsClass self => Attr self Bool\nwebSettingsEnableSiteSpecificQuirks = newAttrFromBoolProperty \"enable-site-specific-quirks\"\n\n#if WEBKIT_CHECK_VERSION (1,1,23)\n-- | Whether to enable the Spatial Navigation. This feature consists in the ability to navigate between\n-- focusable elements in a Web page, such as hyperlinks and form controls, by using Left, Right, Up and\n-- Down arrow keys. For example, if an user presses the Right key, heuristics determine whether there\n-- is an element he might be trying to reach towards the right, and if there are multiple elements,\n-- which element he probably wants.\n-- \n-- Default value: 'False'\n-- \n-- * Since 1.1.23\nwebSettingsEnableSpatialNavigation :: WebSettingsClass self => Attr self Bool\nwebSettingsEnableSpatialNavigation = newAttrFromBoolProperty \"enable-spatial-navigation\"\n#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-----------------------------------------------------------------------------\n-- Module : Graphics.UI.Gtk.WebKit.WebSettings\n-- Author : Cjacker Huang\n-- Copyright : (c) 2009 Cjacker Huang \n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Control the behaviour of a 'WebView'\n-----------------------------------------------------------------------------\n\nmodule Graphics.UI.Gtk.WebKit.WebSettings (\n-- * Types\n WebSettings,\n WebSettingsClass,\n EditingBehavior,\n\n-- * Constructors\n webSettingsNew,\n\n-- * Methods\n webSettingsCopy,\n webSettingsGetUserAgent,\n\n-- * Attributes\n webSettingsAutoLoadImages,\n webSettingsAutoShrinkImages,\n webSettingsCursiveFontFamily,\n webSettingsDefaultEncoding,\n webSettingsDefaultFontFamily,\n webSettingsDefaultFontSize,\n webSettingsDefaultMonospaceFontSize,\n webSettingsEditingBehavior,\n webSettingsEnableCaretBrowsing,\n webSettingsEnableDeveloperExtras,\n#if WEBKIT_CHECK_VERSION (1,1,16)\n webSettingsEnableDomPaste,\n#endif\n webSettingsEnableHtml5Database,\n webSettingsEnableHtml5LocalStorage,\n webSettingsEnableOfflineWebApplicationCache,\n webSettingsEnablePlugins,\n webSettingsEnablePrivateBrowsing,\n webSettingsEnableScripts,\n webSettingsEnableSpellChecking,\n webSettingsEnableUniversalAccessFromFileUris,\n webSettingsEnableXssAuditor,\n webSettingsEnforce96Dpi,\n webSettingsFantasyFontFamily,\n webSettingsJSCanOpenWindowAuto,\n webSettingsMinimumFontSize,\n webSettingsMinimumLogicalFontSize,\n webSettingsMonospaceFontFamily,\n webSettingsPrintBackgrounds,\n webSettingsResizableTextAreas,\n webSettingsSansFontFamily,\n webSettingsSerifFontFamily,\n webSettingsSpellCheckingLang,\n#if WEBKIT_CHECK_VERSION (1,1,17)\n webSettingsTabKeyCyclesThroughElements,\n#endif\n#if WEBKIT_CHECK_VERSION (1,1,18)\n webSettingsEnableDefaultContextMenu,\n webSettingsEnablePageCache,\n#endif\n webSettingsUserAgent,\n webSettingsUserStylesheetUri,\n webSettingsZoomStep,\n webSettingsEnableSiteSpecificQuirks,\n#if WEBKIT_CHECK_VERSION (1,1,23)\n webSettingsEnableSpatialNavigation,\n#endif\n) where\n\nimport Control.Monad\t\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GList\nimport System.Glib.GError \nimport System.Glib.Properties\nimport System.Glib.Attributes\nimport Graphics.UI.Gtk.Gdk.Events\n\n{#import Graphics.UI.Gtk.Abstract.Object#}\t(makeNewObject)\n{#import Graphics.UI.Gtk.WebKit.Types#}\n{#import System.Glib.GObject#}\n\n{#context lib=\"webkit\" prefix =\"webkit\"#}\n\n{#enum EditingBehavior {underscoreToCase}#}\n------------------\n-- Constructors\n\n\n-- | Create a new 'WebSettings' instance.\n-- \n-- A 'WebSettings' can be applied to a 'WebView'\n-- to control the to be used text encoding, color, font size, \n-- printing mode,script support, loading of images and various other things.\nwebSettingsNew :: IO WebSettings\nwebSettingsNew = \n constructNewGObject mkWebSettings $ {#call web_settings_new#}\n\n\n-- | Copy an existing 'WebSettings' instance.\nwebSettingsCopy :: \n WebSettingsClass self => self\n -> IO WebSettings\nwebSettingsCopy websettings = \n constructNewGObject mkWebSettings $ {#call web_settings_copy#} (toWebSettings websettings)\n\n-- | Return the User-Agent string currently used.\nwebSettingsGetUserAgent :: \n WebSettingsClass self => self\n -> IO (Maybe String) -- ^ User-Agent string or @Nothing@ in case failed.\nwebSettingsGetUserAgent websettings = \n {#call web_settings_get_user_agent#} (toWebSettings websettings) >>= maybePeek peekCString\n\n-- | Load images automatically\n--\n-- Default value: True\nwebSettingsAutoLoadImages :: (WebSettingsClass self) => Attr self Bool\nwebSettingsAutoLoadImages = newAttrFromBoolProperty \"auto-load-images\"\n\n-- | Automatically shrink standalone images to fit\n--\n-- Default value: True\nwebSettingsAutoShrinkImages :: (WebSettingsClass self) => Attr self Bool\nwebSettingsAutoShrinkImages = newAttrFromBoolProperty \"auto-shrink-images\"\n\n-- | The default Cursive font family used to display text\n--\n-- Default value \"serif\"\nwebSettingsCursiveFontFamily :: (WebSettingsClass self) => Attr self String\nwebSettingsCursiveFontFamily = newAttrFromStringProperty \"cursive-font-family\"\n\n-- | The default encoding used to display text\n--\n-- Default value \"iso-8859-1\"\n\nwebSettingsDefaultEncoding :: (WebSettingsClass self) => Attr self String\nwebSettingsDefaultEncoding = newAttrFromStringProperty \"default-encoding\"\n\n-- | The default font family used to display text\n--\n-- Default value: \"sans-serif\"\n\nwebSettingsDefaultFontFamily :: (WebSettingsClass self) => Attr self String\nwebSettingsDefaultFontFamily = newAttrFromStringProperty \"default-font-family\"\n\n-- | The default font size used to display text\n--\n-- Default value: >=5\n\nwebSettingsDefaultFontSize :: (WebSettingsClass self) => Attr self Int\nwebSettingsDefaultFontSize = newAttrFromIntProperty \"default-font-size\"\n\n-- | The default font size used to display monospace text\n--\n-- Allowed values: >= 5\n-- \n-- Default value: 10\n\nwebSettingsDefaultMonospaceFontSize :: (WebSettingsClass self) => Attr self Int\nwebSettingsDefaultMonospaceFontSize = newAttrFromIntProperty \"default-monospace-font-size\"\n\n-- | This settings controls various editing behaviors\nwebSettingsEditingBehavior :: (WebSettingsClass self) => Attr self EditingBehavior\nwebSettingsEditingBehavior = newAttrFromEnumProperty \"editing-behavior\"\n {#call pure unsafe webkit_editing_behavior_get_type#}\n-- | Whether to enable caret browsing mode.\nwebSettingsEnableCaretBrowsing :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableCaretBrowsing = newAttrFromBoolProperty \"enable-caret-browsing\"\n\n-- | Whether developer extensions should be enabled.\n--\n-- This enables, for now, the 'WebInspector'\nwebSettingsEnableDeveloperExtras :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableDeveloperExtras = newAttrFromBoolProperty \"enable-developer-extras\"\n\n#if WEBKIT_CHECK_VERSION (1,1,16)\n-- | Whether to enable DOM paste. If set to 'True', document.execCommand(\"Paste\") will correctly execute\n-- and paste content of the clipboard.\n-- \n-- Default value: 'False'\n--\n-- * Since 1.1.16\nwebSettingsEnableDomPaste :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableDomPaste = newAttrFromBoolProperty \"enable-dom-paste\"\n#endif\n\n-- | Whether to enable HTML5 client-side SQL database support.\nwebSettingsEnableHtml5Database :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableHtml5Database = newAttrFromBoolProperty \"enable-html5-database\"\n\n-- | Whether to enable HTML5 localStorage support.\nwebSettingsEnableHtml5LocalStorage :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableHtml5LocalStorage = newAttrFromBoolProperty \"enable-html5-local-storage\"\n\n-- | Whether to enable HTML5 offline web application cache support.\nwebSettingsEnableOfflineWebApplicationCache :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableOfflineWebApplicationCache = newAttrFromBoolProperty \"enable-offline-web-application-cache\"\n\n-- | Enable embedded plugin objects.\nwebSettingsEnablePlugins :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnablePlugins = newAttrFromBoolProperty \"enable-plugins\"\n\n-- | Whether to enable private browsing mode.\nwebSettingsEnablePrivateBrowsing :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnablePrivateBrowsing = newAttrFromBoolProperty \"enable-private-browsing\"\n\n-- | Enable embedded scripting languages\nwebSettingsEnableScripts :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableScripts = newAttrFromBoolProperty \"enable-scripts\"\n\n-- | Whether to enable speel checking while typing.\nwebSettingsEnableSpellChecking :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableSpellChecking = newAttrFromBoolProperty \"enable-spell-checking\"\n\n-- | Whether to allow files loaded through file:\/\/ URLs universal access to all pages.\nwebSettingsEnableUniversalAccessFromFileUris :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableUniversalAccessFromFileUris = newAttrFromBoolProperty \"enable-universal-access-from-file-uris\"\n\n-- | Whether to enable the XSS Auditor.\n--\n-- This feature filters some kinds of reflective XSS attacks on vulnerable web sites.\nwebSettingsEnableXssAuditor :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableXssAuditor = newAttrFromBoolProperty \"enable-xss-auditor\"\n\n-- | Enforce a resolution of 96 DPI.\nwebSettingsEnforce96Dpi :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnforce96Dpi = newAttrFromBoolProperty \"enforce-96-dpi\"\n\n-- | The default Fantasy font family used to display text\nwebSettingsFantasyFontFamily :: (WebSettingsClass self) => Attr self Bool\nwebSettingsFantasyFontFamily = newAttrFromBoolProperty \"fantasy-font-family\"\n\n-- | Whether JavaScript can open popup windows automatically without user intervention.\nwebSettingsJSCanOpenWindowAuto :: (WebSettingsClass self) => Attr self Bool\nwebSettingsJSCanOpenWindowAuto = newAttrFromBoolProperty \"javascript-can-open-windows-automatically\"\n\n-- | The minimum font size used to display text.\n-- \n-- Allowed values: >=1\n--\n-- Default value: 5\nwebSettingsMinimumFontSize :: (WebSettingsClass self) => Attr self Int\nwebSettingsMinimumFontSize = newAttrFromIntProperty \"minimum-font-size\"\n\n-- | The minimum logical font size used to display text\n--\n-- Allowed values: >=1\n--\n-- Default value: 5\nwebSettingsMinimumLogicalFontSize :: (WebSettingsClass self) => Attr self Int\nwebSettingsMinimumLogicalFontSize = newAttrFromIntProperty \"minimum-logical-font-size\"\n\n\n-- | The default font family used to display monospace text.\n-- \n-- Default value: \"monospace\"\nwebSettingsMonospaceFontFamily :: (WebSettingsClass self) => Attr self String\nwebSettingsMonospaceFontFamily = newAttrFromStringProperty \"monospace-font-family\"\n\n-- | Whether background images should be printed\n--\n-- Default value: True\nwebSettingsPrintBackgrounds :: (WebSettingsClass self) => Attr self Bool\nwebSettingsPrintBackgrounds = newAttrFromBoolProperty \"print-backgrounds\"\n\n-- | Whether text areas are resizable\n--\n-- Default value : True\nwebSettingsResizableTextAreas :: (WebSettingsClass self) => Attr self Bool\nwebSettingsResizableTextAreas = newAttrFromBoolProperty \"resizable-text-areas\"\n\n-- | The default Sans Serif font family used to display text\n-- \n-- Default value \"sans-serif\"\nwebSettingsSansFontFamily :: (WebSettingsClass self) => Attr self String\nwebSettingsSansFontFamily = newAttrFromStringProperty \"sans-serif-font-family\"\n\n\n-- | The default Serif font family used to display text\n--\n-- Default value: \"serif\"\nwebSettingsSerifFontFamily :: (WebSettingsClass self) => Attr self String\nwebSettingsSerifFontFamily = newAttrFromStringProperty \"serif-font-family\"\n\n\n-- | The languages to be used for spell checking, separated by commas\n-- \n-- The locale string typically is in the form lang_COUNTRY,\n-- where lang is an ISO-639 language code, and COUNTRY is an ISO-3166 country code. \n-- For instance, sv_FI for Swedish as written in Finland or pt_BR for Portuguese as written in Brazil.\n--\n-- If no value is specified then the value returned by gtk_get_default_language will be used.\n--\n-- Default value: @Nothing@\nwebSettingsSpellCheckingLang :: (WebSettingsClass self) => Attr self (Maybe String)\nwebSettingsSpellCheckingLang = newAttrFromMaybeStringProperty \"spell-checking-languages\"\n\n#if WEBKIT_CHECK_VERSION (1,1,17)\n-- | Whether the tab key cycles through elements on the page.\n-- \n-- If flag is 'True', pressing the tab key will focus the next element in the @webView@. If flag is 'False',\n-- the @webView@ will interpret tab key presses as normal key presses. If the selected element is\n-- editable, the tab key will cause the insertion of a tab character.\n-- \n-- Default value: 'True'\n--\n-- * Since 1.1.17\nwebSettingsTabKeyCyclesThroughElements :: (WebSettingsClass self) => Attr self Bool\nwebSettingsTabKeyCyclesThroughElements = newAttrFromBoolProperty \"tab-key-cycles-through-elements\"\n#endif\n\n#if WEBKIT_CHECK_VERSION (1,1,18)\n-- | Whether right-clicks should be handled automatically to create, and display the context\n-- menu. Turning this off will make WebKitGTK+ not emit the populate-popup signal. Notice that the\n-- default button press event handler may still handle right clicks for other reasons, such as in-page\n-- context menus, or right-clicks that are handled by the page itself.\n-- \n-- Default value: 'True'\n-- \n-- * Since 1.1.18\nwebSettingsEnableDefaultContextMenu :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnableDefaultContextMenu = newAttrFromBoolProperty \"enable-default-context-menu\"\n\n-- | Enable or disable the page cache. Disabling the page cache is generally only useful for special\n-- circumstances like low-memory scenarios or special purpose applications like static HTML\n-- viewers. This setting only controls the Page Cache, this cache is different than the disk-based or\n-- memory-based traditional resource caches, its point is to make going back and forth between pages\n-- much faster. For details about the different types of caches and their purposes see:\n-- http:\/\/webkit.org\/ blog\/427\/webkit-page-cache-i-the-basics\/\n-- \n-- Default value: 'False'\n-- \n-- * Since 1.1.18\nwebSettingsEnablePageCache :: (WebSettingsClass self) => Attr self Bool\nwebSettingsEnablePageCache = newAttrFromBoolProperty \"enable-page-cache\"\n#endif\n\n-- | The User-Agent string used by WebKit\n-- \n-- This will return a default User-Agent string if a custom string wasn't provided by the application. \n-- Setting this property to a NULL value or an empty string will result in \n-- the User-Agent string being reset to the default value.\n--\n-- Default value: \\\"Mozilla\/5.0 (X11; U; Linux x86_64; c) AppleWebKit\/531.2+ (KHTML, like Gecko) Safari\/531.2+\\\"\n\nwebSettingsUserAgent :: (WebSettingsClass self) => Attr self String\nwebSettingsUserAgent = newAttrFromStringProperty \"user-agent\"\n\n-- | The URI of a stylesheet that is applied to every page.\n--\n-- Default value: @Nothing@\n\nwebSettingsUserStylesheetUri :: (WebSettingsClass self) => Attr self (Maybe String)\nwebSettingsUserStylesheetUri = newAttrFromMaybeStringProperty \"user-stylesheet-uri\"\n\n-- | The value by which the zoom level is changed when zooming in or out\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0.1\nwebSettingsZoomStep :: (WebSettingsClass self) => Attr self Float\nwebSettingsZoomStep = newAttrFromFloatProperty \"zoom-step\"\n \n-- | Enables the site-specific compatibility workarounds.\n--\n-- Default value: False\nwebSettingsEnableSiteSpecificQuirks :: WebSettingsClass self => Attr self Bool\nwebSettingsEnableSiteSpecificQuirks = newAttrFromBoolProperty \"enable-site-specific-quirks\"\n\n#if WEBKIT_CHECK_VERSION (1,1,23)\n-- | Whether to enable the Spatial Navigation. This feature consists in the ability to navigate between\n-- focusable elements in a Web page, such as hyperlinks and form controls, by using Left, Right, Up and\n-- Down arrow keys. For example, if an user presses the Right key, heuristics determine whether there\n-- is an element he might be trying to reach towards the right, and if there are multiple elements,\n-- which element he probably wants.\n-- \n-- Default value: 'False'\n-- \n-- * Since 1.1.23\nwebSettingsEnableSpatialNavigation :: WebSettingsClass self => Attr self Bool\nwebSettingsEnableSpatialNavigation = newAttrFromBoolProperty \"enable-spatial-navigation\"\n#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"621c5e9e969df01ffe09b8fcd52b05f2a18e943d","subject":"fix build failure on ghc-7.4 (Eq constraints)","message":"fix build failure on ghc-7.4 (Eq constraints)\n\nMedia\/Streaming\/GStreamer\/Core\/Buffer.chs:216:13:\n Could not deduce (Eq numT) arising from a use of `\/='\n from the context (BufferClass bufferT, Integral intT, Num numT)\n bound by the type signature for\n marshalGetNum :: (BufferClass bufferT, Integral intT, Num numT) =>\n (Ptr Buffer -> IO intT) -> numT -> bufferT -> Maybe numT\n at Media\/Streaming\/GStreamer\/Core\/Buffer.chs:(213,1)-(218,22)\n Possible fix:\n add (Eq numT) to the context of\n the type signature for\n marshalGetNum :: (BufferClass bufferT, Integral intT, Num numT) =>\n (Ptr Buffer -> IO intT) -> numT -> bufferT -> Maybe numT\n In the expression: n \/= invalid\n In the expression: if n \/= invalid then Just n else Nothing\n In the expression:\n let\n n = fromIntegral\n $ unsafePerformIO $ withMiniObject (toBuffer buffer) getAction\n in if n \/= invalid then Just n else Nothing\n\n","repos":"gtk2hs\/gstreamer","old_file":"Media\/Streaming\/GStreamer\/Core\/Buffer.chs","new_file":"Media\/Streaming\/GStreamer\/Core\/Buffer.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to gstreamer -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GStreamer, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GStreamer documentation.\n-- \n-- |\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\n-- \n-- Data-passing buffer type, supporting sub-buffers.\nmodule Media.Streaming.GStreamer.Core.Buffer (\n \n-- * Types\n\n -- | 'Buffer's are the basic unit of data transfer in GStreamer. The\n -- 'Buffer' type provides all the state necessary to define a\n -- region of memory as part of a stream. Sub-buffers are also\n -- supported, allowing a smaller region of a 'Buffer' to become its\n -- own 'Buffer', with mechansims in place to ensure that neither\n -- memory space goes away prematurely.\n Buffer,\n BufferClass,\n castToBuffer,\n gTypeBuffer,\n\n BufferFlags(..),\n\n-- * Buffer Operations\n bufferOffsetNone,\n bufferGetFlags,\n bufferGetFlagsM,\n bufferSetFlagsM,\n bufferUnsetFlagsM,\n bufferGetSize,\n bufferGetSizeM,\n#if __GLASGOW_HASKELL__ >= 606\n bufferGetData,\n bufferGetDataM,\n bufferSetDataM,\n#endif\n unsafeBufferGetPtrM,\n bufferGetTimestamp,\n bufferGetTimestampM,\n bufferSetTimestampM,\n bufferGetDuration,\n bufferGetDurationM,\n bufferSetDurationM,\n bufferGetCaps,\n bufferGetCapsM,\n bufferSetCapsM,\n bufferGetOffset,\n bufferGetOffsetM,\n bufferSetOffsetM,\n bufferGetOffsetEnd,\n bufferGetOffsetEndM,\n bufferSetOffsetEndM,\n bufferIsDiscont,\n bufferIsDiscontM,\n \n bufferCreateEmpty,\n bufferCreate,\n bufferCreateSub,\n \n bufferIsSpanFast,\n bufferSpan,\n bufferMerge\n \n ) where\n\nimport Control.Monad ( liftM\n , when )\nimport Control.Monad.Trans\n#if __GLASGOW_HASKELL__ >= 606\nimport qualified Data.ByteString as BS\n#if __GLASGOW_HASKELL__ < 608\n#define OLD_BYTESTRING\n#endif\n#endif\n\n{#import Media.Streaming.GStreamer.Core.Types#}\nimport System.Glib.FFI\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\n-- | Get the flags set on @buffer@.\nbufferGetFlags :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a 'Buffer'\n -> [BufferFlags] -- ^ the flags set on @buffer@\nbufferGetFlags = mkMiniObjectGetFlags\n\n-- | Get the flags set on the current 'Buffer'.\nbufferGetFlagsM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m [BufferFlags] -- ^ the flags set on the current 'Buffer'\nbufferGetFlagsM = mkMiniObjectGetFlagsM\n\n-- | Set flags on the current 'Buffer'.\nbufferSetFlagsM :: (BufferClass bufferT, MonadIO m)\n => [BufferFlags] -- ^ @flags@ - the flags to set on the current 'Buffer'\n -> MiniObjectT bufferT m ()\nbufferSetFlagsM = mkMiniObjectSetFlagsM\n\n-- | Unset flags on the current 'Buffer'.\nbufferUnsetFlagsM :: (BufferClass bufferT, MonadIO m)\n => [BufferFlags] -- ^ @flags@ - the flags to unset on the current 'Buffer'\n -> MiniObjectT bufferT m ()\nbufferUnsetFlagsM = mkMiniObjectUnsetFlagsM\n\n-- | Get @buffer@'s size in bytes.\nbufferGetSize :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a 'Buffer'\n -> Word -- ^ the size of @buffer@ in bytes\nbufferGetSize buffer =\n fromIntegral $ unsafePerformIO $\n withMiniObject buffer {# get GstBuffer->size #}\n\nmarshalBufferM :: (BufferClass bufferT, MonadIO m)\n => (Ptr Buffer -> IO a)\n -> MiniObjectT bufferT m a\nmarshalBufferM action = do\n ptr <- askMiniObjectPtr\n liftIO $ action $ castPtr ptr\n\n-- | Get the size of the current 'Buffer' in bytes.\nbufferGetSizeM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m Word -- ^ the size of the current 'Buffer' in bytes\nbufferGetSizeM =\n liftM fromIntegral $\n marshalBufferM {# get GstBuffer->size #}\n\n#if __GLASGOW_HASKELL__ >= 606\n-- | Make an O(n) copy of the data stored in @buffer@.\nbufferGetData :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a 'Buffer'\n -> BS.ByteString -- ^ the data stored in @buffer@\nbufferGetData buffer =\n unsafePerformIO $ withMiniObject buffer $ \\bufferPtr ->\n do ptr <- {# get GstBuffer->data #} bufferPtr\n size <- {# get GstBuffer->size #} bufferPtr\n#ifdef OLD_BYTESTRING\n BS.copyCStringLen (castPtr ptr, fromIntegral size)\n#else\n BS.packCStringLen (castPtr ptr, fromIntegral size)\n#endif\n\n-- | Make an O(n) copy of the current 'Buffer'.\nbufferGetDataM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m BS.ByteString -- ^ the data stored in the current 'Buffer'\nbufferGetDataM =\n marshalBufferM $ \\bufferPtr ->\n do ptr <- {# get GstBuffer->data #} bufferPtr\n size <- {# get GstBuffer->size #} bufferPtr\n#ifdef OLD_BYTESTRING\n BS.copyCStringLen (castPtr ptr, fromIntegral size)\n#else\n BS.packCStringLen (castPtr ptr, fromIntegral size)\n#endif\n\n-- | Store an O(n) copy of the provided data in the current 'Buffer'.\nbufferSetDataM :: (BufferClass bufferT, MonadIO m)\n => BS.ByteString -- ^ @bs@ - the data to store in the current 'Buffer'\n -> MiniObjectT bufferT m ()\nbufferSetDataM bs =\n marshalBufferM $ \\bufferPtr ->\n BS.useAsCStringLen bs $ \\(origData, size) ->\n do mallocData <- {# get GstBuffer->malloc_data #} bufferPtr\n when (mallocData \/= nullPtr) $\n {# call g_free #} $ castPtr mallocData\n newData <- liftM castPtr $ {# call g_malloc #} $ fromIntegral size\n copyBytes (castPtr newData) origData size\n {# set GstBuffer->data #} bufferPtr newData\n {# set GstBuffer->malloc_data #} bufferPtr newData\n {# set GstBuffer->size #} bufferPtr $ fromIntegral size\n#endif\n\n-- | Get a raw pointer to the internal data area for the current\n-- buffer. The pointer may be used to write into the data area if\n-- desired. This function is unsafe in that the pointer should not\n-- be used once the 'Buffer' is returned.\nunsafeBufferGetPtrM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m (Ptr Word8) -- ^ a pointer to the data stored in the current 'Buffer'\nunsafeBufferGetPtrM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM castPtr $\n {# get GstBuffer->data #} ptr\n\nmarshalGetNum :: (BufferClass bufferT, Integral intT, Num numT, Eq numT)\n => (Ptr Buffer -> IO intT)\n -> numT\n -> bufferT\n -> Maybe numT\nmarshalGetNum getAction invalid buffer =\n let n = fromIntegral $ unsafePerformIO $\n withMiniObject (toBuffer buffer) getAction\n in if n \/= invalid\n then Just n\n else Nothing\n\nmarshalGetNumM :: (BufferClass bufferT, Integral intT, Num numT, Eq numT, MonadIO m)\n => (Ptr Buffer -> IO intT)\n -> numT\n -> MiniObjectT bufferT m (Maybe numT)\nmarshalGetNumM getAction invalid =\n marshalBufferM $ \\bufferPtr -> do\n n <- liftM fromIntegral $ getAction bufferPtr\n return $ if n \/= invalid\n then Just n\n else Nothing\n\nmarshalSetNumM :: (BufferClass bufferT, Integral intT, Num numT, MonadIO m)\n => (Ptr Buffer -> numT -> IO ())\n -> intT\n -> Maybe intT\n -> MiniObjectT bufferT m ()\nmarshalSetNumM setAction invalid nM =\n let n = case nM of\n Just n' -> n'\n Nothing -> invalid\n in marshalBufferM $ flip setAction $ fromIntegral n\n\n-- | Get the timestamp on @buffer@.\nbufferGetTimestamp :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a 'Buffer'\n -> Maybe ClockTime -- ^ the timestamp on @buffer@\nbufferGetTimestamp =\n marshalGetNum {# get GstBuffer->timestamp #} clockTimeNone\n\n-- | Get the timestamp on the current 'Buffer'.\nbufferGetTimestampM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m (Maybe ClockTime) -- ^ the timestamp on the current 'Buffer'\nbufferGetTimestampM =\n marshalGetNumM {# get GstBuffer->timestamp #} clockTimeNone\n\n-- | Set the timestamp on the current 'Buffer'.\nbufferSetTimestampM :: (BufferClass bufferT, MonadIO m)\n => Maybe ClockTime -- ^ @timestamp@ - the timestamp to set on the current 'Buffer'\n -> MiniObjectT bufferT m ()\nbufferSetTimestampM =\n marshalSetNumM {# set GstBuffer->timestamp #} clockTimeNone\n\n-- | Get the duration of @buffer@.\nbufferGetDuration :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a 'Buffer'\n -> Maybe ClockTime -- ^ the duration of @buffer@\nbufferGetDuration =\n marshalGetNum {# get GstBuffer->duration #} clockTimeNone\n\n-- | Get the duration of the current 'Buffer'.\nbufferGetDurationM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m (Maybe ClockTime) -- ^ the duration of the current 'Buffer'\nbufferGetDurationM =\n marshalGetNumM {# get GstBuffer->duration #} clockTimeNone\n\n-- | Set the duration of the current 'Buffer'.\nbufferSetDurationM :: (BufferClass bufferT, MonadIO m)\n => Maybe ClockTime -- ^ @duration@ - the duration to set on the current 'Buffer'\n -> MiniObjectT bufferT m ()\nbufferSetDurationM =\n marshalSetNumM {# set GstBuffer->duration #} clockTimeNone\n\n-- | Get the 'Caps' of @buffer@.\nbufferGetCaps :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a buffer\n -> Maybe Caps -- ^ the 'Caps' of @buffer@ if set, otherwise 'Nothing'\nbufferGetCaps buffer =\n unsafePerformIO $\n {# call buffer_get_caps #} (toBuffer buffer) >>=\n maybePeek takeCaps\n\n-- | Get the caps of the current 'Buffer'.\nbufferGetCapsM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m (Maybe Caps) -- ^ the 'Caps' of the current 'Buffer'\n -- if set, otherwise 'Nothing'\nbufferGetCapsM = do\n ptr <- askMiniObjectPtr\n liftIO $ gst_buffer_get_caps (castPtr ptr) >>=\n maybePeek takeCaps\n where _ = {# call buffer_get_caps #}\n\n-- | Set the caps of the current 'Buffer'.\nbufferSetCapsM :: (BufferClass bufferT, MonadIO m)\n => Maybe Caps -- ^ @caps@ - the 'Caps' to set on the current\n -- 'Buffer', or 'Nothing' to unset them\n -> MiniObjectT bufferT m ()\nbufferSetCapsM capsM = do\n ptr <- askMiniObjectPtr\n liftIO $ withForeignPtr (case capsM of\n Just caps -> unCaps caps\n Nothing -> nullForeignPtr)\n (gst_buffer_set_caps $ castPtr ptr)\n where _ = {# call buffer_set_caps #}\n\n-- | Get the start offset of the 'Buffer'.\nbufferGetOffset :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a buffer\n -> Maybe Word64 -- ^ the start offset of @buffer@ if set, otherwise 'Nothing'\nbufferGetOffset =\n marshalGetNum {# get GstBuffer->offset #} bufferOffsetNone\n\n-- | Get the start offset of the current 'Buffer'.\nbufferGetOffsetM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m (Maybe Word64) -- ^ the start offset of the current\n -- 'Buffer' if set, otherwise 'Nothing'\nbufferGetOffsetM =\n marshalGetNumM {# get GstBuffer->offset #} bufferOffsetNone\n\n-- | Set the start offset of the current 'Buffer'.\nbufferSetOffsetM :: (BufferClass bufferT, MonadIO m)\n => Maybe Word64 -- ^ @offset@ - the start offset to set on the current buffer\n -> MiniObjectT bufferT m ()\nbufferSetOffsetM =\n marshalSetNumM {# set GstBuffer->offset #} bufferOffsetNone\n\n-- | Get the end offset of the 'Buffer'.\nbufferGetOffsetEnd :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a buffer\n -> Maybe Word64 -- ^ the end offset of @buffer@ if set, otherwise 'Nothing'\nbufferGetOffsetEnd =\n marshalGetNum {# get GstBuffer->offset_end #} bufferOffsetNone\n\n-- | Get the end offset of the current 'Buffer'.\nbufferGetOffsetEndM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m (Maybe Word64) -- ^ the start offset of the current\n -- 'Buffer' if set, otherwise 'Nothing'\nbufferGetOffsetEndM =\n marshalGetNumM {# get GstBuffer->offset_end #} bufferOffsetNone\n\n-- | Set the end offset of the current 'Buffer'.\nbufferSetOffsetEndM :: (BufferClass bufferT, MonadIO m)\n => Maybe Word64 -- ^ @offset@ - the end offset to set on the current buffer\n -> MiniObjectT bufferT m ()\nbufferSetOffsetEndM =\n marshalSetNumM {# set GstBuffer->offset_end #} bufferOffsetNone\n\n-- | Return 'True' if the 'Buffer' marks a discontinuity in a stream, or\n-- 'False' otherwise. This typically occurs after a seek or a\n-- dropped buffer from a live or network source.\nbufferIsDiscont :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a buffer\n -> Bool -- ^ 'True' if @buffer@ marks a discontinuity in a stream\nbufferIsDiscont =\n (elem BufferDiscont) . bufferGetFlags\n\n-- | Return 'True' if the current 'Buffer' marks a discontinuity in a\n-- stream, or 'False' otherwise.\nbufferIsDiscontM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m Bool -- ^ 'True' if the current buffer marks a\n -- discontinuity in a stream\nbufferIsDiscontM =\n liftM (elem BufferDiscont) $ bufferGetFlagsM\n\n-- | Create an empty 'Buffer' and mutate it according to the given\n-- action. Once this function returns, the 'Buffer' is immutable.\nbufferCreateEmpty :: MonadIO m\n => MiniObjectT Buffer m a -- ^ @mutate@ - the mutating action\n -> m (Buffer, a) -- ^ the new buffer and the action's result\nbufferCreateEmpty =\n marshalMiniObjectModify $ liftIO {# call buffer_new #}\n\n-- | Create and mutate a 'Buffer' of the given size.\nbufferCreate :: MonadIO m\n => Word -- ^ @size@ - the size of the 'Buffer' to be created\n -> MiniObjectT Buffer m a -- ^ @mutate@ - the mutating action\n -> m (Buffer, a) -- ^ the new 'Buffer' and the action's result\nbufferCreate size =\n marshalMiniObjectModify $\n liftIO $ {# call buffer_new_and_alloc #} $ fromIntegral size\n\n-- | Create a sub-buffer from an existing 'Buffer' with the given offset\n-- and size. This sub-buffer uses the actual memory space of the\n-- parent buffer. Thus function will copy the offset and timestamp\n-- fields when the offset is 0. Otherwise, they will both be set to\n-- 'Nothing'. If the offset is 0 and the size is the total size of\n-- the parent, the duration and offset end fields are also\n-- copied. Otherwise they will be set to 'Nothing'.\nbufferCreateSub :: BufferClass bufferT\n => bufferT -- ^ @parent@ - the parent buffer\n -> Word -- ^ @offset@ - the offset\n -> Word -- ^ @size@ - the size\n -> Maybe Buffer -- ^ the new sub-buffer\nbufferCreateSub parent offset size =\n unsafePerformIO $\n {# call buffer_create_sub #} (toBuffer parent)\n (fromIntegral offset)\n (fromIntegral size) >>=\n maybePeek takeMiniObject\n\n-- | Return 'True' if 'bufferSpan' can be done without copying the\n-- data, or 'False' otherwise.\nbufferIsSpanFast :: (BufferClass bufferT1, BufferClass bufferT2)\n => bufferT1 -- ^ @buffer1@ - the first buffer\n -> bufferT2 -- ^ @buffer2@ - the second buffer\n -> Bool -- ^ 'True' if the buffers are contiguous,\n -- or 'False' if copying would be\n -- required\nbufferIsSpanFast buffer1 buffer2 =\n toBool $ unsafePerformIO $\n {# call buffer_is_span_fast #} (toBuffer buffer1)\n (toBuffer buffer2)\n\n-- | Create a new 'Buffer' that consists of a span across the given\n-- buffers. Logically, the buffers are concatenated to make a larger\n-- buffer, and a new buffer is created at the given offset and with\n-- the given size.\n-- \n-- If the two buffers are children of the same larger buffer, and\n-- are contiguous, no copying is necessary. You can use\n-- 'bufferIsSpanFast' to determine if copying is needed.\nbufferSpan :: (BufferClass bufferT1, BufferClass bufferT2)\n => bufferT1 -- ^ @buffer1@ - the first buffer\n -> Word32 -- ^ @offset@ - the offset into the concatenated buffer\n -> bufferT2 -- ^ @buffer2@ - the second buffer\n -> Word32 -- ^ @len@ - the length of the final buffer\n -> Maybe Buffer -- ^ the spanning buffer, or 'Nothing' if\n -- the arguments are invalid\nbufferSpan buffer1 offset buffer2 len =\n unsafePerformIO $\n {# call buffer_span #} (toBuffer buffer1)\n (fromIntegral offset)\n (toBuffer buffer2)\n (fromIntegral len) >>=\n maybePeek takeMiniObject\n\n-- | Concatenate two buffers. If the buffers point to contiguous memory\n-- areas, no copying will occur.\nbufferMerge :: (BufferClass bufferT1, BufferClass bufferT2)\n => bufferT1 -- ^ @buffer1@ - a buffer\n -> bufferT2 -- ^ @buffer2@ - a buffer\n -> Buffer -- ^ the concatenation of the buffers\nbufferMerge buffer1 buffer2 =\n unsafePerformIO $\n {# call buffer_merge #} (toBuffer buffer1)\n (toBuffer buffer2) >>=\n takeMiniObject\n","old_contents":"{-# LANGUAGE CPP #-}\n-- GIMP Toolkit (GTK) Binding for Haskell: binding to gstreamer -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GStreamer, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GStreamer documentation.\n-- \n-- |\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\n-- \n-- Data-passing buffer type, supporting sub-buffers.\nmodule Media.Streaming.GStreamer.Core.Buffer (\n \n-- * Types\n\n -- | 'Buffer's are the basic unit of data transfer in GStreamer. The\n -- 'Buffer' type provides all the state necessary to define a\n -- region of memory as part of a stream. Sub-buffers are also\n -- supported, allowing a smaller region of a 'Buffer' to become its\n -- own 'Buffer', with mechansims in place to ensure that neither\n -- memory space goes away prematurely.\n Buffer,\n BufferClass,\n castToBuffer,\n gTypeBuffer,\n\n BufferFlags(..),\n\n-- * Buffer Operations\n bufferOffsetNone,\n bufferGetFlags,\n bufferGetFlagsM,\n bufferSetFlagsM,\n bufferUnsetFlagsM,\n bufferGetSize,\n bufferGetSizeM,\n#if __GLASGOW_HASKELL__ >= 606\n bufferGetData,\n bufferGetDataM,\n bufferSetDataM,\n#endif\n unsafeBufferGetPtrM,\n bufferGetTimestamp,\n bufferGetTimestampM,\n bufferSetTimestampM,\n bufferGetDuration,\n bufferGetDurationM,\n bufferSetDurationM,\n bufferGetCaps,\n bufferGetCapsM,\n bufferSetCapsM,\n bufferGetOffset,\n bufferGetOffsetM,\n bufferSetOffsetM,\n bufferGetOffsetEnd,\n bufferGetOffsetEndM,\n bufferSetOffsetEndM,\n bufferIsDiscont,\n bufferIsDiscontM,\n \n bufferCreateEmpty,\n bufferCreate,\n bufferCreateSub,\n \n bufferIsSpanFast,\n bufferSpan,\n bufferMerge\n \n ) where\n\nimport Control.Monad ( liftM\n , when )\nimport Control.Monad.Trans\n#if __GLASGOW_HASKELL__ >= 606\nimport qualified Data.ByteString as BS\n#if __GLASGOW_HASKELL__ < 608\n#define OLD_BYTESTRING\n#endif\n#endif\n\n{#import Media.Streaming.GStreamer.Core.Types#}\nimport System.Glib.FFI\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\n-- | Get the flags set on @buffer@.\nbufferGetFlags :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a 'Buffer'\n -> [BufferFlags] -- ^ the flags set on @buffer@\nbufferGetFlags = mkMiniObjectGetFlags\n\n-- | Get the flags set on the current 'Buffer'.\nbufferGetFlagsM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m [BufferFlags] -- ^ the flags set on the current 'Buffer'\nbufferGetFlagsM = mkMiniObjectGetFlagsM\n\n-- | Set flags on the current 'Buffer'.\nbufferSetFlagsM :: (BufferClass bufferT, MonadIO m)\n => [BufferFlags] -- ^ @flags@ - the flags to set on the current 'Buffer'\n -> MiniObjectT bufferT m ()\nbufferSetFlagsM = mkMiniObjectSetFlagsM\n\n-- | Unset flags on the current 'Buffer'.\nbufferUnsetFlagsM :: (BufferClass bufferT, MonadIO m)\n => [BufferFlags] -- ^ @flags@ - the flags to unset on the current 'Buffer'\n -> MiniObjectT bufferT m ()\nbufferUnsetFlagsM = mkMiniObjectUnsetFlagsM\n\n-- | Get @buffer@'s size in bytes.\nbufferGetSize :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a 'Buffer'\n -> Word -- ^ the size of @buffer@ in bytes\nbufferGetSize buffer =\n fromIntegral $ unsafePerformIO $\n withMiniObject buffer {# get GstBuffer->size #}\n\nmarshalBufferM :: (BufferClass bufferT, MonadIO m)\n => (Ptr Buffer -> IO a)\n -> MiniObjectT bufferT m a\nmarshalBufferM action = do\n ptr <- askMiniObjectPtr\n liftIO $ action $ castPtr ptr\n\n-- | Get the size of the current 'Buffer' in bytes.\nbufferGetSizeM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m Word -- ^ the size of the current 'Buffer' in bytes\nbufferGetSizeM =\n liftM fromIntegral $\n marshalBufferM {# get GstBuffer->size #}\n\n#if __GLASGOW_HASKELL__ >= 606\n-- | Make an O(n) copy of the data stored in @buffer@.\nbufferGetData :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a 'Buffer'\n -> BS.ByteString -- ^ the data stored in @buffer@\nbufferGetData buffer =\n unsafePerformIO $ withMiniObject buffer $ \\bufferPtr ->\n do ptr <- {# get GstBuffer->data #} bufferPtr\n size <- {# get GstBuffer->size #} bufferPtr\n#ifdef OLD_BYTESTRING\n BS.copyCStringLen (castPtr ptr, fromIntegral size)\n#else\n BS.packCStringLen (castPtr ptr, fromIntegral size)\n#endif\n\n-- | Make an O(n) copy of the current 'Buffer'.\nbufferGetDataM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m BS.ByteString -- ^ the data stored in the current 'Buffer'\nbufferGetDataM =\n marshalBufferM $ \\bufferPtr ->\n do ptr <- {# get GstBuffer->data #} bufferPtr\n size <- {# get GstBuffer->size #} bufferPtr\n#ifdef OLD_BYTESTRING\n BS.copyCStringLen (castPtr ptr, fromIntegral size)\n#else\n BS.packCStringLen (castPtr ptr, fromIntegral size)\n#endif\n\n-- | Store an O(n) copy of the provided data in the current 'Buffer'.\nbufferSetDataM :: (BufferClass bufferT, MonadIO m)\n => BS.ByteString -- ^ @bs@ - the data to store in the current 'Buffer'\n -> MiniObjectT bufferT m ()\nbufferSetDataM bs =\n marshalBufferM $ \\bufferPtr ->\n BS.useAsCStringLen bs $ \\(origData, size) ->\n do mallocData <- {# get GstBuffer->malloc_data #} bufferPtr\n when (mallocData \/= nullPtr) $\n {# call g_free #} $ castPtr mallocData\n newData <- liftM castPtr $ {# call g_malloc #} $ fromIntegral size\n copyBytes (castPtr newData) origData size\n {# set GstBuffer->data #} bufferPtr newData\n {# set GstBuffer->malloc_data #} bufferPtr newData\n {# set GstBuffer->size #} bufferPtr $ fromIntegral size\n#endif\n\n-- | Get a raw pointer to the internal data area for the current\n-- buffer. The pointer may be used to write into the data area if\n-- desired. This function is unsafe in that the pointer should not\n-- be used once the 'Buffer' is returned.\nunsafeBufferGetPtrM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m (Ptr Word8) -- ^ a pointer to the data stored in the current 'Buffer'\nunsafeBufferGetPtrM = do\n ptr <- askMiniObjectPtr\n liftIO $ liftM castPtr $\n {# get GstBuffer->data #} ptr\n\nmarshalGetNum :: (BufferClass bufferT, Integral intT, Num numT)\n => (Ptr Buffer -> IO intT)\n -> numT\n -> bufferT\n -> Maybe numT\nmarshalGetNum getAction invalid buffer =\n let n = fromIntegral $ unsafePerformIO $\n withMiniObject (toBuffer buffer) getAction\n in if n \/= invalid\n then Just n\n else Nothing\n\nmarshalGetNumM :: (BufferClass bufferT, Integral intT, Num numT, MonadIO m)\n => (Ptr Buffer -> IO intT)\n -> numT\n -> MiniObjectT bufferT m (Maybe numT)\nmarshalGetNumM getAction invalid =\n marshalBufferM $ \\bufferPtr -> do\n n <- liftM fromIntegral $ getAction bufferPtr\n return $ if n \/= invalid\n then Just n\n else Nothing\n\nmarshalSetNumM :: (BufferClass bufferT, Integral intT, Num numT, MonadIO m)\n => (Ptr Buffer -> numT -> IO ())\n -> intT\n -> Maybe intT\n -> MiniObjectT bufferT m ()\nmarshalSetNumM setAction invalid nM =\n let n = case nM of\n Just n' -> n'\n Nothing -> invalid\n in marshalBufferM $ flip setAction $ fromIntegral n\n\n-- | Get the timestamp on @buffer@.\nbufferGetTimestamp :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a 'Buffer'\n -> Maybe ClockTime -- ^ the timestamp on @buffer@\nbufferGetTimestamp =\n marshalGetNum {# get GstBuffer->timestamp #} clockTimeNone\n\n-- | Get the timestamp on the current 'Buffer'.\nbufferGetTimestampM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m (Maybe ClockTime) -- ^ the timestamp on the current 'Buffer'\nbufferGetTimestampM =\n marshalGetNumM {# get GstBuffer->timestamp #} clockTimeNone\n\n-- | Set the timestamp on the current 'Buffer'.\nbufferSetTimestampM :: (BufferClass bufferT, MonadIO m)\n => Maybe ClockTime -- ^ @timestamp@ - the timestamp to set on the current 'Buffer'\n -> MiniObjectT bufferT m ()\nbufferSetTimestampM =\n marshalSetNumM {# set GstBuffer->timestamp #} clockTimeNone\n\n-- | Get the duration of @buffer@.\nbufferGetDuration :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a 'Buffer'\n -> Maybe ClockTime -- ^ the duration of @buffer@\nbufferGetDuration =\n marshalGetNum {# get GstBuffer->duration #} clockTimeNone\n\n-- | Get the duration of the current 'Buffer'.\nbufferGetDurationM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m (Maybe ClockTime) -- ^ the duration of the current 'Buffer'\nbufferGetDurationM =\n marshalGetNumM {# get GstBuffer->duration #} clockTimeNone\n\n-- | Set the duration of the current 'Buffer'.\nbufferSetDurationM :: (BufferClass bufferT, MonadIO m)\n => Maybe ClockTime -- ^ @duration@ - the duration to set on the current 'Buffer'\n -> MiniObjectT bufferT m ()\nbufferSetDurationM =\n marshalSetNumM {# set GstBuffer->duration #} clockTimeNone\n\n-- | Get the 'Caps' of @buffer@.\nbufferGetCaps :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a buffer\n -> Maybe Caps -- ^ the 'Caps' of @buffer@ if set, otherwise 'Nothing'\nbufferGetCaps buffer =\n unsafePerformIO $\n {# call buffer_get_caps #} (toBuffer buffer) >>=\n maybePeek takeCaps\n\n-- | Get the caps of the current 'Buffer'.\nbufferGetCapsM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m (Maybe Caps) -- ^ the 'Caps' of the current 'Buffer'\n -- if set, otherwise 'Nothing'\nbufferGetCapsM = do\n ptr <- askMiniObjectPtr\n liftIO $ gst_buffer_get_caps (castPtr ptr) >>=\n maybePeek takeCaps\n where _ = {# call buffer_get_caps #}\n\n-- | Set the caps of the current 'Buffer'.\nbufferSetCapsM :: (BufferClass bufferT, MonadIO m)\n => Maybe Caps -- ^ @caps@ - the 'Caps' to set on the current\n -- 'Buffer', or 'Nothing' to unset them\n -> MiniObjectT bufferT m ()\nbufferSetCapsM capsM = do\n ptr <- askMiniObjectPtr\n liftIO $ withForeignPtr (case capsM of\n Just caps -> unCaps caps\n Nothing -> nullForeignPtr)\n (gst_buffer_set_caps $ castPtr ptr)\n where _ = {# call buffer_set_caps #}\n\n-- | Get the start offset of the 'Buffer'.\nbufferGetOffset :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a buffer\n -> Maybe Word64 -- ^ the start offset of @buffer@ if set, otherwise 'Nothing'\nbufferGetOffset =\n marshalGetNum {# get GstBuffer->offset #} bufferOffsetNone\n\n-- | Get the start offset of the current 'Buffer'.\nbufferGetOffsetM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m (Maybe Word64) -- ^ the start offset of the current\n -- 'Buffer' if set, otherwise 'Nothing'\nbufferGetOffsetM =\n marshalGetNumM {# get GstBuffer->offset #} bufferOffsetNone\n\n-- | Set the start offset of the current 'Buffer'.\nbufferSetOffsetM :: (BufferClass bufferT, MonadIO m)\n => Maybe Word64 -- ^ @offset@ - the start offset to set on the current buffer\n -> MiniObjectT bufferT m ()\nbufferSetOffsetM =\n marshalSetNumM {# set GstBuffer->offset #} bufferOffsetNone\n\n-- | Get the end offset of the 'Buffer'.\nbufferGetOffsetEnd :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a buffer\n -> Maybe Word64 -- ^ the end offset of @buffer@ if set, otherwise 'Nothing'\nbufferGetOffsetEnd =\n marshalGetNum {# get GstBuffer->offset_end #} bufferOffsetNone\n\n-- | Get the end offset of the current 'Buffer'.\nbufferGetOffsetEndM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m (Maybe Word64) -- ^ the start offset of the current\n -- 'Buffer' if set, otherwise 'Nothing'\nbufferGetOffsetEndM =\n marshalGetNumM {# get GstBuffer->offset_end #} bufferOffsetNone\n\n-- | Set the end offset of the current 'Buffer'.\nbufferSetOffsetEndM :: (BufferClass bufferT, MonadIO m)\n => Maybe Word64 -- ^ @offset@ - the end offset to set on the current buffer\n -> MiniObjectT bufferT m ()\nbufferSetOffsetEndM =\n marshalSetNumM {# set GstBuffer->offset_end #} bufferOffsetNone\n\n-- | Return 'True' if the 'Buffer' marks a discontinuity in a stream, or\n-- 'False' otherwise. This typically occurs after a seek or a\n-- dropped buffer from a live or network source.\nbufferIsDiscont :: BufferClass bufferT\n => bufferT -- ^ @buffer@ - a buffer\n -> Bool -- ^ 'True' if @buffer@ marks a discontinuity in a stream\nbufferIsDiscont =\n (elem BufferDiscont) . bufferGetFlags\n\n-- | Return 'True' if the current 'Buffer' marks a discontinuity in a\n-- stream, or 'False' otherwise.\nbufferIsDiscontM :: (BufferClass bufferT, MonadIO m)\n => MiniObjectT bufferT m Bool -- ^ 'True' if the current buffer marks a\n -- discontinuity in a stream\nbufferIsDiscontM =\n liftM (elem BufferDiscont) $ bufferGetFlagsM\n\n-- | Create an empty 'Buffer' and mutate it according to the given\n-- action. Once this function returns, the 'Buffer' is immutable.\nbufferCreateEmpty :: MonadIO m\n => MiniObjectT Buffer m a -- ^ @mutate@ - the mutating action\n -> m (Buffer, a) -- ^ the new buffer and the action's result\nbufferCreateEmpty =\n marshalMiniObjectModify $ liftIO {# call buffer_new #}\n\n-- | Create and mutate a 'Buffer' of the given size.\nbufferCreate :: MonadIO m\n => Word -- ^ @size@ - the size of the 'Buffer' to be created\n -> MiniObjectT Buffer m a -- ^ @mutate@ - the mutating action\n -> m (Buffer, a) -- ^ the new 'Buffer' and the action's result\nbufferCreate size =\n marshalMiniObjectModify $\n liftIO $ {# call buffer_new_and_alloc #} $ fromIntegral size\n\n-- | Create a sub-buffer from an existing 'Buffer' with the given offset\n-- and size. This sub-buffer uses the actual memory space of the\n-- parent buffer. Thus function will copy the offset and timestamp\n-- fields when the offset is 0. Otherwise, they will both be set to\n-- 'Nothing'. If the offset is 0 and the size is the total size of\n-- the parent, the duration and offset end fields are also\n-- copied. Otherwise they will be set to 'Nothing'.\nbufferCreateSub :: BufferClass bufferT\n => bufferT -- ^ @parent@ - the parent buffer\n -> Word -- ^ @offset@ - the offset\n -> Word -- ^ @size@ - the size\n -> Maybe Buffer -- ^ the new sub-buffer\nbufferCreateSub parent offset size =\n unsafePerformIO $\n {# call buffer_create_sub #} (toBuffer parent)\n (fromIntegral offset)\n (fromIntegral size) >>=\n maybePeek takeMiniObject\n\n-- | Return 'True' if 'bufferSpan' can be done without copying the\n-- data, or 'False' otherwise.\nbufferIsSpanFast :: (BufferClass bufferT1, BufferClass bufferT2)\n => bufferT1 -- ^ @buffer1@ - the first buffer\n -> bufferT2 -- ^ @buffer2@ - the second buffer\n -> Bool -- ^ 'True' if the buffers are contiguous,\n -- or 'False' if copying would be\n -- required\nbufferIsSpanFast buffer1 buffer2 =\n toBool $ unsafePerformIO $\n {# call buffer_is_span_fast #} (toBuffer buffer1)\n (toBuffer buffer2)\n\n-- | Create a new 'Buffer' that consists of a span across the given\n-- buffers. Logically, the buffers are concatenated to make a larger\n-- buffer, and a new buffer is created at the given offset and with\n-- the given size.\n-- \n-- If the two buffers are children of the same larger buffer, and\n-- are contiguous, no copying is necessary. You can use\n-- 'bufferIsSpanFast' to determine if copying is needed.\nbufferSpan :: (BufferClass bufferT1, BufferClass bufferT2)\n => bufferT1 -- ^ @buffer1@ - the first buffer\n -> Word32 -- ^ @offset@ - the offset into the concatenated buffer\n -> bufferT2 -- ^ @buffer2@ - the second buffer\n -> Word32 -- ^ @len@ - the length of the final buffer\n -> Maybe Buffer -- ^ the spanning buffer, or 'Nothing' if\n -- the arguments are invalid\nbufferSpan buffer1 offset buffer2 len =\n unsafePerformIO $\n {# call buffer_span #} (toBuffer buffer1)\n (fromIntegral offset)\n (toBuffer buffer2)\n (fromIntegral len) >>=\n maybePeek takeMiniObject\n\n-- | Concatenate two buffers. If the buffers point to contiguous memory\n-- areas, no copying will occur.\nbufferMerge :: (BufferClass bufferT1, BufferClass bufferT2)\n => bufferT1 -- ^ @buffer1@ - a buffer\n -> bufferT2 -- ^ @buffer2@ - a buffer\n -> Buffer -- ^ the concatenation of the buffers\nbufferMerge buffer1 buffer2 =\n unsafePerformIO $\n {# call buffer_merge #} (toBuffer buffer1)\n (toBuffer buffer2) >>=\n takeMiniObject\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"f6c4254b4a9ae0d3848f8a7b87583b8ca7384fcf","subject":"Fix treeView.chs docs.","message":"Fix treeView.chs docs.\n","repos":"gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte","old_file":"gtk\/Graphics\/UI\/Gtk\/ModelView\/TreeView.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/ModelView\/TreeView.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget TreeView\n--\n-- Author : Axel Simon\n--\n-- Created: 9 May 2001\n--\n-- Copyright (C) 2001-2005 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- TODO\n--\n-- gtk_tree_view_get_bin_window is to compare the GDK window from incoming\n-- events. We don't marshal that window parameter, so this function is not\n-- bound either.\n--\n-- The following functions related to drag and drop:\n-- treeViewSetDragDestRow, treeViewGetDragDestRow, treeViewGetDestRowAtPos\n-- these seem to be useful only in cases when the user wants to implement\n-- drag and drop himself rather than use the widget's implementation. I\n-- think this would be a bad idea in the first place.\n--\n-- get_search_equal_func is missing: proper memory management is impossible\n--\n-- gtk_tree_view_set_destroy_count_func is not meant to be useful\n--\n-- expand-collapse-cursor-row needs to be bound if it is useful to expand\n-- and collapse rows in a user-defined manner. Would only work on Gtk 2.2\n-- and higher since the return parameter changed\n--\n-- move_cursor, select_all, select_cursor_parent, select_cursor_row\n-- toggle_cursor_row, unselect_all are not bound.\n-- These functions are only useful to change the widgets\n-- behaviour for these actions. Everything else can be done with\n-- cursor_changed and columns_changed\n--\n-- set_scroll_adjustment makes sense if the user monitors the scroll bars\n-- and the scroll bars can be replaced anytime (the latter is odd)\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- A widget for displaying both trees and lists.\n--\nmodule Graphics.UI.Gtk.ModelView.TreeView (\n-- * Description\n-- \n-- | Widget that displays any object that implements the 'TreeModel'\n-- interface.\n--\n-- The widget supports scrolling natively. This implies that pixel \n-- coordinates can be given in two formats: relative to the current view's\n-- upper left corner or relative to the whole list's coordinates. The former\n-- are called widget coordinates while the letter are called tree \n-- coordinates.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----TreeView\n-- @\n\n-- * Types\n TreeView,\n TreeViewClass,\n castToTreeView, gTypeTreeView,\n toTreeView,\n Point,\n DragAction(..),\n#if GTK_CHECK_VERSION(2,10,0)\n TreeViewGridLines(..),\n#endif\n\n-- * Constructors\n treeViewNew,\n treeViewNewWithModel,\n\n-- * Methods\n treeViewGetModel,\n treeViewSetModel,\n treeViewGetSelection,\n treeViewGetHAdjustment,\n treeViewSetHAdjustment,\n treeViewGetVAdjustment,\n treeViewSetVAdjustment,\n treeViewGetHeadersVisible,\n treeViewSetHeadersVisible,\n treeViewColumnsAutosize,\n treeViewSetHeadersClickable,\n treeViewGetRulesHint,\n treeViewSetRulesHint,\n treeViewAppendColumn,\n treeViewRemoveColumn,\n treeViewInsertColumn,\n treeViewGetColumn,\n treeViewGetColumns,\n treeViewMoveColumnAfter,\n treeViewMoveColumnFirst,\n treeViewSetExpanderColumn,\n treeViewGetExpanderColumn,\n treeViewSetColumnDragFunction,\n treeViewScrollToPoint,\n treeViewScrollToCell,\n treeViewSetCursor,\n#if GTK_CHECK_VERSION(2,2,0)\n treeViewSetCursorOnCell,\n#endif\n treeViewGetCursor,\n treeViewRowActivated,\n treeViewExpandAll,\n treeViewCollapseAll,\n#if GTK_CHECK_VERSION(2,2,0)\n treeViewExpandToPath,\n#endif\n treeViewExpandRow,\n treeViewCollapseRow,\n treeViewMapExpandedRows,\n treeViewRowExpanded,\n treeViewGetReorderable,\n treeViewSetReorderable,\n treeViewGetPathAtPos,\n treeViewGetCellArea,\n treeViewGetBackgroundArea,\n treeViewGetVisibleRect,\n#if GTK_CHECK_VERSION(2,12,0)\n treeViewConvertBinWindowToTreeCoords,\n treeViewConvertBinWindowToWidgetCoords,\n treeViewConvertTreeToBinWindowCoords,\n treeViewConvertTreeToWidgetCoords,\n treeViewConvertWidgetToBinWindowCoords,\n treeViewConvertWidgetToTreeCoords,\n#endif\n treeViewCreateRowDragIcon,\n treeViewGetEnableSearch,\n treeViewSetEnableSearch,\n treeViewGetSearchColumn,\n treeViewSetSearchColumn,\n treeViewSetSearchEqualFunc,\n#if GTK_CHECK_VERSION(2,6,0)\n treeViewGetFixedHeightMode,\n treeViewSetFixedHeightMode,\n treeViewGetHoverSelection,\n treeViewSetHoverSelection,\n treeViewGetHoverExpand,\n treeViewSetHoverExpand,\n#if GTK_CHECK_VERSION(2,10,0)\n treeViewGetHeadersClickable,\n#endif\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n treeViewGetVisibleRange,\n#endif\n#if GTK_CHECK_VERSION(2,10,0)\n treeViewEnableModelDragDest,\n treeViewEnableModelDragSource,\n treeViewUnsetRowsDragSource,\n treeViewUnsetRowsDragDest,\n treeViewGetSearchEntry,\n treeViewSetSearchEntry,\n#endif\n#if GTK_CHECK_VERSION(2,6,0)\n treeViewSetRowSeparatorFunc,\n#if GTK_CHECK_VERSION(2,10,0)\n treeViewGetRubberBanding,\n treeViewSetRubberBanding,\n treeViewGetEnableTreeLines,\n treeViewSetEnableTreeLines,\n treeViewGetGridLines,\n treeViewSetGridLines,\n#endif\n#endif\n-- * Attributes\n treeViewModel,\n treeViewHAdjustment,\n treeViewVAdjustment,\n treeViewHeadersVisible,\n treeViewHeadersClickable,\n treeViewExpanderColumn,\n treeViewReorderable,\n treeViewRulesHint,\n treeViewEnableSearch,\n treeViewSearchColumn,\n#if GTK_CHECK_VERSION(2,4,0)\n treeViewFixedHeightMode,\n#if GTK_CHECK_VERSION(2,6,0)\n treeViewHoverSelection,\n treeViewHoverExpand,\n#endif\n#endif\n treeViewShowExpanders,\n treeViewLevelIndentation,\n treeViewRubberBanding,\n#if GTK_CHECK_VERSION(2,10,0)\n treeViewEnableGridLines,\n#endif\n treeViewEnableTreeLines,\n#if GTK_CHECK_VERSION(2,10,0)\n treeViewGridLines,\n treeViewSearchEntry,\n#endif\n\n-- * Signals\n columnsChanged,\n cursorChanged,\n rowCollapsed,\n rowExpanded,\n testCollapseRow,\n testExpandRow,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n treeViewWidgetToTreeCoords,\n treeViewTreeToWidgetCoords,\n\n onColumnsChanged,\n afterColumnsChanged,\n onCursorChanged,\n afterCursorChanged,\n onRowActivated,\n afterRowActivated,\n onRowCollapsed,\n afterRowCollapsed,\n onRowExpanded,\n afterRowExpanded,\n onStartInteractiveSearch,\n afterStartInteractiveSearch,\n onTestCollapseRow,\n afterTestCollapseRow,\n onTestExpandRow,\n afterTestExpandRow\n#endif\n ) where\n\nimport Control.Monad\t(liftM, mapM)\nimport Data.Maybe\t(fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GList\t\t(fromGList)\nimport System.Glib.Flags\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(makeNewGObject, constructNewGObject,\n\t\t\t\t\t destroyFunPtr)\nimport Graphics.UI.Gtk.Gdk.Enums (DragAction(..))\nimport Graphics.UI.Gtk.Gdk.Events (Modifier(..))\nimport Graphics.UI.Gtk.General.Structs\t(Point, Rectangle)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.ModelView.TreeViewColumn#}\nimport Graphics.UI.Gtk.ModelView.TreeModel (ColumnId, columnIdToNumber,\n makeColumnIdString)\n{#import Graphics.UI.Gtk.ModelView.Types#}\n{#import Graphics.UI.Gtk.General.DNDTypes#} (TargetList(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Creates a new 'TreeView' widget.\n--\ntreeViewNew :: IO TreeView\ntreeViewNew =\n makeNewObject mkTreeView $\n liftM (castPtr :: Ptr Widget -> Ptr TreeView) $\n {# call tree_view_new #}\n\n-- | Create a new 'TreeView' \n-- widget with @model@ as the storage model.\n--\ntreeViewNewWithModel :: TreeModelClass model => model -> IO TreeView\ntreeViewNewWithModel model =\n makeNewObject mkTreeView $\n liftM (castPtr :: Ptr Widget -> Ptr TreeView) $\n {# call tree_view_new_with_model #}\n (toTreeModel model)\n\n--------------------\n-- Methods\n\n-- | Returns the model that supplies the data for\n-- this 'TreeView'. Returns @Nothing@ if the model is unset.\n--\ntreeViewGetModel :: TreeViewClass self => self -> IO (Maybe TreeModel)\ntreeViewGetModel self =\n maybeNull (makeNewGObject mkTreeModel) $\n {# call unsafe tree_view_get_model #}\n (toTreeView self)\n\n-- | Set the 'TreeModel' for the current View.\n--\ntreeViewSetModel :: (TreeViewClass self, TreeModelClass model) => self\n -> model\n -> IO ()\ntreeViewSetModel self model =\n {# call tree_view_set_model #}\n (toTreeView self)\n (toTreeModel model)\n\n-- | Retrieve a 'TreeSelection' that\n-- holds the current selected nodes of the View.\n--\ntreeViewGetSelection :: TreeViewClass self => self -> IO TreeSelection\ntreeViewGetSelection self =\n makeNewGObject mkTreeSelection $\n {# call unsafe tree_view_get_selection #}\n (toTreeView self)\n\n-- | Gets the 'Adjustment' currently being used for the horizontal aspect.\n--\ntreeViewGetHAdjustment :: TreeViewClass self => self -> IO (Maybe Adjustment)\ntreeViewGetHAdjustment self =\n maybeNull (makeNewObject mkAdjustment) $\n {# call unsafe tree_view_get_hadjustment #}\n (toTreeView self)\n\n-- | Sets the 'Adjustment' for the current horizontal aspect.\n--\ntreeViewSetHAdjustment :: TreeViewClass self => self\n -> Maybe Adjustment -- ^ @adjustment@ - The 'Adjustment' to set, or @Nothing@\n -> IO ()\ntreeViewSetHAdjustment self adjustment =\n {# call tree_view_set_hadjustment #}\n (toTreeView self)\n (fromMaybe (Adjustment nullForeignPtr) adjustment)\n\n-- | Gets the 'Adjustment' currently being used for the vertical aspect.\n--\ntreeViewGetVAdjustment :: TreeViewClass self => self -> IO (Maybe Adjustment)\ntreeViewGetVAdjustment self =\n maybeNull (makeNewObject mkAdjustment) $\n {# call unsafe tree_view_get_vadjustment #}\n (toTreeView self)\n\n-- | Sets the 'Adjustment' for the current vertical aspect.\n--\ntreeViewSetVAdjustment :: TreeViewClass self => self\n -> Maybe Adjustment -- ^ @adjustment@ - The 'Adjustment' to set, or @Nothing@\n -> IO ()\ntreeViewSetVAdjustment self adjustment =\n {# call tree_view_set_vadjustment #}\n (toTreeView self)\n (fromMaybe (Adjustment nullForeignPtr) adjustment)\n\n-- | Query if the column headers are visible.\n--\ntreeViewGetHeadersVisible :: TreeViewClass self => self -> IO Bool\ntreeViewGetHeadersVisible self =\n liftM toBool $\n {# call unsafe tree_view_get_headers_visible #}\n (toTreeView self)\n\n-- | Set the visibility state of the column headers.\n--\ntreeViewSetHeadersVisible :: TreeViewClass self => self -> Bool -> IO ()\ntreeViewSetHeadersVisible self headersVisible =\n {# call tree_view_set_headers_visible #}\n (toTreeView self)\n (fromBool headersVisible)\n\n-- | Resize the columns to their optimal size.\n--\ntreeViewColumnsAutosize :: TreeViewClass self => self -> IO ()\ntreeViewColumnsAutosize self =\n {# call tree_view_columns_autosize #}\n (toTreeView self)\n\n-- | Set wether the columns headers are sensitive to mouse clicks.\n--\ntreeViewSetHeadersClickable :: TreeViewClass self => self -> Bool -> IO ()\ntreeViewSetHeadersClickable self setting =\n {# call tree_view_set_headers_clickable #}\n (toTreeView self)\n (fromBool setting)\n\n-- | Query if visual aid for wide columns is turned on.\n--\ntreeViewGetRulesHint :: TreeViewClass self => self -> IO Bool\ntreeViewGetRulesHint self =\n liftM toBool $\n {# call unsafe tree_view_get_rules_hint #}\n (toTreeView self)\n\n-- | This function tells Gtk+ that the user interface for your application\n-- requires users to read across tree rows and associate cells with one\n-- another. By default, Gtk+ will then render the tree with alternating row\n-- colors. Do \/not\/ use it just because you prefer the appearance of the ruled\n-- tree; that's a question for the theme. Some themes will draw tree rows in\n-- alternating colors even when rules are turned off, and users who prefer that\n-- appearance all the time can choose those themes. You should call this\n-- function only as a \/semantic\/ hint to the theme engine that your tree makes\n-- alternating colors useful from a functional standpoint (since it has lots of\n-- columns, generally).\n--\ntreeViewSetRulesHint :: TreeViewClass self => self -> Bool -> IO ()\ntreeViewSetRulesHint self setting =\n {# call tree_view_set_rules_hint #}\n (toTreeView self)\n (fromBool setting)\n\n-- | Append a new column to the 'TreeView'. Returns the new number of columns.\n--\ntreeViewAppendColumn :: TreeViewClass self => self -> TreeViewColumn -> IO Int\ntreeViewAppendColumn self column =\n liftM fromIntegral $\n {# call tree_view_append_column #}\n (toTreeView self)\n column\n\n-- | Remove column @tvc@ from the 'TreeView'\n-- widget. The number of remaining columns is returned.\n--\ntreeViewRemoveColumn :: TreeViewClass self => self -> TreeViewColumn -> IO Int\ntreeViewRemoveColumn self column =\n liftM fromIntegral $\n {# call tree_view_remove_column #}\n (toTreeView self)\n column\n\n-- | Inserts column @tvc@ into the\n-- 'TreeView' widget at the position @pos@. Returns the number of\n-- columns after insertion. Specify -1 for @pos@ to insert the column\n-- at the end.\n--\ntreeViewInsertColumn :: TreeViewClass self => self\n -> TreeViewColumn\n -> Int\n -> IO Int\ntreeViewInsertColumn self column position =\n liftM fromIntegral $\n {# call tree_view_insert_column #}\n (toTreeView self)\n column\n (fromIntegral position)\n\n-- | Retrieve a 'TreeViewColumn'.\n--\n-- * Retrieve the @pos@ th columns of\n-- 'TreeView'. If the index is out of range Nothing is returned.\n--\ntreeViewGetColumn :: TreeViewClass self => self -> Int -> IO (Maybe TreeViewColumn)\ntreeViewGetColumn self pos = do\n tvcPtr <- {# call unsafe tree_view_get_column #} (toTreeView self) \n (fromIntegral pos)\n if tvcPtr==nullPtr then return Nothing else \n liftM Just $ makeNewObject mkTreeViewColumn (return tvcPtr)\n\n-- | Return all 'TreeViewColumn's in this 'TreeView'.\n--\ntreeViewGetColumns :: TreeViewClass self => self -> IO [TreeViewColumn]\ntreeViewGetColumns self = do\n colsList <- {# call unsafe tree_view_get_columns #} (toTreeView self)\n colsPtr <- fromGList colsList\n mapM (makeNewObject mkTreeViewColumn) (map return colsPtr)\n\n-- | Move a specific column.\n--\n-- * Use 'treeViewMoveColumnToFront' if you want to move the column\n-- to the left end of the 'TreeView'.\n--\ntreeViewMoveColumnAfter :: TreeViewClass self => self\n -> TreeViewColumn\n -> TreeViewColumn\n -> IO ()\ntreeViewMoveColumnAfter self column baseColumn =\n {# call tree_view_move_column_after #}\n (toTreeView self)\n column\n baseColumn\n\n-- | Move a specific column.\n--\n-- * Use 'treeViewMoveColumnAfter' if you want to move the column\n-- somewhere else than to the leftmost position.\n--\ntreeViewMoveColumnFirst :: TreeViewClass self => self -> TreeViewColumn -> IO ()\ntreeViewMoveColumnFirst self which =\n {# call tree_view_move_column_after #}\n (toTreeView self)\n which\n (TreeViewColumn nullForeignPtr)\n\n-- | Set location of hierarchy controls.\n--\n-- * Sets the column to draw the expander arrow at. If @col@\n-- is @Nothing@, then the expander arrow is always at the first\n-- visible column.\n--\n-- If you do not want expander arrow to appear in your tree, set the\n-- expander column to a hidden column.\n--\ntreeViewSetExpanderColumn :: TreeViewClass self => self\n -> Maybe TreeViewColumn\n -> IO ()\ntreeViewSetExpanderColumn self column =\n {# call unsafe tree_view_set_expander_column #}\n (toTreeView self)\n (fromMaybe (TreeViewColumn nullForeignPtr) column)\n\n-- | Get location of hierarchy controls.\n--\n-- * Gets the column to draw the expander arrow at. If @col@\n-- is @Nothing@, then the expander arrow is always at the first\n-- visible column.\n--\ntreeViewGetExpanderColumn :: TreeViewClass self => self\n -> IO TreeViewColumn\ntreeViewGetExpanderColumn self =\n makeNewObject mkTreeViewColumn $\n {# call unsafe tree_view_get_expander_column #}\n (toTreeView self)\n\n-- | Specify where a column may be dropped.\n--\n-- * Sets a user function for determining where a column may be dropped when\n-- dragged. This function is called on every column pair in turn at the\n-- beginning of a column drag to determine where a drop can take place.\n--\n-- * The callback function take the 'TreeViewColumn' to be moved, the\n-- second and third arguments are the columns on the left and right side\n-- of the new location. At most one of them might be @Nothing@\n-- which indicates that the column is about to be dropped at the left or\n-- right end of the 'TreeView'.\n--\n-- * The predicate @pred@ should return @True@ if it is ok\n-- to insert the column at this place.\n--\n-- * Use @Nothing@ for the predicate if columns can be inserted\n-- anywhere.\n--\ntreeViewSetColumnDragFunction :: TreeViewClass self => self\n -> Maybe (TreeViewColumn\n -> Maybe TreeViewColumn\n -> Maybe TreeViewColumn\n -> IO Bool)\n -> IO ()\ntreeViewSetColumnDragFunction self Nothing =\n {# call tree_view_set_column_drag_function #} (toTreeView self)\n nullFunPtr nullPtr nullFunPtr\ntreeViewSetColumnDragFunction self (Just pred) = do\n fPtr <- mkTreeViewColumnDropFunc $ \\_ target prev next _ -> do\n target' <- makeNewObject mkTreeViewColumn (return target)\n prev' <- if prev==nullPtr then return Nothing else liftM Just $\n makeNewObject mkTreeViewColumn (return prev)\n next' <- if next==nullPtr then return Nothing else liftM Just $\n makeNewObject mkTreeViewColumn (return next)\n res <- pred target' prev' next'\n return (fromBool res)\n {# call tree_view_set_column_drag_function #}\n (toTreeView self)\n fPtr\n (castFunPtrToPtr fPtr) destroyFunPtr\n\n{#pointer TreeViewColumnDropFunc#}\n\nforeign import ccall \"wrapper\" mkTreeViewColumnDropFunc ::\n (Ptr () -> Ptr TreeViewColumn -> Ptr TreeViewColumn -> Ptr TreeViewColumn ->\n Ptr () -> IO {#type gboolean#}) -> IO TreeViewColumnDropFunc\n\n-- | Scroll to a coordinate.\n--\n-- * Scrolls the tree view such that the top-left corner of the\n-- visible area is @treeX@, @treeY@, where @treeX@\n-- and @treeY@ are specified in tree window coordinates.\n-- The 'TreeView' must be realized before this function is\n-- called. If it isn't, you probably want to use\n-- 'treeViewScrollToCell'.\n--\ntreeViewScrollToPoint :: TreeViewClass self => self\n -> Int\n -> Int\n -> IO ()\ntreeViewScrollToPoint self treeX treeY =\n {# call tree_view_scroll_to_point #}\n (toTreeView self)\n (fromIntegral treeX)\n (fromIntegral treeY)\n\n-- | Scroll to a cell.\n--\n-- * Scroll to a cell as specified by @path@ and @tvc@. \n-- The cell is aligned within the 'TreeView' widget as\n-- follows: horizontally by @hor@ from left (@0.0@) to\n-- right (@1.0@) and vertically by @ver@ from top\n-- (@0.0@) to buttom (@1.0@).\n--\ntreeViewScrollToCell :: TreeViewClass self => self\n -> TreePath\n -> TreeViewColumn\n -> Maybe (Float, Float)\n -> IO ()\ntreeViewScrollToCell self path column (Just (ver,hor)) =\n withTreePath path $ \\path ->\n {# call tree_view_scroll_to_cell #}\n (toTreeView self)\n path\n column\n 1 \n (realToFrac ver)\n (realToFrac hor)\ntreeViewScrollToCell self path column Nothing = \n withTreePath path $ \\path ->\n {# call tree_view_scroll_to_cell #}\n (toTreeView self)\n path\n column\n 0\n 0.0\n 0.0\n\n-- | Selects a specific row.\n--\n-- * Sets the current keyboard focus to be at @path@, and\n-- selects it. This is useful when you want to focus the user\\'s\n-- attention on a particular row. If @focusColumn@ is given,\n-- then the input focus is given to the column specified by\n-- it. Additionally, if @focusColumn@ is specified, and \n-- @startEditing@ is @True@,\n-- then editing will be started in the\n-- specified cell. This function is often followed by a\n-- 'widgetGrabFocus' to the 'TreeView' in order\n-- to give keyboard focus to the widget.\n--\ntreeViewSetCursor :: TreeViewClass self => self\n -> TreePath\n -> (Maybe (TreeViewColumn, Bool))\n -> IO ()\ntreeViewSetCursor self path Nothing =\n withTreePath path $ \\path ->\n {# call tree_view_set_cursor #}\n (toTreeView self)\n path\n (TreeViewColumn nullForeignPtr)\n (fromBool False)\ntreeViewSetCursor self path (Just (focusColumn, startEditing)) =\n withTreePath path $ \\path ->\n {# call tree_view_set_cursor #}\n (toTreeView self)\n path\n focusColumn\n (fromBool startEditing)\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Selects a cell in a specific row.\n--\n-- * Similar to 'treeViewSetCursor' but allows a column to\n-- containt several 'CellRenderer's.\n--\n-- * Only available in Gtk 2.2 and higher.\n--\ntreeViewSetCursorOnCell :: (TreeViewClass self, CellRendererClass focusCell) => self\n -> TreePath\n -> TreeViewColumn\n -> focusCell\n -> Bool\n -> IO ()\ntreeViewSetCursorOnCell self path focusColumn focusCell startEditing =\n withTreePath path $ \\path ->\n {# call tree_view_set_cursor_on_cell #}\n (toTreeView self)\n path\n focusColumn\n (toCellRenderer focusCell)\n (fromBool startEditing)\n#endif\n\n-- | Retrieves the position of the focus.\n--\n-- * Returns a pair @(path, column)@.If the cursor is not currently\n-- set, @path@ will be @[]@. If no column is currently\n-- selected, @column@ will be @Nothing@.\n--\ntreeViewGetCursor :: TreeViewClass self => self\n -> IO (TreePath, Maybe TreeViewColumn)\ntreeViewGetCursor self =\n alloca $ \\tpPtrPtr -> alloca $ \\tvcPtrPtr -> do\n {# call unsafe tree_view_get_cursor #}\n (toTreeView self)\n (castPtr tpPtrPtr)\n (castPtr tvcPtrPtr)\n tpPtr <- peek tpPtrPtr\n tvcPtr <- peek tvcPtrPtr\n tp <- fromTreePath tpPtr\n tvc <- if tvcPtr==nullPtr then return Nothing else liftM Just $\n makeNewObject mkTreeViewColumn (return tvcPtr)\n return (tp,tvc)\n\n-- | Emit the activated signal on a cell.\n--\ntreeViewRowActivated :: TreeViewClass self => self\n -> TreePath\n -> TreeViewColumn\n -> IO ()\ntreeViewRowActivated self path column =\n withTreePath path $ \\path ->\n {# call tree_view_row_activated #}\n (toTreeView self)\n path\n column\n\n-- | Recursively expands all nodes in the tree view.\n--\ntreeViewExpandAll :: TreeViewClass self => self -> IO ()\ntreeViewExpandAll self =\n {# call tree_view_expand_all #}\n (toTreeView self)\n\n-- | Recursively collapses all visible, expanded nodes in the tree view.\n--\ntreeViewCollapseAll :: TreeViewClass self => self -> IO ()\ntreeViewCollapseAll self =\n {# call tree_view_collapse_all #}\n (toTreeView self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Make a certain path visible.\n--\n-- * This will expand all parent rows of @tp@ as necessary.\n--\n-- * Only available in Gtk 2.2 and higher.\n--\ntreeViewExpandToPath :: TreeViewClass self => self -> TreePath -> IO ()\ntreeViewExpandToPath self path =\n withTreePath path $ \\path ->\n {# call tree_view_expand_to_path #}\n (toTreeView self)\n path\n#endif\n\n-- | Opens the row so its children are visible.\n--\ntreeViewExpandRow :: TreeViewClass self => self\n -> TreePath -- ^ @path@ - path to a row\n -> Bool -- ^ @openAll@ - whether to recursively expand, or just expand\n -- immediate children\n -> IO Bool -- ^ returns @True@ if the row existed and had children\ntreeViewExpandRow self path openAll =\n liftM toBool $\n withTreePath path $ \\path ->\n {# call tree_view_expand_row #}\n (toTreeView self)\n path\n (fromBool openAll)\n\n-- | Collapses a row (hides its child rows, if they exist).\n--\ntreeViewCollapseRow :: TreeViewClass self => self\n -> TreePath -- ^ @path@ - path to a row in the tree view\n -> IO Bool -- ^ returns @True@ if the row was collapsed.\ntreeViewCollapseRow self path =\n liftM toBool $\n withTreePath path $ \\path ->\n {# call tree_view_collapse_row #}\n (toTreeView self)\n path\n\n-- | Call function for every expaned row.\n--\ntreeViewMapExpandedRows :: TreeViewClass self => self\n -> (TreePath -> IO ())\n -> IO ()\ntreeViewMapExpandedRows self func = do\n fPtr <- mkTreeViewMappingFunc $ \\_ tpPtr _ -> fromTreePath tpPtr >>= func\n {# call tree_view_map_expanded_rows #}\n (toTreeView self)\n fPtr\n nullPtr\n freeHaskellFunPtr fPtr\n\n{#pointer TreeViewMappingFunc#}\n\nforeign import ccall \"wrapper\" mkTreeViewMappingFunc ::\n (Ptr () -> Ptr NativeTreePath -> Ptr () -> IO ()) ->\n IO TreeViewMappingFunc\n\n-- | Check if row is expanded.\n--\ntreeViewRowExpanded :: TreeViewClass self => self\n -> TreePath -- ^ @path@ - A 'TreePath' to test expansion state.\n -> IO Bool -- ^ returns @True@ if @path@ is expanded.\ntreeViewRowExpanded self path =\n liftM toBool $\n withTreePath path $ \\path ->\n {# call unsafe tree_view_row_expanded #}\n (toTreeView self)\n path\n\n-- | Query if rows can be moved around.\n--\n-- * See 'treeViewSetReorderable'.\n--\ntreeViewGetReorderable :: TreeViewClass self => self -> IO Bool\ntreeViewGetReorderable self =\n liftM toBool $\n {# call unsafe tree_view_get_reorderable #}\n (toTreeView self)\n\n-- | Check if rows can be moved around.\n--\n-- * Set whether the user can use drag and drop (DND) to reorder the rows in\n-- the store. This works on both 'TreeStore' and 'ListStore' models. If @ro@\n-- is @True@, then the user can reorder the model by dragging and dropping\n-- rows. The developer can listen to these changes by connecting to the\n-- model's signals. If you need to control which rows may be dragged or\n-- where rows may be dropped, you can override the\n-- 'Graphics.UI.Gtk.ModelView.CustomStore.treeDragSourceRowDraggable'\n-- function in the default DND implementation of the model.\n--\ntreeViewSetReorderable :: TreeViewClass self => self\n -> Bool\n -> IO ()\ntreeViewSetReorderable self reorderable =\n {# call tree_view_set_reorderable #}\n (toTreeView self)\n (fromBool reorderable)\n\n-- | Map a pixel to the specific cell.\n--\n-- * Finds the path at the 'Point' @(x, y)@. The\n-- coordinates @x@ and @y@ are relative to the top left\n-- corner of the 'TreeView' drawing window. As such, coordinates\n-- in a mouse click event can be used directly to determine the cell\n-- which the user clicked on. This function is useful to realize\n-- popup menus.\n--\n-- * The returned point is the input point relative to the cell's upper\n-- left corner. The whole 'TreeView' is divided between all cells.\n-- The returned point is relative to the rectangle this cell occupies\n-- within the 'TreeView'.\n--\ntreeViewGetPathAtPos :: TreeViewClass self => self\n -> Point\n -> IO (Maybe (TreePath, TreeViewColumn, Point))\ntreeViewGetPathAtPos self (x,y) =\n alloca $ \\tpPtrPtr ->\n alloca $ \\tvcPtrPtr ->\n alloca $ \\xPtr ->\n alloca $ \\yPtr -> do\n res <- liftM toBool $\n {# call unsafe tree_view_get_path_at_pos #}\n (toTreeView self)\n (fromIntegral x)\n (fromIntegral y)\n (castPtr tpPtrPtr)\n (castPtr tvcPtrPtr)\n xPtr\n yPtr\n tpPtr <- peek tpPtrPtr\n tvcPtr <- peek tvcPtrPtr\n xCell <- peek xPtr\n yCell <- peek yPtr\n if not res then return Nothing else do\n tp <- fromTreePath tpPtr\n tvc <- makeNewObject mkTreeViewColumn (return tvcPtr)\n return (Just (tp,tvc,(fromIntegral xCell, fromIntegral yCell)))\n\n-- | Retrieve the smallest bounding box of a cell.\n--\n-- * Fills the bounding rectangle in tree window coordinates for the\n-- cell at the row specified by @tp@ and the column specified by\n-- @tvc@.\n-- If @path@ is @Nothing@ or points to a path not\n-- currently displayed, the @y@ and @height@ fields of\n-- the 'Rectangle' will be filled with @0@. The sum of\n-- all cell rectangles does not cover the entire tree; there are extra\n-- pixels in between rows, for example.\n--\ntreeViewGetCellArea :: TreeViewClass self => self\n -> Maybe TreePath\n -> TreeViewColumn\n -> IO Rectangle\ntreeViewGetCellArea self Nothing tvc =\n alloca $ \\rPtr ->\n {# call unsafe tree_view_get_cell_area #}\n (toTreeView self)\n (NativeTreePath nullPtr)\n tvc\n (castPtr (rPtr :: Ptr Rectangle))\n >> peek rPtr\ntreeViewGetCellArea self (Just tp) tvc = \n withTreePath tp $ \\tp ->\n alloca $ \\rPtr -> do\n {# call unsafe tree_view_get_cell_area #}\n (toTreeView self)\n tp\n tvc\n (castPtr (rPtr :: Ptr Rectangle))\n >> peek rPtr\n\n-- | Retrieve the largest bounding box of a cell.\n--\n-- * Fills the bounding rectangle in tree window coordinates for the\n-- cell at the row specified by @tp@ and the column specified by\n-- @tvc@.\n-- If @path@ is @Nothing@ or points to a path not\n-- currently displayed, the @y@ and @height@ fields of\n-- the 'Rectangle' will be filled with @0@. The background\n-- areas tile the widget's area to cover the entire tree window \n-- (except for the area used for header buttons). Contrast this with\n-- 'treeViewGetCellArea'.\n--\ntreeViewGetBackgroundArea :: TreeViewClass self => self\n -> Maybe TreePath\n -> TreeViewColumn\n -> IO Rectangle\ntreeViewGetBackgroundArea self Nothing tvc =\n alloca $ \\rPtr ->\n {# call unsafe tree_view_get_background_area #}\n (toTreeView self)\n (NativeTreePath nullPtr)\n tvc\n (castPtr (rPtr :: Ptr Rectangle))\n >> peek rPtr\ntreeViewGetBackgroundArea self (Just tp) tvc = \n withTreePath tp $ \\tp -> alloca $ \\rPtr ->\n {# call unsafe tree_view_get_background_area #}\n (toTreeView self)\n tp\n tvc\n (castPtr (rPtr :: Ptr Rectangle))\n >> peek rPtr\n\n-- | Retrieve the currently visible area.\n--\n-- * The returned rectangle gives the visible part of the tree in tree\n-- coordinates.\n--\ntreeViewGetVisibleRect :: TreeViewClass self => self -> IO Rectangle\ntreeViewGetVisibleRect self =\n alloca $ \\rPtr -> do\n {# call unsafe tree_view_get_visible_rect #}\n (toTreeView self)\n (castPtr (rPtr :: Ptr Rectangle))\n peek rPtr\n\n#ifndef DISABLE_DEPRECATED\n-- | 'treeViewTreeToWidgetCoords' has been deprecated since version 2.12 and should not be used in\n-- newly-written code. Due to historial reasons the name of this function is incorrect. For converting\n-- bin window coordinates to coordinates relative to bin window, please see\n-- 'treeViewConvertBinWindowToWidgetCoords'.\n-- \n-- Converts tree coordinates (coordinates in full scrollable area of the tree) to bin window\n-- coordinates.\n--\ntreeViewTreeToWidgetCoords :: TreeViewClass self => self\n -> Point -- ^ @(tx, ty)@ - tree X and Y coordinates\n -> IO Point -- ^ @(wx, wy)@ returns widget X and Y coordinates\ntreeViewTreeToWidgetCoords self (tx, ty) =\n alloca $ \\wxPtr ->\n alloca $ \\wyPtr -> do\n {# call unsafe tree_view_tree_to_widget_coords #}\n (toTreeView self)\n (fromIntegral tx)\n (fromIntegral ty)\n wxPtr\n wyPtr\n wx <- peek wxPtr\n wy <- peek wyPtr\n return (fromIntegral wx, fromIntegral wy)\n\n-- | 'treeViewWidgetToTreeCoords' has been deprecated since version 2.12 and should not be used in\n-- newly-written code. Due to historial reasons the name of this function is incorrect. For converting\n-- coordinates relative to the widget to bin window coordinates, please see\n-- 'treeViewConvertWidgetToBinWindowCoords'.\n-- \n-- Converts bin window coordinates to coordinates for the tree (the full scrollable area of the tree).\n--\ntreeViewWidgetToTreeCoords :: TreeViewClass self => self\n -> Point -- ^ @(wx, wy)@ - widget X and Y coordinates\n -> IO Point -- ^ @(tx, ty)@ returns tree X and Y coordinates\ntreeViewWidgetToTreeCoords self (wx, wy) =\n alloca $ \\txPtr ->\n alloca $ \\tyPtr -> do\n {# call unsafe tree_view_widget_to_tree_coords #}\n (toTreeView self)\n (fromIntegral wx)\n (fromIntegral wy)\n txPtr\n tyPtr\n tx <- peek txPtr\n ty <- peek tyPtr\n return (fromIntegral tx, fromIntegral ty)\n#endif\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Converts bin window coordinates to coordinates for the tree (the full scrollable area of the tree).\ntreeViewConvertBinWindowToTreeCoords :: TreeViewClass self => self\n -> Point -- ^ @(bx, by)@ - bin window X and Y coordinates\n -> IO Point -- ^ @(tx, ty)@ returns tree X and Y coordinates \ntreeViewConvertBinWindowToTreeCoords self (bx, by) =\n alloca $ \\txPtr ->\n alloca $ \\tyPtr -> do\n {# call unsafe tree_view_convert_bin_window_to_tree_coords #}\n (toTreeView self)\n (fromIntegral bx)\n (fromIntegral by)\n txPtr\n tyPtr\n tx <- peek txPtr\n ty <- peek tyPtr\n return (fromIntegral tx, fromIntegral ty)\n\n-- | Converts bin window coordinates (see 'treeViewGetBinWindow' to widget relative coordinates.\ntreeViewConvertBinWindowToWidgetCoords :: TreeViewClass self => self\n -> Point -- ^ @(bx, by)@ - bin window X and Y coordinates\n -> IO Point -- ^ @(wx, wy)@ returns widget X and Y coordinates \ntreeViewConvertBinWindowToWidgetCoords self (bx, by) =\n alloca $ \\wxPtr ->\n alloca $ \\wyPtr -> do\n {# call unsafe tree_view_convert_bin_window_to_widget_coords #}\n (toTreeView self)\n (fromIntegral bx)\n (fromIntegral by)\n wxPtr\n wyPtr\n wx <- peek wxPtr\n wy <- peek wyPtr\n return (fromIntegral wx, fromIntegral wy)\n\n-- | Converts tree coordinates (coordinates in full scrollable area of the tree) to bin window\n-- coordinates.\ntreeViewConvertTreeToBinWindowCoords :: TreeViewClass self => self\n -> Point -- ^ @(tx, ty)@ - tree X and Y coordinates\n -> IO Point -- ^ @(bx, by)@ returns bin window X and Y coordinates \ntreeViewConvertTreeToBinWindowCoords self (tx, ty) =\n alloca $ \\bxPtr ->\n alloca $ \\byPtr -> do\n {# call unsafe tree_view_convert_tree_to_bin_window_coords #}\n (toTreeView self)\n (fromIntegral tx)\n (fromIntegral ty)\n bxPtr\n byPtr\n bx <- peek bxPtr\n by <- peek byPtr\n return (fromIntegral bx, fromIntegral by)\n\n-- | Converts tree coordinates (coordinates in full scrollable area of the tree) to widget coordinates.\ntreeViewConvertTreeToWidgetCoords :: TreeViewClass self => self\n -> Point -- ^ @(tx, ty)@ - tree X and Y coordinates\n -> IO Point -- ^ @(wx, wy)@ returns widget X and Y coordinates \ntreeViewConvertTreeToWidgetCoords self (wx, wy) =\n alloca $ \\bxPtr ->\n alloca $ \\byPtr -> do\n {# call unsafe tree_view_convert_tree_to_widget_coords #}\n (toTreeView self)\n (fromIntegral wx)\n (fromIntegral wy)\n bxPtr\n byPtr\n bx <- peek bxPtr\n by <- peek byPtr\n return (fromIntegral bx, fromIntegral by)\n\n-- | Converts widget coordinates to coordinates for the window (see 'treeViewGetBinWindow' ).\ntreeViewConvertWidgetToBinWindowCoords :: TreeViewClass self => self\n -> Point -- ^ @(wx, wy)@ - widget X and Y coordinates\n -> IO Point -- ^ @(bx, by)@ returns bin window X and Y coordinates \ntreeViewConvertWidgetToBinWindowCoords self (wx, wy) =\n alloca $ \\bxPtr ->\n alloca $ \\byPtr -> do\n {# call unsafe tree_view_convert_widget_to_bin_window_coords #}\n (toTreeView self)\n (fromIntegral wx)\n (fromIntegral wy)\n bxPtr\n byPtr\n bx <- peek bxPtr\n by <- peek byPtr\n return (fromIntegral bx, fromIntegral by)\n\n-- | Converts widget coordinates to coordinates for the tree (the full scrollable area of the tree).\ntreeViewConvertWidgetToTreeCoords :: TreeViewClass self => self\n -> Point -- ^ @(wx, wy)@ - bin window X and Y coordinates\n -> IO Point -- ^ @(tx, ty)@ returns tree X and Y coordinates \ntreeViewConvertWidgetToTreeCoords self (wx, wy) =\n alloca $ \\txPtr ->\n alloca $ \\tyPtr -> do\n {# call unsafe tree_view_convert_widget_to_tree_coords #}\n (toTreeView self)\n (fromIntegral wx)\n (fromIntegral wy)\n txPtr\n tyPtr\n tx <- peek txPtr\n ty <- peek tyPtr\n return (fromIntegral tx, fromIntegral ty)\n#endif\n\n-- | Creates a 'Pixmap' representation of the row at the given path. This image\n-- can be used for a drag icon.\n--\ntreeViewCreateRowDragIcon :: TreeViewClass self => self\n -> TreePath\n -> IO Pixmap\ntreeViewCreateRowDragIcon self path =\n constructNewGObject mkPixmap $\n withTreePath path $ \\path ->\n {# call unsafe tree_view_create_row_drag_icon #}\n (toTreeView self)\n path\n\n-- | Returns whether or not the tree allows to start interactive searching by\n-- typing in text.\n--\n-- * If enabled, the user can type in text which will set the cursor to\n-- the first matching entry.\n--\ntreeViewGetEnableSearch :: TreeViewClass self => self -> IO Bool\ntreeViewGetEnableSearch self =\n liftM toBool $\n {# call unsafe tree_view_get_enable_search #}\n (toTreeView self)\n\n-- | If this is set, then the user can type in text to search\n-- through the tree interactively (this is sometimes called \\\"typeahead\n-- find\\\").\n--\n-- Note that even if this is @False@, the user can still initiate a search\n-- using the \\\"start-interactive-search\\\" key binding. In any case,\n-- a predicate that compares a row of the model with the text the user\n-- has typed must be set using 'treeViewSetSearchEqualFunc'.\n--\ntreeViewSetEnableSearch :: TreeViewClass self => self -> Bool -> IO ()\ntreeViewSetEnableSearch self enableSearch =\n {# call tree_view_set_enable_search #}\n (toTreeView self)\n (fromBool enableSearch)\n\n-- %hash c:ecc5 d:bed6\n-- | Gets the column searched on by the interactive search code.\n--\ntreeViewGetSearchColumn :: TreeViewClass self => self\n -> IO (ColumnId row String) -- ^ returns the column the interactive search code searches in.\ntreeViewGetSearchColumn self =\n liftM (makeColumnIdString . fromIntegral) $\n {# call unsafe tree_view_get_search_column #}\n (toTreeView self)\n\n-- %hash c:d0d0\n-- | Sets @column@ as the column where the interactive search code should\n-- search in.\n--\n-- If the sort column is set, users can use the \\\"start-interactive-search\\\"\n-- key binding to bring up search popup. The enable-search property controls\n-- whether simply typing text will also start an interactive search.\n--\n-- Note that @column@ refers to a column of the model. Furthermore, the\n-- search column is not used if a comparison function is set, see\n-- 'treeViewSetSearchEqualFunc'.\n--\ntreeViewSetSearchColumn :: TreeViewClass self => self\n -> (ColumnId row String) -- ^ @column@ - the column of the model to search in, or -1 to disable\n -- searching\n -> IO ()\ntreeViewSetSearchColumn self column =\n {# call tree_view_set_search_column #}\n (toTreeView self)\n (fromIntegral (columnIdToNumber column))\n\n\n-- | Set the predicate to test for equality.\n--\n-- * The predicate must returns @True@ if the text entered by the user\n-- and the row of the model match. Calling this function will overwrite\n-- the 'treeViewSearchColumn' (which isn't used anyway when a comparison\n-- function is installed).\n--\ntreeViewSetSearchEqualFunc :: TreeViewClass self => self\n -> Maybe (String -> TreeIter -> IO Bool)\n -> IO ()\ntreeViewSetSearchEqualFunc self (Just pred) = do\n fPtr <- mkTreeViewSearchEqualFunc (\\_ _ keyPtr iterPtr _ -> do\n key <- peekUTFString keyPtr\n iter <- peek iterPtr\n liftM (fromBool . not) $ pred key iter)\n {# call tree_view_set_search_equal_func #} (toTreeView self) fPtr \n (castFunPtrToPtr fPtr) destroyFunPtr\n {# call tree_view_set_search_column #} (toTreeView self) 0\ntreeViewSetSearchEqualFunc self Nothing = do\n {# call tree_view_set_search_equal_func #} (toTreeView self)\n nullFunPtr nullPtr nullFunPtr\n {# call tree_view_set_search_column #} (toTreeView self) (-1)\n\n{#pointer TreeViewSearchEqualFunc#}\n\nforeign import ccall \"wrapper\" mkTreeViewSearchEqualFunc ::\n (Ptr TreeModel -> {#type gint#} -> CString -> Ptr TreeIter -> Ptr () ->\n IO {#type gboolean#}) -> IO TreeViewSearchEqualFunc\n\n-- helper to marshal native tree paths to TreePaths\nreadNTP :: Ptr TreePath -> IO TreePath\nreadNTP ptr = peekTreePath (castPtr ptr)\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Returns whether fixed height mode is turned on for the tree view.\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewGetFixedHeightMode :: TreeViewClass self => self\n -> IO Bool -- ^ returns @True@ if the tree view is in fixed height mode\ntreeViewGetFixedHeightMode self =\n liftM toBool $\n {# call gtk_tree_view_get_fixed_height_mode #}\n (toTreeView self)\n\n-- | Enables or disables the fixed height mode of the tree view. Fixed height\n-- mode speeds up 'TreeView' by assuming that all rows have the same height.\n-- Only enable this option if all rows are the same height and all columns are\n-- of type 'TreeViewColumnFixed'.\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewSetFixedHeightMode :: TreeViewClass self => self\n -> Bool -- ^ @enable@ - @True@ to enable fixed height mode\n -> IO ()\ntreeViewSetFixedHeightMode self enable =\n {# call gtk_tree_view_set_fixed_height_mode #}\n (toTreeView self)\n (fromBool enable)\n\n-- | Returns whether hover selection mode is turned on for @treeView@.\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewGetHoverSelection :: TreeViewClass self => self\n -> IO Bool -- ^ returns @True@ if the tree view is in hover selection mode\ntreeViewGetHoverSelection self =\n liftM toBool $\n {# call gtk_tree_view_get_hover_selection #}\n (toTreeView self)\n\n-- | Enables of disables the hover selection mode of the tree view. Hover\n-- selection makes the selected row follow the pointer. Currently, this works\n-- only for the selection modes 'SelectionSingle' and 'SelectionBrowse'.\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewSetHoverSelection :: TreeViewClass self => self\n -> Bool -- ^ @hover@ - @True@ to enable hover selection mode\n -> IO ()\ntreeViewSetHoverSelection self hover =\n {# call gtk_tree_view_set_hover_selection #}\n (toTreeView self)\n (fromBool hover)\n\n-- | Returns whether hover expansion mode is turned on for the tree view.\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewGetHoverExpand :: TreeViewClass self => self\n -> IO Bool -- ^ returns @True@ if the tree view is in hover expansion mode\ntreeViewGetHoverExpand self =\n liftM toBool $\n {# call gtk_tree_view_get_hover_expand #}\n (toTreeView self)\n\n-- | Enables of disables the hover expansion mode of the tree view. Hover\n-- expansion makes rows expand or collaps if the pointer moves over them.\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewSetHoverExpand :: TreeViewClass self => self\n -> Bool -- ^ @expand@ - @True@ to enable hover selection mode\n -> IO ()\ntreeViewSetHoverExpand self expand =\n {# call gtk_tree_view_set_hover_expand #}\n (toTreeView self)\n (fromBool expand)\n#endif\n\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:88cb d:65c9\n-- | Returns whether all header columns are clickable.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewGetHeadersClickable :: TreeViewClass self => self\n -> IO Bool -- ^ returns @True@ if all header columns are clickable, otherwise\n -- @False@\ntreeViewGetHeadersClickable self =\n liftM toBool $\n {# call gtk_tree_view_get_headers_clickable #}\n (toTreeView self)\n#endif\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:1d81 d:3587\n-- | Return the first and last visible path.\n-- Note that there may be invisible paths in between.\n--\n-- * Available since Gtk+ version 2.8\n--\ntreeViewGetVisibleRange :: TreeViewClass self => self\n -> IO (TreePath, TreePath) -- ^ the first and the last node that is visible\ntreeViewGetVisibleRange self = alloca $ \\startPtr -> alloca $ \\endPtr -> do\n valid <- liftM toBool $\n {# call gtk_tree_view_get_visible_range #}\n (toTreeView self) (castPtr startPtr) (castPtr endPtr)\n if not valid then return ([],[]) else do\n startTPPtr <- peek startPtr\n endTPPtr <- peek endPtr\n startPath <- fromTreePath startTPPtr\n endPath <- fromTreePath endTPPtr\n return (startPath, endPath)\n \n#endif\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:61e1 d:3a0a\n-- | Turns @treeView@ into a drop destination for automatic DND.\n--\ntreeViewEnableModelDragDest :: TreeViewClass self => self\n -> TargetList -- ^ @targets@ - the list of targets that the\n -- the view will support\n -> [DragAction] -- ^ @actions@ - flags denoting the possible actions\n -- for a drop into this widget\n -> IO ()\ntreeViewEnableModelDragDest self targets actions =\n alloca $ \\nTargetsPtr -> do\n tlPtr <- {#call unsafe gtk_target_table_new_from_list#} targets nTargetsPtr\n nTargets <- peek nTargetsPtr\n {# call gtk_tree_view_enable_model_drag_dest #}\n (toTreeView self)\n tlPtr\n nTargets\n ((fromIntegral . fromFlags) actions)\n {#call unsafe gtk_target_table_free#} tlPtr nTargets\n\n-- %hash c:1df9 d:622\n-- | Turns @treeView@ into a drag source for automatic DND.\n--\ntreeViewEnableModelDragSource :: TreeViewClass self => self\n -> [Modifier] -- ^ @startButtonMask@ - Mask of allowed buttons\n -- to start drag\n -> TargetList -- ^ @targets@ - the list of targets that the\n -- the view will support\n -> [DragAction] -- ^ @actions@ - flags denoting the possible actions\n -- for a drag from this widget\n -> IO ()\ntreeViewEnableModelDragSource self startButtonMask targets actions =\n alloca $ \\nTargetsPtr -> do\n tlPtr <- {#call unsafe gtk_target_table_new_from_list#} targets nTargetsPtr\n nTargets <- peek nTargetsPtr\n {# call gtk_tree_view_enable_model_drag_source #}\n (toTreeView self)\n ((fromIntegral . fromFlags) startButtonMask)\n tlPtr\n nTargets\n ((fromIntegral . fromFlags) actions)\n {#call unsafe gtk_target_table_free#} tlPtr nTargets\n\n-- %hash c:5201 d:f3be\n-- | Undoes the effect of 'treeViewEnableModelDragSource'.\n--\ntreeViewUnsetRowsDragSource :: TreeViewClass self => self -> IO ()\ntreeViewUnsetRowsDragSource self =\n {# call gtk_tree_view_unset_rows_drag_source #}\n (toTreeView self)\n\n-- %hash c:e31e d:323d\n-- | Undoes the effect of 'treeViewEnableModelDragDest'.\n--\ntreeViewUnsetRowsDragDest :: TreeViewClass self => self -> IO ()\ntreeViewUnsetRowsDragDest self =\n {# call gtk_tree_view_unset_rows_drag_dest #}\n (toTreeView self)\n\n-- %hash c:3355 d:3bbe\n-- | Returns the 'Entry' which is currently in use as interactive search entry\n-- for @treeView@. In case the built-in entry is being used, @Nothing@ will be\n-- returned.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewGetSearchEntry :: TreeViewClass self => self\n -> IO (Maybe Entry) -- ^ returns the entry currently in use as search entry.\ntreeViewGetSearchEntry self = do\n ePtr <- {# call gtk_tree_view_get_search_entry #}\n (toTreeView self)\n if ePtr==nullPtr then return Nothing else liftM Just $\n makeNewObject mkEntry (return ePtr)\n\n-- %hash c:5e11 d:8ec5\n-- | Sets the entry which the interactive search code will use for this\n-- @treeView@. This is useful when you want to provide a search entry in our\n-- interface at all time at a fixed position. Passing @Nothing@ for @entry@\n-- will make the interactive search code use the built-in popup entry again.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewSetSearchEntry :: (TreeViewClass self, EntryClass entry) => self\n -> (Maybe entry)\n -- ^ @entry@ - the entry the interactive search code of @treeView@\n -- should use or @Nothing@\n -> IO ()\ntreeViewSetSearchEntry self (Just entry) =\n {# call gtk_tree_view_set_search_entry #}\n (toTreeView self)\n (toEntry entry)\ntreeViewSetSearchEntry self Nothing =\n {# call gtk_tree_view_set_search_entry #}\n (toTreeView self)\n (Entry nullForeignPtr)\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- %hash c:6326 d:a050\n-- | Sets the row separator function, which is used to determine whether a row\n-- should be drawn as a separator. If the row separator function is @Nothing@,\n-- no separators are drawn. This is the default value.\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewSetRowSeparatorFunc :: TreeViewClass self => self\n -> Maybe (TreeIter -> IO Bool) -- ^ @func@ - a callback function that\n -- returns @True@ if the given row of\n -- the model should be drawn as separator\n -> IO ()\ntreeViewSetRowSeparatorFunc self Nothing =\n {# call gtk_tree_view_set_row_separator_func #}\n (toTreeView self) nullFunPtr nullPtr nullFunPtr\ntreeViewSetRowSeparatorFunc self (Just func) = do\n funcPtr <- mkTreeViewRowSeparatorFunc $ \\_ tiPtr _ -> do\n ti <- peekTreeIter tiPtr\n liftM fromBool $ func ti\n {# call gtk_tree_view_set_row_separator_func #}\n (toTreeView self) funcPtr (castFunPtrToPtr funcPtr) destroyFunPtr\n\n{#pointer TreeViewRowSeparatorFunc #}\n\nforeign import ccall \"wrapper\" mkTreeViewRowSeparatorFunc ::\n (Ptr TreeModel -> Ptr TreeIter -> Ptr () -> IO {#type gboolean#}) ->\n IO TreeViewRowSeparatorFunc\n \n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:778a d:eacd\n-- | Returns whether rubber banding is turned on for @treeView@. If the\n-- selection mode is 'SelectionMultiple', rubber banding will allow the user to\n-- select multiple rows by dragging the mouse.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewGetRubberBanding :: TreeViewClass self => self\n -> IO Bool -- ^ returns @True@ if rubber banding in @treeView@ is enabled.\ntreeViewGetRubberBanding self =\n liftM toBool $\n {# call gtk_tree_view_get_rubber_banding #}\n (toTreeView self)\n\n-- %hash c:4a69 d:93aa\n-- | Enables or disables rubber banding in @treeView@. If the selection mode\n-- is 'SelectionMultiple', rubber banding will allow the user to select\n-- multiple rows by dragging the mouse.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewSetRubberBanding :: TreeViewClass self => self\n -> Bool -- ^ @enable@ - @True@ to enable rubber banding\n -> IO ()\ntreeViewSetRubberBanding self enable =\n {# call gtk_tree_view_set_rubber_banding #}\n (toTreeView self)\n (fromBool enable)\n\n-- %hash c:c8f8 d:c47\n-- | Returns whether or not tree lines are drawn in @treeView@.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewGetEnableTreeLines :: TreeViewClass self => self\n -> IO Bool -- ^ returns @True@ if tree lines are drawn in @treeView@, @False@\n -- otherwise.\ntreeViewGetEnableTreeLines self =\n liftM toBool $\n {# call gtk_tree_view_get_enable_tree_lines #}\n (toTreeView self)\n\n-- %hash c:205d d:1df9\n-- | Sets whether to draw lines interconnecting the expanders in @treeView@.\n-- This does not have any visible effects for lists.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewSetEnableTreeLines :: TreeViewClass self => self\n -> Bool -- ^ @enabled@ - @True@ to enable tree line drawing, @False@\n -- otherwise.\n -> IO ()\ntreeViewSetEnableTreeLines self enabled =\n {# call gtk_tree_view_set_enable_tree_lines #}\n (toTreeView self)\n (fromBool enabled)\n\n-- | Grid lines.\n{#enum TreeViewGridLines {underscoreToCase}#}\n\n-- %hash c:cd40 d:fe96\n-- | Returns which grid lines are enabled in @treeView@.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewGetGridLines :: TreeViewClass self => self\n -> IO TreeViewGridLines -- ^ returns a 'TreeViewGridLines' value indicating\n -- which grid lines are enabled.\ntreeViewGetGridLines self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_tree_view_get_grid_lines #}\n (toTreeView self)\n\n-- %hash c:74b0 d:79f0\n-- | Sets which grid lines to draw in @treeView@.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewSetGridLines :: TreeViewClass self => self\n -> TreeViewGridLines -- ^ @gridLines@ - a 'TreeViewGridLines' value\n -- indicating which grid lines to enable.\n -> IO ()\ntreeViewSetGridLines self gridLines =\n {# call gtk_tree_view_set_grid_lines #}\n (toTreeView self)\n ((fromIntegral . fromEnum) gridLines)\n#endif\n#endif\n\n--------------------\n-- Attributes\n\n-- | The model for the tree view.\n--\ntreeViewModel :: (TreeViewClass self, TreeModelClass model) => ReadWriteAttr self (Maybe TreeModel) model\ntreeViewModel = newAttr\n treeViewGetModel\n treeViewSetModel\n\n-- | Horizontal Adjustment for the widget.\n--\ntreeViewHAdjustment :: TreeViewClass self => Attr self (Maybe Adjustment)\ntreeViewHAdjustment = newAttr\n treeViewGetHAdjustment\n treeViewSetHAdjustment\n\n-- | Vertical Adjustment for the widget.\n--\ntreeViewVAdjustment :: TreeViewClass self => Attr self (Maybe Adjustment)\ntreeViewVAdjustment = newAttr\n treeViewGetVAdjustment\n treeViewSetVAdjustment\n\n-- | Show the column header buttons.\n--\n-- Default value: @True@\n--\ntreeViewHeadersVisible :: TreeViewClass self => Attr self Bool\ntreeViewHeadersVisible = newAttr\n treeViewGetHeadersVisible\n treeViewSetHeadersVisible\n\n-- | Column headers respond to click events.\n--\n-- Default value: @False@\n--\ntreeViewHeadersClickable :: TreeViewClass self => Attr self Bool\ntreeViewHeadersClickable = newAttrFromBoolProperty \"headers-clickable\"\n\n-- | Set the column for the expander column.\n--\ntreeViewExpanderColumn :: TreeViewClass self => ReadWriteAttr self TreeViewColumn (Maybe TreeViewColumn)\ntreeViewExpanderColumn = newAttr\n treeViewGetExpanderColumn\n treeViewSetExpanderColumn\n\n-- | View is reorderable.\n--\n-- Default value: @False@\n--\ntreeViewReorderable :: TreeViewClass self => Attr self Bool\ntreeViewReorderable = newAttr\n treeViewGetReorderable\n treeViewSetReorderable\n\n-- | Set a hint to the theme engine to draw rows in alternating colors.\n--\n-- Default value: @False@\n--\ntreeViewRulesHint :: TreeViewClass self => Attr self Bool\ntreeViewRulesHint = newAttr\n treeViewGetRulesHint\n treeViewSetRulesHint\n\n-- | View allows user to search through columns interactively.\n--\n-- Default value: @True@\n--\ntreeViewEnableSearch :: TreeViewClass self => Attr self Bool\ntreeViewEnableSearch = newAttr\n treeViewGetEnableSearch\n treeViewSetEnableSearch\n\n-- %hash c:e732\n-- | Model column to search through when searching through code.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\ntreeViewSearchColumn :: TreeViewClass self => Attr self (ColumnId row String)\ntreeViewSearchColumn = newAttr\n treeViewGetSearchColumn\n treeViewSetSearchColumn\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:c7ff d:24d1\n-- | Setting the 'treeViewFixedHeightMode' property to @True@ speeds up 'TreeView'\n-- by assuming that all rows have the same height. Only enable this option if\n-- all rows are the same height. Please see 'treeViewSetFixedHeightMode' for\n-- more information on this option.\n--\n-- Default value: @False@\n--\n-- * Available since Gtk+ version 2.4\n--\ntreeViewFixedHeightMode :: TreeViewClass self => Attr self Bool\ntreeViewFixedHeightMode = newAttrFromBoolProperty \"fixed-height-mode\"\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- %hash c:2026 d:839a\n-- | Enables of disables the hover selection mode of @treeView@. Hover\n-- selection makes the selected row follow the pointer. Currently, this works\n-- only for the selection modes 'SelectionSingle' and 'SelectionBrowse'.\n--\n-- This mode is primarily intended for 'TreeView's in popups, e.g. in\n-- 'ComboBox' or 'EntryCompletion'.\n--\n-- Default value: @False@\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewHoverSelection :: TreeViewClass self => Attr self Bool\ntreeViewHoverSelection = newAttrFromBoolProperty \"hover-selection\"\n\n-- %hash c:c694 d:3f15\n-- | Enables of disables the hover expansion mode of @treeView@. Hover\n-- expansion makes rows expand or collaps if the pointer moves over them.\n--\n-- This mode is primarily intended for 'TreeView's in popups, e.g. in\n-- 'ComboBox' or 'EntryCompletion'.\n--\n-- Default value: @False@\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewHoverExpand :: TreeViewClass self => Attr self Bool\ntreeViewHoverExpand = newAttrFromBoolProperty \"hover-expand\"\n#endif\n#endif\n\n-- %hash c:b409 d:2ed2\n-- | View has expanders.\n--\n-- Default value: @True@\n--\ntreeViewShowExpanders :: TreeViewClass self => Attr self Bool\ntreeViewShowExpanders = newAttrFromBoolProperty \"show-expanders\"\n\n-- %hash c:f0e5 d:9017\n-- | Extra indentation for each level.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntreeViewLevelIndentation :: TreeViewClass self => Attr self Int\ntreeViewLevelIndentation = newAttrFromIntProperty \"level-indentation\"\n\n-- %hash c:a647 d:9e53\n-- | Whether to enable selection of multiple items by dragging the mouse\n-- pointer.\n--\n-- Default value: @False@\n--\ntreeViewRubberBanding :: TreeViewClass self => Attr self Bool\ntreeViewRubberBanding = newAttrFromBoolProperty \"rubber-banding\"\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:e926 d:86a8\n-- | Whether grid lines should be drawn in the tree view.\n--\n-- Default value: 'TreeViewGridLinesNone'\n--\ntreeViewEnableGridLines :: TreeViewClass self => Attr self TreeViewGridLines\ntreeViewEnableGridLines = newAttrFromEnumProperty \"enable-grid-lines\"\n {# call pure unsafe gtk_tree_view_grid_lines_get_type #}\n#endif\n\n-- %hash c:a7eb d:4c53\n-- | Whether tree lines should be drawn in the tree view.\n--\n-- Default value: @False@\n--\ntreeViewEnableTreeLines :: TreeViewClass self => Attr self Bool\ntreeViewEnableTreeLines = newAttrFromBoolProperty \"enable-tree-lines\"\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:688c d:cbcd\n-- | \\'gridLines\\' property. See 'treeViewGetGridLines' and\n-- 'treeViewSetGridLines'\n--\ntreeViewGridLines :: TreeViewClass self => Attr self TreeViewGridLines\ntreeViewGridLines = newAttr\n treeViewGetGridLines\n treeViewSetGridLines\n\n-- %hash c:9cbe d:2962\n-- | \\'searchEntry\\' property. See 'treeViewGetSearchEntry' and\n-- 'treeViewSetSearchEntry'\n--\ntreeViewSearchEntry :: (TreeViewClass self, EntryClass entry) => ReadWriteAttr self (Maybe Entry) (Maybe entry)\ntreeViewSearchEntry = newAttr\n treeViewGetSearchEntry\n treeViewSetSearchEntry\n#endif\n\n--------------------\n-- Signals\n\n-- %hash c:9fc5 d:3e66\n-- | The given row is about to be expanded (show its children nodes). Use this\n-- signal if you need to control the expandability of individual rows.\n--\ntestExpandRow :: TreeViewClass self => Signal self (TreeIter -> TreePath -> IO Bool)\ntestExpandRow = Signal (connect_BOXED_BOXED__BOOL \"test-expand-row\" peek readNTP)\n\n-- %hash c:20de d:96a3\n-- | The given row is about to be collapsed (hide its children nodes). Use\n-- this signal if you need to control the collapsibility of individual rows.\n--\ntestCollapseRow :: TreeViewClass self => Signal self (TreeIter -> TreePath -> IO Bool)\ntestCollapseRow = Signal (connect_BOXED_BOXED__BOOL \"test-collapse-row\" peek readNTP)\n\n-- %hash c:16dc d:b113\n-- | The given row has been expanded (child nodes are shown).\n--\nrowExpanded :: TreeViewClass self => Signal self (TreeIter -> TreePath -> IO ())\nrowExpanded = Signal (connect_BOXED_BOXED__NONE \"row-expanded\" peek readNTP)\n\n-- %hash c:9ee6 d:325e\n-- | The given row has been collapsed (child nodes are hidden).\n--\nrowCollapsed :: TreeViewClass self => Signal self (TreeIter -> TreePath -> IO ())\nrowCollapsed = Signal (connect_BOXED_BOXED__NONE \"row-collapsed\" peek readNTP)\n\n-- %hash c:4350 d:4f94\n-- | The number of columns of the treeview has changed.\n--\ncolumnsChanged :: TreeViewClass self => Signal self (IO ())\ncolumnsChanged = Signal (connect_NONE__NONE \"columns-changed\")\n\n-- %hash c:6487 d:5b57\n-- | The position of the cursor (focused cell) has changed.\n--\ncursorChanged :: TreeViewClass self => Signal self (IO ())\ncursorChanged = Signal (connect_NONE__NONE \"cursor-changed\")\n\n--------------------\n-- Deprecated Signals\n\n#ifndef DISABLE_DEPRECATED\n\n-- | The user has dragged a column to another position.\n--\nonColumnsChanged, afterColumnsChanged :: TreeViewClass self => self\n -> IO ()\n -> IO (ConnectId self)\nonColumnsChanged = connect_NONE__NONE \"columns_changed\" False\nafterColumnsChanged = connect_NONE__NONE \"columns_changed\" True\n\n-- | The cursor in the tree has moved.\n--\nonCursorChanged, afterCursorChanged :: TreeViewClass self => self\n -> IO ()\n -> IO (ConnectId self)\nonCursorChanged = connect_NONE__NONE \"cursor_changed\" False\nafterCursorChanged = connect_NONE__NONE \"cursor_changed\" True\n\n-- | A row was activated.\n--\n-- * Activation usually means the user has pressed return on a row.\n--\nonRowActivated, afterRowActivated :: TreeViewClass self => self\n -> (TreePath -> TreeViewColumn -> IO ())\n -> IO (ConnectId self)\nonRowActivated = connect_BOXED_OBJECT__NONE \"row_activated\" \n\t\t readNTP False\nafterRowActivated = connect_BOXED_OBJECT__NONE \"row_activated\" \n\t\t readNTP True\n\n-- | Children of this node were hidden.\n--\nonRowCollapsed, afterRowCollapsed :: TreeViewClass self => self\n -> (TreeIter -> TreePath -> IO ())\n -> IO (ConnectId self)\nonRowCollapsed = connect_BOXED_BOXED__NONE \"row_collapsed\"\n peek readNTP False\nafterRowCollapsed = connect_BOXED_BOXED__NONE \"row_collapsed\"\n peek readNTP True\n\n-- | Children of this node are made visible.\n--\nonRowExpanded, afterRowExpanded :: TreeViewClass self => self\n -> (TreeIter -> TreePath -> IO ())\n -> IO (ConnectId self)\nonRowExpanded = connect_BOXED_BOXED__NONE \"row_expanded\"\n peek readNTP False\nafterRowExpanded = connect_BOXED_BOXED__NONE \"row_expanded\"\n peek readNTP True\n\n-- | The user wants to search interactively.\n--\n-- * Connect to this signal if you want to provide you own search facility.\n-- Note that you must handle all keyboard input yourself.\n--\nonStartInteractiveSearch, afterStartInteractiveSearch :: \n TreeViewClass self => self -> IO () -> IO (ConnectId self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\nonStartInteractiveSearch self fun =\n connect_NONE__BOOL \"start_interactive_search\" False self (fun >> return True)\nafterStartInteractiveSearch self fun =\n connect_NONE__BOOL \"start_interactive_search\" True self (fun >> return True)\n\n#else\n\nonStartInteractiveSearch =\n connect_NONE__NONE \"start_interactive_search\" False\nafterStartInteractiveSearch = \n connect_NONE__NONE \"start_interactive_search\" True\n\n#endif\n\n-- | Determine if this row should be collapsed.\n--\n-- * If the application connects to this function and returns @False@,\n-- the specifc row will not be altered.\n--\nonTestCollapseRow, afterTestCollapseRow :: TreeViewClass self => self\n -> (TreeIter -> TreePath -> IO Bool)\n -> IO (ConnectId self)\nonTestCollapseRow = connect_BOXED_BOXED__BOOL \"test_collapse_row\"\n peek readNTP False\nafterTestCollapseRow = connect_BOXED_BOXED__BOOL \"test_collapse_row\"\n peek readNTP True\n\n-- | Determine if this row should be expanded.\n--\n-- * If the application connects to this function and returns @False@,\n-- the specifc row will not be altered.\n--\nonTestExpandRow, afterTestExpandRow :: TreeViewClass self => self\n -> (TreeIter -> TreePath -> IO Bool)\n -> IO (ConnectId self)\nonTestExpandRow = connect_BOXED_BOXED__BOOL \"test_expand_row\"\n peek readNTP False\nafterTestExpandRow = connect_BOXED_BOXED__BOOL \"test_expand_row\"\n peek readNTP True\n#endif\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget TreeView\n--\n-- Author : Axel Simon\n--\n-- Created: 9 May 2001\n--\n-- Copyright (C) 2001-2005 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- TODO\n--\n-- gtk_tree_view_get_bin_window is to compare the GDK window from incoming\n-- events. We don't marshal that window parameter, so this function is not\n-- bound either.\n--\n-- The following functions related to drag and drop:\n-- treeViewSetDragDestRow, treeViewGetDragDestRow, treeViewGetDestRowAtPos\n-- these seem to be useful only in cases when the user wants to implement\n-- drag and drop himself rather than use the widget's implementation. I\n-- think this would be a bad idea in the first place.\n--\n-- get_search_equal_func is missing: proper memory management is impossible\n--\n-- gtk_tree_view_set_destroy_count_func is not meant to be useful\n--\n-- expand-collapse-cursor-row needs to be bound if it is useful to expand\n-- and collapse rows in a user-defined manner. Would only work on Gtk 2.2\n-- and higher since the return parameter changed\n--\n-- move_cursor, select_all, select_cursor_parent, select_cursor_row\n-- toggle_cursor_row, unselect_all are not bound.\n-- These functions are only useful to change the widgets\n-- behaviour for these actions. Everything else can be done with\n-- cursor_changed and columns_changed\n--\n-- set_scroll_adjustment makes sense if the user monitors the scroll bars\n-- and the scroll bars can be replaced anytime (the latter is odd)\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- A widget for displaying both trees and lists.\n--\nmodule Graphics.UI.Gtk.ModelView.TreeView (\n-- * Description\n-- \n-- | Widget that displays any object that implements the 'TreeModel'\n-- interface.\n--\n-- The widget supports scrolling natively. This implies that pixel \n-- coordinates can be given in two formats: relative to the current view's\n-- upper left corner or relative to the whole list's coordinates. The former\n-- are called widget coordinates while the letter are called tree \n-- coordinates.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----TreeView\n-- @\n\n-- * Types\n TreeView,\n TreeViewClass,\n castToTreeView, gTypeTreeView,\n toTreeView,\n Point,\n DragAction(..),\n#if GTK_CHECK_VERSION(2,10,0)\n TreeViewGridLines(..),\n#endif\n\n-- * Constructors\n treeViewNew,\n treeViewNewWithModel,\n\n-- * Methods\n treeViewGetModel,\n treeViewSetModel,\n treeViewGetSelection,\n treeViewGetHAdjustment,\n treeViewSetHAdjustment,\n treeViewGetVAdjustment,\n treeViewSetVAdjustment,\n treeViewGetHeadersVisible,\n treeViewSetHeadersVisible,\n treeViewColumnsAutosize,\n treeViewSetHeadersClickable,\n treeViewGetRulesHint,\n treeViewSetRulesHint,\n treeViewAppendColumn,\n treeViewRemoveColumn,\n treeViewInsertColumn,\n treeViewGetColumn,\n treeViewGetColumns,\n treeViewMoveColumnAfter,\n treeViewMoveColumnFirst,\n treeViewSetExpanderColumn,\n treeViewGetExpanderColumn,\n treeViewSetColumnDragFunction,\n treeViewScrollToPoint,\n treeViewScrollToCell,\n treeViewSetCursor,\n#if GTK_CHECK_VERSION(2,2,0)\n treeViewSetCursorOnCell,\n#endif\n treeViewGetCursor,\n treeViewRowActivated,\n treeViewExpandAll,\n treeViewCollapseAll,\n#if GTK_CHECK_VERSION(2,2,0)\n treeViewExpandToPath,\n#endif\n treeViewExpandRow,\n treeViewCollapseRow,\n treeViewMapExpandedRows,\n treeViewRowExpanded,\n treeViewGetReorderable,\n treeViewSetReorderable,\n treeViewGetPathAtPos,\n treeViewGetCellArea,\n treeViewGetBackgroundArea,\n treeViewGetVisibleRect,\n#if GTK_CHECK_VERSION(2,12,0)\n treeViewConvertBinWindowToTreeCoords,\n treeViewConvertBinWindowToWidgetCoords,\n treeViewConvertTreeToBinWindowCoords,\n treeViewConvertTreeToWidgetCoords,\n treeViewConvertWidgetToBinWindowCoords,\n treeViewConvertWidgetToTreeCoords,\n#endif\n treeViewCreateRowDragIcon,\n treeViewGetEnableSearch,\n treeViewSetEnableSearch,\n treeViewGetSearchColumn,\n treeViewSetSearchColumn,\n treeViewSetSearchEqualFunc,\n#if GTK_CHECK_VERSION(2,6,0)\n treeViewGetFixedHeightMode,\n treeViewSetFixedHeightMode,\n treeViewGetHoverSelection,\n treeViewSetHoverSelection,\n treeViewGetHoverExpand,\n treeViewSetHoverExpand,\n#if GTK_CHECK_VERSION(2,10,0)\n treeViewGetHeadersClickable,\n#endif\n#endif\n#if GTK_CHECK_VERSION(2,8,0)\n treeViewGetVisibleRange,\n#endif\n#if GTK_CHECK_VERSION(2,10,0)\n treeViewEnableModelDragDest,\n treeViewEnableModelDragSource,\n treeViewUnsetRowsDragSource,\n treeViewUnsetRowsDragDest,\n treeViewGetSearchEntry,\n treeViewSetSearchEntry,\n#endif\n#if GTK_CHECK_VERSION(2,6,0)\n treeViewSetRowSeparatorFunc,\n#if GTK_CHECK_VERSION(2,10,0)\n treeViewGetRubberBanding,\n treeViewSetRubberBanding,\n treeViewGetEnableTreeLines,\n treeViewSetEnableTreeLines,\n treeViewGetGridLines,\n treeViewSetGridLines,\n#endif\n#endif\n-- * Attributes\n treeViewModel,\n treeViewHAdjustment,\n treeViewVAdjustment,\n treeViewHeadersVisible,\n treeViewHeadersClickable,\n treeViewExpanderColumn,\n treeViewReorderable,\n treeViewRulesHint,\n treeViewEnableSearch,\n treeViewSearchColumn,\n#if GTK_CHECK_VERSION(2,4,0)\n treeViewFixedHeightMode,\n#if GTK_CHECK_VERSION(2,6,0)\n treeViewHoverSelection,\n treeViewHoverExpand,\n#endif\n#endif\n treeViewShowExpanders,\n treeViewLevelIndentation,\n treeViewRubberBanding,\n#if GTK_CHECK_VERSION(2,10,0)\n treeViewEnableGridLines,\n#endif\n treeViewEnableTreeLines,\n#if GTK_CHECK_VERSION(2,10,0)\n treeViewGridLines,\n treeViewSearchEntry,\n#endif\n\n-- * Signals\n columnsChanged,\n cursorChanged,\n rowCollapsed,\n rowExpanded,\n testCollapseRow,\n testExpandRow,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n treeViewWidgetToTreeCoords,\n treeViewTreeToWidgetCoords,\n\n onColumnsChanged,\n afterColumnsChanged,\n onCursorChanged,\n afterCursorChanged,\n onRowActivated,\n afterRowActivated,\n onRowCollapsed,\n afterRowCollapsed,\n onRowExpanded,\n afterRowExpanded,\n onStartInteractiveSearch,\n afterStartInteractiveSearch,\n onTestCollapseRow,\n afterTestCollapseRow,\n onTestExpandRow,\n afterTestExpandRow\n#endif\n ) where\n\nimport Control.Monad\t(liftM, mapM)\nimport Data.Maybe\t(fromMaybe)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.GList\t\t(fromGList)\nimport System.Glib.Flags\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport System.Glib.GObject\t\t(makeNewGObject, constructNewGObject,\n\t\t\t\t\t destroyFunPtr)\nimport Graphics.UI.Gtk.Gdk.Enums (DragAction(..))\nimport Graphics.UI.Gtk.Gdk.Events (Modifier(..))\nimport Graphics.UI.Gtk.General.Structs\t(Point, Rectangle)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.ModelView.TreeViewColumn#}\nimport Graphics.UI.Gtk.ModelView.TreeModel (ColumnId, columnIdToNumber,\n makeColumnIdString)\n{#import Graphics.UI.Gtk.ModelView.Types#}\n{#import Graphics.UI.Gtk.General.DNDTypes#} (TargetList(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Creates a new 'TreeView' widget.\n--\ntreeViewNew :: IO TreeView\ntreeViewNew =\n makeNewObject mkTreeView $\n liftM (castPtr :: Ptr Widget -> Ptr TreeView) $\n {# call tree_view_new #}\n\n-- | Create a new 'TreeView' \n-- widget with @model@ as the storage model.\n--\ntreeViewNewWithModel :: TreeModelClass model => model -> IO TreeView\ntreeViewNewWithModel model =\n makeNewObject mkTreeView $\n liftM (castPtr :: Ptr Widget -> Ptr TreeView) $\n {# call tree_view_new_with_model #}\n (toTreeModel model)\n\n--------------------\n-- Methods\n\n-- | Returns the model that supplies the data for\n-- this 'TreeView'. Returns @Nothing@ if the model is unset.\n--\ntreeViewGetModel :: TreeViewClass self => self -> IO (Maybe TreeModel)\ntreeViewGetModel self =\n maybeNull (makeNewGObject mkTreeModel) $\n {# call unsafe tree_view_get_model #}\n (toTreeView self)\n\n-- | Set the 'TreeModel' for the current View.\n--\ntreeViewSetModel :: (TreeViewClass self, TreeModelClass model) => self\n -> model\n -> IO ()\ntreeViewSetModel self model =\n {# call tree_view_set_model #}\n (toTreeView self)\n (toTreeModel model)\n\n-- | Retrieve a 'TreeSelection' that\n-- holds the current selected nodes of the View.\n--\ntreeViewGetSelection :: TreeViewClass self => self -> IO TreeSelection\ntreeViewGetSelection self =\n makeNewGObject mkTreeSelection $\n {# call unsafe tree_view_get_selection #}\n (toTreeView self)\n\n-- | Gets the 'Adjustment' currently being used for the horizontal aspect.\n--\ntreeViewGetHAdjustment :: TreeViewClass self => self -> IO (Maybe Adjustment)\ntreeViewGetHAdjustment self =\n maybeNull (makeNewObject mkAdjustment) $\n {# call unsafe tree_view_get_hadjustment #}\n (toTreeView self)\n\n-- | Sets the 'Adjustment' for the current horizontal aspect.\n--\ntreeViewSetHAdjustment :: TreeViewClass self => self\n -> Maybe Adjustment -- ^ @adjustment@ - The 'Adjustment' to set, or @Nothing@\n -> IO ()\ntreeViewSetHAdjustment self adjustment =\n {# call tree_view_set_hadjustment #}\n (toTreeView self)\n (fromMaybe (Adjustment nullForeignPtr) adjustment)\n\n-- | Gets the 'Adjustment' currently being used for the vertical aspect.\n--\ntreeViewGetVAdjustment :: TreeViewClass self => self -> IO (Maybe Adjustment)\ntreeViewGetVAdjustment self =\n maybeNull (makeNewObject mkAdjustment) $\n {# call unsafe tree_view_get_vadjustment #}\n (toTreeView self)\n\n-- | Sets the 'Adjustment' for the current vertical aspect.\n--\ntreeViewSetVAdjustment :: TreeViewClass self => self\n -> Maybe Adjustment -- ^ @adjustment@ - The 'Adjustment' to set, or @Nothing@\n -> IO ()\ntreeViewSetVAdjustment self adjustment =\n {# call tree_view_set_vadjustment #}\n (toTreeView self)\n (fromMaybe (Adjustment nullForeignPtr) adjustment)\n\n-- | Query if the column headers are visible.\n--\ntreeViewGetHeadersVisible :: TreeViewClass self => self -> IO Bool\ntreeViewGetHeadersVisible self =\n liftM toBool $\n {# call unsafe tree_view_get_headers_visible #}\n (toTreeView self)\n\n-- | Set the visibility state of the column headers.\n--\ntreeViewSetHeadersVisible :: TreeViewClass self => self -> Bool -> IO ()\ntreeViewSetHeadersVisible self headersVisible =\n {# call tree_view_set_headers_visible #}\n (toTreeView self)\n (fromBool headersVisible)\n\n-- | Resize the columns to their optimal size.\n--\ntreeViewColumnsAutosize :: TreeViewClass self => self -> IO ()\ntreeViewColumnsAutosize self =\n {# call tree_view_columns_autosize #}\n (toTreeView self)\n\n-- | Set wether the columns headers are sensitive to mouse clicks.\n--\ntreeViewSetHeadersClickable :: TreeViewClass self => self -> Bool -> IO ()\ntreeViewSetHeadersClickable self setting =\n {# call tree_view_set_headers_clickable #}\n (toTreeView self)\n (fromBool setting)\n\n-- | Query if visual aid for wide columns is turned on.\n--\ntreeViewGetRulesHint :: TreeViewClass self => self -> IO Bool\ntreeViewGetRulesHint self =\n liftM toBool $\n {# call unsafe tree_view_get_rules_hint #}\n (toTreeView self)\n\n-- | This function tells Gtk+ that the user interface for your application\n-- requires users to read across tree rows and associate cells with one\n-- another. By default, Gtk+ will then render the tree with alternating row\n-- colors. Do \/not\/ use it just because you prefer the appearance of the ruled\n-- tree; that's a question for the theme. Some themes will draw tree rows in\n-- alternating colors even when rules are turned off, and users who prefer that\n-- appearance all the time can choose those themes. You should call this\n-- function only as a \/semantic\/ hint to the theme engine that your tree makes\n-- alternating colors useful from a functional standpoint (since it has lots of\n-- columns, generally).\n--\ntreeViewSetRulesHint :: TreeViewClass self => self -> Bool -> IO ()\ntreeViewSetRulesHint self setting =\n {# call tree_view_set_rules_hint #}\n (toTreeView self)\n (fromBool setting)\n\n-- | Append a new column to the 'TreeView'. Returns the new number of columns.\n--\ntreeViewAppendColumn :: TreeViewClass self => self -> TreeViewColumn -> IO Int\ntreeViewAppendColumn self column =\n liftM fromIntegral $\n {# call tree_view_append_column #}\n (toTreeView self)\n column\n\n-- | Remove column @tvc@ from the 'TreeView'\n-- widget. The number of remaining columns is returned.\n--\ntreeViewRemoveColumn :: TreeViewClass self => self -> TreeViewColumn -> IO Int\ntreeViewRemoveColumn self column =\n liftM fromIntegral $\n {# call tree_view_remove_column #}\n (toTreeView self)\n column\n\n-- | Inserts column @tvc@ into the\n-- 'TreeView' widget at the position @pos@. Returns the number of\n-- columns after insertion. Specify -1 for @pos@ to insert the column\n-- at the end.\n--\ntreeViewInsertColumn :: TreeViewClass self => self\n -> TreeViewColumn\n -> Int\n -> IO Int\ntreeViewInsertColumn self column position =\n liftM fromIntegral $\n {# call tree_view_insert_column #}\n (toTreeView self)\n column\n (fromIntegral position)\n\n-- | Retrieve a 'TreeViewColumn'.\n--\n-- * Retrieve the @pos@ th columns of\n-- 'TreeView'. If the index is out of range Nothing is returned.\n--\ntreeViewGetColumn :: TreeViewClass self => self -> Int -> IO (Maybe TreeViewColumn)\ntreeViewGetColumn self pos = do\n tvcPtr <- {# call unsafe tree_view_get_column #} (toTreeView self) \n (fromIntegral pos)\n if tvcPtr==nullPtr then return Nothing else \n liftM Just $ makeNewObject mkTreeViewColumn (return tvcPtr)\n\n-- | Return all 'TreeViewColumn's in this 'TreeView'.\n--\ntreeViewGetColumns :: TreeViewClass self => self -> IO [TreeViewColumn]\ntreeViewGetColumns self = do\n colsList <- {# call unsafe tree_view_get_columns #} (toTreeView self)\n colsPtr <- fromGList colsList\n mapM (makeNewObject mkTreeViewColumn) (map return colsPtr)\n\n-- | Move a specific column.\n--\n-- * Use 'treeViewMoveColumnToFront' if you want to move the column\n-- to the left end of the 'TreeView'.\n--\ntreeViewMoveColumnAfter :: TreeViewClass self => self\n -> TreeViewColumn\n -> TreeViewColumn\n -> IO ()\ntreeViewMoveColumnAfter self column baseColumn =\n {# call tree_view_move_column_after #}\n (toTreeView self)\n column\n baseColumn\n\n-- | Move a specific column.\n--\n-- * Use 'treeViewMoveColumnAfter' if you want to move the column\n-- somewhere else than to the leftmost position.\n--\ntreeViewMoveColumnFirst :: TreeViewClass self => self -> TreeViewColumn -> IO ()\ntreeViewMoveColumnFirst self which =\n {# call tree_view_move_column_after #}\n (toTreeView self)\n which\n (TreeViewColumn nullForeignPtr)\n\n-- | Set location of hierarchy controls.\n--\n-- * Sets the column to draw the expander arrow at. If @col@\n-- is @Nothing@, then the expander arrow is always at the first\n-- visible column.\n--\n-- If you do not want expander arrow to appear in your tree, set the\n-- expander column to a hidden column.\n--\ntreeViewSetExpanderColumn :: TreeViewClass self => self\n -> Maybe TreeViewColumn\n -> IO ()\ntreeViewSetExpanderColumn self column =\n {# call unsafe tree_view_set_expander_column #}\n (toTreeView self)\n (fromMaybe (TreeViewColumn nullForeignPtr) column)\n\n-- | Get location of hierarchy controls.\n--\n-- * Gets the column to draw the expander arrow at. If @col@\n-- is @Nothing@, then the expander arrow is always at the first\n-- visible column.\n--\ntreeViewGetExpanderColumn :: TreeViewClass self => self\n -> IO TreeViewColumn\ntreeViewGetExpanderColumn self =\n makeNewObject mkTreeViewColumn $\n {# call unsafe tree_view_get_expander_column #}\n (toTreeView self)\n\n-- | Specify where a column may be dropped.\n--\n-- * Sets a user function for determining where a column may be dropped when\n-- dragged. This function is called on every column pair in turn at the\n-- beginning of a column drag to determine where a drop can take place.\n--\n-- * The callback function take the 'TreeViewColumn' to be moved, the\n-- second and third arguments are the columns on the left and right side\n-- of the new location. At most one of them might be @Nothing@\n-- which indicates that the column is about to be dropped at the left or\n-- right end of the 'TreeView'.\n--\n-- * The predicate @pred@ should return @True@ if it is ok\n-- to insert the column at this place.\n--\n-- * Use @Nothing@ for the predicate if columns can be inserted\n-- anywhere.\n--\ntreeViewSetColumnDragFunction :: TreeViewClass self => self\n -> Maybe (TreeViewColumn\n -> Maybe TreeViewColumn\n -> Maybe TreeViewColumn\n -> IO Bool)\n -> IO ()\ntreeViewSetColumnDragFunction self Nothing =\n {# call tree_view_set_column_drag_function #} (toTreeView self)\n nullFunPtr nullPtr nullFunPtr\ntreeViewSetColumnDragFunction self (Just pred) = do\n fPtr <- mkTreeViewColumnDropFunc $ \\_ target prev next _ -> do\n target' <- makeNewObject mkTreeViewColumn (return target)\n prev' <- if prev==nullPtr then return Nothing else liftM Just $\n makeNewObject mkTreeViewColumn (return prev)\n next' <- if next==nullPtr then return Nothing else liftM Just $\n makeNewObject mkTreeViewColumn (return next)\n res <- pred target' prev' next'\n return (fromBool res)\n {# call tree_view_set_column_drag_function #}\n (toTreeView self)\n fPtr\n (castFunPtrToPtr fPtr) destroyFunPtr\n\n{#pointer TreeViewColumnDropFunc#}\n\nforeign import ccall \"wrapper\" mkTreeViewColumnDropFunc ::\n (Ptr () -> Ptr TreeViewColumn -> Ptr TreeViewColumn -> Ptr TreeViewColumn ->\n Ptr () -> IO {#type gboolean#}) -> IO TreeViewColumnDropFunc\n\n-- | Scroll to a coordinate.\n--\n-- * Scrolls the tree view such that the top-left corner of the\n-- visible area is @treeX@, @treeY@, where @treeX@\n-- and @treeY@ are specified in tree window coordinates.\n-- The 'TreeView' must be realized before this function is\n-- called. If it isn't, you probably want to use\n-- 'treeViewScrollToCell'.\n--\ntreeViewScrollToPoint :: TreeViewClass self => self\n -> Int\n -> Int\n -> IO ()\ntreeViewScrollToPoint self treeX treeY =\n {# call tree_view_scroll_to_point #}\n (toTreeView self)\n (fromIntegral treeX)\n (fromIntegral treeY)\n\n-- | Scroll to a cell.\n--\n-- * Scroll to a cell as specified by @path@ and @tvc@. \n-- The cell is aligned within the 'TreeView' widget as\n-- follows: horizontally by @hor@ from left (@0.0@) to\n-- right (@1.0@) and vertically by @ver@ from top\n-- (@0.0@) to buttom (@1.0@).\n--\ntreeViewScrollToCell :: TreeViewClass self => self\n -> TreePath\n -> TreeViewColumn\n -> Maybe (Float, Float)\n -> IO ()\ntreeViewScrollToCell self path column (Just (ver,hor)) =\n withTreePath path $ \\path ->\n {# call tree_view_scroll_to_cell #}\n (toTreeView self)\n path\n column\n 1 \n (realToFrac ver)\n (realToFrac hor)\ntreeViewScrollToCell self path column Nothing = \n withTreePath path $ \\path ->\n {# call tree_view_scroll_to_cell #}\n (toTreeView self)\n path\n column\n 0\n 0.0\n 0.0\n\n-- | Selects a specific row.\n--\n-- * Sets the current keyboard focus to be at @path@, and\n-- selects it. This is useful when you want to focus the user\\'s\n-- attention on a particular row. If @focusColumn@ is given,\n-- then the input focus is given to the column specified by\n-- it. Additionally, if @focusColumn@ is specified, and \n-- @startEditing@ is @True@,\n-- then editing will be started in the\n-- specified cell. This function is often followed by a\n-- 'widgetGrabFocus' to the 'TreeView' in order\n-- to give keyboard focus to the widget.\n--\ntreeViewSetCursor :: TreeViewClass self => self\n -> TreePath\n -> (Maybe (TreeViewColumn, Bool))\n -> IO ()\ntreeViewSetCursor self path Nothing =\n withTreePath path $ \\path ->\n {# call tree_view_set_cursor #}\n (toTreeView self)\n path\n (TreeViewColumn nullForeignPtr)\n (fromBool False)\ntreeViewSetCursor self path (Just (focusColumn, startEditing)) =\n withTreePath path $ \\path ->\n {# call tree_view_set_cursor #}\n (toTreeView self)\n path\n focusColumn\n (fromBool startEditing)\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Selects a cell in a specific row.\n--\n-- * Similar to 'treeViewSetCursor' but allows a column to\n-- containt several 'CellRenderer's.\n--\n-- * Only available in Gtk 2.2 and higher.\n--\ntreeViewSetCursorOnCell :: (TreeViewClass self, CellRendererClass focusCell) => self\n -> TreePath\n -> TreeViewColumn\n -> focusCell\n -> Bool\n -> IO ()\ntreeViewSetCursorOnCell self path focusColumn focusCell startEditing =\n withTreePath path $ \\path ->\n {# call tree_view_set_cursor_on_cell #}\n (toTreeView self)\n path\n focusColumn\n (toCellRenderer focusCell)\n (fromBool startEditing)\n#endif\n\n-- | Retrieves the position of the focus.\n--\n-- * Returns a pair @(path, column)@.If the cursor is not currently\n-- set, @path@ will be @[]@. If no column is currently\n-- selected, @column@ will be @Nothing@.\n--\ntreeViewGetCursor :: TreeViewClass self => self\n -> IO (TreePath, Maybe TreeViewColumn)\ntreeViewGetCursor self =\n alloca $ \\tpPtrPtr -> alloca $ \\tvcPtrPtr -> do\n {# call unsafe tree_view_get_cursor #}\n (toTreeView self)\n (castPtr tpPtrPtr)\n (castPtr tvcPtrPtr)\n tpPtr <- peek tpPtrPtr\n tvcPtr <- peek tvcPtrPtr\n tp <- fromTreePath tpPtr\n tvc <- if tvcPtr==nullPtr then return Nothing else liftM Just $\n makeNewObject mkTreeViewColumn (return tvcPtr)\n return (tp,tvc)\n\n-- | Emit the activated signal on a cell.\n--\ntreeViewRowActivated :: TreeViewClass self => self\n -> TreePath\n -> TreeViewColumn\n -> IO ()\ntreeViewRowActivated self path column =\n withTreePath path $ \\path ->\n {# call tree_view_row_activated #}\n (toTreeView self)\n path\n column\n\n-- | Recursively expands all nodes in the tree view.\n--\ntreeViewExpandAll :: TreeViewClass self => self -> IO ()\ntreeViewExpandAll self =\n {# call tree_view_expand_all #}\n (toTreeView self)\n\n-- | Recursively collapses all visible, expanded nodes in the tree view.\n--\ntreeViewCollapseAll :: TreeViewClass self => self -> IO ()\ntreeViewCollapseAll self =\n {# call tree_view_collapse_all #}\n (toTreeView self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n-- | Make a certain path visible.\n--\n-- * This will expand all parent rows of @tp@ as necessary.\n--\n-- * Only available in Gtk 2.2 and higher.\n--\ntreeViewExpandToPath :: TreeViewClass self => self -> TreePath -> IO ()\ntreeViewExpandToPath self path =\n withTreePath path $ \\path ->\n {# call tree_view_expand_to_path #}\n (toTreeView self)\n path\n#endif\n\n-- | Opens the row so its children are visible.\n--\ntreeViewExpandRow :: TreeViewClass self => self\n -> TreePath -- ^ @path@ - path to a row\n -> Bool -- ^ @openAll@ - whether to recursively expand, or just expand\n -- immediate children\n -> IO Bool -- ^ returns @True@ if the row existed and had children\ntreeViewExpandRow self path openAll =\n liftM toBool $\n withTreePath path $ \\path ->\n {# call tree_view_expand_row #}\n (toTreeView self)\n path\n (fromBool openAll)\n\n-- | Collapses a row (hides its child rows, if they exist).\n--\ntreeViewCollapseRow :: TreeViewClass self => self\n -> TreePath -- ^ @path@ - path to a row in the tree view\n -> IO Bool -- ^ returns @True@ if the row was collapsed.\ntreeViewCollapseRow self path =\n liftM toBool $\n withTreePath path $ \\path ->\n {# call tree_view_collapse_row #}\n (toTreeView self)\n path\n\n-- | Call function for every expaned row.\n--\ntreeViewMapExpandedRows :: TreeViewClass self => self\n -> (TreePath -> IO ())\n -> IO ()\ntreeViewMapExpandedRows self func = do\n fPtr <- mkTreeViewMappingFunc $ \\_ tpPtr _ -> fromTreePath tpPtr >>= func\n {# call tree_view_map_expanded_rows #}\n (toTreeView self)\n fPtr\n nullPtr\n freeHaskellFunPtr fPtr\n\n{#pointer TreeViewMappingFunc#}\n\nforeign import ccall \"wrapper\" mkTreeViewMappingFunc ::\n (Ptr () -> Ptr NativeTreePath -> Ptr () -> IO ()) ->\n IO TreeViewMappingFunc\n\n-- | Check if row is expanded.\n--\ntreeViewRowExpanded :: TreeViewClass self => self\n -> TreePath -- ^ @path@ - A 'TreePath' to test expansion state.\n -> IO Bool -- ^ returns @True@ if @path@ is expanded.\ntreeViewRowExpanded self path =\n liftM toBool $\n withTreePath path $ \\path ->\n {# call unsafe tree_view_row_expanded #}\n (toTreeView self)\n path\n\n-- | Query if rows can be moved around.\n--\n-- * See 'treeViewSetReorderable'.\n--\ntreeViewGetReorderable :: TreeViewClass self => self -> IO Bool\ntreeViewGetReorderable self =\n liftM toBool $\n {# call unsafe tree_view_get_reorderable #}\n (toTreeView self)\n\n-- | Check if rows can be moved around.\n--\n-- * Set whether the user can use drag and drop (DND) to reorder the rows in\n-- the store. This works on both 'TreeStore' and 'ListStore' models. If @ro@\n-- is @True@, then the user can reorder the model by dragging and dropping\n-- rows. The developer can listen to these changes by connecting to the\n-- model's signals. If you need to control which rows may be dragged or\n-- where rows may be dropped, you can override the\n-- 'Graphics.UI.Gtk.ModelView.CustomStore.treeDragSourceRowDraggable'\n-- function in the default DND implementation of the model.\n--\ntreeViewSetReorderable :: TreeViewClass self => self\n -> Bool\n -> IO ()\ntreeViewSetReorderable self reorderable =\n {# call tree_view_set_reorderable #}\n (toTreeView self)\n (fromBool reorderable)\n\n-- | Map a pixel to the specific cell.\n--\n-- * Finds the path at the 'Point' @(x, y)@. The\n-- coordinates @x@ and @y@ are relative to the top left\n-- corner of the 'TreeView' drawing window. As such, coordinates\n-- in a mouse click event can be used directly to determine the cell\n-- which the user clicked on. This function is useful to realize\n-- popup menus.\n--\n-- * The returned point is the input point relative to the cell's upper\n-- left corner. The whole 'TreeView' is divided between all cells.\n-- The returned point is relative to the rectangle this cell occupies\n-- within the 'TreeView'.\n--\ntreeViewGetPathAtPos :: TreeViewClass self => self\n -> Point\n -> IO (Maybe (TreePath, TreeViewColumn, Point))\ntreeViewGetPathAtPos self (x,y) =\n alloca $ \\tpPtrPtr ->\n alloca $ \\tvcPtrPtr ->\n alloca $ \\xPtr ->\n alloca $ \\yPtr -> do\n res <- liftM toBool $\n {# call unsafe tree_view_get_path_at_pos #}\n (toTreeView self)\n (fromIntegral x)\n (fromIntegral y)\n (castPtr tpPtrPtr)\n (castPtr tvcPtrPtr)\n xPtr\n yPtr\n tpPtr <- peek tpPtrPtr\n tvcPtr <- peek tvcPtrPtr\n xCell <- peek xPtr\n yCell <- peek yPtr\n if not res then return Nothing else do\n tp <- fromTreePath tpPtr\n tvc <- makeNewObject mkTreeViewColumn (return tvcPtr)\n return (Just (tp,tvc,(fromIntegral xCell, fromIntegral yCell)))\n\n-- | Retrieve the smallest bounding box of a cell.\n--\n-- * Fills the bounding rectangle in tree window coordinates for the\n-- cell at the row specified by @tp@ and the column specified by\n-- @tvc@.\n-- If @path@ is @Nothing@ or points to a path not\n-- currently displayed, the @y@ and @height@ fields of\n-- the 'Rectangle' will be filled with @0@. The sum of\n-- all cell rectangles does not cover the entire tree; there are extra\n-- pixels in between rows, for example.\n--\ntreeViewGetCellArea :: TreeViewClass self => self\n -> Maybe TreePath\n -> TreeViewColumn\n -> IO Rectangle\ntreeViewGetCellArea self Nothing tvc =\n alloca $ \\rPtr ->\n {# call unsafe tree_view_get_cell_area #}\n (toTreeView self)\n (NativeTreePath nullPtr)\n tvc\n (castPtr (rPtr :: Ptr Rectangle))\n >> peek rPtr\ntreeViewGetCellArea self (Just tp) tvc = \n withTreePath tp $ \\tp ->\n alloca $ \\rPtr -> do\n {# call unsafe tree_view_get_cell_area #}\n (toTreeView self)\n tp\n tvc\n (castPtr (rPtr :: Ptr Rectangle))\n >> peek rPtr\n\n-- | Retrieve the largest bounding box of a cell.\n--\n-- * Fills the bounding rectangle in tree window coordinates for the\n-- cell at the row specified by @tp@ and the column specified by\n-- @tvc@.\n-- If @path@ is @Nothing@ or points to a path not\n-- currently displayed, the @y@ and @height@ fields of\n-- the 'Rectangle' will be filled with @0@. The background\n-- areas tile the widget's area to cover the entire tree window \n-- (except for the area used for header buttons). Contrast this with\n-- 'treeViewGetCellArea'.\n--\ntreeViewGetBackgroundArea :: TreeViewClass self => self\n -> Maybe TreePath\n -> TreeViewColumn\n -> IO Rectangle\ntreeViewGetBackgroundArea self Nothing tvc =\n alloca $ \\rPtr ->\n {# call unsafe tree_view_get_background_area #}\n (toTreeView self)\n (NativeTreePath nullPtr)\n tvc\n (castPtr (rPtr :: Ptr Rectangle))\n >> peek rPtr\ntreeViewGetBackgroundArea self (Just tp) tvc = \n withTreePath tp $ \\tp -> alloca $ \\rPtr ->\n {# call unsafe tree_view_get_background_area #}\n (toTreeView self)\n tp\n tvc\n (castPtr (rPtr :: Ptr Rectangle))\n >> peek rPtr\n\n-- | Retrieve the currently visible area.\n--\n-- * The returned rectangle gives the visible part of the tree in tree\n-- coordinates.\n--\ntreeViewGetVisibleRect :: TreeViewClass self => self -> IO Rectangle\ntreeViewGetVisibleRect self =\n alloca $ \\rPtr -> do\n {# call unsafe tree_view_get_visible_rect #}\n (toTreeView self)\n (castPtr (rPtr :: Ptr Rectangle))\n peek rPtr\n\n#ifndef DISABLE_DEPRECATED\n-- | @gtkTreeViewTreeToWidgetCoords@ has been deprecated since version 2.12 and should not be used in\n-- newly-written code. Due to historial reasons the name of this function is incorrect. For converting\n-- @binWindow@ coordinates to coordinates relative to @binWindow@, please see\n-- 'treeViewConvertBinWindowToWidgetCoords'.\n-- \n-- Converts tree coordinates (coordinates in full scrollable area of the tree) to @binWindow@\n-- coordinates.\n--\ntreeViewTreeToWidgetCoords :: TreeViewClass self => self\n -> Point -- ^ @(tx, ty)@ - tree X and Y coordinates\n -> IO Point -- ^ @(wx, wy)@ returns widget X and Y coordinates\ntreeViewTreeToWidgetCoords self (tx, ty) =\n alloca $ \\wxPtr ->\n alloca $ \\wyPtr -> do\n {# call unsafe tree_view_tree_to_widget_coords #}\n (toTreeView self)\n (fromIntegral tx)\n (fromIntegral ty)\n wxPtr\n wyPtr\n wx <- peek wxPtr\n wy <- peek wyPtr\n return (fromIntegral wx, fromIntegral wy)\n\n-- | @gtkTreeViewWidgetToTreeCoords@ has been deprecated since version 2.12 and should not be used in\n-- newly-written code. Due to historial reasons the name of this function is incorrect. For converting\n-- coordinates relative to the widget to @binWindow@ coordinates, please see\n-- 'treeViewConvertWidgetToBinWindowCoords'.\n-- \n-- Converts @binWindow@ coordinates to coordinates for the tree (the full scrollable area of the tree).\n--\ntreeViewWidgetToTreeCoords :: TreeViewClass self => self\n -> Point -- ^ @(wx, wy)@ - widget X and Y coordinates\n -> IO Point -- ^ @(tx, ty)@ returns tree X and Y coordinates\ntreeViewWidgetToTreeCoords self (wx, wy) =\n alloca $ \\txPtr ->\n alloca $ \\tyPtr -> do\n {# call unsafe tree_view_widget_to_tree_coords #}\n (toTreeView self)\n (fromIntegral wx)\n (fromIntegral wy)\n txPtr\n tyPtr\n tx <- peek txPtr\n ty <- peek tyPtr\n return (fromIntegral tx, fromIntegral ty)\n#endif\n\n#if GTK_CHECK_VERSION(2,12,0)\n-- | Converts bin window coordinates to coordinates for the tree (the full scrollable area of the tree).\ntreeViewConvertBinWindowToTreeCoords :: TreeViewClass self => self\n -> Point -- ^ @(bx, by)@ - bin window X and Y coordinates\n -> IO Point -- ^ @(tx, ty)@ returns tree X and Y coordinates \ntreeViewConvertBinWindowToTreeCoords self (bx, by) =\n alloca $ \\txPtr ->\n alloca $ \\tyPtr -> do\n {# call unsafe tree_view_convert_bin_window_to_tree_coords #}\n (toTreeView self)\n (fromIntegral bx)\n (fromIntegral by)\n txPtr\n tyPtr\n tx <- peek txPtr\n ty <- peek tyPtr\n return (fromIntegral tx, fromIntegral ty)\n\n-- | Converts bin window coordinates (see 'treeViewGetBinWindow' to widget relative coordinates.\ntreeViewConvertBinWindowToWidgetCoords :: TreeViewClass self => self\n -> Point -- ^ @(bx, by)@ - bin window X and Y coordinates\n -> IO Point -- ^ @(wx, wy)@ returns widget X and Y coordinates \ntreeViewConvertBinWindowToWidgetCoords self (bx, by) =\n alloca $ \\wxPtr ->\n alloca $ \\wyPtr -> do\n {# call unsafe tree_view_convert_bin_window_to_widget_coords #}\n (toTreeView self)\n (fromIntegral bx)\n (fromIntegral by)\n wxPtr\n wyPtr\n wx <- peek wxPtr\n wy <- peek wyPtr\n return (fromIntegral wx, fromIntegral wy)\n\n-- | Converts tree coordinates (coordinates in full scrollable area of the tree) to bin window\n-- coordinates.\ntreeViewConvertTreeToBinWindowCoords :: TreeViewClass self => self\n -> Point -- ^ @(tx, ty)@ - tree X and Y coordinates\n -> IO Point -- ^ @(bx, by)@ returns bin window X and Y coordinates \ntreeViewConvertTreeToBinWindowCoords self (tx, ty) =\n alloca $ \\bxPtr ->\n alloca $ \\byPtr -> do\n {# call unsafe tree_view_convert_tree_to_bin_window_coords #}\n (toTreeView self)\n (fromIntegral tx)\n (fromIntegral ty)\n bxPtr\n byPtr\n bx <- peek bxPtr\n by <- peek byPtr\n return (fromIntegral bx, fromIntegral by)\n\n-- | Converts tree coordinates (coordinates in full scrollable area of the tree) to widget coordinates.\ntreeViewConvertTreeToWidgetCoords :: TreeViewClass self => self\n -> Point -- ^ @(tx, ty)@ - tree X and Y coordinates\n -> IO Point -- ^ @(wx, wy)@ returns widget X and Y coordinates \ntreeViewConvertTreeToWidgetCoords self (wx, wy) =\n alloca $ \\bxPtr ->\n alloca $ \\byPtr -> do\n {# call unsafe tree_view_convert_tree_to_widget_coords #}\n (toTreeView self)\n (fromIntegral wx)\n (fromIntegral wy)\n bxPtr\n byPtr\n bx <- peek bxPtr\n by <- peek byPtr\n return (fromIntegral bx, fromIntegral by)\n\n-- | Converts widget coordinates to coordinates for the 'window (see gtkTreeViewGetBinWindow'.\ntreeViewConvertWidgetToBinWindowCoords :: TreeViewClass self => self\n -> Point -- ^ @(wx, wy)@ - widget X and Y coordinates\n -> IO Point -- ^ @(bx, by)@ returns bin window X and Y coordinates \ntreeViewConvertWidgetToBinWindowCoords self (wx, wy) =\n alloca $ \\bxPtr ->\n alloca $ \\byPtr -> do\n {# call unsafe tree_view_convert_widget_to_bin_window_coords #}\n (toTreeView self)\n (fromIntegral wx)\n (fromIntegral wy)\n bxPtr\n byPtr\n bx <- peek bxPtr\n by <- peek byPtr\n return (fromIntegral bx, fromIntegral by)\n\n-- | Converts widget coordinates to coordinates for the tree (the full scrollable area of the tree).\ntreeViewConvertWidgetToTreeCoords :: TreeViewClass self => self\n -> Point -- ^ @(wx, wy)@ - bin window X and Y coordinates\n -> IO Point -- ^ @(tx, ty)@ returns tree X and Y coordinates \ntreeViewConvertWidgetToTreeCoords self (wx, wy) =\n alloca $ \\txPtr ->\n alloca $ \\tyPtr -> do\n {# call unsafe tree_view_convert_widget_to_tree_coords #}\n (toTreeView self)\n (fromIntegral wx)\n (fromIntegral wy)\n txPtr\n tyPtr\n tx <- peek txPtr\n ty <- peek tyPtr\n return (fromIntegral tx, fromIntegral ty)\n#endif\n\n-- | Creates a 'Pixmap' representation of the row at the given path. This image\n-- can be used for a drag icon.\n--\ntreeViewCreateRowDragIcon :: TreeViewClass self => self\n -> TreePath\n -> IO Pixmap\ntreeViewCreateRowDragIcon self path =\n constructNewGObject mkPixmap $\n withTreePath path $ \\path ->\n {# call unsafe tree_view_create_row_drag_icon #}\n (toTreeView self)\n path\n\n-- | Returns whether or not the tree allows to start interactive searching by\n-- typing in text.\n--\n-- * If enabled, the user can type in text which will set the cursor to\n-- the first matching entry.\n--\ntreeViewGetEnableSearch :: TreeViewClass self => self -> IO Bool\ntreeViewGetEnableSearch self =\n liftM toBool $\n {# call unsafe tree_view_get_enable_search #}\n (toTreeView self)\n\n-- | If this is set, then the user can type in text to search\n-- through the tree interactively (this is sometimes called \\\"typeahead\n-- find\\\").\n--\n-- Note that even if this is @False@, the user can still initiate a search\n-- using the \\\"start-interactive-search\\\" key binding. In any case,\n-- a predicate that compares a row of the model with the text the user\n-- has typed must be set using 'treeViewSetSearchEqualFunc'.\n--\ntreeViewSetEnableSearch :: TreeViewClass self => self -> Bool -> IO ()\ntreeViewSetEnableSearch self enableSearch =\n {# call tree_view_set_enable_search #}\n (toTreeView self)\n (fromBool enableSearch)\n\n-- %hash c:ecc5 d:bed6\n-- | Gets the column searched on by the interactive search code.\n--\ntreeViewGetSearchColumn :: TreeViewClass self => self\n -> IO (ColumnId row String) -- ^ returns the column the interactive search code searches in.\ntreeViewGetSearchColumn self =\n liftM (makeColumnIdString . fromIntegral) $\n {# call unsafe tree_view_get_search_column #}\n (toTreeView self)\n\n-- %hash c:d0d0\n-- | Sets @column@ as the column where the interactive search code should\n-- search in.\n--\n-- If the sort column is set, users can use the \\\"start-interactive-search\\\"\n-- key binding to bring up search popup. The enable-search property controls\n-- whether simply typing text will also start an interactive search.\n--\n-- Note that @column@ refers to a column of the model. Furthermore, the\n-- search column is not used if a comparison function is set, see\n-- 'treeViewSetSearchEqualFunc'.\n--\ntreeViewSetSearchColumn :: TreeViewClass self => self\n -> (ColumnId row String) -- ^ @column@ - the column of the model to search in, or -1 to disable\n -- searching\n -> IO ()\ntreeViewSetSearchColumn self column =\n {# call tree_view_set_search_column #}\n (toTreeView self)\n (fromIntegral (columnIdToNumber column))\n\n\n-- | Set the predicate to test for equality.\n--\n-- * The predicate must returns @True@ if the text entered by the user\n-- and the row of the model match. Calling this function will overwrite\n-- the 'treeViewSearchColumn' (which isn't used anyway when a comparison\n-- function is installed).\n--\ntreeViewSetSearchEqualFunc :: TreeViewClass self => self\n -> Maybe (String -> TreeIter -> IO Bool)\n -> IO ()\ntreeViewSetSearchEqualFunc self (Just pred) = do\n fPtr <- mkTreeViewSearchEqualFunc (\\_ _ keyPtr iterPtr _ -> do\n key <- peekUTFString keyPtr\n iter <- peek iterPtr\n liftM (fromBool . not) $ pred key iter)\n {# call tree_view_set_search_equal_func #} (toTreeView self) fPtr \n (castFunPtrToPtr fPtr) destroyFunPtr\n {# call tree_view_set_search_column #} (toTreeView self) 0\ntreeViewSetSearchEqualFunc self Nothing = do\n {# call tree_view_set_search_equal_func #} (toTreeView self)\n nullFunPtr nullPtr nullFunPtr\n {# call tree_view_set_search_column #} (toTreeView self) (-1)\n\n{#pointer TreeViewSearchEqualFunc#}\n\nforeign import ccall \"wrapper\" mkTreeViewSearchEqualFunc ::\n (Ptr TreeModel -> {#type gint#} -> CString -> Ptr TreeIter -> Ptr () ->\n IO {#type gboolean#}) -> IO TreeViewSearchEqualFunc\n\n-- helper to marshal native tree paths to TreePaths\nreadNTP :: Ptr TreePath -> IO TreePath\nreadNTP ptr = peekTreePath (castPtr ptr)\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Returns whether fixed height mode is turned on for the tree view.\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewGetFixedHeightMode :: TreeViewClass self => self\n -> IO Bool -- ^ returns @True@ if the tree view is in fixed height mode\ntreeViewGetFixedHeightMode self =\n liftM toBool $\n {# call gtk_tree_view_get_fixed_height_mode #}\n (toTreeView self)\n\n-- | Enables or disables the fixed height mode of the tree view. Fixed height\n-- mode speeds up 'TreeView' by assuming that all rows have the same height.\n-- Only enable this option if all rows are the same height and all columns are\n-- of type 'TreeViewColumnFixed'.\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewSetFixedHeightMode :: TreeViewClass self => self\n -> Bool -- ^ @enable@ - @True@ to enable fixed height mode\n -> IO ()\ntreeViewSetFixedHeightMode self enable =\n {# call gtk_tree_view_set_fixed_height_mode #}\n (toTreeView self)\n (fromBool enable)\n\n-- | Returns whether hover selection mode is turned on for @treeView@.\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewGetHoverSelection :: TreeViewClass self => self\n -> IO Bool -- ^ returns @True@ if the tree view is in hover selection mode\ntreeViewGetHoverSelection self =\n liftM toBool $\n {# call gtk_tree_view_get_hover_selection #}\n (toTreeView self)\n\n-- | Enables of disables the hover selection mode of the tree view. Hover\n-- selection makes the selected row follow the pointer. Currently, this works\n-- only for the selection modes 'SelectionSingle' and 'SelectionBrowse'.\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewSetHoverSelection :: TreeViewClass self => self\n -> Bool -- ^ @hover@ - @True@ to enable hover selection mode\n -> IO ()\ntreeViewSetHoverSelection self hover =\n {# call gtk_tree_view_set_hover_selection #}\n (toTreeView self)\n (fromBool hover)\n\n-- | Returns whether hover expansion mode is turned on for the tree view.\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewGetHoverExpand :: TreeViewClass self => self\n -> IO Bool -- ^ returns @True@ if the tree view is in hover expansion mode\ntreeViewGetHoverExpand self =\n liftM toBool $\n {# call gtk_tree_view_get_hover_expand #}\n (toTreeView self)\n\n-- | Enables of disables the hover expansion mode of the tree view. Hover\n-- expansion makes rows expand or collaps if the pointer moves over them.\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewSetHoverExpand :: TreeViewClass self => self\n -> Bool -- ^ @expand@ - @True@ to enable hover selection mode\n -> IO ()\ntreeViewSetHoverExpand self expand =\n {# call gtk_tree_view_set_hover_expand #}\n (toTreeView self)\n (fromBool expand)\n#endif\n\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:88cb d:65c9\n-- | Returns whether all header columns are clickable.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewGetHeadersClickable :: TreeViewClass self => self\n -> IO Bool -- ^ returns @True@ if all header columns are clickable, otherwise\n -- @False@\ntreeViewGetHeadersClickable self =\n liftM toBool $\n {# call gtk_tree_view_get_headers_clickable #}\n (toTreeView self)\n#endif\n\n#if GTK_CHECK_VERSION(2,8,0)\n-- %hash c:1d81 d:3587\n-- | Return the first and last visible path.\n-- Note that there may be invisible paths in between.\n--\n-- * Available since Gtk+ version 2.8\n--\ntreeViewGetVisibleRange :: TreeViewClass self => self\n -> IO (TreePath, TreePath) -- ^ the first and the last node that is visible\ntreeViewGetVisibleRange self = alloca $ \\startPtr -> alloca $ \\endPtr -> do\n valid <- liftM toBool $\n {# call gtk_tree_view_get_visible_range #}\n (toTreeView self) (castPtr startPtr) (castPtr endPtr)\n if not valid then return ([],[]) else do\n startTPPtr <- peek startPtr\n endTPPtr <- peek endPtr\n startPath <- fromTreePath startTPPtr\n endPath <- fromTreePath endTPPtr\n return (startPath, endPath)\n \n#endif\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:61e1 d:3a0a\n-- | Turns @treeView@ into a drop destination for automatic DND.\n--\ntreeViewEnableModelDragDest :: TreeViewClass self => self\n -> TargetList -- ^ @targets@ - the list of targets that the\n -- the view will support\n -> [DragAction] -- ^ @actions@ - flags denoting the possible actions\n -- for a drop into this widget\n -> IO ()\ntreeViewEnableModelDragDest self targets actions =\n alloca $ \\nTargetsPtr -> do\n tlPtr <- {#call unsafe gtk_target_table_new_from_list#} targets nTargetsPtr\n nTargets <- peek nTargetsPtr\n {# call gtk_tree_view_enable_model_drag_dest #}\n (toTreeView self)\n tlPtr\n nTargets\n ((fromIntegral . fromFlags) actions)\n {#call unsafe gtk_target_table_free#} tlPtr nTargets\n\n-- %hash c:1df9 d:622\n-- | Turns @treeView@ into a drag source for automatic DND.\n--\ntreeViewEnableModelDragSource :: TreeViewClass self => self\n -> [Modifier] -- ^ @startButtonMask@ - Mask of allowed buttons\n -- to start drag\n -> TargetList -- ^ @targets@ - the list of targets that the\n -- the view will support\n -> [DragAction] -- ^ @actions@ - flags denoting the possible actions\n -- for a drag from this widget\n -> IO ()\ntreeViewEnableModelDragSource self startButtonMask targets actions =\n alloca $ \\nTargetsPtr -> do\n tlPtr <- {#call unsafe gtk_target_table_new_from_list#} targets nTargetsPtr\n nTargets <- peek nTargetsPtr\n {# call gtk_tree_view_enable_model_drag_source #}\n (toTreeView self)\n ((fromIntegral . fromFlags) startButtonMask)\n tlPtr\n nTargets\n ((fromIntegral . fromFlags) actions)\n {#call unsafe gtk_target_table_free#} tlPtr nTargets\n\n-- %hash c:5201 d:f3be\n-- | Undoes the effect of 'treeViewEnableModelDragSource'.\n--\ntreeViewUnsetRowsDragSource :: TreeViewClass self => self -> IO ()\ntreeViewUnsetRowsDragSource self =\n {# call gtk_tree_view_unset_rows_drag_source #}\n (toTreeView self)\n\n-- %hash c:e31e d:323d\n-- | Undoes the effect of 'treeViewEnableModelDragDest'.\n--\ntreeViewUnsetRowsDragDest :: TreeViewClass self => self -> IO ()\ntreeViewUnsetRowsDragDest self =\n {# call gtk_tree_view_unset_rows_drag_dest #}\n (toTreeView self)\n\n-- %hash c:3355 d:3bbe\n-- | Returns the 'Entry' which is currently in use as interactive search entry\n-- for @treeView@. In case the built-in entry is being used, @Nothing@ will be\n-- returned.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewGetSearchEntry :: TreeViewClass self => self\n -> IO (Maybe Entry) -- ^ returns the entry currently in use as search entry.\ntreeViewGetSearchEntry self = do\n ePtr <- {# call gtk_tree_view_get_search_entry #}\n (toTreeView self)\n if ePtr==nullPtr then return Nothing else liftM Just $\n makeNewObject mkEntry (return ePtr)\n\n-- %hash c:5e11 d:8ec5\n-- | Sets the entry which the interactive search code will use for this\n-- @treeView@. This is useful when you want to provide a search entry in our\n-- interface at all time at a fixed position. Passing @Nothing@ for @entry@\n-- will make the interactive search code use the built-in popup entry again.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewSetSearchEntry :: (TreeViewClass self, EntryClass entry) => self\n -> (Maybe entry)\n -- ^ @entry@ - the entry the interactive search code of @treeView@\n -- should use or @Nothing@\n -> IO ()\ntreeViewSetSearchEntry self (Just entry) =\n {# call gtk_tree_view_set_search_entry #}\n (toTreeView self)\n (toEntry entry)\ntreeViewSetSearchEntry self Nothing =\n {# call gtk_tree_view_set_search_entry #}\n (toTreeView self)\n (Entry nullForeignPtr)\n#endif\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- %hash c:6326 d:a050\n-- | Sets the row separator function, which is used to determine whether a row\n-- should be drawn as a separator. If the row separator function is @Nothing@,\n-- no separators are drawn. This is the default value.\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewSetRowSeparatorFunc :: TreeViewClass self => self\n -> Maybe (TreeIter -> IO Bool) -- ^ @func@ - a callback function that\n -- returns @True@ if the given row of\n -- the model should be drawn as separator\n -> IO ()\ntreeViewSetRowSeparatorFunc self Nothing =\n {# call gtk_tree_view_set_row_separator_func #}\n (toTreeView self) nullFunPtr nullPtr nullFunPtr\ntreeViewSetRowSeparatorFunc self (Just func) = do\n funcPtr <- mkTreeViewRowSeparatorFunc $ \\_ tiPtr _ -> do\n ti <- peekTreeIter tiPtr\n liftM fromBool $ func ti\n {# call gtk_tree_view_set_row_separator_func #}\n (toTreeView self) funcPtr (castFunPtrToPtr funcPtr) destroyFunPtr\n\n{#pointer TreeViewRowSeparatorFunc #}\n\nforeign import ccall \"wrapper\" mkTreeViewRowSeparatorFunc ::\n (Ptr TreeModel -> Ptr TreeIter -> Ptr () -> IO {#type gboolean#}) ->\n IO TreeViewRowSeparatorFunc\n \n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:778a d:eacd\n-- | Returns whether rubber banding is turned on for @treeView@. If the\n-- selection mode is 'SelectionMultiple', rubber banding will allow the user to\n-- select multiple rows by dragging the mouse.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewGetRubberBanding :: TreeViewClass self => self\n -> IO Bool -- ^ returns @True@ if rubber banding in @treeView@ is enabled.\ntreeViewGetRubberBanding self =\n liftM toBool $\n {# call gtk_tree_view_get_rubber_banding #}\n (toTreeView self)\n\n-- %hash c:4a69 d:93aa\n-- | Enables or disables rubber banding in @treeView@. If the selection mode\n-- is 'SelectionMultiple', rubber banding will allow the user to select\n-- multiple rows by dragging the mouse.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewSetRubberBanding :: TreeViewClass self => self\n -> Bool -- ^ @enable@ - @True@ to enable rubber banding\n -> IO ()\ntreeViewSetRubberBanding self enable =\n {# call gtk_tree_view_set_rubber_banding #}\n (toTreeView self)\n (fromBool enable)\n\n-- %hash c:c8f8 d:c47\n-- | Returns whether or not tree lines are drawn in @treeView@.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewGetEnableTreeLines :: TreeViewClass self => self\n -> IO Bool -- ^ returns @True@ if tree lines are drawn in @treeView@, @False@\n -- otherwise.\ntreeViewGetEnableTreeLines self =\n liftM toBool $\n {# call gtk_tree_view_get_enable_tree_lines #}\n (toTreeView self)\n\n-- %hash c:205d d:1df9\n-- | Sets whether to draw lines interconnecting the expanders in @treeView@.\n-- This does not have any visible effects for lists.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewSetEnableTreeLines :: TreeViewClass self => self\n -> Bool -- ^ @enabled@ - @True@ to enable tree line drawing, @False@\n -- otherwise.\n -> IO ()\ntreeViewSetEnableTreeLines self enabled =\n {# call gtk_tree_view_set_enable_tree_lines #}\n (toTreeView self)\n (fromBool enabled)\n\n-- | Grid lines.\n{#enum TreeViewGridLines {underscoreToCase}#}\n\n-- %hash c:cd40 d:fe96\n-- | Returns which grid lines are enabled in @treeView@.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewGetGridLines :: TreeViewClass self => self\n -> IO TreeViewGridLines -- ^ returns a 'TreeViewGridLines' value indicating\n -- which grid lines are enabled.\ntreeViewGetGridLines self =\n liftM (toEnum . fromIntegral) $\n {# call gtk_tree_view_get_grid_lines #}\n (toTreeView self)\n\n-- %hash c:74b0 d:79f0\n-- | Sets which grid lines to draw in @treeView@.\n--\n-- * Available since Gtk+ version 2.10\n--\ntreeViewSetGridLines :: TreeViewClass self => self\n -> TreeViewGridLines -- ^ @gridLines@ - a 'TreeViewGridLines' value\n -- indicating which grid lines to enable.\n -> IO ()\ntreeViewSetGridLines self gridLines =\n {# call gtk_tree_view_set_grid_lines #}\n (toTreeView self)\n ((fromIntegral . fromEnum) gridLines)\n#endif\n#endif\n\n--------------------\n-- Attributes\n\n-- | The model for the tree view.\n--\ntreeViewModel :: (TreeViewClass self, TreeModelClass model) => ReadWriteAttr self (Maybe TreeModel) model\ntreeViewModel = newAttr\n treeViewGetModel\n treeViewSetModel\n\n-- | Horizontal Adjustment for the widget.\n--\ntreeViewHAdjustment :: TreeViewClass self => Attr self (Maybe Adjustment)\ntreeViewHAdjustment = newAttr\n treeViewGetHAdjustment\n treeViewSetHAdjustment\n\n-- | Vertical Adjustment for the widget.\n--\ntreeViewVAdjustment :: TreeViewClass self => Attr self (Maybe Adjustment)\ntreeViewVAdjustment = newAttr\n treeViewGetVAdjustment\n treeViewSetVAdjustment\n\n-- | Show the column header buttons.\n--\n-- Default value: @True@\n--\ntreeViewHeadersVisible :: TreeViewClass self => Attr self Bool\ntreeViewHeadersVisible = newAttr\n treeViewGetHeadersVisible\n treeViewSetHeadersVisible\n\n-- | Column headers respond to click events.\n--\n-- Default value: @False@\n--\ntreeViewHeadersClickable :: TreeViewClass self => Attr self Bool\ntreeViewHeadersClickable = newAttrFromBoolProperty \"headers-clickable\"\n\n-- | Set the column for the expander column.\n--\ntreeViewExpanderColumn :: TreeViewClass self => ReadWriteAttr self TreeViewColumn (Maybe TreeViewColumn)\ntreeViewExpanderColumn = newAttr\n treeViewGetExpanderColumn\n treeViewSetExpanderColumn\n\n-- | View is reorderable.\n--\n-- Default value: @False@\n--\ntreeViewReorderable :: TreeViewClass self => Attr self Bool\ntreeViewReorderable = newAttr\n treeViewGetReorderable\n treeViewSetReorderable\n\n-- | Set a hint to the theme engine to draw rows in alternating colors.\n--\n-- Default value: @False@\n--\ntreeViewRulesHint :: TreeViewClass self => Attr self Bool\ntreeViewRulesHint = newAttr\n treeViewGetRulesHint\n treeViewSetRulesHint\n\n-- | View allows user to search through columns interactively.\n--\n-- Default value: @True@\n--\ntreeViewEnableSearch :: TreeViewClass self => Attr self Bool\ntreeViewEnableSearch = newAttr\n treeViewGetEnableSearch\n treeViewSetEnableSearch\n\n-- %hash c:e732\n-- | Model column to search through when searching through code.\n--\n-- Allowed values: >= -1\n--\n-- Default value: -1\n--\ntreeViewSearchColumn :: TreeViewClass self => Attr self (ColumnId row String)\ntreeViewSearchColumn = newAttr\n treeViewGetSearchColumn\n treeViewSetSearchColumn\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- %hash c:c7ff d:24d1\n-- | Setting the 'treeViewFixedHeightMode' property to @True@ speeds up 'TreeView'\n-- by assuming that all rows have the same height. Only enable this option if\n-- all rows are the same height. Please see 'treeViewSetFixedHeightMode' for\n-- more information on this option.\n--\n-- Default value: @False@\n--\n-- * Available since Gtk+ version 2.4\n--\ntreeViewFixedHeightMode :: TreeViewClass self => Attr self Bool\ntreeViewFixedHeightMode = newAttrFromBoolProperty \"fixed-height-mode\"\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- %hash c:2026 d:839a\n-- | Enables of disables the hover selection mode of @treeView@. Hover\n-- selection makes the selected row follow the pointer. Currently, this works\n-- only for the selection modes 'SelectionSingle' and 'SelectionBrowse'.\n--\n-- This mode is primarily intended for 'TreeView's in popups, e.g. in\n-- 'ComboBox' or 'EntryCompletion'.\n--\n-- Default value: @False@\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewHoverSelection :: TreeViewClass self => Attr self Bool\ntreeViewHoverSelection = newAttrFromBoolProperty \"hover-selection\"\n\n-- %hash c:c694 d:3f15\n-- | Enables of disables the hover expansion mode of @treeView@. Hover\n-- expansion makes rows expand or collaps if the pointer moves over them.\n--\n-- This mode is primarily intended for 'TreeView's in popups, e.g. in\n-- 'ComboBox' or 'EntryCompletion'.\n--\n-- Default value: @False@\n--\n-- * Available since Gtk+ version 2.6\n--\ntreeViewHoverExpand :: TreeViewClass self => Attr self Bool\ntreeViewHoverExpand = newAttrFromBoolProperty \"hover-expand\"\n#endif\n#endif\n\n-- %hash c:b409 d:2ed2\n-- | View has expanders.\n--\n-- Default value: @True@\n--\ntreeViewShowExpanders :: TreeViewClass self => Attr self Bool\ntreeViewShowExpanders = newAttrFromBoolProperty \"show-expanders\"\n\n-- %hash c:f0e5 d:9017\n-- | Extra indentation for each level.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntreeViewLevelIndentation :: TreeViewClass self => Attr self Int\ntreeViewLevelIndentation = newAttrFromIntProperty \"level-indentation\"\n\n-- %hash c:a647 d:9e53\n-- | Whether to enable selection of multiple items by dragging the mouse\n-- pointer.\n--\n-- Default value: @False@\n--\ntreeViewRubberBanding :: TreeViewClass self => Attr self Bool\ntreeViewRubberBanding = newAttrFromBoolProperty \"rubber-banding\"\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:e926 d:86a8\n-- | Whether grid lines should be drawn in the tree view.\n--\n-- Default value: 'TreeViewGridLinesNone'\n--\ntreeViewEnableGridLines :: TreeViewClass self => Attr self TreeViewGridLines\ntreeViewEnableGridLines = newAttrFromEnumProperty \"enable-grid-lines\"\n {# call pure unsafe gtk_tree_view_grid_lines_get_type #}\n#endif\n\n-- %hash c:a7eb d:4c53\n-- | Whether tree lines should be drawn in the tree view.\n--\n-- Default value: @False@\n--\ntreeViewEnableTreeLines :: TreeViewClass self => Attr self Bool\ntreeViewEnableTreeLines = newAttrFromBoolProperty \"enable-tree-lines\"\n\n#if GTK_CHECK_VERSION(2,10,0)\n-- %hash c:688c d:cbcd\n-- | \\'gridLines\\' property. See 'treeViewGetGridLines' and\n-- 'treeViewSetGridLines'\n--\ntreeViewGridLines :: TreeViewClass self => Attr self TreeViewGridLines\ntreeViewGridLines = newAttr\n treeViewGetGridLines\n treeViewSetGridLines\n\n-- %hash c:9cbe d:2962\n-- | \\'searchEntry\\' property. See 'treeViewGetSearchEntry' and\n-- 'treeViewSetSearchEntry'\n--\ntreeViewSearchEntry :: (TreeViewClass self, EntryClass entry) => ReadWriteAttr self (Maybe Entry) (Maybe entry)\ntreeViewSearchEntry = newAttr\n treeViewGetSearchEntry\n treeViewSetSearchEntry\n#endif\n\n--------------------\n-- Signals\n\n-- %hash c:9fc5 d:3e66\n-- | The given row is about to be expanded (show its children nodes). Use this\n-- signal if you need to control the expandability of individual rows.\n--\ntestExpandRow :: TreeViewClass self => Signal self (TreeIter -> TreePath -> IO Bool)\ntestExpandRow = Signal (connect_BOXED_BOXED__BOOL \"test-expand-row\" peek readNTP)\n\n-- %hash c:20de d:96a3\n-- | The given row is about to be collapsed (hide its children nodes). Use\n-- this signal if you need to control the collapsibility of individual rows.\n--\ntestCollapseRow :: TreeViewClass self => Signal self (TreeIter -> TreePath -> IO Bool)\ntestCollapseRow = Signal (connect_BOXED_BOXED__BOOL \"test-collapse-row\" peek readNTP)\n\n-- %hash c:16dc d:b113\n-- | The given row has been expanded (child nodes are shown).\n--\nrowExpanded :: TreeViewClass self => Signal self (TreeIter -> TreePath -> IO ())\nrowExpanded = Signal (connect_BOXED_BOXED__NONE \"row-expanded\" peek readNTP)\n\n-- %hash c:9ee6 d:325e\n-- | The given row has been collapsed (child nodes are hidden).\n--\nrowCollapsed :: TreeViewClass self => Signal self (TreeIter -> TreePath -> IO ())\nrowCollapsed = Signal (connect_BOXED_BOXED__NONE \"row-collapsed\" peek readNTP)\n\n-- %hash c:4350 d:4f94\n-- | The number of columns of the treeview has changed.\n--\ncolumnsChanged :: TreeViewClass self => Signal self (IO ())\ncolumnsChanged = Signal (connect_NONE__NONE \"columns-changed\")\n\n-- %hash c:6487 d:5b57\n-- | The position of the cursor (focused cell) has changed.\n--\ncursorChanged :: TreeViewClass self => Signal self (IO ())\ncursorChanged = Signal (connect_NONE__NONE \"cursor-changed\")\n\n--------------------\n-- Deprecated Signals\n\n#ifndef DISABLE_DEPRECATED\n\n-- | The user has dragged a column to another position.\n--\nonColumnsChanged, afterColumnsChanged :: TreeViewClass self => self\n -> IO ()\n -> IO (ConnectId self)\nonColumnsChanged = connect_NONE__NONE \"columns_changed\" False\nafterColumnsChanged = connect_NONE__NONE \"columns_changed\" True\n\n-- | The cursor in the tree has moved.\n--\nonCursorChanged, afterCursorChanged :: TreeViewClass self => self\n -> IO ()\n -> IO (ConnectId self)\nonCursorChanged = connect_NONE__NONE \"cursor_changed\" False\nafterCursorChanged = connect_NONE__NONE \"cursor_changed\" True\n\n-- | A row was activated.\n--\n-- * Activation usually means the user has pressed return on a row.\n--\nonRowActivated, afterRowActivated :: TreeViewClass self => self\n -> (TreePath -> TreeViewColumn -> IO ())\n -> IO (ConnectId self)\nonRowActivated = connect_BOXED_OBJECT__NONE \"row_activated\" \n\t\t readNTP False\nafterRowActivated = connect_BOXED_OBJECT__NONE \"row_activated\" \n\t\t readNTP True\n\n-- | Children of this node were hidden.\n--\nonRowCollapsed, afterRowCollapsed :: TreeViewClass self => self\n -> (TreeIter -> TreePath -> IO ())\n -> IO (ConnectId self)\nonRowCollapsed = connect_BOXED_BOXED__NONE \"row_collapsed\"\n peek readNTP False\nafterRowCollapsed = connect_BOXED_BOXED__NONE \"row_collapsed\"\n peek readNTP True\n\n-- | Children of this node are made visible.\n--\nonRowExpanded, afterRowExpanded :: TreeViewClass self => self\n -> (TreeIter -> TreePath -> IO ())\n -> IO (ConnectId self)\nonRowExpanded = connect_BOXED_BOXED__NONE \"row_expanded\"\n peek readNTP False\nafterRowExpanded = connect_BOXED_BOXED__NONE \"row_expanded\"\n peek readNTP True\n\n-- | The user wants to search interactively.\n--\n-- * Connect to this signal if you want to provide you own search facility.\n-- Note that you must handle all keyboard input yourself.\n--\nonStartInteractiveSearch, afterStartInteractiveSearch :: \n TreeViewClass self => self -> IO () -> IO (ConnectId self)\n\n#if GTK_CHECK_VERSION(2,2,0)\n\nonStartInteractiveSearch self fun =\n connect_NONE__BOOL \"start_interactive_search\" False self (fun >> return True)\nafterStartInteractiveSearch self fun =\n connect_NONE__BOOL \"start_interactive_search\" True self (fun >> return True)\n\n#else\n\nonStartInteractiveSearch =\n connect_NONE__NONE \"start_interactive_search\" False\nafterStartInteractiveSearch = \n connect_NONE__NONE \"start_interactive_search\" True\n\n#endif\n\n-- | Determine if this row should be collapsed.\n--\n-- * If the application connects to this function and returns @False@,\n-- the specifc row will not be altered.\n--\nonTestCollapseRow, afterTestCollapseRow :: TreeViewClass self => self\n -> (TreeIter -> TreePath -> IO Bool)\n -> IO (ConnectId self)\nonTestCollapseRow = connect_BOXED_BOXED__BOOL \"test_collapse_row\"\n peek readNTP False\nafterTestCollapseRow = connect_BOXED_BOXED__BOOL \"test_collapse_row\"\n peek readNTP True\n\n-- | Determine if this row should be expanded.\n--\n-- * If the application connects to this function and returns @False@,\n-- the specifc row will not be altered.\n--\nonTestExpandRow, afterTestExpandRow :: TreeViewClass self => self\n -> (TreeIter -> TreePath -> IO Bool)\n -> IO (ConnectId self)\nonTestExpandRow = connect_BOXED_BOXED__BOOL \"test_expand_row\"\n peek readNTP False\nafterTestExpandRow = connect_BOXED_BOXED__BOOL \"test_expand_row\"\n peek readNTP True\n#endif\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"fc96a7a8819048f2407893f2965c1f6c9c02b633","subject":"Fix textView signals (rename `setScrollAdjustments` to `setTextViewScrollAdjustments`) and fix signal docs.","message":"Fix textView signals (rename `setScrollAdjustments` to `setTextViewScrollAdjustments`) and fix signal docs.\n","repos":"gtk2hs\/gtksourceview,gtk2hs\/gtksourceview","old_file":"gtk\/Graphics\/UI\/Gtk\/Multiline\/TextView.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Multiline\/TextView.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget TextView\n--\n-- Author : Axel Simon\n--\n-- Created: 23 February 2002\n--\n-- Copyright (C) 2002-2005 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- TODO\n--\n-- If PangoTabArray is bound: \n-- Fucntions: textViewSetTabs and textViewGetTabs\n-- Properties: textViewTabs\n--\n-- All on... and after... signales had incorrect names (underscore instead of hypens). Thus\n-- they could not have been used in applications and removing them can't break anything.\n-- Thus, I've removed them. Also, all key-binding singals are now removed as there is\n-- no way to add additional key bindings programatically in a type-safe way, let alone\n-- use these signals.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Widget that displays a 'TextBuffer'\n--\nmodule Graphics.UI.Gtk.Multiline.TextView (\n-- * Detail\n-- \n-- | You may wish to begin by reading the text widget conceptual overview\n-- which gives an overview of all the objects and data types related to the\n-- text widget and how they work together.\n--\n-- Throughout we distinguish between buffer coordinates which are pixels with\n-- the origin at the upper left corner of the first character on the first\n-- line. Window coordinates are relative to the top left pixel which is visible\n-- in the current 'TextView'. Coordinates from Events are in the latter\n-- relation. The conversion can be done with 'textViewWindowToBufferCoords'.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----TextView\n-- |\n-- |\n-- | 'GObject'\n-- | +----TextChildAnchor\n-- @\n\n-- * Types\n TextView,\n TextViewClass,\n TextChildAnchor,\n TextChildAnchorClass,\n castToTextView, gTypeTextView,\n toTextView,\n DeleteType(..),\n DirectionType(..),\n Justification(..),\n MovementStep(..),\n TextWindowType(..),\n WrapMode(..),\n\n-- * Constructors\n textViewNew,\n textViewNewWithBuffer,\n\n-- * Methods\n textViewSetBuffer,\n textViewGetBuffer,\n textViewScrollToMark,\n textViewScrollToIter,\n textViewScrollMarkOnscreen,\n textViewMoveMarkOnscreen,\n textViewPlaceCursorOnscreen,\n textViewGetLineAtY,\n textViewGetLineYrange,\n textViewGetIterAtLocation,\n textViewBufferToWindowCoords,\n textViewWindowToBufferCoords,\n textViewGetWindow,\n textViewGetWindowType,\n textViewSetBorderWindowSize,\n textViewGetBorderWindowSize,\n textViewForwardDisplayLine,\n textViewBackwardDisplayLine,\n textViewForwardDisplayLineEnd,\n textViewBackwardDisplayLineStart,\n textViewStartsDisplayLine,\n textViewMoveVisually,\n textViewAddChildAtAnchor,\n textChildAnchorNew,\n textChildAnchorGetWidgets,\n textChildAnchorGetDeleted,\n textViewAddChildInWindow,\n textViewMoveChild,\n textViewSetWrapMode,\n textViewGetWrapMode,\n textViewSetEditable,\n textViewGetEditable,\n textViewSetCursorVisible,\n textViewGetCursorVisible,\n textViewSetPixelsAboveLines,\n textViewGetPixelsAboveLines,\n textViewSetPixelsBelowLines,\n textViewGetPixelsBelowLines,\n textViewSetPixelsInsideWrap,\n textViewGetPixelsInsideWrap,\n textViewSetJustification,\n textViewGetJustification,\n textViewSetLeftMargin,\n textViewGetLeftMargin,\n textViewSetRightMargin,\n textViewGetRightMargin,\n textViewSetIndent,\n textViewGetIndent,\n textViewGetDefaultAttributes,\n textViewGetVisibleRect,\n textViewGetIterLocation,\n#if GTK_CHECK_VERSION(2,6,0)\n textViewGetIterAtPosition,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n textViewSetOverwrite,\n textViewGetOverwrite,\n textViewSetAcceptsTab,\n textViewGetAcceptsTab,\n#endif\n\n-- * Attributes\n textViewPixelsAboveLines,\n textViewPixelsBelowLines,\n textViewPixelsInsideWrap,\n textViewEditable,\n textViewImModule,\n textViewWrapMode,\n textViewJustification,\n textViewLeftMargin,\n textViewRightMargin,\n textViewIndent,\n textViewCursorVisible,\n textViewBuffer,\n#if GTK_CHECK_VERSION(2,4,0)\n textViewOverwrite,\n textViewAcceptsTab,\n#endif\n\n-- * Signals\n backspace,\n copyClipboard,\n cutClipboard,\n deleteFromCursor,\n insertAtCursor,\n moveCursor,\n moveViewport,\n moveFocus,\n pageHorizontally,\n pasteClipboard,\n populatePopup,\n selectAll,\n setAnchor,\n setTextViewScrollAdjustments,\n toggleCursorVisible,\n toggleOverwrite,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\nimport System.Glib.Properties (newAttrFromStringProperty)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Multiline.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n{#import Graphics.UI.Gtk.Multiline.TextTag#}\nimport Graphics.UI.Gtk.General.Enums\t(TextWindowType(..), DeleteType(..),\n\t\t\t\t\t DirectionType(..), Justification(..),\n\t\t\t\t\t MovementStep(..), WrapMode(..),\n ScrollStep (..))\nimport System.Glib.GList\t\t(fromGList)\nimport Graphics.UI.Gtk.General.Structs\t(Rectangle(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Creates a new 'TextView'. If you don't call 'textViewSetBuffer' before\n-- using the text view, an empty default buffer will be created for you. Get\n-- the buffer with 'textViewGetBuffer'. If you want to specify your own buffer,\n-- consider 'textViewNewWithBuffer'.\n--\ntextViewNew :: IO TextView\ntextViewNew =\n makeNewObject mkTextView $\n liftM (castPtr :: Ptr Widget -> Ptr TextView) $\n {# call unsafe text_view_new #}\n\n-- | Creates a new 'TextView' widget displaying the buffer @buffer@. One\n-- buffer can be shared among many widgets.\n--\ntextViewNewWithBuffer :: TextBufferClass buffer => buffer -> IO TextView\ntextViewNewWithBuffer buffer =\n makeNewObject mkTextView $\n liftM (castPtr :: Ptr Widget -> Ptr TextView) $\n {# call text_view_new_with_buffer #}\n (toTextBuffer buffer)\n\n--------------------\n-- Methods\n\n-- | Sets the given buffer as the buffer being displayed by the text view.\n--\ntextViewSetBuffer :: (TextViewClass self, TextBufferClass buffer) => self -> buffer -> IO ()\ntextViewSetBuffer self buffer =\n {# call text_view_set_buffer #}\n (toTextView self)\n (toTextBuffer buffer)\n\n-- | Returns the 'TextBuffer' being displayed by this text view.\n--\ntextViewGetBuffer :: TextViewClass self => self -> IO TextBuffer\ntextViewGetBuffer self =\n makeNewGObject mkTextBuffer $\n {# call unsafe text_view_get_buffer #}\n (toTextView self)\n\n-- | Scrolls the text view so that @mark@ is on the screen in the position\n-- indicated by @xalign@ and @yalign@. An alignment of 0.0 indicates left or\n-- top, 1.0 indicates right or bottom, 0.5 means center. If the alignment is\n-- @Nothing@, the text scrolls the minimal distance to get the mark onscreen,\n-- possibly not scrolling at all. The effective screen for purposes of this\n-- function is reduced by a margin of size @withinMargin@.\n--\ntextViewScrollToMark :: (TextViewClass self, TextMarkClass mark) => self\n -> mark -- ^ @mark@ - a 'TextMark'\n -> Double -- ^ @withinMargin@ - margin as a [0.0,0.5) fraction of screen size\n -- and imposes an extra margin at all four sides of the window\n -- within which @xalign@ and @yalign@ are evaluated.\n -> Maybe (Double, Double) -- ^ @Just (xalign, yalign)@ - horizontal and\n -- vertical alignment of mark within visible area (if @Nothing@,\n -- scroll just enough to get the mark onscreen)\n -> IO ()\ntextViewScrollToMark self mark withinMargin align =\n let (useAlign, xalign, yalign) = case align of\n Nothing -> (False, 0, 0)\n Just (xalign, yalign) -> (True, xalign, yalign)\n in\n {# call text_view_scroll_to_mark #}\n (toTextView self)\n (toTextMark mark)\n (realToFrac withinMargin)\n (fromBool useAlign)\n (realToFrac xalign)\n (realToFrac yalign)\n\n-- | Scrolls the text view so that @iter@ is on the screen in the position\n-- indicated by @xalign@ and @yalign@. An alignment of 0.0 indicates left or\n-- top, 1.0 indicates right or bottom, 0.5 means center. If the alignment is\n-- @Nothing@, the text scrolls the minimal distance to get the mark onscreen,\n-- possibly not scrolling at all. The effective screen for purposes of this\n-- function is reduced by a margin of size @withinMargin@.\n--\n-- * This function\n-- uses the currently-computed height of the lines in the text buffer. Note\n-- that line heights are computed in an idle handler; so this function may\n-- not\n-- have the desired effect if it's called before the height computations. To\n-- avoid oddness, consider using 'textViewScrollToMark' which saves a point\n-- to be scrolled to after line validation. This is particularly important\n-- if you add new text to the buffer and immediately ask the view to scroll\n-- to it (which it can't since it is not updated until the main loop runs).\n--\ntextViewScrollToIter :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> Double -- ^ @withinMargin@ - margin as a [0.0,0.5) fraction of screen\n -- size\n -> Maybe (Double, Double) -- ^ @Just (xalign, yalign)@ - horizontal and\n -- vertical alignment of mark within visible area (if @Nothing@,\n -- scroll just enough to get the iterator onscreen)\n -> IO Bool -- ^ returns @True@ if scrolling occurred\ntextViewScrollToIter self iter withinMargin align = \n let (useAlign, xalign, yalign) = case align of\n Nothing -> (False, 0, 0)\n Just (xalign, yalign) -> (True, xalign, yalign)\n in\n liftM toBool $\n {# call text_view_scroll_to_iter #}\n (toTextView self)\n iter\n (realToFrac withinMargin)\n (fromBool useAlign)\n (realToFrac xalign)\n (realToFrac yalign)\n\n-- | Scrolls the text view the minimum distance such that @mark@ is contained\n-- within the visible area of the widget.\n--\ntextViewScrollMarkOnscreen :: (TextViewClass self, TextMarkClass mark) => self\n -> mark -- ^ @mark@ - a mark in the buffer for the text view\n -> IO ()\ntextViewScrollMarkOnscreen self mark =\n {# call text_view_scroll_mark_onscreen #}\n (toTextView self)\n (toTextMark mark)\n\n-- | Moves a mark within the buffer so that it's located within the\n-- currently-visible text area.\n--\ntextViewMoveMarkOnscreen :: (TextViewClass self, TextMarkClass mark) => self\n -> mark -- ^ @mark@ - a 'TextMark'\n -> IO Bool -- ^ returns @True@ if the mark moved (wasn't already onscreen)\ntextViewMoveMarkOnscreen self mark =\n liftM toBool $\n {# call text_view_move_mark_onscreen #}\n (toTextView self)\n (toTextMark mark)\n\n-- | Moves the cursor to the currently visible region of the buffer, it it\n-- isn't there already.\n--\ntextViewPlaceCursorOnscreen :: TextViewClass self => self\n -> IO Bool -- ^ returns @True@ if the cursor had to be moved.\ntextViewPlaceCursorOnscreen self =\n liftM toBool $\n {# call text_view_place_cursor_onscreen #}\n (toTextView self)\n\n-- | Returns the currently-visible region of the buffer, in\n-- buffer coordinates. Convert to window coordinates with\n-- 'textViewBufferToWindowCoords'.\n--\ntextViewGetVisibleRect :: TextViewClass self => self -> IO Rectangle\ntextViewGetVisibleRect self =\n alloca $ \\rectPtr -> do\n {# call unsafe text_view_get_visible_rect #}\n (toTextView self)\n (castPtr rectPtr)\n peek rectPtr\n\n-- | Gets a rectangle which roughly contains the character at @iter@. The\n-- rectangle position is in buffer coordinates; use\n-- 'textViewBufferToWindowCoords' to convert these coordinates to coordinates\n-- for one of the windows in the text view.\n--\ntextViewGetIterLocation :: TextViewClass self => self -> TextIter -> IO Rectangle\ntextViewGetIterLocation self iter =\n alloca $ \\rectPtr -> do\n {# call unsafe text_view_get_iter_location #}\n (toTextView self)\n iter\n (castPtr rectPtr)\n peek rectPtr\n\n-- | Gets the 'TextIter' at the start of the line containing the coordinate\n-- @y@. @y@ is in buffer coordinates, convert from window coordinates with\n-- 'textViewWindowToBufferCoords'. Also returns @lineTop@ the\n-- coordinate of the top edge of the line.\n--\ntextViewGetLineAtY :: TextViewClass self => self\n -> Int -- ^ @y@ - a y coordinate\n -> IO (TextIter, Int) -- ^ @(targetIter, lineTop)@ - returns the iter and the\n -- top coordinate of the line\ntextViewGetLineAtY self y =\n makeEmptyTextIter >>= \\targetIter ->\n alloca $ \\lineTopPtr -> do\n {# call unsafe text_view_get_line_at_y #}\n (toTextView self)\n targetIter\n (fromIntegral y)\n lineTopPtr\n lineTop <- peek lineTopPtr\n return (targetIter, fromIntegral lineTop)\n\n-- | Gets the y coordinate of the top of the line containing @iter@, and the\n-- height of the line. The coordinate is a buffer coordinate; convert to window\n-- coordinates with 'textViewBufferToWindowCoords'.\n--\ntextViewGetLineYrange :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO (Int, Int) -- ^ @(y, height)@ - y coordinate and height of the line\ntextViewGetLineYrange self iter =\n alloca $ \\yPtr ->\n alloca $ \\heightPtr -> do\n {# call unsafe text_view_get_line_yrange #}\n (toTextView self)\n iter\n yPtr\n heightPtr\n y <- peek yPtr\n height <- peek heightPtr\n return (fromIntegral y, fromIntegral height)\n\n-- | Retrieves the iterator at buffer coordinates @x@ and @y@. Buffer\n-- coordinates are coordinates for the entire buffer, not just the\n-- currently-displayed portion. If you have coordinates from an event, you have\n-- to convert those to buffer coordinates with 'textViewWindowToBufferCoords'.\n--\ntextViewGetIterAtLocation :: TextViewClass self => self\n -> Int -- ^ @x@ - x position, in buffer coordinates\n -> Int -- ^ @y@ - y position, in buffer coordinates\n -> IO TextIter\ntextViewGetIterAtLocation self x y = do\n iter <- makeEmptyTextIter\n {# call unsafe text_view_get_iter_at_location #}\n (toTextView self)\n iter\n (fromIntegral x)\n (fromIntegral y)\n return iter\n\n-- | Converts coordinate @(bufferX, bufferY)@ to coordinates for the window\n-- @win@\n--\n-- Note that you can't convert coordinates for a nonexisting window (see\n-- 'textViewSetBorderWindowSize').\n--\ntextViewBufferToWindowCoords :: TextViewClass self => self\n -> TextWindowType -- ^ @win@ - a 'TextWindowType' except 'TextWindowPrivate'\n -> (Int, Int) -- ^ @(bufferX, bufferY)@ - buffer x and y coordinates\n -> IO (Int, Int) -- ^ returns window x and y coordinates\ntextViewBufferToWindowCoords self win (bufferX, bufferY) =\n alloca $ \\windowXPtr ->\n alloca $ \\windowYPtr -> do\n {# call unsafe text_view_buffer_to_window_coords #}\n (toTextView self)\n ((fromIntegral . fromEnum) win)\n (fromIntegral bufferX)\n (fromIntegral bufferY)\n windowXPtr\n windowYPtr\n windowX <- peek windowXPtr\n windowY <- peek windowYPtr\n return (fromIntegral windowX, fromIntegral windowY)\n\n-- | Converts coordinates on the window identified by @win@ to buffer\n-- coordinates.\n--\n-- Note that you can't convert coordinates for a nonexisting window (see\n-- 'textViewSetBorderWindowSize').\n--\ntextViewWindowToBufferCoords :: TextViewClass self => self\n -> TextWindowType -- ^ @win@ - a 'TextWindowType' except 'TextWindowPrivate'\n -> (Int, Int) -- ^ @(windowX, windowY)@ - window x and y coordinates\n -> IO (Int, Int) -- ^ returns buffer x and y coordinates\ntextViewWindowToBufferCoords self win (windowX, windowY) =\n alloca $ \\bufferXPtr ->\n alloca $ \\bufferYPtr -> do\n {# call unsafe text_view_window_to_buffer_coords #}\n (toTextView self)\n ((fromIntegral . fromEnum) win)\n (fromIntegral windowX)\n (fromIntegral windowY)\n bufferXPtr\n bufferYPtr\n bufferX <- peek bufferXPtr\n bufferY <- peek bufferYPtr\n return (fromIntegral bufferX, fromIntegral bufferY)\n\n-- | Retrieves the 'DrawWindow' corresponding to an area of the text view;\n-- possible windows include the overall widget window, child windows on the\n-- left, right, top, bottom, and the window that displays the text buffer.\n-- Windows are @Nothing@ and nonexistent if their width or height is 0, and are\n-- nonexistent before the widget has been realized.\n--\ntextViewGetWindow :: TextViewClass self => self\n -> TextWindowType -- ^ @win@ - window to get\n -> IO (Maybe DrawWindow) -- ^ returns a 'DrawWindow', or @Nothing@\ntextViewGetWindow self win =\n maybeNull (makeNewGObject mkDrawWindow) $\n {# call unsafe text_view_get_window #}\n (toTextView self)\n ((fromIntegral . fromEnum) win)\n\n-- | Retrieve the type of window the 'TextView' widget contains.\n--\n-- Usually used to find out which window an event corresponds to. An emission\n-- of an event signal of 'TextView' yields a 'DrawWindow'. This function can be\n-- used to see if the event actually belongs to the main text window.\n--\ntextViewGetWindowType :: TextViewClass self => self\n -> DrawWindow\n -> IO TextWindowType\ntextViewGetWindowType self window =\n liftM (toEnum . fromIntegral) $\n {# call unsafe text_view_get_window_type #}\n (toTextView self)\n window\n\n-- | Sets the width of 'TextWindowLeft' or 'TextWindowRight', or the height of\n-- 'TextWindowTop' or 'TextWindowBottom'. Automatically destroys the\n-- corresponding window if the size is set to 0, and creates the window if the\n-- size is set to non-zero. This function can only be used for the \\\"border\n-- windows\\\", it doesn't work with 'TextWindowWidget', 'TextWindowText', or\n-- 'TextWindowPrivate'.\n--\ntextViewSetBorderWindowSize :: TextViewClass self => self\n -> TextWindowType -- ^ @type@ - window to affect\n -> Int -- ^ @size@ - width or height of the window\n -> IO ()\ntextViewSetBorderWindowSize self type_ size =\n {# call text_view_set_border_window_size #}\n (toTextView self)\n ((fromIntegral . fromEnum) type_)\n (fromIntegral size)\n\n-- | Gets the width of the specified border window. See\n-- 'textViewSetBorderWindowSize'.\n--\ntextViewGetBorderWindowSize :: TextViewClass self => self\n -> TextWindowType -- ^ @type@ - window to return size from\n -> IO Int -- ^ returns width of window\ntextViewGetBorderWindowSize self type_ =\n liftM fromIntegral $\n {# call unsafe text_view_get_border_window_size #}\n (toTextView self)\n ((fromIntegral . fromEnum) type_)\n\n-- | Moves the given @iter@ forward by one display (wrapped) line. A display\n-- line is different from a paragraph. Paragraphs are separated by newlines or\n-- other paragraph separator characters. Display lines are created by\n-- line-wrapping a paragraph. If wrapping is turned off, display lines and\n-- paragraphs will be the same. Display lines are divided differently for each\n-- view, since they depend on the view's width; paragraphs are the same in all\n-- views, since they depend on the contents of the 'TextBuffer'.\n--\ntextViewForwardDisplayLine :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ was moved and is not on the end\n -- iterator\ntextViewForwardDisplayLine self iter =\n liftM toBool $\n {# call unsafe text_view_forward_display_line #}\n (toTextView self)\n iter\n\n-- | Moves the given @iter@ backward by one display (wrapped) line. A display\n-- line is different from a paragraph. Paragraphs are separated by newlines or\n-- other paragraph separator characters. Display lines are created by\n-- line-wrapping a paragraph. If wrapping is turned off, display lines and\n-- paragraphs will be the same. Display lines are divided differently for each\n-- view, since they depend on the view's width; paragraphs are the same in all\n-- views, since they depend on the contents of the 'TextBuffer'.\n--\ntextViewBackwardDisplayLine :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ was moved and is not on the end\n -- iterator\ntextViewBackwardDisplayLine self iter =\n liftM toBool $\n {# call unsafe text_view_backward_display_line #}\n (toTextView self)\n iter\n\n-- | Moves the given @iter@ forward to the next display line end. A display\n-- line is different from a paragraph. Paragraphs are separated by newlines or\n-- other paragraph separator characters. Display lines are created by\n-- line-wrapping a paragraph. If wrapping is turned off, display lines and\n-- paragraphs will be the same. Display lines are divided differently for each\n-- view, since they depend on the view's width; paragraphs are the same in all\n-- views, since they depend on the contents of the 'TextBuffer'.\n--\ntextViewForwardDisplayLineEnd :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ was moved and is not on the end\n -- iterator\ntextViewForwardDisplayLineEnd self iter =\n liftM toBool $\n {# call unsafe text_view_forward_display_line_end #}\n (toTextView self)\n iter\n\n-- | Moves the given @iter@ backward to the next display line start. A display\n-- line is different from a paragraph. Paragraphs are separated by newlines or\n-- other paragraph separator characters. Display lines are created by\n-- line-wrapping a paragraph. If wrapping is turned off, display lines and\n-- paragraphs will be the same. Display lines are divided differently for each\n-- view, since they depend on the view's width; paragraphs are the same in all\n-- views, since they depend on the contents of the 'TextBuffer'.\n--\ntextViewBackwardDisplayLineStart :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ was moved and is not on the end\n -- iterator\ntextViewBackwardDisplayLineStart self iter =\n liftM toBool $\n {# call unsafe text_view_backward_display_line_start #}\n (toTextView self)\n iter\n\n-- | Determines whether @iter@ is at the start of a display line. See\n-- 'textViewForwardDisplayLine' for an explanation of display lines vs.\n-- paragraphs.\n--\ntextViewStartsDisplayLine :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ begins a wrapped line\ntextViewStartsDisplayLine self iter =\n liftM toBool $\n {# call unsafe text_view_starts_display_line #}\n (toTextView self)\n iter\n\n-- | Move the iterator a given number of characters visually, treating it as\n-- the strong cursor position. If @count@ is positive, then the new strong\n-- cursor position will be @count@ positions to the right of the old cursor\n-- position. If @count@ is negative then the new strong cursor position will be\n-- @count@ positions to the left of the old cursor position.\n--\n-- In the presence of bidirection text, the correspondence between logical\n-- and visual order will depend on the direction of the current run, and there\n-- may be jumps when the cursor is moved off of the end of a run.\n--\ntextViewMoveVisually :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> Int -- ^ @count@ - number of characters to move (negative moves left,\n -- positive moves right)\n -> IO Bool -- ^ returns @True@ if @iter@ moved and is not on the end\n -- iterator\ntextViewMoveVisually self iter count =\n liftM toBool $\n {# call unsafe text_view_move_visually #}\n (toTextView self)\n iter\n (fromIntegral count)\n\n-- | Adds a child widget in the text buffer, at the given @anchor@.\n--\ntextViewAddChildAtAnchor :: (TextViewClass self, WidgetClass child) => self\n -> child -- ^ @child@ - a 'Widget'\n -> TextChildAnchor -- ^ @anchor@ - a 'TextChildAnchor' in the 'TextBuffer'\n -- for the text view\n -> IO ()\ntextViewAddChildAtAnchor self child anchor =\n {# call text_view_add_child_at_anchor #}\n (toTextView self)\n (toWidget child)\n anchor\n\n-- | Create a new 'TextChildAnchor'.\n--\n-- * Using 'textBufferCreateChildAnchor' is usually simpler then\n-- executing this function and 'textBufferInsertChildAnchor'.\n--\ntextChildAnchorNew :: IO TextChildAnchor\ntextChildAnchorNew =\n constructNewGObject mkTextChildAnchor\n {# call unsafe text_child_anchor_new #}\n\n-- | Retrieve all 'Widget's at this\n-- 'TextChildAnchor'.\n--\n-- * The widgets in the returned list need to be upcasted to what they were.\n--\ntextChildAnchorGetWidgets :: TextChildAnchor -> IO [Widget]\ntextChildAnchorGetWidgets tca = do\n gList <- {# call text_child_anchor_get_widgets #} tca\n wList <- fromGList gList\n mapM (makeNewObject mkWidget) (map return wList)\n\n-- | Query if an anchor was deleted.\n--\ntextChildAnchorGetDeleted :: TextChildAnchor -> IO Bool\ntextChildAnchorGetDeleted tca =\n liftM toBool $\n {# call unsafe text_child_anchor_get_deleted #} tca\n\n-- | Adds a child at fixed coordinates in one of the text widget's windows.\n-- The window must have nonzero size (see 'textViewSetBorderWindowSize'). Note\n-- that the child coordinates are given relative to the 'DrawWindow' in\n-- question, and that these coordinates have no sane relationship to scrolling.\n-- When placing a child in 'TextWindowWidget', scrolling is irrelevant, the\n-- child floats above all scrollable areas. If you want the widget to move when\n-- the text view scrolls, use 'textViewAddChildAtAnchor' instead.\n--\ntextViewAddChildInWindow :: (TextViewClass self, WidgetClass child) => self\n -> child -- ^ @child@ - a 'Widget'\n -> TextWindowType -- ^ @whichWindow@ - which window the child should appear\n -- in\n -> Int -- ^ @xpos@ - X position of child in window coordinates\n -> Int -- ^ @ypos@ - Y position of child in window coordinates\n -> IO ()\ntextViewAddChildInWindow self child whichWindow xpos ypos =\n {# call text_view_add_child_in_window #}\n (toTextView self)\n (toWidget child)\n ((fromIntegral . fromEnum) whichWindow)\n (fromIntegral xpos)\n (fromIntegral ypos)\n\n-- | Move a child widget within the 'TextView'. This is really only apprpriate\n-- for \\\"floating\\\" child widgets added using 'textViewAddChildInWindow'.\n--\ntextViewMoveChild :: (TextViewClass self, WidgetClass child) => self\n -> child -- ^ @child@ - child widget already added to the text view\n -> Int -- ^ @xpos@ - new X position in window coordinates\n -> Int -- ^ @ypos@ - new Y position in window coordinates\n -> IO ()\ntextViewMoveChild self child xpos ypos =\n {# call text_view_move_child #}\n (toTextView self)\n (toWidget child)\n (fromIntegral xpos)\n (fromIntegral ypos)\n\n-- | Sets the line wrapping for the view.\n--\ntextViewSetWrapMode :: TextViewClass self => self -> WrapMode -> IO ()\ntextViewSetWrapMode self wrapMode =\n {# call text_view_set_wrap_mode #}\n (toTextView self)\n ((fromIntegral . fromEnum) wrapMode)\n\n-- | Gets the line wrapping for the view.\n--\ntextViewGetWrapMode :: TextViewClass self => self -> IO WrapMode\ntextViewGetWrapMode self =\n liftM (toEnum . fromIntegral) $\n {# call unsafe text_view_get_wrap_mode #}\n (toTextView self)\n\n-- | Sets the default editability of the 'TextView'. You can override this\n-- default setting with tags in the buffer, using the \\\"editable\\\" attribute of\n-- tags.\n--\ntextViewSetEditable :: TextViewClass self => self -> Bool -> IO ()\ntextViewSetEditable self setting =\n {# call text_view_set_editable #}\n (toTextView self)\n (fromBool setting)\n\n-- | Returns the default editability of the 'TextView'. Tags in the buffer may\n-- override this setting for some ranges of text.\n--\ntextViewGetEditable :: TextViewClass self => self -> IO Bool\ntextViewGetEditable self =\n liftM toBool $\n {# call unsafe text_view_get_editable #}\n (toTextView self)\n\n-- | Toggles whether the insertion point is displayed. A buffer with no\n-- editable text probably shouldn't have a visible cursor, so you may want to\n-- turn the cursor off.\n--\ntextViewSetCursorVisible :: TextViewClass self => self -> Bool -> IO ()\ntextViewSetCursorVisible self setting =\n {# call text_view_set_cursor_visible #}\n (toTextView self)\n (fromBool setting)\n\n-- | Find out whether the cursor is being displayed.\n--\ntextViewGetCursorVisible :: TextViewClass self => self -> IO Bool\ntextViewGetCursorVisible self =\n liftM toBool $\n {# call unsafe text_view_get_cursor_visible #}\n (toTextView self)\n\n-- | Sets the default number of blank pixels above paragraphs in the text view.\n-- Tags in the buffer for the text view may override the defaults.\n--\n-- * Tags in the buffer may override this default.\n--\ntextViewSetPixelsAboveLines :: TextViewClass self => self -> Int -> IO ()\ntextViewSetPixelsAboveLines self pixelsAboveLines =\n {# call text_view_set_pixels_above_lines #}\n (toTextView self)\n (fromIntegral pixelsAboveLines)\n\n-- | Gets the default number of pixels to put above paragraphs.\n--\ntextViewGetPixelsAboveLines :: TextViewClass self => self -> IO Int\ntextViewGetPixelsAboveLines self =\n liftM fromIntegral $\n {# call unsafe text_view_get_pixels_above_lines #}\n (toTextView self)\n\n-- | Sets the default number of pixels of blank space to put below paragraphs\n-- in the text view. May be overridden by tags applied to the text view's\n-- buffer.\n--\ntextViewSetPixelsBelowLines :: TextViewClass self => self -> Int -> IO ()\ntextViewSetPixelsBelowLines self pixelsBelowLines =\n {# call text_view_set_pixels_below_lines #}\n (toTextView self)\n (fromIntegral pixelsBelowLines)\n\n-- | Gets the default number of blank pixels below each paragraph.\n--\ntextViewGetPixelsBelowLines :: TextViewClass self => self -> IO Int\ntextViewGetPixelsBelowLines self =\n liftM fromIntegral $\n {# call unsafe text_view_get_pixels_below_lines #}\n (toTextView self)\n\n-- | Sets the default number of pixels of blank space to leave between\n-- display\\\/wrapped lines within a paragraph. May be overridden by tags in\n-- the text view's buffer.\n--\ntextViewSetPixelsInsideWrap :: TextViewClass self => self -> Int -> IO ()\ntextViewSetPixelsInsideWrap self pixelsInsideWrap =\n {# call text_view_set_pixels_inside_wrap #}\n (toTextView self)\n (fromIntegral pixelsInsideWrap)\n\n-- | Gets the default number of pixels of blank space between lines in a\n-- wrapped paragraph.\n--\ntextViewGetPixelsInsideWrap :: TextViewClass self => self -> IO Int\ntextViewGetPixelsInsideWrap self =\n liftM fromIntegral $\n {# call unsafe text_view_get_pixels_inside_wrap #}\n (toTextView self)\n\n-- | Sets the default justification of text in the text view. Tags in the\n-- view's buffer may override the default.\n--\ntextViewSetJustification :: TextViewClass self => self -> Justification -> IO ()\ntextViewSetJustification self justification =\n {# call text_view_set_justification #}\n (toTextView self)\n ((fromIntegral . fromEnum) justification)\n\n-- | Gets the default justification of paragraphs in the text view. Tags in the\n-- buffer may override the default.\n--\ntextViewGetJustification :: TextViewClass self => self -> IO Justification\ntextViewGetJustification self =\n liftM (toEnum . fromIntegral) $\n {# call unsafe text_view_get_justification #}\n (toTextView self)\n\n-- | Sets the default left margin for text in the text view. Tags in the buffer\n-- may override the default.\n--\ntextViewSetLeftMargin :: TextViewClass self => self\n -> Int -- ^ @leftMargin@ - left margin in pixels\n -> IO ()\ntextViewSetLeftMargin self leftMargin =\n {# call text_view_set_left_margin #}\n (toTextView self)\n (fromIntegral leftMargin)\n\n-- | Gets the default left margin size of paragraphs in the text view. Tags\n-- in the buffer may override the default.\n--\ntextViewGetLeftMargin :: TextViewClass self => self\n -> IO Int -- ^ returns left margin in pixels\ntextViewGetLeftMargin self =\n liftM fromIntegral $\n {# call unsafe text_view_get_left_margin #}\n (toTextView self)\n\n-- | Sets the default right margin for text in the text view. Tags in the\n-- buffer may override the default.\n--\ntextViewSetRightMargin :: TextViewClass self => self\n -> Int -- ^ @rightMargin@ - right margin in pixels\n -> IO ()\ntextViewSetRightMargin self rightMargin =\n {# call text_view_set_right_margin #}\n (toTextView self)\n (fromIntegral rightMargin)\n\n-- | Gets the default right margin for text in the text view. Tags in the\n-- buffer may override the default.\n--\ntextViewGetRightMargin :: TextViewClass self => self\n -> IO Int -- ^ returns right margin in pixels\ntextViewGetRightMargin self =\n liftM fromIntegral $\n {# call unsafe text_view_get_right_margin #}\n (toTextView self)\n\n-- | Sets the default indentation for paragraphs in the text view. Tags in the\n-- buffer may override the default.\n--\ntextViewSetIndent :: TextViewClass self => self\n -> Int -- ^ @indent@ - indentation in pixels (may be negative)\n -> IO ()\ntextViewSetIndent self indent =\n {# call text_view_set_indent #}\n (toTextView self)\n (fromIntegral indent)\n\n-- | Gets the default indentation of paragraphs in the text view. Tags in the\n-- view's buffer may override the default. The indentation may be negative.\n--\ntextViewGetIndent :: TextViewClass self => self\n -> IO Int -- ^ returns number of pixels of indentation\ntextViewGetIndent self =\n liftM fromIntegral $\n {# call unsafe text_view_get_indent #}\n (toTextView self)\n\n-- | Obtains a copy of the default text attributes. These are the attributes\n-- used for text unless a tag overrides them. You'd typically pass the default\n-- attributes in to 'textIterGetAttributes' in order to get the attributes in\n-- effect at a given text position.\n--\ntextViewGetDefaultAttributes :: TextViewClass self => self -> IO TextAttributes\ntextViewGetDefaultAttributes self =\n {# call gtk_text_view_get_default_attributes #}\n (toTextView self)\n >>= makeNewTextAttributes\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Retrieves the iterator pointing to the character at buffer coordinates\n-- @x@ and @y@. Buffer coordinates are coordinates for the entire buffer, not\n-- just the currently-displayed portion. If you have coordinates from an event,\n-- you have to convert those to buffer coordinates with\n-- 'textViewWindowToBufferCoords'.\n--\n-- Note that this is different from 'textViewGetIterAtLocation', which\n-- returns cursor locations, i.e. positions \/between\/ characters.\n--\n-- * Available since Gtk+ version 2.6\n--\ntextViewGetIterAtPosition :: TextViewClass self => self\n -> Int -- ^ @x@ - x position, in buffer coordinates\n -> Int -- ^ @y@ - y position, in buffer coordinates\n -> IO (TextIter, Int) -- ^ @(iter, trailing)@ - returns the iterator and\n -- an integer indicating where in the grapheme the\n -- user clicked. It will either be zero, or the\n -- number of characters in the grapheme. 0 represents\n -- the trailing edge of the grapheme.\ntextViewGetIterAtPosition self x y =\n alloca $ \\trailingPtr -> do\n iter <- makeEmptyTextIter\n {# call gtk_text_view_get_iter_at_position #}\n (toTextView self)\n iter\n trailingPtr\n (fromIntegral x)\n (fromIntegral y)\n trailing <- peek trailingPtr\n return (iter, fromIntegral trailing)\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Changes the 'TextView' overwrite mode.\n--\n-- * Available since Gtk+ version 2.4\n--\ntextViewSetOverwrite :: TextViewClass self => self\n -> Bool -- ^ @overwrite@ - @True@ to turn on overwrite mode, @False@ to turn\n -- it off\n -> IO ()\ntextViewSetOverwrite self overwrite =\n {# call gtk_text_view_set_overwrite #}\n (toTextView self)\n (fromBool overwrite)\n\n-- | Returns whether the 'TextView' is in overwrite mode or not.\n--\n-- * Available since Gtk+ version 2.4\n--\ntextViewGetOverwrite :: TextViewClass self => self -> IO Bool\ntextViewGetOverwrite self =\n liftM toBool $\n {# call gtk_text_view_get_overwrite #}\n (toTextView self)\n\n-- | Sets the behavior of the text widget when the Tab key is pressed. If\n-- @acceptsTab@ is @True@ a tab character is inserted. If @acceptsTab@ is\n-- @False@ the keyboard focus is moved to the next widget in the focus chain.\n--\n-- * Available since Gtk+ version 2.4\n--\ntextViewSetAcceptsTab :: TextViewClass self => self\n -> Bool -- ^ @acceptsTab@ - @True@ if pressing the Tab key should insert a\n -- tab character, @False@, if pressing the Tab key should move the\n -- keyboard focus.\n -> IO ()\ntextViewSetAcceptsTab self acceptsTab =\n {# call gtk_text_view_set_accepts_tab #}\n (toTextView self)\n (fromBool acceptsTab)\n\n-- | Returns whether pressing the Tab key inserts a tab characters.\n-- 'textViewSetAcceptsTab'.\n--\n-- * Available since Gtk+ version 2.4\n--\ntextViewGetAcceptsTab :: TextViewClass self => self\n -> IO Bool -- ^ returns @True@ if pressing the Tab key inserts a tab\n -- character, @False@ if pressing the Tab key moves the keyboard\n -- focus.\ntextViewGetAcceptsTab self =\n liftM toBool $\n {# call gtk_text_view_get_accepts_tab #}\n (toTextView self)\n#endif\n\n--------------------\n-- Attributes\n\n-- | Pixels of blank space above paragraphs.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewPixelsAboveLines :: TextViewClass self => Attr self Int\ntextViewPixelsAboveLines = newAttr\n textViewGetPixelsAboveLines\n textViewSetPixelsAboveLines\n\n-- | Pixels of blank space below paragraphs.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewPixelsBelowLines :: TextViewClass self => Attr self Int\ntextViewPixelsBelowLines = newAttr\n textViewGetPixelsBelowLines\n textViewSetPixelsBelowLines\n\n-- | Pixels of blank space between wrapped lines in a paragraph.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewPixelsInsideWrap :: TextViewClass self => Attr self Int\ntextViewPixelsInsideWrap = newAttr\n textViewGetPixelsInsideWrap\n textViewSetPixelsInsideWrap\n\n-- | Whether the text can be modified by the user.\n--\n-- Default value: @True@\n--\ntextViewEditable :: TextViewClass self => Attr self Bool\ntextViewEditable = newAttr\n textViewGetEditable\n textViewSetEditable\n\n-- | Which IM (input method) module should be used for this entry. See GtkIMContext.\n-- Setting this to a non-empty value overrides the system-wide IM module setting. \n-- See the GtkSettings \"gtk-im-module\" property.\n--\n-- Default value: \\\"\\\"\n--\ntextViewImModule :: TextViewClass self => Attr self String\ntextViewImModule = \n newAttrFromStringProperty \"im-module\"\n\n-- | Whether to wrap lines never, at word boundaries, or at character\n-- boundaries.\n--\n-- Default value: 'WrapNone'\n--\ntextViewWrapMode :: TextViewClass self => Attr self WrapMode\ntextViewWrapMode = newAttr\n textViewGetWrapMode\n textViewSetWrapMode\n\n-- | Left, right, or center justification.\n--\n-- Default value: 'JustifyLeft'\n--\ntextViewJustification :: TextViewClass self => Attr self Justification\ntextViewJustification = newAttr\n textViewGetJustification\n textViewSetJustification\n\n-- | Width of the left margin in pixels.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewLeftMargin :: TextViewClass self => Attr self Int\ntextViewLeftMargin = newAttr\n textViewGetLeftMargin\n textViewSetLeftMargin\n\n-- | Width of the right margin in pixels.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewRightMargin :: TextViewClass self => Attr self Int\ntextViewRightMargin = newAttr\n textViewGetRightMargin\n textViewSetRightMargin\n\n-- | Amount to indent the paragraph, in pixels.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewIndent :: TextViewClass self => Attr self Int\ntextViewIndent = newAttr\n textViewGetIndent\n textViewSetIndent\n\n-- | If the insertion cursor is shown.\n--\n-- Default value: @True@\n--\ntextViewCursorVisible :: TextViewClass self => Attr self Bool\ntextViewCursorVisible = newAttr\n textViewGetCursorVisible\n textViewSetCursorVisible\n\n-- | The buffer which is displayed.\n--\ntextViewBuffer :: TextViewClass self => Attr self TextBuffer\ntextViewBuffer = newAttr\n textViewGetBuffer\n textViewSetBuffer\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Whether entered text overwrites existing contents.\n--\n-- Default value: @False@\n--\ntextViewOverwrite :: TextViewClass self => Attr self Bool\ntextViewOverwrite = newAttr\n textViewGetOverwrite\n textViewSetOverwrite\n\n-- | Whether Tab will result in a tab character being entered.\n--\n-- Default value: @True@\n--\ntextViewAcceptsTab :: TextViewClass self => Attr self Bool\ntextViewAcceptsTab = newAttr\n textViewGetAcceptsTab\n textViewSetAcceptsTab\n#endif\n\n--------------------\n-- Signals\n-- | The 'backspace' signal is a keybinding signal which gets emitted when the user asks for it.\n--\n-- The default bindings for this signal are Backspace and Shift-Backspace.\n--\nbackspace :: TextViewClass self => Signal self (IO ())\nbackspace = Signal (connect_NONE__NONE \"on-backspace\")\n\n-- | Copying to the clipboard.\n--\n-- * This signal is emitted when a selection is copied to the clipboard. \n--\n-- * The action itself happens when the 'TextView' processes this\n-- signal.\n--\ncopyClipboard :: TextViewClass self => Signal self (IO ())\ncopyClipboard = Signal (connect_NONE__NONE \"copy-clipboard\")\n\n-- | Cutting to the clipboard.\n--\n-- * This signal is emitted when a selection is cut out and copied to the\n-- clipboard. The action itself happens when the textview processed this\n-- request.\n--\ncutClipboard :: TextViewClass self => Signal self (IO ())\ncutClipboard = Signal (connect_NONE__NONE \"cut-clipboard\")\n\n-- | Deleting text.\n--\n-- * The widget will remove the specified number of units in the text where\n-- the meaning of units depends on the kind of deletion.\n--\n-- * The action itself happens when the 'TextView' processes this\n-- signal.\n--\ndeleteFromCursor :: TextViewClass self => Signal self (DeleteType -> Int -> IO ())\ndeleteFromCursor = Signal (connect_ENUM_INT__NONE \"delete-from-cursor\")\n\n-- | Inserting text.\n--\n-- * The widget will insert the string into the text where the meaning\n-- of units depends on the kind of deletion.\n--\n-- * The action itself happens when the 'TextView' processes this\n-- signal.\n--\ninsertAtCursor :: TextViewClass self => Signal self (String -> IO ())\ninsertAtCursor = Signal (connect_STRING__NONE \"insert-at-cursor\")\n\n-- | Moving the cursor.\n--\n-- * The signal specifies what kind and how many steps the cursor will do.\n-- The flag is set to @True@ if this movement extends a selection.\n--\n-- * The action itself happens when the 'TextView' processes this\n-- signal.\n--\nmoveCursor :: TextViewClass self => Signal self (MovementStep -> Int -> Bool -> IO ())\nmoveCursor = Signal (connect_ENUM_INT_BOOL__NONE \"move-cursor\")\n\n-- | The 'moveViewport' signal is a keybinding signal which can be bound to key combinations \n-- to allow the user to move the viewport, i.e. \n-- change what part of the text view is visible in a containing scrolled window.\n-- There are no default bindings for this signal.\n-- \nmoveViewport :: TextViewClass self => Signal self (ScrollStep -> Int -> IO ())\nmoveViewport = Signal (connect_ENUM_INT__NONE \"move-viewport\")\n\n-- | Moving the focus.\n--\n-- * The action itself happens when the 'TextView' processes this\n-- signal.\n--\nmoveFocus :: TextViewClass self => Signal self (DirectionType -> IO ())\nmoveFocus = Signal (connect_ENUM__NONE \"move-focus\")\n\n-- | Page change signals.\n--\n-- * The signal specifies how many pages the view should move up or down.\n-- The flag is set to @True@ if this movement extends a selection.\n--\n-- * The action itself happens when the 'TextView' processes this\n-- signal.\n--\n-- * Figure out why this signal is called horizontally, not vertically.\n--\npageHorizontally :: TextViewClass self => Signal self (Int -> Bool -> IO ())\npageHorizontally = Signal (connect_INT_BOOL__NONE \"page-horizontally\")\n\n-- | Pasting from the clipboard.\n--\n-- * This signal is emitted when something is pasted from the clipboard. \n--\n-- * The action itself happens when the 'TextView' processes this\n-- signal.\n--\npasteClipboard :: TextViewClass self => Signal self (IO ())\npasteClipboard = Signal (connect_NONE__NONE \"paste-clipboard\")\n\n-- | Add menu entries to context menus.\n--\n-- * This signal is emitted if a context menu within the 'TextView'\n-- is opened. This signal can be used to add application specific menu\n-- items to this popup.\n--\npopulatePopup :: TextViewClass self => Signal self (Menu -> IO ())\npopulatePopup = Signal (connect_OBJECT__NONE \"populate-popup\")\n\n-- | Inserting an anchor.\n--\n-- * This signal is emitted when anchor is inserted into the text. \n--\n-- * The action itself happens when the 'TextView' processes this\n-- signal.\n--\nselectAll :: TextViewClass self => Signal self (Bool -> IO ())\nselectAll = Signal (connect_BOOL__NONE \"select-all\")\n\n-- | The scroll-bars changed.\n--\nsetAnchor :: TextViewClass self => Signal self (IO ())\nsetAnchor = Signal (connect_NONE__NONE \"set-anchor\")\n\n-- | The 'setTextViewScrollAdjustments' signal is a keybinding signal which \n-- gets emitted to toggle the visibility of the cursor.\n-- The default binding for this signal is F7.\n--\nsetTextViewScrollAdjustments :: TextViewClass self => Signal self (Adjustment -> Adjustment -> IO ())\nsetTextViewScrollAdjustments = Signal (connect_OBJECT_OBJECT__NONE \"set-scroll-adjustments\")\n\n-- | The 'toggleCursorVisible' signal is a keybinding signal \n-- which gets emitted to toggle the visibility of the cursor.\n-- The default binding for this signal is F7.\n--\ntoggleCursorVisible :: TextViewClass self => Signal self (IO ())\ntoggleCursorVisible = Signal (connect_NONE__NONE \"toggle-cursor-visible\")\n\n-- | Insert Overwrite mode has changed.\n--\n-- * This signal is emitted when the 'TextView' changes from\n-- inserting mode to overwriting mode and vice versa. \n--\n-- * The action itself happens when the 'TextView' processes this\n-- signal.\n--\ntoggleOverwrite :: TextViewClass self => Signal self (IO ())\ntoggleOverwrite = Signal (connect_NONE__NONE \"toggle-overwrite\")\n\n","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget TextView\n--\n-- Author : Axel Simon\n--\n-- Created: 23 February 2002\n--\n-- Copyright (C) 2002-2005 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- TODO\n--\n-- If PangoTabArray is bound: \n-- Fucntions: textViewSetTabs and textViewGetTabs\n-- Properties: textViewTabs\n--\n-- All on... and after... signales had incorrect names (underscore instead of hypens). Thus\n-- they could not have been used in applications and removing them can't break anything.\n-- Thus, I've removed them. Also, all key-binding singals are now removed as there is\n-- no way to add additional key bindings programatically in a type-safe way, let alone\n-- use these signals.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Widget that displays a 'TextBuffer'\n--\nmodule Graphics.UI.Gtk.Multiline.TextView (\n-- * Detail\n-- \n-- | You may wish to begin by reading the text widget conceptual overview\n-- which gives an overview of all the objects and data types related to the\n-- text widget and how they work together.\n--\n-- Throughout we distinguish between buffer coordinates which are pixels with\n-- the origin at the upper left corner of the first character on the first\n-- line. Window coordinates are relative to the top left pixel which is visible\n-- in the current 'TextView'. Coordinates from Events are in the latter\n-- relation. The conversion can be done with 'textViewWindowToBufferCoords'.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----TextView\n-- |\n-- |\n-- | 'GObject'\n-- | +----TextChildAnchor\n-- @\n\n-- * Types\n TextView,\n TextViewClass,\n TextChildAnchor,\n TextChildAnchorClass,\n castToTextView, gTypeTextView,\n toTextView,\n DeleteType(..),\n DirectionType(..),\n Justification(..),\n MovementStep(..),\n TextWindowType(..),\n WrapMode(..),\n\n-- * Constructors\n textViewNew,\n textViewNewWithBuffer,\n\n-- * Methods\n textViewSetBuffer,\n textViewGetBuffer,\n textViewScrollToMark,\n textViewScrollToIter,\n textViewScrollMarkOnscreen,\n textViewMoveMarkOnscreen,\n textViewPlaceCursorOnscreen,\n textViewGetLineAtY,\n textViewGetLineYrange,\n textViewGetIterAtLocation,\n textViewBufferToWindowCoords,\n textViewWindowToBufferCoords,\n textViewGetWindow,\n textViewGetWindowType,\n textViewSetBorderWindowSize,\n textViewGetBorderWindowSize,\n textViewForwardDisplayLine,\n textViewBackwardDisplayLine,\n textViewForwardDisplayLineEnd,\n textViewBackwardDisplayLineStart,\n textViewStartsDisplayLine,\n textViewMoveVisually,\n textViewAddChildAtAnchor,\n textChildAnchorNew,\n textChildAnchorGetWidgets,\n textChildAnchorGetDeleted,\n textViewAddChildInWindow,\n textViewMoveChild,\n textViewSetWrapMode,\n textViewGetWrapMode,\n textViewSetEditable,\n textViewGetEditable,\n textViewSetCursorVisible,\n textViewGetCursorVisible,\n textViewSetPixelsAboveLines,\n textViewGetPixelsAboveLines,\n textViewSetPixelsBelowLines,\n textViewGetPixelsBelowLines,\n textViewSetPixelsInsideWrap,\n textViewGetPixelsInsideWrap,\n textViewSetJustification,\n textViewGetJustification,\n textViewSetLeftMargin,\n textViewGetLeftMargin,\n textViewSetRightMargin,\n textViewGetRightMargin,\n textViewSetIndent,\n textViewGetIndent,\n textViewGetDefaultAttributes,\n textViewGetVisibleRect,\n textViewGetIterLocation,\n#if GTK_CHECK_VERSION(2,6,0)\n textViewGetIterAtPosition,\n#endif\n#if GTK_CHECK_VERSION(2,4,0)\n textViewSetOverwrite,\n textViewGetOverwrite,\n textViewSetAcceptsTab,\n textViewGetAcceptsTab,\n#endif\n\n-- * Attributes\n textViewPixelsAboveLines,\n textViewPixelsBelowLines,\n textViewPixelsInsideWrap,\n textViewEditable,\n textViewImModule,\n textViewWrapMode,\n textViewJustification,\n textViewLeftMargin,\n textViewRightMargin,\n textViewIndent,\n textViewCursorVisible,\n textViewBuffer,\n#if GTK_CHECK_VERSION(2,4,0)\n textViewOverwrite,\n textViewAcceptsTab,\n#endif\n\n-- * Signals\n backspace,\n copyClipboard,\n cutClipboard,\n deleteFromCursor,\n insertAtCursor,\n moveCursor,\n moveViewport,\n moveFocus,\n pageHorizontally,\n pasteClipboard,\n populatePopup,\n selectAll,\n setAnchor,\n setScrollAdjustments,\n toggleCursorVisible,\n toggleOverwrite,\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.Attributes\nimport System.Glib.Properties (newAttrFromStringProperty)\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\nimport System.Glib.GObject\t\t(constructNewGObject, makeNewGObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\n{#import Graphics.UI.Gtk.Multiline.Types#}\n{#import Graphics.UI.Gtk.Multiline.TextIter#}\n{#import Graphics.UI.Gtk.Multiline.TextTag#}\nimport Graphics.UI.Gtk.General.Enums\t(TextWindowType(..), DeleteType(..),\n\t\t\t\t\t DirectionType(..), Justification(..),\n\t\t\t\t\t MovementStep(..), WrapMode(..),\n ScrollStep (..))\nimport System.Glib.GList\t\t(fromGList)\nimport Graphics.UI.Gtk.General.Structs\t(Rectangle(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Creates a new 'TextView'. If you don't call 'textViewSetBuffer' before\n-- using the text view, an empty default buffer will be created for you. Get\n-- the buffer with 'textViewGetBuffer'. If you want to specify your own buffer,\n-- consider 'textViewNewWithBuffer'.\n--\ntextViewNew :: IO TextView\ntextViewNew =\n makeNewObject mkTextView $\n liftM (castPtr :: Ptr Widget -> Ptr TextView) $\n {# call unsafe text_view_new #}\n\n-- | Creates a new 'TextView' widget displaying the buffer @buffer@. One\n-- buffer can be shared among many widgets.\n--\ntextViewNewWithBuffer :: TextBufferClass buffer => buffer -> IO TextView\ntextViewNewWithBuffer buffer =\n makeNewObject mkTextView $\n liftM (castPtr :: Ptr Widget -> Ptr TextView) $\n {# call text_view_new_with_buffer #}\n (toTextBuffer buffer)\n\n--------------------\n-- Methods\n\n-- | Sets the given buffer as the buffer being displayed by the text view.\n--\ntextViewSetBuffer :: (TextViewClass self, TextBufferClass buffer) => self -> buffer -> IO ()\ntextViewSetBuffer self buffer =\n {# call text_view_set_buffer #}\n (toTextView self)\n (toTextBuffer buffer)\n\n-- | Returns the 'TextBuffer' being displayed by this text view.\n--\ntextViewGetBuffer :: TextViewClass self => self -> IO TextBuffer\ntextViewGetBuffer self =\n makeNewGObject mkTextBuffer $\n {# call unsafe text_view_get_buffer #}\n (toTextView self)\n\n-- | Scrolls the text view so that @mark@ is on the screen in the position\n-- indicated by @xalign@ and @yalign@. An alignment of 0.0 indicates left or\n-- top, 1.0 indicates right or bottom, 0.5 means center. If the alignment is\n-- @Nothing@, the text scrolls the minimal distance to get the mark onscreen,\n-- possibly not scrolling at all. The effective screen for purposes of this\n-- function is reduced by a margin of size @withinMargin@.\n--\ntextViewScrollToMark :: (TextViewClass self, TextMarkClass mark) => self\n -> mark -- ^ @mark@ - a 'TextMark'\n -> Double -- ^ @withinMargin@ - margin as a [0.0,0.5) fraction of screen size\n -- and imposes an extra margin at all four sides of the window\n -- within which @xalign@ and @yalign@ are evaluated.\n -> Maybe (Double, Double) -- ^ @Just (xalign, yalign)@ - horizontal and\n -- vertical alignment of mark within visible area (if @Nothing@,\n -- scroll just enough to get the mark onscreen)\n -> IO ()\ntextViewScrollToMark self mark withinMargin align =\n let (useAlign, xalign, yalign) = case align of\n Nothing -> (False, 0, 0)\n Just (xalign, yalign) -> (True, xalign, yalign)\n in\n {# call text_view_scroll_to_mark #}\n (toTextView self)\n (toTextMark mark)\n (realToFrac withinMargin)\n (fromBool useAlign)\n (realToFrac xalign)\n (realToFrac yalign)\n\n-- | Scrolls the text view so that @iter@ is on the screen in the position\n-- indicated by @xalign@ and @yalign@. An alignment of 0.0 indicates left or\n-- top, 1.0 indicates right or bottom, 0.5 means center. If the alignment is\n-- @Nothing@, the text scrolls the minimal distance to get the mark onscreen,\n-- possibly not scrolling at all. The effective screen for purposes of this\n-- function is reduced by a margin of size @withinMargin@.\n--\n-- * This function\n-- uses the currently-computed height of the lines in the text buffer. Note\n-- that line heights are computed in an idle handler; so this function may\n-- not\n-- have the desired effect if it's called before the height computations. To\n-- avoid oddness, consider using 'textViewScrollToMark' which saves a point\n-- to be scrolled to after line validation. This is particularly important\n-- if you add new text to the buffer and immediately ask the view to scroll\n-- to it (which it can't since it is not updated until the main loop runs).\n--\ntextViewScrollToIter :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> Double -- ^ @withinMargin@ - margin as a [0.0,0.5) fraction of screen\n -- size\n -> Maybe (Double, Double) -- ^ @Just (xalign, yalign)@ - horizontal and\n -- vertical alignment of mark within visible area (if @Nothing@,\n -- scroll just enough to get the iterator onscreen)\n -> IO Bool -- ^ returns @True@ if scrolling occurred\ntextViewScrollToIter self iter withinMargin align = \n let (useAlign, xalign, yalign) = case align of\n Nothing -> (False, 0, 0)\n Just (xalign, yalign) -> (True, xalign, yalign)\n in\n liftM toBool $\n {# call text_view_scroll_to_iter #}\n (toTextView self)\n iter\n (realToFrac withinMargin)\n (fromBool useAlign)\n (realToFrac xalign)\n (realToFrac yalign)\n\n-- | Scrolls the text view the minimum distance such that @mark@ is contained\n-- within the visible area of the widget.\n--\ntextViewScrollMarkOnscreen :: (TextViewClass self, TextMarkClass mark) => self\n -> mark -- ^ @mark@ - a mark in the buffer for the text view\n -> IO ()\ntextViewScrollMarkOnscreen self mark =\n {# call text_view_scroll_mark_onscreen #}\n (toTextView self)\n (toTextMark mark)\n\n-- | Moves a mark within the buffer so that it's located within the\n-- currently-visible text area.\n--\ntextViewMoveMarkOnscreen :: (TextViewClass self, TextMarkClass mark) => self\n -> mark -- ^ @mark@ - a 'TextMark'\n -> IO Bool -- ^ returns @True@ if the mark moved (wasn't already onscreen)\ntextViewMoveMarkOnscreen self mark =\n liftM toBool $\n {# call text_view_move_mark_onscreen #}\n (toTextView self)\n (toTextMark mark)\n\n-- | Moves the cursor to the currently visible region of the buffer, it it\n-- isn't there already.\n--\ntextViewPlaceCursorOnscreen :: TextViewClass self => self\n -> IO Bool -- ^ returns @True@ if the cursor had to be moved.\ntextViewPlaceCursorOnscreen self =\n liftM toBool $\n {# call text_view_place_cursor_onscreen #}\n (toTextView self)\n\n-- | Returns the currently-visible region of the buffer, in\n-- buffer coordinates. Convert to window coordinates with\n-- 'textViewBufferToWindowCoords'.\n--\ntextViewGetVisibleRect :: TextViewClass self => self -> IO Rectangle\ntextViewGetVisibleRect self =\n alloca $ \\rectPtr -> do\n {# call unsafe text_view_get_visible_rect #}\n (toTextView self)\n (castPtr rectPtr)\n peek rectPtr\n\n-- | Gets a rectangle which roughly contains the character at @iter@. The\n-- rectangle position is in buffer coordinates; use\n-- 'textViewBufferToWindowCoords' to convert these coordinates to coordinates\n-- for one of the windows in the text view.\n--\ntextViewGetIterLocation :: TextViewClass self => self -> TextIter -> IO Rectangle\ntextViewGetIterLocation self iter =\n alloca $ \\rectPtr -> do\n {# call unsafe text_view_get_iter_location #}\n (toTextView self)\n iter\n (castPtr rectPtr)\n peek rectPtr\n\n-- | Gets the 'TextIter' at the start of the line containing the coordinate\n-- @y@. @y@ is in buffer coordinates, convert from window coordinates with\n-- 'textViewWindowToBufferCoords'. Also returns @lineTop@ the\n-- coordinate of the top edge of the line.\n--\ntextViewGetLineAtY :: TextViewClass self => self\n -> Int -- ^ @y@ - a y coordinate\n -> IO (TextIter, Int) -- ^ @(targetIter, lineTop)@ - returns the iter and the\n -- top coordinate of the line\ntextViewGetLineAtY self y =\n makeEmptyTextIter >>= \\targetIter ->\n alloca $ \\lineTopPtr -> do\n {# call unsafe text_view_get_line_at_y #}\n (toTextView self)\n targetIter\n (fromIntegral y)\n lineTopPtr\n lineTop <- peek lineTopPtr\n return (targetIter, fromIntegral lineTop)\n\n-- | Gets the y coordinate of the top of the line containing @iter@, and the\n-- height of the line. The coordinate is a buffer coordinate; convert to window\n-- coordinates with 'textViewBufferToWindowCoords'.\n--\ntextViewGetLineYrange :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO (Int, Int) -- ^ @(y, height)@ - y coordinate and height of the line\ntextViewGetLineYrange self iter =\n alloca $ \\yPtr ->\n alloca $ \\heightPtr -> do\n {# call unsafe text_view_get_line_yrange #}\n (toTextView self)\n iter\n yPtr\n heightPtr\n y <- peek yPtr\n height <- peek heightPtr\n return (fromIntegral y, fromIntegral height)\n\n-- | Retrieves the iterator at buffer coordinates @x@ and @y@. Buffer\n-- coordinates are coordinates for the entire buffer, not just the\n-- currently-displayed portion. If you have coordinates from an event, you have\n-- to convert those to buffer coordinates with 'textViewWindowToBufferCoords'.\n--\ntextViewGetIterAtLocation :: TextViewClass self => self\n -> Int -- ^ @x@ - x position, in buffer coordinates\n -> Int -- ^ @y@ - y position, in buffer coordinates\n -> IO TextIter\ntextViewGetIterAtLocation self x y = do\n iter <- makeEmptyTextIter\n {# call unsafe text_view_get_iter_at_location #}\n (toTextView self)\n iter\n (fromIntegral x)\n (fromIntegral y)\n return iter\n\n-- | Converts coordinate @(bufferX, bufferY)@ to coordinates for the window\n-- @win@\n--\n-- Note that you can't convert coordinates for a nonexisting window (see\n-- 'textViewSetBorderWindowSize').\n--\ntextViewBufferToWindowCoords :: TextViewClass self => self\n -> TextWindowType -- ^ @win@ - a 'TextWindowType' except 'TextWindowPrivate'\n -> (Int, Int) -- ^ @(bufferX, bufferY)@ - buffer x and y coordinates\n -> IO (Int, Int) -- ^ returns window x and y coordinates\ntextViewBufferToWindowCoords self win (bufferX, bufferY) =\n alloca $ \\windowXPtr ->\n alloca $ \\windowYPtr -> do\n {# call unsafe text_view_buffer_to_window_coords #}\n (toTextView self)\n ((fromIntegral . fromEnum) win)\n (fromIntegral bufferX)\n (fromIntegral bufferY)\n windowXPtr\n windowYPtr\n windowX <- peek windowXPtr\n windowY <- peek windowYPtr\n return (fromIntegral windowX, fromIntegral windowY)\n\n-- | Converts coordinates on the window identified by @win@ to buffer\n-- coordinates.\n--\n-- Note that you can't convert coordinates for a nonexisting window (see\n-- 'textViewSetBorderWindowSize').\n--\ntextViewWindowToBufferCoords :: TextViewClass self => self\n -> TextWindowType -- ^ @win@ - a 'TextWindowType' except 'TextWindowPrivate'\n -> (Int, Int) -- ^ @(windowX, windowY)@ - window x and y coordinates\n -> IO (Int, Int) -- ^ returns buffer x and y coordinates\ntextViewWindowToBufferCoords self win (windowX, windowY) =\n alloca $ \\bufferXPtr ->\n alloca $ \\bufferYPtr -> do\n {# call unsafe text_view_window_to_buffer_coords #}\n (toTextView self)\n ((fromIntegral . fromEnum) win)\n (fromIntegral windowX)\n (fromIntegral windowY)\n bufferXPtr\n bufferYPtr\n bufferX <- peek bufferXPtr\n bufferY <- peek bufferYPtr\n return (fromIntegral bufferX, fromIntegral bufferY)\n\n-- | Retrieves the 'DrawWindow' corresponding to an area of the text view;\n-- possible windows include the overall widget window, child windows on the\n-- left, right, top, bottom, and the window that displays the text buffer.\n-- Windows are @Nothing@ and nonexistent if their width or height is 0, and are\n-- nonexistent before the widget has been realized.\n--\ntextViewGetWindow :: TextViewClass self => self\n -> TextWindowType -- ^ @win@ - window to get\n -> IO (Maybe DrawWindow) -- ^ returns a 'DrawWindow', or @Nothing@\ntextViewGetWindow self win =\n maybeNull (makeNewGObject mkDrawWindow) $\n {# call unsafe text_view_get_window #}\n (toTextView self)\n ((fromIntegral . fromEnum) win)\n\n-- | Retrieve the type of window the 'TextView' widget contains.\n--\n-- Usually used to find out which window an event corresponds to. An emission\n-- of an event signal of 'TextView' yields a 'DrawWindow'. This function can be\n-- used to see if the event actually belongs to the main text window.\n--\ntextViewGetWindowType :: TextViewClass self => self\n -> DrawWindow\n -> IO TextWindowType\ntextViewGetWindowType self window =\n liftM (toEnum . fromIntegral) $\n {# call unsafe text_view_get_window_type #}\n (toTextView self)\n window\n\n-- | Sets the width of 'TextWindowLeft' or 'TextWindowRight', or the height of\n-- 'TextWindowTop' or 'TextWindowBottom'. Automatically destroys the\n-- corresponding window if the size is set to 0, and creates the window if the\n-- size is set to non-zero. This function can only be used for the \\\"border\n-- windows\\\", it doesn't work with 'TextWindowWidget', 'TextWindowText', or\n-- 'TextWindowPrivate'.\n--\ntextViewSetBorderWindowSize :: TextViewClass self => self\n -> TextWindowType -- ^ @type@ - window to affect\n -> Int -- ^ @size@ - width or height of the window\n -> IO ()\ntextViewSetBorderWindowSize self type_ size =\n {# call text_view_set_border_window_size #}\n (toTextView self)\n ((fromIntegral . fromEnum) type_)\n (fromIntegral size)\n\n-- | Gets the width of the specified border window. See\n-- 'textViewSetBorderWindowSize'.\n--\ntextViewGetBorderWindowSize :: TextViewClass self => self\n -> TextWindowType -- ^ @type@ - window to return size from\n -> IO Int -- ^ returns width of window\ntextViewGetBorderWindowSize self type_ =\n liftM fromIntegral $\n {# call unsafe text_view_get_border_window_size #}\n (toTextView self)\n ((fromIntegral . fromEnum) type_)\n\n-- | Moves the given @iter@ forward by one display (wrapped) line. A display\n-- line is different from a paragraph. Paragraphs are separated by newlines or\n-- other paragraph separator characters. Display lines are created by\n-- line-wrapping a paragraph. If wrapping is turned off, display lines and\n-- paragraphs will be the same. Display lines are divided differently for each\n-- view, since they depend on the view's width; paragraphs are the same in all\n-- views, since they depend on the contents of the 'TextBuffer'.\n--\ntextViewForwardDisplayLine :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ was moved and is not on the end\n -- iterator\ntextViewForwardDisplayLine self iter =\n liftM toBool $\n {# call unsafe text_view_forward_display_line #}\n (toTextView self)\n iter\n\n-- | Moves the given @iter@ backward by one display (wrapped) line. A display\n-- line is different from a paragraph. Paragraphs are separated by newlines or\n-- other paragraph separator characters. Display lines are created by\n-- line-wrapping a paragraph. If wrapping is turned off, display lines and\n-- paragraphs will be the same. Display lines are divided differently for each\n-- view, since they depend on the view's width; paragraphs are the same in all\n-- views, since they depend on the contents of the 'TextBuffer'.\n--\ntextViewBackwardDisplayLine :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ was moved and is not on the end\n -- iterator\ntextViewBackwardDisplayLine self iter =\n liftM toBool $\n {# call unsafe text_view_backward_display_line #}\n (toTextView self)\n iter\n\n-- | Moves the given @iter@ forward to the next display line end. A display\n-- line is different from a paragraph. Paragraphs are separated by newlines or\n-- other paragraph separator characters. Display lines are created by\n-- line-wrapping a paragraph. If wrapping is turned off, display lines and\n-- paragraphs will be the same. Display lines are divided differently for each\n-- view, since they depend on the view's width; paragraphs are the same in all\n-- views, since they depend on the contents of the 'TextBuffer'.\n--\ntextViewForwardDisplayLineEnd :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ was moved and is not on the end\n -- iterator\ntextViewForwardDisplayLineEnd self iter =\n liftM toBool $\n {# call unsafe text_view_forward_display_line_end #}\n (toTextView self)\n iter\n\n-- | Moves the given @iter@ backward to the next display line start. A display\n-- line is different from a paragraph. Paragraphs are separated by newlines or\n-- other paragraph separator characters. Display lines are created by\n-- line-wrapping a paragraph. If wrapping is turned off, display lines and\n-- paragraphs will be the same. Display lines are divided differently for each\n-- view, since they depend on the view's width; paragraphs are the same in all\n-- views, since they depend on the contents of the 'TextBuffer'.\n--\ntextViewBackwardDisplayLineStart :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ was moved and is not on the end\n -- iterator\ntextViewBackwardDisplayLineStart self iter =\n liftM toBool $\n {# call unsafe text_view_backward_display_line_start #}\n (toTextView self)\n iter\n\n-- | Determines whether @iter@ is at the start of a display line. See\n-- 'textViewForwardDisplayLine' for an explanation of display lines vs.\n-- paragraphs.\n--\ntextViewStartsDisplayLine :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> IO Bool -- ^ returns @True@ if @iter@ begins a wrapped line\ntextViewStartsDisplayLine self iter =\n liftM toBool $\n {# call unsafe text_view_starts_display_line #}\n (toTextView self)\n iter\n\n-- | Move the iterator a given number of characters visually, treating it as\n-- the strong cursor position. If @count@ is positive, then the new strong\n-- cursor position will be @count@ positions to the right of the old cursor\n-- position. If @count@ is negative then the new strong cursor position will be\n-- @count@ positions to the left of the old cursor position.\n--\n-- In the presence of bidirection text, the correspondence between logical\n-- and visual order will depend on the direction of the current run, and there\n-- may be jumps when the cursor is moved off of the end of a run.\n--\ntextViewMoveVisually :: TextViewClass self => self\n -> TextIter -- ^ @iter@ - a 'TextIter'\n -> Int -- ^ @count@ - number of characters to move (negative moves left,\n -- positive moves right)\n -> IO Bool -- ^ returns @True@ if @iter@ moved and is not on the end\n -- iterator\ntextViewMoveVisually self iter count =\n liftM toBool $\n {# call unsafe text_view_move_visually #}\n (toTextView self)\n iter\n (fromIntegral count)\n\n-- | Adds a child widget in the text buffer, at the given @anchor@.\n--\ntextViewAddChildAtAnchor :: (TextViewClass self, WidgetClass child) => self\n -> child -- ^ @child@ - a 'Widget'\n -> TextChildAnchor -- ^ @anchor@ - a 'TextChildAnchor' in the 'TextBuffer'\n -- for the text view\n -> IO ()\ntextViewAddChildAtAnchor self child anchor =\n {# call text_view_add_child_at_anchor #}\n (toTextView self)\n (toWidget child)\n anchor\n\n-- | Create a new 'TextChildAnchor'.\n--\n-- * Using 'textBufferCreateChildAnchor' is usually simpler then\n-- executing this function and 'textBufferInsertChildAnchor'.\n--\ntextChildAnchorNew :: IO TextChildAnchor\ntextChildAnchorNew =\n constructNewGObject mkTextChildAnchor\n {# call unsafe text_child_anchor_new #}\n\n-- | Retrieve all 'Widget's at this\n-- 'TextChildAnchor'.\n--\n-- * The widgets in the returned list need to be upcasted to what they were.\n--\ntextChildAnchorGetWidgets :: TextChildAnchor -> IO [Widget]\ntextChildAnchorGetWidgets tca = do\n gList <- {# call text_child_anchor_get_widgets #} tca\n wList <- fromGList gList\n mapM (makeNewObject mkWidget) (map return wList)\n\n-- | Query if an anchor was deleted.\n--\ntextChildAnchorGetDeleted :: TextChildAnchor -> IO Bool\ntextChildAnchorGetDeleted tca =\n liftM toBool $\n {# call unsafe text_child_anchor_get_deleted #} tca\n\n-- | Adds a child at fixed coordinates in one of the text widget's windows.\n-- The window must have nonzero size (see 'textViewSetBorderWindowSize'). Note\n-- that the child coordinates are given relative to the 'DrawWindow' in\n-- question, and that these coordinates have no sane relationship to scrolling.\n-- When placing a child in 'TextWindowWidget', scrolling is irrelevant, the\n-- child floats above all scrollable areas. If you want the widget to move when\n-- the text view scrolls, use 'textViewAddChildAtAnchor' instead.\n--\ntextViewAddChildInWindow :: (TextViewClass self, WidgetClass child) => self\n -> child -- ^ @child@ - a 'Widget'\n -> TextWindowType -- ^ @whichWindow@ - which window the child should appear\n -- in\n -> Int -- ^ @xpos@ - X position of child in window coordinates\n -> Int -- ^ @ypos@ - Y position of child in window coordinates\n -> IO ()\ntextViewAddChildInWindow self child whichWindow xpos ypos =\n {# call text_view_add_child_in_window #}\n (toTextView self)\n (toWidget child)\n ((fromIntegral . fromEnum) whichWindow)\n (fromIntegral xpos)\n (fromIntegral ypos)\n\n-- | Move a child widget within the 'TextView'. This is really only apprpriate\n-- for \\\"floating\\\" child widgets added using 'textViewAddChildInWindow'.\n--\ntextViewMoveChild :: (TextViewClass self, WidgetClass child) => self\n -> child -- ^ @child@ - child widget already added to the text view\n -> Int -- ^ @xpos@ - new X position in window coordinates\n -> Int -- ^ @ypos@ - new Y position in window coordinates\n -> IO ()\ntextViewMoveChild self child xpos ypos =\n {# call text_view_move_child #}\n (toTextView self)\n (toWidget child)\n (fromIntegral xpos)\n (fromIntegral ypos)\n\n-- | Sets the line wrapping for the view.\n--\ntextViewSetWrapMode :: TextViewClass self => self -> WrapMode -> IO ()\ntextViewSetWrapMode self wrapMode =\n {# call text_view_set_wrap_mode #}\n (toTextView self)\n ((fromIntegral . fromEnum) wrapMode)\n\n-- | Gets the line wrapping for the view.\n--\ntextViewGetWrapMode :: TextViewClass self => self -> IO WrapMode\ntextViewGetWrapMode self =\n liftM (toEnum . fromIntegral) $\n {# call unsafe text_view_get_wrap_mode #}\n (toTextView self)\n\n-- | Sets the default editability of the 'TextView'. You can override this\n-- default setting with tags in the buffer, using the \\\"editable\\\" attribute of\n-- tags.\n--\ntextViewSetEditable :: TextViewClass self => self -> Bool -> IO ()\ntextViewSetEditable self setting =\n {# call text_view_set_editable #}\n (toTextView self)\n (fromBool setting)\n\n-- | Returns the default editability of the 'TextView'. Tags in the buffer may\n-- override this setting for some ranges of text.\n--\ntextViewGetEditable :: TextViewClass self => self -> IO Bool\ntextViewGetEditable self =\n liftM toBool $\n {# call unsafe text_view_get_editable #}\n (toTextView self)\n\n-- | Toggles whether the insertion point is displayed. A buffer with no\n-- editable text probably shouldn't have a visible cursor, so you may want to\n-- turn the cursor off.\n--\ntextViewSetCursorVisible :: TextViewClass self => self -> Bool -> IO ()\ntextViewSetCursorVisible self setting =\n {# call text_view_set_cursor_visible #}\n (toTextView self)\n (fromBool setting)\n\n-- | Find out whether the cursor is being displayed.\n--\ntextViewGetCursorVisible :: TextViewClass self => self -> IO Bool\ntextViewGetCursorVisible self =\n liftM toBool $\n {# call unsafe text_view_get_cursor_visible #}\n (toTextView self)\n\n-- | Sets the default number of blank pixels above paragraphs in the text view.\n-- Tags in the buffer for the text view may override the defaults.\n--\n-- * Tags in the buffer may override this default.\n--\ntextViewSetPixelsAboveLines :: TextViewClass self => self -> Int -> IO ()\ntextViewSetPixelsAboveLines self pixelsAboveLines =\n {# call text_view_set_pixels_above_lines #}\n (toTextView self)\n (fromIntegral pixelsAboveLines)\n\n-- | Gets the default number of pixels to put above paragraphs.\n--\ntextViewGetPixelsAboveLines :: TextViewClass self => self -> IO Int\ntextViewGetPixelsAboveLines self =\n liftM fromIntegral $\n {# call unsafe text_view_get_pixels_above_lines #}\n (toTextView self)\n\n-- | Sets the default number of pixels of blank space to put below paragraphs\n-- in the text view. May be overridden by tags applied to the text view's\n-- buffer.\n--\ntextViewSetPixelsBelowLines :: TextViewClass self => self -> Int -> IO ()\ntextViewSetPixelsBelowLines self pixelsBelowLines =\n {# call text_view_set_pixels_below_lines #}\n (toTextView self)\n (fromIntegral pixelsBelowLines)\n\n-- | Gets the default number of blank pixels below each paragraph.\n--\ntextViewGetPixelsBelowLines :: TextViewClass self => self -> IO Int\ntextViewGetPixelsBelowLines self =\n liftM fromIntegral $\n {# call unsafe text_view_get_pixels_below_lines #}\n (toTextView self)\n\n-- | Sets the default number of pixels of blank space to leave between\n-- display\\\/wrapped lines within a paragraph. May be overridden by tags in\n-- the text view's buffer.\n--\ntextViewSetPixelsInsideWrap :: TextViewClass self => self -> Int -> IO ()\ntextViewSetPixelsInsideWrap self pixelsInsideWrap =\n {# call text_view_set_pixels_inside_wrap #}\n (toTextView self)\n (fromIntegral pixelsInsideWrap)\n\n-- | Gets the default number of pixels of blank space between lines in a\n-- wrapped paragraph.\n--\ntextViewGetPixelsInsideWrap :: TextViewClass self => self -> IO Int\ntextViewGetPixelsInsideWrap self =\n liftM fromIntegral $\n {# call unsafe text_view_get_pixels_inside_wrap #}\n (toTextView self)\n\n-- | Sets the default justification of text in the text view. Tags in the\n-- view's buffer may override the default.\n--\ntextViewSetJustification :: TextViewClass self => self -> Justification -> IO ()\ntextViewSetJustification self justification =\n {# call text_view_set_justification #}\n (toTextView self)\n ((fromIntegral . fromEnum) justification)\n\n-- | Gets the default justification of paragraphs in the text view. Tags in the\n-- buffer may override the default.\n--\ntextViewGetJustification :: TextViewClass self => self -> IO Justification\ntextViewGetJustification self =\n liftM (toEnum . fromIntegral) $\n {# call unsafe text_view_get_justification #}\n (toTextView self)\n\n-- | Sets the default left margin for text in the text view. Tags in the buffer\n-- may override the default.\n--\ntextViewSetLeftMargin :: TextViewClass self => self\n -> Int -- ^ @leftMargin@ - left margin in pixels\n -> IO ()\ntextViewSetLeftMargin self leftMargin =\n {# call text_view_set_left_margin #}\n (toTextView self)\n (fromIntegral leftMargin)\n\n-- | Gets the default left margin size of paragraphs in the text view. Tags\n-- in the buffer may override the default.\n--\ntextViewGetLeftMargin :: TextViewClass self => self\n -> IO Int -- ^ returns left margin in pixels\ntextViewGetLeftMargin self =\n liftM fromIntegral $\n {# call unsafe text_view_get_left_margin #}\n (toTextView self)\n\n-- | Sets the default right margin for text in the text view. Tags in the\n-- buffer may override the default.\n--\ntextViewSetRightMargin :: TextViewClass self => self\n -> Int -- ^ @rightMargin@ - right margin in pixels\n -> IO ()\ntextViewSetRightMargin self rightMargin =\n {# call text_view_set_right_margin #}\n (toTextView self)\n (fromIntegral rightMargin)\n\n-- | Gets the default right margin for text in the text view. Tags in the\n-- buffer may override the default.\n--\ntextViewGetRightMargin :: TextViewClass self => self\n -> IO Int -- ^ returns right margin in pixels\ntextViewGetRightMargin self =\n liftM fromIntegral $\n {# call unsafe text_view_get_right_margin #}\n (toTextView self)\n\n-- | Sets the default indentation for paragraphs in the text view. Tags in the\n-- buffer may override the default.\n--\ntextViewSetIndent :: TextViewClass self => self\n -> Int -- ^ @indent@ - indentation in pixels (may be negative)\n -> IO ()\ntextViewSetIndent self indent =\n {# call text_view_set_indent #}\n (toTextView self)\n (fromIntegral indent)\n\n-- | Gets the default indentation of paragraphs in the text view. Tags in the\n-- view's buffer may override the default. The indentation may be negative.\n--\ntextViewGetIndent :: TextViewClass self => self\n -> IO Int -- ^ returns number of pixels of indentation\ntextViewGetIndent self =\n liftM fromIntegral $\n {# call unsafe text_view_get_indent #}\n (toTextView self)\n\n-- | Obtains a copy of the default text attributes. These are the attributes\n-- used for text unless a tag overrides them. You'd typically pass the default\n-- attributes in to 'textIterGetAttributes' in order to get the attributes in\n-- effect at a given text position.\n--\ntextViewGetDefaultAttributes :: TextViewClass self => self -> IO TextAttributes\ntextViewGetDefaultAttributes self =\n {# call gtk_text_view_get_default_attributes #}\n (toTextView self)\n >>= makeNewTextAttributes\n\n#if GTK_CHECK_VERSION(2,6,0)\n-- | Retrieves the iterator pointing to the character at buffer coordinates\n-- @x@ and @y@. Buffer coordinates are coordinates for the entire buffer, not\n-- just the currently-displayed portion. If you have coordinates from an event,\n-- you have to convert those to buffer coordinates with\n-- 'textViewWindowToBufferCoords'.\n--\n-- Note that this is different from 'textViewGetIterAtLocation', which\n-- returns cursor locations, i.e. positions \/between\/ characters.\n--\n-- * Available since Gtk+ version 2.6\n--\ntextViewGetIterAtPosition :: TextViewClass self => self\n -> Int -- ^ @x@ - x position, in buffer coordinates\n -> Int -- ^ @y@ - y position, in buffer coordinates\n -> IO (TextIter, Int) -- ^ @(iter, trailing)@ - returns the iterator and\n -- an integer indicating where in the grapheme the\n -- user clicked. It will either be zero, or the\n -- number of characters in the grapheme. 0 represents\n -- the trailing edge of the grapheme.\ntextViewGetIterAtPosition self x y =\n alloca $ \\trailingPtr -> do\n iter <- makeEmptyTextIter\n {# call gtk_text_view_get_iter_at_position #}\n (toTextView self)\n iter\n trailingPtr\n (fromIntegral x)\n (fromIntegral y)\n trailing <- peek trailingPtr\n return (iter, fromIntegral trailing)\n#endif\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Changes the 'TextView' overwrite mode.\n--\n-- * Available since Gtk+ version 2.4\n--\ntextViewSetOverwrite :: TextViewClass self => self\n -> Bool -- ^ @overwrite@ - @True@ to turn on overwrite mode, @False@ to turn\n -- it off\n -> IO ()\ntextViewSetOverwrite self overwrite =\n {# call gtk_text_view_set_overwrite #}\n (toTextView self)\n (fromBool overwrite)\n\n-- | Returns whether the 'TextView' is in overwrite mode or not.\n--\n-- * Available since Gtk+ version 2.4\n--\ntextViewGetOverwrite :: TextViewClass self => self -> IO Bool\ntextViewGetOverwrite self =\n liftM toBool $\n {# call gtk_text_view_get_overwrite #}\n (toTextView self)\n\n-- | Sets the behavior of the text widget when the Tab key is pressed. If\n-- @acceptsTab@ is @True@ a tab character is inserted. If @acceptsTab@ is\n-- @False@ the keyboard focus is moved to the next widget in the focus chain.\n--\n-- * Available since Gtk+ version 2.4\n--\ntextViewSetAcceptsTab :: TextViewClass self => self\n -> Bool -- ^ @acceptsTab@ - @True@ if pressing the Tab key should insert a\n -- tab character, @False@, if pressing the Tab key should move the\n -- keyboard focus.\n -> IO ()\ntextViewSetAcceptsTab self acceptsTab =\n {# call gtk_text_view_set_accepts_tab #}\n (toTextView self)\n (fromBool acceptsTab)\n\n-- | Returns whether pressing the Tab key inserts a tab characters.\n-- 'textViewSetAcceptsTab'.\n--\n-- * Available since Gtk+ version 2.4\n--\ntextViewGetAcceptsTab :: TextViewClass self => self\n -> IO Bool -- ^ returns @True@ if pressing the Tab key inserts a tab\n -- character, @False@ if pressing the Tab key moves the keyboard\n -- focus.\ntextViewGetAcceptsTab self =\n liftM toBool $\n {# call gtk_text_view_get_accepts_tab #}\n (toTextView self)\n#endif\n\n--------------------\n-- Attributes\n\n-- | Pixels of blank space above paragraphs.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewPixelsAboveLines :: TextViewClass self => Attr self Int\ntextViewPixelsAboveLines = newAttr\n textViewGetPixelsAboveLines\n textViewSetPixelsAboveLines\n\n-- | Pixels of blank space below paragraphs.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewPixelsBelowLines :: TextViewClass self => Attr self Int\ntextViewPixelsBelowLines = newAttr\n textViewGetPixelsBelowLines\n textViewSetPixelsBelowLines\n\n-- | Pixels of blank space between wrapped lines in a paragraph.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewPixelsInsideWrap :: TextViewClass self => Attr self Int\ntextViewPixelsInsideWrap = newAttr\n textViewGetPixelsInsideWrap\n textViewSetPixelsInsideWrap\n\n-- | Whether the text can be modified by the user.\n--\n-- Default value: @True@\n--\ntextViewEditable :: TextViewClass self => Attr self Bool\ntextViewEditable = newAttr\n textViewGetEditable\n textViewSetEditable\n\n-- | Which IM (input method) module should be used for this entry. See GtkIMContext.\n-- Setting this to a non-empty value overrides the system-wide IM module setting. \n-- See the GtkSettings \"gtk-im-module\" property.\n--\n-- Default value: \\\"\\\"\n--\ntextViewImModule :: TextViewClass self => Attr self String\ntextViewImModule = \n newAttrFromStringProperty \"im-module\"\n\n-- | Whether to wrap lines never, at word boundaries, or at character\n-- boundaries.\n--\n-- Default value: 'WrapNone'\n--\ntextViewWrapMode :: TextViewClass self => Attr self WrapMode\ntextViewWrapMode = newAttr\n textViewGetWrapMode\n textViewSetWrapMode\n\n-- | Left, right, or center justification.\n--\n-- Default value: 'JustifyLeft'\n--\ntextViewJustification :: TextViewClass self => Attr self Justification\ntextViewJustification = newAttr\n textViewGetJustification\n textViewSetJustification\n\n-- | Width of the left margin in pixels.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewLeftMargin :: TextViewClass self => Attr self Int\ntextViewLeftMargin = newAttr\n textViewGetLeftMargin\n textViewSetLeftMargin\n\n-- | Width of the right margin in pixels.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewRightMargin :: TextViewClass self => Attr self Int\ntextViewRightMargin = newAttr\n textViewGetRightMargin\n textViewSetRightMargin\n\n-- | Amount to indent the paragraph, in pixels.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\ntextViewIndent :: TextViewClass self => Attr self Int\ntextViewIndent = newAttr\n textViewGetIndent\n textViewSetIndent\n\n-- | If the insertion cursor is shown.\n--\n-- Default value: @True@\n--\ntextViewCursorVisible :: TextViewClass self => Attr self Bool\ntextViewCursorVisible = newAttr\n textViewGetCursorVisible\n textViewSetCursorVisible\n\n-- | The buffer which is displayed.\n--\ntextViewBuffer :: TextViewClass self => Attr self TextBuffer\ntextViewBuffer = newAttr\n textViewGetBuffer\n textViewSetBuffer\n\n#if GTK_CHECK_VERSION(2,4,0)\n-- | Whether entered text overwrites existing contents.\n--\n-- Default value: @False@\n--\ntextViewOverwrite :: TextViewClass self => Attr self Bool\ntextViewOverwrite = newAttr\n textViewGetOverwrite\n textViewSetOverwrite\n\n-- | Whether Tab will result in a tab character being entered.\n--\n-- Default value: @True@\n--\ntextViewAcceptsTab :: TextViewClass self => Attr self Bool\ntextViewAcceptsTab = newAttr\n textViewGetAcceptsTab\n textViewSetAcceptsTab\n#endif\n\n--------------------\n-- Signals\nbackspace :: TextBufferClass self => Signal self (IO ())\nbackspace = Signal (connect_NONE__NONE \"on_backspace\")\n\ncopyClipboard :: TextBufferClass self => Signal self (IO ())\ncopyClipboard = Signal (connect_NONE__NONE \"copy_clipboard\")\n\ncutClipboard :: TextBufferClass self => Signal self (IO ())\ncutClipboard = Signal (connect_NONE__NONE \"cut_clipboard\")\n\ndeleteFromCursor :: TextBufferClass self => Signal self (DeleteType -> Int -> IO ())\ndeleteFromCursor = Signal (connect_ENUM_INT__NONE \"delete_from_cursor\")\n\ninsertAtCursor :: TextBufferClass self => Signal self (String -> IO ())\ninsertAtCursor = Signal (connect_STRING__NONE \"insert_at_cursor\")\n\nmoveCursor :: TextBufferClass self => Signal self (MovementStep -> Int -> Bool -> IO ())\nmoveCursor = Signal (connect_ENUM_INT_BOOL__NONE \"move_cursor\")\n\nmoveViewport :: TextBufferClass self => Signal self (ScrollStep -> Int -> IO ())\nmoveViewport = Signal (connect_ENUM_INT__NONE \"move_viewport\")\n\nmoveFocus :: TextBufferClass self => Signal self (DirectionType -> IO ())\nmoveFocus = Signal (connect_ENUM__NONE \"move_focus\")\n\npageHorizontally :: TextBufferClass self => Signal self (Int -> Bool -> IO ())\npageHorizontally = Signal (connect_INT_BOOL__NONE \"page_horizontally\")\n\npasteClipboard :: TextBufferClass self => Signal self (IO ())\npasteClipboard = Signal (connect_NONE__NONE \"paste_clipboard\")\n\npopulatePopup :: TextBufferClass self => Signal self (Menu -> IO ())\npopulatePopup = Signal (connect_OBJECT__NONE \"populate_popup\")\n\nselectAll :: TextBufferClass self => Signal self (Bool -> IO ())\nselectAll = Signal (connect_BOOL__NONE \"select-all\")\n\nsetAnchor :: TextBufferClass self => Signal self (IO ())\nsetAnchor = Signal (connect_NONE__NONE \"set_anchor\")\n\nsetScrollAdjustments :: TextBufferClass self => Signal self (Adjustment -> Adjustment -> IO ())\nsetScrollAdjustments = Signal (connect_OBJECT_OBJECT__NONE \"set_scroll_adjustments\")\n\ntoggleCursorVisible :: TextBufferClass self => Signal self (IO ())\ntoggleCursorVisible = Signal (connect_NONE__NONE \"toggle_cursor_visible\")\n\ntoggleOverwrite :: TextBufferClass self => Signal self (IO ())\ntoggleOverwrite = Signal (connect_NONE__NONE \"toggle_overwrite\")\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"a96692ec283e963954d1b1823afcb139efbaf9cd","subject":"Fix types, remove key binding signals.","message":"Fix types, remove key binding signals.\n","repos":"gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/gstreamer,gtk2hs\/webkit","old_file":"gtk\/Graphics\/UI\/Gtk\/Windows\/Dialog.chs","new_file":"gtk\/Graphics\/UI\/Gtk\/Windows\/Dialog.chs","new_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Dialog\n--\n-- Author : Axel Simon, Andy Stewart\n--\n-- Created: 23 May 2001\n--\n-- Copyright (C) 1999-2005 Axel Simon\n-- Copyright (C) 2009 Andy Stewart\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Create popup windows\n-- \n-- NOTE: \n-- Now FFI haven't support variadic function `gtk_dialog_set_alternative_button_order`\n--\nmodule Graphics.UI.Gtk.Windows.Dialog (\n-- * Detail\n-- \n-- | Dialog boxes are a convenient way to prompt the user for a small amount\n-- of input, e.g. to display a message, ask a question, or anything else that\n-- does not require extensive effort on the user's part.\n--\n-- Gtk+ treats a dialog as a window split vertically. The top section is a\n-- 'VBox', and is where widgets such as a 'Label' or a 'Entry' should be\n-- packed. The bottom area is known as the action_area. This is generally used\n-- for packing buttons into the dialog which may perform functions such as\n-- cancel, ok, or apply. The two areas are separated by a 'HSeparator'.\n--\n-- 'Dialog' boxes are created with a call to 'dialogNew' or\n-- 'dialogNewWithButtons'. 'dialogNewWithButtons' is recommended; it allows you\n-- to set the dialog title, some convenient flags, and add simple buttons.\n--\n-- If \\'dialog\\' is a newly created dialog, the two primary areas of the\n-- window can be accessed using 'dialogGetUpper' and\n-- 'dialogGetActionArea'.\n--\n-- A \\'modal\\' dialog (that is, one which freezes the rest of the\n-- application from user input), can be created by calling 'windowSetModal' on\n-- the dialog. When using 'dialogNewWithButtons' you can also\n-- pass the 'DialogModal' flag to make a dialog modal.\n--\n-- If you add buttons to 'Dialog' using 'dialogNewWithButtons',\n-- 'dialogAddButton', 'dialogAddButtons', or 'dialogAddActionWidget', clicking\n-- the button will emit a signal called \\\"response\\\" with a response ID that\n-- you specified. Gtk+ will never assign a meaning to positive response IDs;\n-- these are entirely user-defined. But for convenience, you can use the\n-- response IDs in the 'ResponseType' enumeration (these all have values less\n-- than zero). If a dialog receives a delete event, the \\\"response\\\" signal\n-- will be emitted with a response ID of 'ResponseNone'.\n--\n-- If you want to block waiting for a dialog to return before returning\n-- control flow to your code, you can call 'dialogRun'. This function enters a\n-- recursive main loop and waits for the user to respond to the dialog,\n-- returning the response ID corresponding to the button the user clicked.\n--\n-- For a simple message box, you probably want to use \n-- 'Graphics.UI.Gtk.Windows.MessageDialog.MessageDialog' which provides\n-- convenience functions\n-- for creating standard dialogs containing simple messages to inform\n-- or ask the user.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----'Bin'\n-- | +----'Window'\n-- | +----Dialog\n-- | +----'AboutDialog'\n-- | +----'ColorSelectionDialog'\n-- | +----'FileChooserDialog'\n-- | +----'FileSelection'\n-- | +----'FontSelectionDialog'\n-- | +----'InputDialog'\n-- | +----'MessageDialog'\n-- @\n\n-- * Types\n Dialog,\n DialogClass,\n castToDialog,\n toDialog,\n\n-- * Constructors\n dialogNew,\n\n-- * Methods\n dialogGetUpper,\n dialogGetActionArea,\n dialogRun,\n dialogResponse,\n ResponseId(..),\n dialogAddButton,\n dialogAddActionWidget,\n dialogGetHasSeparator,\n dialogSetDefaultResponse,\n dialogSetHasSeparator,\n dialogSetResponseSensitive,\n dialogGetResponseForWidget,\n dialogAlternativeDialogButtonOrder,\n dialogSetAlternativeButtonOrderFromArray,\n\n-- * Attributes\n dialogHasSeparator,\n dialogActionAreaBorder,\n dialogButtonSpacing,\n dialogContentAreaBorder,\n dialogContentAreaSpacing,\n\n-- * Signals\n response,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n onResponse,\n afterResponse,\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.General.Structs\t(dialogGetUpper, dialogGetActionArea,\n\t\t\t\t\tResponseId(..), fromResponse, toResponse)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Creates a new dialog box. Widgets should not be packed into this 'Window'\n-- directly, but into the \\\"upper\\\" and \\\"action area\\\", which are obtained\n-- using 'dialogGetUpper' and 'dialogGetActionArea'.\n--\ndialogNew :: IO Dialog\ndialogNew =\n makeNewObject mkDialog $\n liftM (castPtr :: Ptr Widget -> Ptr Dialog) $\n {# call unsafe dialog_new #}\n\n--------------------\n-- Methods\n\n-- | Blocks in a recursive main loop until the dialog either emits the\n-- response signal, or is destroyed. If the dialog is destroyed during the call\n-- to 'dialogRun', it returns 'ResponseNone'. Otherwise, it returns the\n-- response ID from the \\\"response\\\" signal emission. Before entering the\n-- recursive main loop, 'dialogRun' calls 'widgetShow' on the dialog for you.\n-- Note that you still need to show any children of the dialog yourself.\n--\n-- During 'dialogRun', the default behavior of \\\"delete_event\\\" is disabled;\n-- if the dialog receives \\\"delete_event\\\", it will not be destroyed as windows\n-- usually are, and 'dialogRun' will return 'ResponseDeleteEvent'. Also, during\n-- 'dialogRun' the dialog will be modal. You can force 'dialogRun' to return at\n-- any time by calling 'dialogResponse' to emit the \\\"response\\\" signal.\n-- Destroying the dialog during 'dialogRun' is a very bad idea, because your\n-- post-run code won't know whether the dialog was destroyed or not.\n-- Hence, you should not call 'Graphics.UI.Gtk.Abstract.widgetDestroy'\n-- before 'dialogRun' has returned.\n--\n-- After 'dialogRun' returns, you are responsible for hiding or destroying\n-- the dialog if you wish to do so.\n--\n-- Note that even though the recursive main loop gives the effect of a modal\n-- dialog (it prevents the user from interacting with other windows while the\n-- dialog is run), callbacks such as timeouts, IO channel watches, DND drops,\n-- etc, \/will\/ be triggered during a 'dialogRun' call.\n--\ndialogRun :: DialogClass self => self\n -> IO ResponseId\ndialogRun self =\n liftM toResponse $\n {# call dialog_run #}\n (toDialog self)\n\n-- | Emits the \\\"response\\\" signal with the given response ID. Used to\n-- indicate that the user has responded to the dialog in some way; typically\n-- either you or 'dialogRun' will be monitoring the \\\"response\\\" signal and\n-- take appropriate action.\n--\n-- This function can be used to add a custom widget to the action area that\n-- should close the dialog when activated or to close the dialog otherwise.\n--\ndialogResponse :: DialogClass self => self\n -> ResponseId\n -> IO ()\ndialogResponse self responseId =\n {# call dialog_response #}\n (toDialog self)\n (fromResponse responseId)\n\n-- | Adds a button with the given text (or a stock button, if @buttonText@ is\n-- a stock ID) and sets things up so that clicking the button will emit the\n-- \\\"response\\\" signal with the given @responseId@. The button is appended to\n-- the end of the dialog's action area. The button widget is returned, but\n-- usually you don't need it.\n--\ndialogAddButton :: DialogClass self => self\n -> String -- ^ @buttonText@ - text of button, or stock ID\n -> ResponseId -- ^ @responseId@ - response ID for the button\n -> IO Button -- ^ returns the button widget that was added\ndialogAddButton self buttonText responseId =\n makeNewObject mkButton $ liftM castPtr $\n withUTFString buttonText $ \\buttonTextPtr ->\n {# call dialog_add_button #}\n (toDialog self)\n buttonTextPtr\n (fromResponse responseId)\n\n-- | Adds an activatable widget to the action area of a 'Dialog', connecting a\n-- signal handler that will emit the \\\"response\\\" signal on the dialog when the\n-- widget is activated. The widget is appended to the end of the dialog's\n-- action area. If you want to add a non-activatable widget, simply pack it\n-- into the action area.\n--\ndialogAddActionWidget :: (DialogClass self, WidgetClass child) => self\n -> child -- ^ @child@ - an activatable widget\n -> ResponseId -- ^ @responseId@ - response ID for @child@\n -> IO ()\ndialogAddActionWidget self child responseId =\n {# call dialog_add_action_widget #}\n (toDialog self)\n (toWidget child)\n (fromResponse responseId)\n\n-- | Query if the dialog has a visible horizontal separator.\n--\ndialogGetHasSeparator :: DialogClass self => self -> IO Bool\ndialogGetHasSeparator self =\n liftM toBool $\n {# call unsafe dialog_get_has_separator #}\n (toDialog self)\n\n-- | Sets the last widget in the dialog's action area with the given\n-- 'ResponseId' as the default widget for the dialog. Pressing \\\"Enter\\\"\n-- normally activates the default widget.\n--\n-- * The default response is reset once it is triggered. Hence, if you\n-- hide the dialog (rather than closing it) and re-display it later,\n-- you need to call this function again.\n--\ndialogSetDefaultResponse :: DialogClass self => self\n -> ResponseId\n -> IO ()\ndialogSetDefaultResponse self responseId =\n {# call dialog_set_default_response #}\n (toDialog self)\n (fromResponse responseId)\n\n-- | Sets whether the dialog has a separator above the buttons. @True@ by\n-- default.\n--\ndialogSetHasSeparator :: DialogClass self => self -> Bool -> IO ()\ndialogSetHasSeparator self setting =\n {# call dialog_set_has_separator #}\n (toDialog self)\n (fromBool setting)\n\n-- | Calls @'widgetSetSensitive' widget setting@ for each widget in the\n-- dialog's action area with the given @responseId@. A convenient way to\n-- sensitize\\\/desensitize dialog buttons.\n--\ndialogSetResponseSensitive :: DialogClass self => self\n -> ResponseId -- ^ @responseId@ - a response ID\n -> Bool -- ^ @setting@ - @True@ for sensitive\n -> IO ()\ndialogSetResponseSensitive self responseId setting =\n {# call dialog_set_response_sensitive #}\n (toDialog self)\n (fromResponse responseId)\n (fromBool setting)\n\n-- | Gets the response id of a widget in the action area of a dialog.\ndialogGetResponseForWidget :: (DialogClass self, WidgetClass widget) => self\n -> widget -- ^ @widget@ - a widget in the action area of dialog \n -> IO ResponseId -- ^ return the response id of widget, or 'ResponseNone' if widget doesn't have a response id set. \ndialogGetResponseForWidget self widget = liftM toResponse $\n {# call dialog_get_response_for_widget #}\n (toDialog self)\n (toWidget widget)\n\n-- | Returns @True@ if dialogs are expected to use an alternative button order on the screen screen. \n-- See 'dialogSetAlternativeButtonOrder' for more details about alternative button order.\n--\n-- If you need to use this function, you should probably connect to the 'alternativeButtonOrder' signal on the GtkSettings object associated to screen, in order to be notified if the button order setting changes.\n--\n-- * Available since Gtk+ version 2.6\n--\ndialogAlternativeDialogButtonOrder :: \n Maybe Screen -- ^ @screen@ - a 'Screen', or @Nothing@ to use the default screen \n -> IO Bool -- ^ returns whether the alternative button order should be used \ndialogAlternativeDialogButtonOrder (Just screen) = liftM toBool $\n {# call alternative_dialog_button_order #} screen\ndialogAlternativeDialogButtonOrder Nothing = liftM toBool $\n {# call alternative_dialog_button_order #} (Screen nullForeignPtr)\n\n-- | Sets an alternative button order.\n-- \n-- If the 'alternativeButtonOrder' setting is set to @True@, the dialog\n-- buttons are reordered according to the order of the response ids in\n-- @newOrder@.\n--\n-- See 'dialogSetAlternativeButtonOrder' for more information.\n--\n-- This function is for use by language bindings.\n--\n-- * Available since Gtk+ version 2.6\n--\ndialogSetAlternativeButtonOrderFromArray :: DialogClass self => self\n -> [ResponseId] -- ^ @newOrder@ - an array of response ids of dialog's buttons \n -> IO ()\ndialogSetAlternativeButtonOrderFromArray self newOrder = \n withArray (map fromResponse newOrder) $ \\newOrderPtr ->\n {# call dialog_set_alternative_button_order_from_array #}\n (toDialog self)\n (fromIntegral (length newOrder))\n newOrderPtr\n\n--------------------\n-- Attributes\n\n-- | The dialog has a separator bar above its buttons.\n--\n-- Default value: @True@\n--\ndialogHasSeparator :: DialogClass self => Attr self Bool\ndialogHasSeparator = newAttr\n dialogGetHasSeparator\n dialogSetHasSeparator\n\n-- | Width of border around the button area at the bottom of the dialog.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 5\n--\ndialogActionAreaBorder :: DialogClass self => ReadAttr self Int\ndialogActionAreaBorder = readAttrFromIntProperty \"action-area-border\"\n\n-- | Spacing between buttons.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 6\n--\ndialogButtonSpacing :: DialogClass self => ReadAttr self Int\ndialogButtonSpacing = readAttrFromIntProperty \"button-spacing\"\n\n-- | Width of border around the main dialog area.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 2\n--\ndialogContentAreaBorder :: DialogClass self => ReadAttr self Int\ndialogContentAreaBorder = readAttrFromIntProperty \"content-area-border\"\n\n-- | The default spacing used between elements of the content area of the dialog, \n-- as returned by 'dialogSetContentArea', unless 'boxSetSpacing' was called on that widget directly.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\n-- * Available since Gtk+ version 2.16\n--\ndialogContentAreaSpacing :: DialogClass self => ReadAttr self Int\ndialogContentAreaSpacing = readAttrFromIntProperty \"content-area-spacing\"\n\n--------------------\n-- Signals\n\n-- | Emitted when an action widget is clicked, the dialog receives a delete\n-- event, or the application programmer calls 'dialogResponse'. On a delete\n-- event, the response ID is 'ResponseNone'. Otherwise, it depends on which\n-- action widget was clicked.\n--\nresponse :: DialogClass self => Signal self (ResponseId -> IO ())\nresponse = Signal (\\after obj fun ->\n connect_INT__NONE \"response\" after obj (\\i -> fun (toResponse i)))\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n-- | Emitted when an action widget is clicked, the dialog receives a delete\n-- event, or the application programmer calls 'dialogResponse'. On a delete\n-- event, the response ID is 'ResponseNone'. Otherwise, it depends on which\n-- action widget was clicked.\n--\nonResponse, afterResponse :: DialogClass self => self\n -> (ResponseId -> IO ())\n -> IO (ConnectId self)\nonResponse dia act = connect_INT__NONE \"response\" False dia (act . toResponse)\nafterResponse dia act = connect_INT__NONE \"response\" True dia (act . toResponse)\n#endif","old_contents":"{-# LANGUAGE CPP #-}\n-- -*-haskell-*-\n-- GIMP Toolkit (GTK) Widget Dialog\n--\n-- Author : Axel Simon, Andy Stewart\n--\n-- Created: 23 May 2001\n--\n-- Copyright (C) 1999-2005 Axel Simon\n-- Copyright (C) 2009 Andy Stewart\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- Create popup windows\n-- \n-- NOTE: \n-- Now FFI haven't support variadic function `gtk_dialog_set_alternative_button_order`\n--\nmodule Graphics.UI.Gtk.Windows.Dialog (\n-- * Detail\n-- \n-- | Dialog boxes are a convenient way to prompt the user for a small amount\n-- of input, e.g. to display a message, ask a question, or anything else that\n-- does not require extensive effort on the user's part.\n--\n-- Gtk+ treats a dialog as a window split vertically. The top section is a\n-- 'VBox', and is where widgets such as a 'Label' or a 'Entry' should be\n-- packed. The bottom area is known as the action_area. This is generally used\n-- for packing buttons into the dialog which may perform functions such as\n-- cancel, ok, or apply. The two areas are separated by a 'HSeparator'.\n--\n-- 'Dialog' boxes are created with a call to 'dialogNew' or\n-- 'dialogNewWithButtons'. 'dialogNewWithButtons' is recommended; it allows you\n-- to set the dialog title, some convenient flags, and add simple buttons.\n--\n-- If \\'dialog\\' is a newly created dialog, the two primary areas of the\n-- window can be accessed using 'dialogGetUpper' and\n-- 'dialogGetActionArea'.\n--\n-- A \\'modal\\' dialog (that is, one which freezes the rest of the\n-- application from user input), can be created by calling 'windowSetModal' on\n-- the dialog. When using 'dialogNewWithButtons' you can also\n-- pass the 'DialogModal' flag to make a dialog modal.\n--\n-- If you add buttons to 'Dialog' using 'dialogNewWithButtons',\n-- 'dialogAddButton', 'dialogAddButtons', or 'dialogAddActionWidget', clicking\n-- the button will emit a signal called \\\"response\\\" with a response ID that\n-- you specified. Gtk+ will never assign a meaning to positive response IDs;\n-- these are entirely user-defined. But for convenience, you can use the\n-- response IDs in the 'ResponseType' enumeration (these all have values less\n-- than zero). If a dialog receives a delete event, the \\\"response\\\" signal\n-- will be emitted with a response ID of 'ResponseNone'.\n--\n-- If you want to block waiting for a dialog to return before returning\n-- control flow to your code, you can call 'dialogRun'. This function enters a\n-- recursive main loop and waits for the user to respond to the dialog,\n-- returning the response ID corresponding to the button the user clicked.\n--\n-- For a simple message box, you probably want to use \n-- 'Graphics.UI.Gtk.Windows.MessageDialog.MessageDialog' which provides\n-- convenience functions\n-- for creating standard dialogs containing simple messages to inform\n-- or ask the user.\n\n-- * Class Hierarchy\n-- |\n-- @\n-- | 'GObject'\n-- | +----'Object'\n-- | +----'Widget'\n-- | +----'Container'\n-- | +----'Bin'\n-- | +----'Window'\n-- | +----Dialog\n-- | +----'AboutDialog'\n-- | +----'ColorSelectionDialog'\n-- | +----'FileChooserDialog'\n-- | +----'FileSelection'\n-- | +----'FontSelectionDialog'\n-- | +----'InputDialog'\n-- | +----'MessageDialog'\n-- @\n\n-- * Types\n Dialog,\n DialogClass,\n castToDialog,\n toDialog,\n\n-- * Constructors\n dialogNew,\n\n-- * Methods\n dialogGetUpper,\n dialogGetActionArea,\n dialogRun,\n dialogResponse,\n ResponseId(..),\n dialogAddButton,\n dialogAddActionWidget,\n dialogGetHasSeparator,\n dialogSetDefaultResponse,\n dialogSetHasSeparator,\n dialogSetResponseSensitive,\n dialogGetResponseForWidget,\n alternativeDialogButtonOrder,\n dialogSetAlternativeButtonOrderFromArray,\n\n-- * Attributes\n dialogHasSeparator,\n dialogActionAreaBorder,\n dialogButtonSpacing,\n dialogContentAreaBorder,\n dialogContentAreaSpacing,\n\n-- * Signals\n close,\n response,\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n onResponse,\n afterResponse,\n#endif\n ) where\n\nimport Control.Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.UTFString\nimport System.Glib.Attributes\nimport System.Glib.Properties\nimport Graphics.UI.Gtk.Abstract.Object\t(makeNewObject)\n{#import Graphics.UI.Gtk.Types#}\n{#import Graphics.UI.Gtk.Signals#}\nimport Graphics.UI.Gtk.General.Structs\t(dialogGetUpper, dialogGetActionArea,\n\t\t\t\t\tResponseId(..), fromResponse, toResponse)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n--------------------\n-- Constructors\n\n-- | Creates a new dialog box. Widgets should not be packed into this 'Window'\n-- directly, but into the \\\"upper\\\" and \\\"action area\\\", which are obtained\n-- using 'dialogGetUpper' and 'dialogGetActionArea'.\n--\ndialogNew :: IO Dialog\ndialogNew =\n makeNewObject mkDialog $\n liftM (castPtr :: Ptr Widget -> Ptr Dialog) $\n {# call unsafe dialog_new #}\n\n--------------------\n-- Methods\n\n-- | Blocks in a recursive main loop until the dialog either emits the\n-- response signal, or is destroyed. If the dialog is destroyed during the call\n-- to 'dialogRun', it returns 'ResponseNone'. Otherwise, it returns the\n-- response ID from the \\\"response\\\" signal emission. Before entering the\n-- recursive main loop, 'dialogRun' calls 'widgetShow' on the dialog for you.\n-- Note that you still need to show any children of the dialog yourself.\n--\n-- During 'dialogRun', the default behavior of \\\"delete_event\\\" is disabled;\n-- if the dialog receives \\\"delete_event\\\", it will not be destroyed as windows\n-- usually are, and 'dialogRun' will return 'ResponseDeleteEvent'. Also, during\n-- 'dialogRun' the dialog will be modal. You can force 'dialogRun' to return at\n-- any time by calling 'dialogResponse' to emit the \\\"response\\\" signal.\n-- Destroying the dialog during 'dialogRun' is a very bad idea, because your\n-- post-run code won't know whether the dialog was destroyed or not.\n-- Hence, you should not call 'Graphics.UI.Gtk.Abstract.widgetDestroy'\n-- before 'dialogRun' has returned.\n--\n-- After 'dialogRun' returns, you are responsible for hiding or destroying\n-- the dialog if you wish to do so.\n--\n-- Note that even though the recursive main loop gives the effect of a modal\n-- dialog (it prevents the user from interacting with other windows while the\n-- dialog is run), callbacks such as timeouts, IO channel watches, DND drops,\n-- etc, \/will\/ be triggered during a 'dialogRun' call.\n--\ndialogRun :: DialogClass self => self\n -> IO ResponseId\ndialogRun self =\n liftM toResponse $\n {# call dialog_run #}\n (toDialog self)\n\n-- | Emits the \\\"response\\\" signal with the given response ID. Used to\n-- indicate that the user has responded to the dialog in some way; typically\n-- either you or 'dialogRun' will be monitoring the \\\"response\\\" signal and\n-- take appropriate action.\n--\n-- This function can be used to add a custom widget to the action area that\n-- should close the dialog when activated or to close the dialog otherwise.\n--\ndialogResponse :: DialogClass self => self\n -> ResponseId\n -> IO ()\ndialogResponse self responseId =\n {# call dialog_response #}\n (toDialog self)\n (fromResponse responseId)\n\n-- | Adds a button with the given text (or a stock button, if @buttonText@ is\n-- a stock ID) and sets things up so that clicking the button will emit the\n-- \\\"response\\\" signal with the given @responseId@. The button is appended to\n-- the end of the dialog's action area. The button widget is returned, but\n-- usually you don't need it.\n--\ndialogAddButton :: DialogClass self => self\n -> String -- ^ @buttonText@ - text of button, or stock ID\n -> ResponseId -- ^ @responseId@ - response ID for the button\n -> IO Button -- ^ returns the button widget that was added\ndialogAddButton self buttonText responseId =\n makeNewObject mkButton $ liftM castPtr $\n withUTFString buttonText $ \\buttonTextPtr ->\n {# call dialog_add_button #}\n (toDialog self)\n buttonTextPtr\n (fromResponse responseId)\n\n-- | Adds an activatable widget to the action area of a 'Dialog', connecting a\n-- signal handler that will emit the \\\"response\\\" signal on the dialog when the\n-- widget is activated. The widget is appended to the end of the dialog's\n-- action area. If you want to add a non-activatable widget, simply pack it\n-- into the action area.\n--\ndialogAddActionWidget :: (DialogClass self, WidgetClass child) => self\n -> child -- ^ @child@ - an activatable widget\n -> ResponseId -- ^ @responseId@ - response ID for @child@\n -> IO ()\ndialogAddActionWidget self child responseId =\n {# call dialog_add_action_widget #}\n (toDialog self)\n (toWidget child)\n (fromResponse responseId)\n\n-- | Query if the dialog has a visible horizontal separator.\n--\ndialogGetHasSeparator :: DialogClass self => self -> IO Bool\ndialogGetHasSeparator self =\n liftM toBool $\n {# call unsafe dialog_get_has_separator #}\n (toDialog self)\n\n-- | Sets the last widget in the dialog's action area with the given\n-- 'ResponseId' as the default widget for the dialog. Pressing \\\"Enter\\\"\n-- normally activates the default widget.\n--\n-- * The default response is reset once it is triggered. Hence, if you\n-- hide the dialog (rather than closing it) and re-display it later,\n-- you need to call this function again.\n--\ndialogSetDefaultResponse :: DialogClass self => self\n -> ResponseId\n -> IO ()\ndialogSetDefaultResponse self responseId =\n {# call dialog_set_default_response #}\n (toDialog self)\n (fromResponse responseId)\n\n-- | Sets whether the dialog has a separator above the buttons. @True@ by\n-- default.\n--\ndialogSetHasSeparator :: DialogClass self => self -> Bool -> IO ()\ndialogSetHasSeparator self setting =\n {# call dialog_set_has_separator #}\n (toDialog self)\n (fromBool setting)\n\n-- | Calls @'widgetSetSensitive' widget setting@ for each widget in the\n-- dialog's action area with the given @responseId@. A convenient way to\n-- sensitize\\\/desensitize dialog buttons.\n--\ndialogSetResponseSensitive :: DialogClass self => self\n -> ResponseId -- ^ @responseId@ - a response ID\n -> Bool -- ^ @setting@ - @True@ for sensitive\n -> IO ()\ndialogSetResponseSensitive self responseId setting =\n {# call dialog_set_response_sensitive #}\n (toDialog self)\n (fromResponse responseId)\n (fromBool setting)\n\n-- | Gets the response id of a widget in the action area of a dialog.\ndialogGetResponseForWidget :: (DialogClass self, WidgetClass widget) => self\n -> widget -- ^ @widget@ - a widget in the action area of dialog \n -> IO Int -- ^ return the response id of widget, or 'ResponseNone' if widget doesn't have a response id set. \ndialogGetResponseForWidget self widget = liftM fromIntegral $\n {# call dialog_get_response_for_widget #}\n (toDialog self)\n (toWidget widget)\n\n-- | Returns @True@ if dialogs are expected to use an alternative button order on the screen screen. \n-- See 'dialogSetAlternativeButtonOrder' for more details about alternative button order.\n--\n-- If you need to use this function, you should probably connect to the 'alternativeButtonOrder' signal on the GtkSettings object associated to screen, in order to be notified if the button order setting changes.\n--\n-- * Available since Gtk+ version 2.6\n--\nalternativeDialogButtonOrder :: \n Maybe Screen -- ^ @screen@ - a 'Screen', or @Nothing@ to use the default screen \n -> IO Bool -- ^ return Whether the alternative button order should be used \nalternativeDialogButtonOrder (Just screen) = liftM toBool $\n {# call alternative_dialog_button_order #} screen\nalternativeDialogButtonOrder Nothing = liftM toBool $\n {# call alternative_dialog_button_order #} (Screen nullForeignPtr)\n\n-- | Sets an alternative button order. \n-- If the 'alternativeButtonOrder' setting is set to @True@, the dialog buttons are reordered according to the order of the response ids in new_order.\n--\n-- See 'dialogSetAlternativeButtonOrder' for more information.\n--\n-- This function is for use by language bindings.\n--\n-- * Available since Gtk+ version 2.6\n--\ndialogSetAlternativeButtonOrderFromArray :: DialogClass self => self\n -> Int -- ^ @nParams@ - the number of response ids in new_order \n -> [Int] -- ^ @newOrder@ - an array of response ids of dialog's buttons \n -> IO ()\ndialogSetAlternativeButtonOrderFromArray self nParams newOrder = \n withArray (map fromIntegral newOrder) $ \\newOrderPtr ->\n {# call dialog_set_alternative_button_order_from_array #}\n (toDialog self)\n (fromIntegral nParams)\n newOrderPtr\n\n--------------------\n-- Attributes\n\n-- | The dialog has a separator bar above its buttons.\n--\n-- Default value: @True@\n--\ndialogHasSeparator :: DialogClass self => Attr self Bool\ndialogHasSeparator = newAttr\n dialogGetHasSeparator\n dialogSetHasSeparator\n\n-- | Width of border around the button area at the bottom of the dialog.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 5\n--\ndialogActionAreaBorder :: DialogClass self => ReadAttr self Int\ndialogActionAreaBorder = readAttrFromIntProperty \"action-area-border\"\n\n-- | Spacing between buttons.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 6\n--\ndialogButtonSpacing :: DialogClass self => ReadAttr self Int\ndialogButtonSpacing = readAttrFromIntProperty \"button-spacing\"\n\n-- | Width of border around the main dialog area.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 2\n--\ndialogContentAreaBorder :: DialogClass self => ReadAttr self Int\ndialogContentAreaBorder = readAttrFromIntProperty \"content-area-border\"\n\n-- | The default spacing used between elements of the content area of the dialog, \n-- as returned by 'dialogSetContentArea', unless 'boxSetSpacing' was called on that widget directly.\n--\n-- Allowed values: >= 0\n--\n-- Default value: 0\n--\n-- * Available since Gtk+ version 2.16\n--\ndialogContentAreaSpacing :: DialogClass self => ReadAttr self Int\ndialogContentAreaSpacing = readAttrFromIntProperty \"content-area-spacing\"\n\n--------------------\n-- Signals\nclose :: DialogClass self => Signal self (IO ())\nclose = Signal (connect_NONE__NONE \"close\")\n\nresponse :: DialogClass self => Signal self (Int -> IO ())\nresponse = Signal (connect_INT__NONE \"response\")\n\n-- * Deprecated\n#ifndef DISABLE_DEPRECATED\n-- | Emitted when an action widget is clicked, the dialog receives a delete\n-- event, or the application programmer calls 'dialogResponse'. On a delete\n-- event, the response ID is 'ResponseNone'. Otherwise, it depends on which\n-- action widget was clicked.\n--\nonResponse, afterResponse :: DialogClass self => self\n -> (ResponseId -> IO ())\n -> IO (ConnectId self)\nonResponse dia act = connect_INT__NONE \"response\" False dia (act . toResponse)\nafterResponse dia act = connect_INT__NONE \"response\" True dia (act . toResponse)\n#endif","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"6cd9e7268ac4afba89831a4a78f13bdd8ab67a67","subject":"expose Types and flags constructors in System.GIO.File","message":"expose Types and flags constructors in System.GIO.File\n\ndarcs-hash:20081124001402-ac6dd-4137de7b0d62d00dbde8bd4e816f1208c770fc2e.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"gio\/System\/GIO\/File.chs","new_file":"gio\/System\/GIO\/File.chs","new_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gio -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 13-Oct-2008\n--\n-- Copyright (c) 2008 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GIO, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GIO documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.GIO.File (\n module System.GIO.Types,\n FileQueryInfoFlags(..),\n FileCreateFlags(..),\n FileCopyFlags(..),\n FileMonitorFlags(..),\n FilesystemPreviewType(..),\n FileProgressCallback,\n FileReadMoreCallback,\n fileFromPath,\n fileFromURI,\n fileFromCommandlineArg,\n fileFromParseName,\n fileEqual,\n fileBasename,\n filePath,\n fileURI,\n fileParseName,\n fileGetChild,\n fileGetChildForDisplayName,\n fileHasPrefix,\n fileGetRelativePath,\n fileResolveRelativePath,\n fileIsNative,\n fileHasURIScheme,\n fileURIScheme,\n fileRead,\n fileReadAsync,\n fileReadFinish,\n fileAppendTo,\n fileCreate,\n fileReplace,\n fileAppendToAsync,\n fileAppendToFinish,\n fileCreateAsync,\n fileCreateFinish,\n fileReplaceAsync,\n fileReplaceFinish,\n fileQueryInfo,\n fileQueryInfoAsync,\n fileQueryInfoFinish,\n fileQueryExists,\n fileQueryFilesystemInfo,\n fileQueryFilesystemInfoAsync,\n fileQueryFilesystemInfoFinish,\n fileQueryDefaultHandler,\n fileFindEnclosingMount,\n fileFindEnclosingMountAsync,\n fileFindEnclosingMountFinish,\n fileEnumerateChildren,\n fileEnumerateChildrenAsync,\n fileEnumerateChildrenFinish,\n fileSetDisplayName,\n fileSetDisplayNameAsync,\n fileSetDisplayNameFinish,\n fileDelete,\n fileTrash,\n fileCopy,\n fileCopyAsync,\n fileCopyFinish,\n fileMove,\n fileMakeDirectory,\n fileMakeDirectoryWithParents,\n fileMakeSymbolicLink,\n fileQuerySettableAttributes,\n fileQueryWritableNamespaces\n ) where\n\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport Data.Typeable\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.UTFString\n\nimport System.GIO.Base\n{#import System.GIO.Types#}\nimport System.GIO.FileAttribute\n\n{# context lib = \"gio\" prefix = \"g\" #}\n\n{# enum GFileQueryInfoFlags as FileQueryInfoFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileQueryInfoFlags\n\n{# enum GFileCreateFlags as FileCreateFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCreateFlags\n\n{# enum GFileCopyFlags as FileCopyFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCopyFlags\n\n{# enum GFileMonitorFlags as FileMonitorFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileMonitorFlags\n\n{# enum GFilesystemPreviewType as FilesystemPreviewType {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\ntype FileProgressCallback = Offset -> Offset -> IO ()\ntype CFileProgressCallback = {# type goffset #} -> {# type goffset #} -> Ptr () -> IO ()\nforeign import ccall \"wrapper\"\n makeFileProgressCallback :: CFileProgressCallback\n -> IO {# type GFileProgressCallback #}\n\nmarshalFileProgressCallback :: FileProgressCallback -> IO {# type GFileProgressCallback #}\nmarshalFileProgressCallback fileProgressCallback =\n makeFileProgressCallback cFileProgressCallback\n where cFileProgressCallback :: CFileProgressCallback\n cFileProgressCallback cCurrentNumBytes cTotalNumBytes _ = do\n fileProgressCallback (fromIntegral cCurrentNumBytes)\n (fromIntegral cTotalNumBytes)\n\ntype FileReadMoreCallback = BS.ByteString -> IO Bool\n\nfileFromPath :: FilePath -> File\nfileFromPath path =\n unsafePerformIO $ withUTFString path $ \\cPath -> {# call file_new_for_path #} cPath >>= takeGObject\n\nfileFromURI :: String -> File\nfileFromURI uri =\n unsafePerformIO $ withUTFString uri $ \\cURI -> {# call file_new_for_uri #} cURI >>= takeGObject\n\nfileFromCommandlineArg :: String -> File\nfileFromCommandlineArg arg =\n unsafePerformIO $ withUTFString arg $ \\cArg -> {# call file_new_for_commandline_arg #} cArg >>= takeGObject\n\nfileFromParseName :: String -> File\nfileFromParseName parseName =\n unsafePerformIO $ withUTFString parseName $ \\cParseName -> {# call file_parse_name #} cParseName >>= takeGObject\n\nfileEqual :: (FileClass file1, FileClass file2)\n => file1 -> file2 -> Bool\nfileEqual file1 file2 =\n unsafePerformIO $ liftM toBool $ {# call file_equal #} (toFile file1) (toFile file2)\n\ninstance Eq File where\n (==) = fileEqual\n\nfileBasename :: FileClass file => file -> String\nfileBasename file =\n unsafePerformIO $ {# call file_get_basename #} (toFile file) >>= readUTFString\n\nfilePath :: FileClass file => file -> FilePath\nfilePath file =\n unsafePerformIO $ {# call file_get_path #} (toFile file) >>= readUTFString\n\nfileURI :: FileClass file => file -> String\nfileURI file =\n unsafePerformIO $ {# call file_get_uri #} (toFile file) >>= readUTFString\n\nfileParseName :: FileClass file => file -> String\nfileParseName file =\n unsafePerformIO $ {# call file_get_parse_name #} (toFile file) >>= readUTFString\n\nfileParent :: FileClass file => file -> Maybe File\nfileParent file =\n unsafePerformIO $ {# call file_get_parent #} (toFile file) >>= maybePeek takeGObject\n\nfileGetChild :: FileClass file => file -> String -> File\nfileGetChild file name =\n unsafePerformIO $\n withUTFString name $ \\cName ->\n {# call file_get_child #} (toFile file) cName >>= takeGObject\n\nfileGetChildForDisplayName :: FileClass file => file -> String -> Maybe File\nfileGetChildForDisplayName file displayName =\n unsafePerformIO $\n withUTFString displayName $ \\cDisplayName ->\n propagateGError ({# call file_get_child_for_display_name #} (toFile file) cDisplayName) >>=\n maybePeek takeGObject\n\nfileHasPrefix :: (FileClass file1, FileClass file2) => file1 -> file2 -> Bool\nfileHasPrefix file1 file2 =\n unsafePerformIO $\n liftM toBool $ {# call file_has_prefix #} (toFile file1) (toFile file2)\n\nfileGetRelativePath :: (FileClass file1, FileClass file2) => file1 -> file2 -> Maybe FilePath\nfileGetRelativePath file1 file2 =\n unsafePerformIO $\n {# call file_get_relative_path #} (toFile file1) (toFile file2) >>=\n maybePeek readUTFString\n\nfileResolveRelativePath :: FileClass file => file -> FilePath -> Maybe File\nfileResolveRelativePath file relativePath =\n unsafePerformIO $\n withUTFString relativePath $ \\cRelativePath ->\n {# call file_resolve_relative_path #} (toFile file) cRelativePath >>=\n maybePeek takeGObject\n\nfileIsNative :: FileClass file => file -> Bool\nfileIsNative =\n unsafePerformIO .\n liftM toBool . {# call file_is_native #} . toFile\n\nfileHasURIScheme :: FileClass file => file -> String -> Bool\nfileHasURIScheme file uriScheme =\n unsafePerformIO $\n withUTFString uriScheme $ \\cURIScheme ->\n liftM toBool $ {# call file_has_uri_scheme #} (toFile file) cURIScheme\n\nfileURIScheme :: FileClass file => file -> String\nfileURIScheme file =\n unsafePerformIO $ {# call file_get_uri_scheme #} (toFile file) >>= readUTFString\n\nfileRead :: FileClass file => file -> Maybe Cancellable -> IO FileInputStream\nfileRead file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_read cFile cCancellable) >>= takeGObject\n where _ = {# call file_read #}\n\nfileReadAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReadAsync file ioPriority mbCancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject mbCancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_read_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_read_async #}\n\nfileReadFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInputStream\nfileReadFinish file asyncResult =\n propagateGError ({# call file_read_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileAppendTo :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileAppendTo file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_append_to cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_append_to #}\n\nfileCreate :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileCreate file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_create cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_create #}\n\nfileReplace :: FileClass file\n => file\n -> Maybe String\n -> Bool\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileReplace file etag makeBackup flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_replace cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_replace #}\n\nfileAppendToAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileAppendToAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_append_to_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_append_to_async #}\n\nfileAppendToFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileAppendToFinish file asyncResult =\n propagateGError ({# call file_append_to_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileCreateAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileCreateAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_create_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_create_async #}\n\nfileCreateFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileCreateFinish file asyncResult =\n propagateGError ({# call file_create_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileReplaceAsync :: FileClass file\n => file\n -> String\n -> Bool\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReplaceAsync file etag makeBackup flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_replace_async cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_replace_async #}\n\nfileReplaceFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileReplaceFinish file asyncResult =\n propagateGError ({# call file_replace_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileQueryInfo :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryInfo file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_info cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_query_info #}\n\nfileQueryInfoAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryInfoAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_info_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_info_async #}\n\nfileQueryInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryInfoFinish file asyncResult =\n propagateGError ({#call file_query_info_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileQueryExists :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Bool\nfileQueryExists file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n liftM toBool $ g_file_query_exists cFile cCancellable\n where _ = {# call file_query_exists #}\n\nfileQueryFilesystemInfo :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryFilesystemInfo file attributes cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_filesystem_info cFile cAttributes cCancellable) >>=\n takeGObject\n where _ = {# call file_query_filesystem_info #}\n\nfileQueryFilesystemInfoAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryFilesystemInfoAsync file attributes ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_filesystem_info_async cFile\n cAttributes\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_filesystem_info_async #}\n\nfileQueryFilesystemInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryFilesystemInfoFinish file asyncResult =\n propagateGError ({# call file_query_filesystem_info_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileQueryDefaultHandler :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO AppInfo\nfileQueryDefaultHandler file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_default_handler cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_query_default_handler #}\n\nfileFindEnclosingMount :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Mount\nfileFindEnclosingMount file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_find_enclosing_mount cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_find_enclosing_mount #}\n\nfileFindEnclosingMountAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileFindEnclosingMountAsync file ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_find_enclosing_mount_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_find_enclosing_mount_async #}\n\nfileFindEnclosingMountFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Mount\nfileFindEnclosingMountFinish file asyncResult =\n propagateGError ({# call file_find_enclosing_mount_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileEnumerateChildren :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileEnumerator\nfileEnumerateChildren file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_enumerate_children cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_enumerate_children #}\n\nfileEnumerateChildrenAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileEnumerateChildrenAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_enumerate_children_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_enumerate_children_async #}\n\nfileEnumerateChildrenFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileEnumerator\nfileEnumerateChildrenFinish file asyncResult =\n propagateGError ({# call file_enumerate_children_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileSetDisplayName :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO File\nfileSetDisplayName file displayName cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_set_display_name cFile cDisplayName cCancellable) >>=\n takeGObject\n where _ = {# call file_set_display_name #}\n\nfileSetDisplayNameAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileSetDisplayNameAsync file displayName ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_set_display_name_async cFile\n cDisplayName\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_set_display_name_async #}\n\nfileSetDisplayNameFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO File\nfileSetDisplayNameFinish file asyncResult =\n propagateGError ({# call file_set_display_name_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileDelete :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileDelete file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_delete cFile cCancellable) >> return ()\n where _ = {# call file_delete #}\n\nfileTrash :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileTrash file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_trash cFile cCancellable) >> return ()\n where _ = {# call file_trash #}\n\nfileCopy :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileCopy source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_copy cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_copy #}\n\nfileCopyAsync :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Int\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> AsyncReadyCallback\n -> IO ()\nfileCopyAsync source destination flags ioPriority cancellable progressCallback callback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n cCallback <- marshalAsyncReadyCallback $ \\sourceObject res -> do\n freeHaskellFunPtr cProgressCallback\n callback sourceObject res\n g_file_copy_async cSource\n cDestination\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cProgressCallback\n nullPtr\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_copy_async #}\n\nfileCopyFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Bool\nfileCopyFinish file asyncResult =\n liftM toBool $ propagateGError ({# call file_copy_finish #} (toFile file) asyncResult)\n\nfileMove :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileMove source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_move cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_move #}\n\nfileMakeDirectory :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectory file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory cFile cCancellable\n return ()\n where _ = {# call file_make_directory #}\n\nfileMakeDirectoryWithParents :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectoryWithParents file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory_with_parents cFile cCancellable\n return ()\n where _ = {# call file_make_directory_with_parents #}\n\nfileMakeSymbolicLink :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO ()\nfileMakeSymbolicLink file symlinkValue cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString symlinkValue $ \\cSymlinkValue ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_symbolic_link cFile cSymlinkValue cCancellable\n return ()\n where _ = {# call file_make_symbolic_link #}\n\n{# pointer *FileAttributeInfoList newtype #}\ntakeFileAttributeInfoList :: Ptr FileAttributeInfoList\n -> IO [FileAttributeInfo]\ntakeFileAttributeInfoList ptr =\n do cInfos <- liftM castPtr $ {# get FileAttributeInfoList->infos #} ptr\n cNInfos <- {# get FileAttributeInfoList->n_infos #} ptr\n infos <- peekArray (fromIntegral cNInfos) cInfos\n g_file_attribute_info_list_unref ptr\n return infos\n where _ = {# call file_attribute_info_list_unref #}\n\nfileQuerySettableAttributes :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO [FileAttributeInfo]\nfileQuerySettableAttributes file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n ptr <- propagateGError $ g_file_query_settable_attributes cFile cCancellable\n infos <- takeFileAttributeInfoList ptr\n return infos\n where _ = {# call file_query_settable_attributes #}\n\nfileQueryWritableNamespaces :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO [FileAttributeInfo]\nfileQueryWritableNamespaces file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n ptr <- propagateGError $ g_file_query_writable_namespaces cFile cCancellable\n infos <- takeFileAttributeInfoList ptr\n return infos\n where _ = {# call file_query_writable_namespaces #}\n\n","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gio -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 13-Oct-2008\n--\n-- Copyright (c) 2008 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GIO, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GIO documentation.\n-- \n-- | Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\nmodule System.GIO.File (\n File,\n FileClass,\n FileQueryInfoFlags,\n FileCreateFlags,\n FileCopyFlags,\n FileMonitorFlags,\n FilesystemPreviewType,\n FileProgressCallback,\n FileReadMoreCallback,\n fileFromPath,\n fileFromURI,\n fileFromCommandlineArg,\n fileFromParseName,\n fileEqual,\n fileBasename,\n filePath,\n fileURI,\n fileParseName,\n fileGetChild,\n fileGetChildForDisplayName,\n fileHasPrefix,\n fileGetRelativePath,\n fileResolveRelativePath,\n fileIsNative,\n fileHasURIScheme,\n fileURIScheme,\n fileRead,\n fileReadAsync,\n fileReadFinish,\n fileAppendTo,\n fileCreate,\n fileReplace,\n fileAppendToAsync,\n fileAppendToFinish,\n fileCreateAsync,\n fileCreateFinish,\n fileReplaceAsync,\n fileReplaceFinish,\n fileQueryInfo,\n fileQueryInfoAsync,\n fileQueryInfoFinish,\n fileQueryExists,\n fileQueryFilesystemInfo,\n fileQueryFilesystemInfoAsync,\n fileQueryFilesystemInfoFinish,\n fileQueryDefaultHandler,\n fileFindEnclosingMount,\n fileFindEnclosingMountAsync,\n fileFindEnclosingMountFinish,\n fileEnumerateChildren,\n fileEnumerateChildrenAsync,\n fileEnumerateChildrenFinish,\n fileSetDisplayName,\n fileSetDisplayNameAsync,\n fileSetDisplayNameFinish,\n fileDelete,\n fileTrash,\n fileCopy,\n fileCopyAsync,\n fileCopyFinish,\n fileMove,\n fileMakeDirectory,\n fileMakeDirectoryWithParents,\n fileMakeSymbolicLink,\n fileQuerySettableAttributes,\n fileQueryWritableNamespaces\n ) where\n\nimport Control.Monad\nimport qualified Data.ByteString as BS\nimport Data.Typeable\n\nimport System.Glib.FFI\nimport System.Glib.Flags\nimport System.Glib.GError\nimport System.Glib.UTFString\n\nimport System.GIO.Base\n{#import System.GIO.Types#}\nimport System.GIO.FileAttribute\n\n{# context lib = \"gio\" prefix = \"g\" #}\n\n{# enum GFileQueryInfoFlags as FileQueryInfoFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileQueryInfoFlags\n\n{# enum GFileCreateFlags as FileCreateFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCreateFlags\n\n{# enum GFileCopyFlags as FileCopyFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileCopyFlags\n\n{# enum GFileMonitorFlags as FileMonitorFlags {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\ninstance Flags FileMonitorFlags\n\n{# enum GFilesystemPreviewType as FilesystemPreviewType {underscoreToCase} with prefix = \"G\" deriving (Eq, Ord, Bounded, Show, Typeable) #}\n\ntype FileProgressCallback = Offset -> Offset -> IO ()\ntype CFileProgressCallback = {# type goffset #} -> {# type goffset #} -> Ptr () -> IO ()\nforeign import ccall \"wrapper\"\n makeFileProgressCallback :: CFileProgressCallback\n -> IO {# type GFileProgressCallback #}\n\nmarshalFileProgressCallback :: FileProgressCallback -> IO {# type GFileProgressCallback #}\nmarshalFileProgressCallback fileProgressCallback =\n makeFileProgressCallback cFileProgressCallback\n where cFileProgressCallback :: CFileProgressCallback\n cFileProgressCallback cCurrentNumBytes cTotalNumBytes _ = do\n fileProgressCallback (fromIntegral cCurrentNumBytes)\n (fromIntegral cTotalNumBytes)\n\ntype FileReadMoreCallback = BS.ByteString -> IO Bool\n\nfileFromPath :: FilePath -> File\nfileFromPath path =\n unsafePerformIO $ withUTFString path $ \\cPath -> {# call file_new_for_path #} cPath >>= takeGObject\n\nfileFromURI :: String -> File\nfileFromURI uri =\n unsafePerformIO $ withUTFString uri $ \\cURI -> {# call file_new_for_uri #} cURI >>= takeGObject\n\nfileFromCommandlineArg :: String -> File\nfileFromCommandlineArg arg =\n unsafePerformIO $ withUTFString arg $ \\cArg -> {# call file_new_for_commandline_arg #} cArg >>= takeGObject\n\nfileFromParseName :: String -> File\nfileFromParseName parseName =\n unsafePerformIO $ withUTFString parseName $ \\cParseName -> {# call file_parse_name #} cParseName >>= takeGObject\n\nfileEqual :: (FileClass file1, FileClass file2)\n => file1 -> file2 -> Bool\nfileEqual file1 file2 =\n unsafePerformIO $ liftM toBool $ {# call file_equal #} (toFile file1) (toFile file2)\n\ninstance Eq File where\n (==) = fileEqual\n\nfileBasename :: FileClass file => file -> String\nfileBasename file =\n unsafePerformIO $ {# call file_get_basename #} (toFile file) >>= readUTFString\n\nfilePath :: FileClass file => file -> FilePath\nfilePath file =\n unsafePerformIO $ {# call file_get_path #} (toFile file) >>= readUTFString\n\nfileURI :: FileClass file => file -> String\nfileURI file =\n unsafePerformIO $ {# call file_get_uri #} (toFile file) >>= readUTFString\n\nfileParseName :: FileClass file => file -> String\nfileParseName file =\n unsafePerformIO $ {# call file_get_parse_name #} (toFile file) >>= readUTFString\n\nfileParent :: FileClass file => file -> Maybe File\nfileParent file =\n unsafePerformIO $ {# call file_get_parent #} (toFile file) >>= maybePeek takeGObject\n\nfileGetChild :: FileClass file => file -> String -> File\nfileGetChild file name =\n unsafePerformIO $\n withUTFString name $ \\cName ->\n {# call file_get_child #} (toFile file) cName >>= takeGObject\n\nfileGetChildForDisplayName :: FileClass file => file -> String -> Maybe File\nfileGetChildForDisplayName file displayName =\n unsafePerformIO $\n withUTFString displayName $ \\cDisplayName ->\n propagateGError ({# call file_get_child_for_display_name #} (toFile file) cDisplayName) >>=\n maybePeek takeGObject\n\nfileHasPrefix :: (FileClass file1, FileClass file2) => file1 -> file2 -> Bool\nfileHasPrefix file1 file2 =\n unsafePerformIO $\n liftM toBool $ {# call file_has_prefix #} (toFile file1) (toFile file2)\n\nfileGetRelativePath :: (FileClass file1, FileClass file2) => file1 -> file2 -> Maybe FilePath\nfileGetRelativePath file1 file2 =\n unsafePerformIO $\n {# call file_get_relative_path #} (toFile file1) (toFile file2) >>=\n maybePeek readUTFString\n\nfileResolveRelativePath :: FileClass file => file -> FilePath -> Maybe File\nfileResolveRelativePath file relativePath =\n unsafePerformIO $\n withUTFString relativePath $ \\cRelativePath ->\n {# call file_resolve_relative_path #} (toFile file) cRelativePath >>=\n maybePeek takeGObject\n\nfileIsNative :: FileClass file => file -> Bool\nfileIsNative =\n unsafePerformIO .\n liftM toBool . {# call file_is_native #} . toFile\n\nfileHasURIScheme :: FileClass file => file -> String -> Bool\nfileHasURIScheme file uriScheme =\n unsafePerformIO $\n withUTFString uriScheme $ \\cURIScheme ->\n liftM toBool $ {# call file_has_uri_scheme #} (toFile file) cURIScheme\n\nfileURIScheme :: FileClass file => file -> String\nfileURIScheme file =\n unsafePerformIO $ {# call file_get_uri_scheme #} (toFile file) >>= readUTFString\n\nfileRead :: FileClass file => file -> Maybe Cancellable -> IO FileInputStream\nfileRead file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_read cFile cCancellable) >>= takeGObject\n where _ = {# call file_read #}\n\nfileReadAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReadAsync file ioPriority mbCancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject mbCancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_read_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_read_async #}\n\nfileReadFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInputStream\nfileReadFinish file asyncResult =\n propagateGError ({# call file_read_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileAppendTo :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileAppendTo file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_append_to cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_append_to #}\n\nfileCreate :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileCreate file flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_create cFile (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_create #}\n\nfileReplace :: FileClass file\n => file\n -> Maybe String\n -> Bool\n -> [FileCreateFlags]\n -> Maybe Cancellable\n -> IO FileOutputStream\nfileReplace file etag makeBackup flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_replace cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_replace #}\n\nfileAppendToAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileAppendToAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_append_to_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_append_to_async #}\n\nfileAppendToFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileAppendToFinish file asyncResult =\n propagateGError ({# call file_append_to_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileCreateAsync :: FileClass file\n => file\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileCreateAsync file flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_create_async cFile\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_create_async #}\n\nfileCreateFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileCreateFinish file asyncResult =\n propagateGError ({# call file_create_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileReplaceAsync :: FileClass file\n => file\n -> String\n -> Bool\n -> [FileCreateFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileReplaceAsync file etag makeBackup flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString etag $ \\cEtag ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_replace_async cFile\n cEtag\n (fromBool makeBackup)\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_replace_async #}\n\nfileReplaceFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileOutputStream\nfileReplaceFinish file asyncResult =\n propagateGError ({# call file_replace_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileQueryInfo :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryInfo file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_info cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_query_info #}\n\nfileQueryInfoAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryInfoAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_info_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_info_async #}\n\nfileQueryInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryInfoFinish file asyncResult =\n propagateGError ({#call file_query_info_finish #} (toFile file) asyncResult) >>= takeGObject\n\nfileQueryExists :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Bool\nfileQueryExists file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n liftM toBool $ g_file_query_exists cFile cCancellable\n where _ = {# call file_query_exists #}\n\nfileQueryFilesystemInfo :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO FileInfo\nfileQueryFilesystemInfo file attributes cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_filesystem_info cFile cAttributes cCancellable) >>=\n takeGObject\n where _ = {# call file_query_filesystem_info #}\n\nfileQueryFilesystemInfoAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileQueryFilesystemInfoAsync file attributes ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_query_filesystem_info_async cFile\n cAttributes\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_query_filesystem_info_async #}\n\nfileQueryFilesystemInfoFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileInfo\nfileQueryFilesystemInfoFinish file asyncResult =\n propagateGError ({# call file_query_filesystem_info_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileQueryDefaultHandler :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO AppInfo\nfileQueryDefaultHandler file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_query_default_handler cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_query_default_handler #}\n\nfileFindEnclosingMount :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO Mount\nfileFindEnclosingMount file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_find_enclosing_mount cFile cCancellable) >>=\n takeGObject\n where _ = {# call file_find_enclosing_mount #}\n\nfileFindEnclosingMountAsync :: FileClass file\n => file\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileFindEnclosingMountAsync file ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_find_enclosing_mount_async cFile\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_find_enclosing_mount_async #}\n\nfileFindEnclosingMountFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Mount\nfileFindEnclosingMountFinish file asyncResult =\n propagateGError ({# call file_find_enclosing_mount_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileEnumerateChildren :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Maybe Cancellable\n -> IO FileEnumerator\nfileEnumerateChildren file attributes flags cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_enumerate_children cFile cAttributes (cFromFlags flags) cCancellable) >>=\n takeGObject\n where _ = {# call file_enumerate_children #}\n\nfileEnumerateChildrenAsync :: FileClass file\n => file\n -> String\n -> [FileQueryInfoFlags]\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileEnumerateChildrenAsync file attributes flags ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString attributes $ \\cAttributes ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_enumerate_children_async cFile\n cAttributes\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_enumerate_children_async #}\n\nfileEnumerateChildrenFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO FileEnumerator\nfileEnumerateChildrenFinish file asyncResult =\n propagateGError ({# call file_enumerate_children_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileSetDisplayName :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO File\nfileSetDisplayName file displayName cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_set_display_name cFile cDisplayName cCancellable) >>=\n takeGObject\n where _ = {# call file_set_display_name #}\n\nfileSetDisplayNameAsync :: FileClass file\n => file\n -> String\n -> Int\n -> Maybe Cancellable\n -> AsyncReadyCallback\n -> IO ()\nfileSetDisplayNameAsync file displayName ioPriority cancellable callback =\n withGObject (toFile file) $ \\cFile ->\n withUTFString displayName $ \\cDisplayName ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cCallback <- marshalAsyncReadyCallback callback\n g_file_set_display_name_async cFile\n cDisplayName\n (fromIntegral ioPriority)\n cCancellable\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_set_display_name_async #}\n\nfileSetDisplayNameFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO File\nfileSetDisplayNameFinish file asyncResult =\n propagateGError ({# call file_set_display_name_finish #} (toFile file) asyncResult) >>=\n takeGObject\n\nfileDelete :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileDelete file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_delete cFile cCancellable) >> return ()\n where _ = {# call file_delete #}\n\nfileTrash :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileTrash file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable ->\n propagateGError (g_file_trash cFile cCancellable) >> return ()\n where _ = {# call file_trash #}\n\nfileCopy :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileCopy source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_copy cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_copy #}\n\nfileCopyAsync :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Int\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> AsyncReadyCallback\n -> IO ()\nfileCopyAsync source destination flags ioPriority cancellable progressCallback callback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n cCallback <- marshalAsyncReadyCallback $ \\sourceObject res -> do\n freeHaskellFunPtr cProgressCallback\n callback sourceObject res\n g_file_copy_async cSource\n cDestination\n (cFromFlags flags)\n (fromIntegral ioPriority)\n cCancellable\n cProgressCallback\n nullPtr\n cCallback\n (castFunPtrToPtr cCallback)\n where _ = {# call file_copy_async #}\n\nfileCopyFinish :: FileClass file\n => file\n -> AsyncResult\n -> IO Bool\nfileCopyFinish file asyncResult =\n liftM toBool $ propagateGError ({# call file_copy_finish #} (toFile file) asyncResult)\n\nfileMove :: (FileClass source, FileClass destination)\n => source\n -> destination\n -> [FileCopyFlags]\n -> Maybe Cancellable\n -> Maybe FileProgressCallback\n -> IO Bool\nfileMove source destination flags cancellable progressCallback =\n withGObject (toFile source) $ \\cSource ->\n withGObject (toFile destination) $ \\cDestination ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n cProgressCallback <- maybe (return nullFunPtr) marshalFileProgressCallback progressCallback\n propagateGError $ \\cError -> do\n ret <- g_file_move cSource\n cDestination\n (cFromFlags flags)\n cCancellable\n cProgressCallback\n nullPtr\n cError\n freeHaskellFunPtr cProgressCallback\n return $ toBool ret\n where _ = {# call file_move #}\n\nfileMakeDirectory :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectory file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory cFile cCancellable\n return ()\n where _ = {# call file_make_directory #}\n\nfileMakeDirectoryWithParents :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO ()\nfileMakeDirectoryWithParents file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_directory_with_parents cFile cCancellable\n return ()\n where _ = {# call file_make_directory_with_parents #}\n\nfileMakeSymbolicLink :: FileClass file\n => file\n -> String\n -> Maybe Cancellable\n -> IO ()\nfileMakeSymbolicLink file symlinkValue cancellable =\n withGObject (toFile file) $ \\cFile ->\n withUTFString symlinkValue $ \\cSymlinkValue ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n propagateGError $ g_file_make_symbolic_link cFile cSymlinkValue cCancellable\n return ()\n where _ = {# call file_make_symbolic_link #}\n\n{# pointer *FileAttributeInfoList newtype #}\ntakeFileAttributeInfoList :: Ptr FileAttributeInfoList\n -> IO [FileAttributeInfo]\ntakeFileAttributeInfoList ptr =\n do cInfos <- liftM castPtr $ {# get FileAttributeInfoList->infos #} ptr\n cNInfos <- {# get FileAttributeInfoList->n_infos #} ptr\n infos <- peekArray (fromIntegral cNInfos) cInfos\n g_file_attribute_info_list_unref ptr\n return infos\n where _ = {# call file_attribute_info_list_unref #}\n\nfileQuerySettableAttributes :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO [FileAttributeInfo]\nfileQuerySettableAttributes file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n ptr <- propagateGError $ g_file_query_settable_attributes cFile cCancellable\n infos <- takeFileAttributeInfoList ptr\n return infos\n where _ = {# call file_query_settable_attributes #}\n\nfileQueryWritableNamespaces :: FileClass file\n => file\n -> Maybe Cancellable\n -> IO [FileAttributeInfo]\nfileQueryWritableNamespaces file cancellable =\n withGObject (toFile file) $ \\cFile ->\n maybeWith withGObject cancellable $ \\cCancellable -> do\n ptr <- propagateGError $ g_file_query_writable_namespaces cFile cCancellable\n infos <- takeFileAttributeInfoList ptr\n return infos\n where _ = {# call file_query_writable_namespaces #}\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"febbbd42fd1066162ef61d7db40c9ac620d34a86","subject":"Export CLChannelOrder and CLChannelType types and constructors.","message":"Export CLChannelOrder and CLChannelType types and constructors.\n","repos":"IFCA\/opencl,Delan90\/opencl,IFCA\/opencl,Delan90\/opencl","old_file":"src\/Control\/Parallel\/OpenCL\/Memory.chs","new_file":"src\/Control\/Parallel\/OpenCL\/Memory.chs","new_contents":"{- Copyright (c) 2011 Luis Cabellos,\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided\n with the distribution.\n\n * Neither the name of nor the names of other\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables, CPP #-}\nmodule Control.Parallel.OpenCL.Memory(\n -- * Types\n CLMem, CLSampler, CLMemFlag(..), CLMemObjectType(..), CLAddressingMode(..), \n CLFilterMode(..), CLImageFormat(..), CLChannelOrder(..), CLChannelType(..),\n -- * Memory Functions\n clCreateBuffer, clRetainMemObject, clReleaseMemObject, clGetMemType, \n clGetMemFlags, clGetMemSize, clGetMemHostPtr, clGetMemMapCount, \n clGetMemReferenceCount, clGetMemContext, clCreateFromGLBuffer,\n -- * Image Functions\n clCreateImage2D, clCreateImage3D, clCreateFromGLTexture2D,\n clGetSupportedImageFormats, clGetImageFormat, clGetImageElementSize, \n clGetImageRowPitch, clGetImageSlicePitch, clGetImageWidth, clGetImageHeight, \n clGetImageDepth,\n -- * Sampler Functions\n clCreateSampler, clRetainSampler, clReleaseSampler, clGetSamplerReferenceCount, \n clGetSamplerContext, clGetSamplerAddressingMode, clGetSamplerFilterMode, \n clGetSamplerNormalizedCoords\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Control.Applicative( (<$>), (<*>) )\nimport Control.Parallel.OpenCL.Types( \n CLMem, CLContext, CLSampler, CLint, CLuint, CLbool, CLMemFlags_,\n CLMemInfo_, CLAddressingMode_, CLFilterMode_, CLSamplerInfo_, CLImageInfo_,\n CLAddressingMode(..), CLFilterMode(..), CLMemFlag(..), CLMemObjectType_, \n CLMemObjectType(..), \n wrapPError, wrapCheckSuccess, wrapGetInfo, whenSuccess, getEnumCL, \n bitmaskFromFlags, bitmaskToMemFlags, getCLValue )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\nforeign import CALLCONV \"clCreateBuffer\" raw_clCreateBuffer :: \n CLContext -> CLMemFlags_ -> CSize -> Ptr () -> Ptr CLint -> IO CLMem\nforeign import CALLCONV \"clCreateImage2D\" raw_clCreateImage2D :: \n CLContext -> CLMemFlags_ -> CLImageFormat_p -> CSize -> CSize -> CSize \n -> Ptr () -> Ptr CLint -> IO CLMem\nforeign import CALLCONV \"clCreateImage3D\" raw_clCreateImage3D :: \n CLContext -> CLMemFlags_-> CLImageFormat_p -> CSize -> CSize -> CSize -> CSize \n -> CSize -> Ptr () -> Ptr CLint -> IO CLMem\nforeign import CALLCONV \"clCreateFromGLTexture2D\" raw_clCreateFromGLTexture2D ::\n CLContext -> CLMemFlags_ -> CLuint -> CLint -> CLuint -> Ptr CLint -> IO CLMem\nforeign import CALLCONV \"clCreateFromGLBuffer\" raw_clCreateFromGLBuffer ::\n CLContext -> CLMemFlags_ -> CLuint -> Ptr CLint -> IO CLMem\nforeign import CALLCONV \"clRetainMemObject\" raw_clRetainMemObject :: \n CLMem -> IO CLint\nforeign import CALLCONV \"clReleaseMemObject\" raw_clReleaseMemObject :: \n CLMem -> IO CLint\nforeign import CALLCONV \"clGetSupportedImageFormats\" raw_clGetSupportedImageFormats :: \n CLContext -> CLMemFlags_ -> CLMemObjectType_ -> CLuint -> CLImageFormat_p \n -> Ptr CLuint -> IO CLint\nforeign import CALLCONV \"clGetMemObjectInfo\" raw_clGetMemObjectInfo :: \n CLMem -> CLMemInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clGetImageInfo\" raw_clGetImageInfo ::\n CLMem -> CLImageInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clCreateSampler\" raw_clCreateSampler :: \n CLContext -> CLbool -> CLAddressingMode_ -> CLFilterMode_ -> Ptr CLint -> IO CLSampler\nforeign import CALLCONV \"clRetainSampler\" raw_clRetainSampler :: \n CLSampler -> IO CLint\nforeign import CALLCONV \"clReleaseSampler\" raw_clReleaseSampler :: \n CLSampler -> IO CLint\nforeign import CALLCONV \"clGetSamplerInfo\" raw_clGetSamplerInfo :: \n CLSampler -> CLSamplerInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n{-| Creates a buffer object. Returns a valid non-zero buffer object if the\nbuffer object is created successfully. Otherwise, it throws the 'CLError': \n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_INVALID_VALUE' if values specified in flags are not valid.\n\n * 'CL_INVALID_BUFFER_SIZE' if size is 0 or is greater than\n'clDeviceMaxMemAllocSize' value for all devices in context.\n\n * 'CL_INVALID_HOST_PTR' if host_ptr is NULL and 'CL_MEM_USE_HOST_PTR' or\n'CL_MEM_COPY_HOST_PTR' are set in flags or if host_ptr is not NULL but\n'CL_MEM_COPY_HOST_PTR' or 'CL_MEM_USE_HOST_PTR' are not set in flags.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor buffer object.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n-}\nclCreateBuffer :: Integral a => CLContext -> [CLMemFlag] -> (a, Ptr ()) -> IO CLMem\nclCreateBuffer ctx xs (sbuff,buff) = wrapPError $ \\perr -> do\n raw_clCreateBuffer ctx flags (fromIntegral sbuff) buff perr\n where\n flags = bitmaskFromFlags xs\n\n{-| Creates an OpenCL buffer object from an OpenGL buffer object. Returns a valid non-zero OpenCL buffer object if the buffer object is created successfully. Otherwise it throws the 'CLError':\n * 'CL_INVALID_CONTEXT' if context is not a valid context or was not created from a GL context.\n\n * 'CL_INVALID_VALUE' if values specified in flags are not valid.\n\n * 'CL_INVALID_GL_OBJECT' if bufobj is not a GL buffer object or is a GL buffer object but does not have an existing data store.\n\n * 'CL_OUT_OF_RESOURCES' if there is a failure to allocate resources required by the OpenCL implementation on the device.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required by the OpenCL implementation on the host.\n-}\nclCreateFromGLBuffer :: Integral a => CLContext -> [CLMemFlag] -> a -> IO CLMem\nclCreateFromGLBuffer ctx xs glObj = wrapPError $ \\perr -> do\n raw_clCreateFromGLBuffer ctx flags cglObj perr\n where flags = bitmaskFromFlags xs\n cglObj = fromIntegral glObj\n \n-- | Increments the memory object reference count. returns 'True' if the\n-- function is executed successfully. After the memobj reference count becomes\n-- zero and commands queued for execution on a command-queue(s) that use memobj\n-- have finished, the memory object is deleted. It returns 'False' if memobj is\n-- not a valid memory object.\nclRetainMemObject :: CLMem -> IO Bool\nclRetainMemObject mem = wrapCheckSuccess $ raw_clRetainMemObject mem\n\n-- | Decrements the memory object reference count. After the memobj reference\n-- count becomes zero and commands queued for execution on a command-queue(s)\n-- that use memobj have finished, the memory object is deleted. Returns 'True'\n-- if the function is executed successfully. It returns 'False' if memobj is not\n-- a valid memory object.\nclReleaseMemObject :: CLMem -> IO Bool\nclReleaseMemObject mem = wrapCheckSuccess $ raw_clReleaseMemObject mem\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLChannelOrder {\n cL_R=CL_R,\n cL_A=CL_A,\n cL_INTENSITY=CL_INTENSITY,\n cL_LUMINANCE=CL_LUMINANCE,\n cL_RG=CL_RG,\n cL_RA=CL_RA,\n cL_RGB=CL_RGB,\n cL_RGBA=CL_RGBA,\n cL_ARGB=CL_ARGB,\n cL_BGRA=CL_BGRA,\n };\n#endc\n{-| Specifies the number of channels and the channel layout i.e. the memory\nlayout in which channels are stored in the image. Valid values are described in\nthe table below.\n \n * 'CL_R', 'CL_A'.\n\n * 'CL_INTENSITY', This format can only be used if channel data type =\n'CL_UNORM_INT8', 'CL_UNORM_INT16', 'CL_SNORM_INT8', 'CL_SNORM_INT16',\n'CL_HALF_FLOAT', or 'CL_FLOAT'.\n\n * 'CL_LUMINANCE', This format can only be used if channel data type =\n'CL_UNORM_INT8', 'CL_UNORM_INT16', 'CL_SNORM_INT8', 'CL_SNORM_INT16',\n'CL_HALF_FLOAT', or 'CL_FLOAT'.\n\n * 'CL_RG', 'CL_RA'.\n\n * 'CL_RGB', This format can only be used if channel data type =\n'CL_UNORM_SHORT_565', 'CL_UNORM_SHORT_555' or 'CL_UNORM_INT101010'.\n\n * 'CL_RGBA'.\n\n * 'CL_ARGB', 'CL_BGRA'. This format can only be used if channel data type =\n'CL_UNORM_INT8', 'CL_SNORM_INT8', 'CL_SIGNED_INT8' or 'CL_UNSIGNED_INT8'. \n-}\n{#enum CLChannelOrder {upcaseFirstLetter} deriving(Show)#}\n\n#c\nenum CLChannelType {\n cL_SNORM_INT8=CL_SNORM_INT8,\n cL_SNORM_INT16=CL_SNORM_INT16,\n cL_UNORM_INT8=CL_UNORM_INT8,\n cL_UNORM_INT16=CL_UNORM_INT16,\n cL_UNORM_SHORT_565=CL_UNORM_SHORT_565,\n cL_UNORM_SHORT_555=CL_UNORM_SHORT_555,\n cL_UNORM_INT_101010=CL_UNORM_INT_101010,\n cL_SIGNED_INT8=CL_SIGNED_INT8,\n cL_SIGNED_INT16=CL_SIGNED_INT16,\n cL_SIGNED_INT32=CL_SIGNED_INT32,\n cL_UNSIGNED_INT8=CL_UNSIGNED_INT8,\n cL_UNSIGNED_INT16=CL_UNSIGNED_INT16,\n cL_UNSIGNED_INT32=CL_UNSIGNED_INT32,\n cL_HALF_FLOAT=CL_HALF_FLOAT,\n cL_FLOAT=CL_FLOAT,\n };\n#endc\n{-| Describes the size of the channel data type. The number of bits per element\ndetermined by the image_channel_data_type and image_channel_order must be a\npower of two. The list of supported values is described in the table below.\n\n * 'CL_SNORM_INT8', Each channel component is a normalized signed 8-bit integer\nvalue.\n\n * 'CL_SNORM_INT16', Each channel component is a normalized signed 16-bit\ninteger value.\n\n * 'CL_UNORM_INT8', Each channel component is a normalized unsigned 8-bit\ninteger value.\n\n * 'CL_UNORM_INT16', Each channel component is a normalized unsigned 16-bit\ninteger value.\n\n * 'CL_UNORM_SHORT_565', Represents a normalized 5-6-5 3-channel RGB image. The\nchannel order must be 'CL_RGB'.\n\n * 'CL_UNORM_SHORT_555', Represents a normalized x-5-5-5 4-channel xRGB\nimage. The channel order must be 'CL_RGB'.\n\n * 'CL_UNORM_INT_101010', Represents a normalized x-10-10-10 4-channel xRGB\nimage. The channel order must be 'CL_RGB'.\n\n * 'CL_SIGNED_INT8', Each channel component is an unnormalized signed 8-bit\ninteger value.\n\n * 'CL_SIGNED_INT16', Each channel component is an unnormalized signed 16-bit\ninteger value.\n\n * 'CL_SIGNED_INT32', Each channel component is an unnormalized signed 32-bit\ninteger value.\n\n * 'CL_UNSIGNED_INT8', Each channel component is an unnormalized unsigned 8-bit\ninteger value.\n\n * 'CL_UNSIGNED_INT16', Each channel component is an unnormalized unsigned\n16-bit integer value.\n\n * 'CL_UNSIGNED_INT32', Each channel component is an unnormalized unsigned\n32-bit integer value.\n\n * 'CL_HALF_FLOAT', Each channel component is a 16-bit half-float value.\n\n * 'CL_FLOAT', Each channel component is a single precision floating-point\nvalue.\n-}\n{#enum CLChannelType {upcaseFirstLetter} deriving(Show)#}\n\ndata CLImageFormat = CLImageFormat\n { image_channel_order :: ! CLChannelOrder\n , image_channel_data_type :: ! CLChannelType }\n deriving( Show )\n{#pointer *cl_image_format as CLImageFormat_p -> CLImageFormat#}\ninstance Storable CLImageFormat where\n alignment _ = alignment (undefined :: CDouble)\n sizeOf _ = {#sizeof cl_image_format #}\n peek p =\n CLImageFormat <$> fmap getEnumCL ({#get cl_image_format.image_channel_order #} p)\n <*> fmap getEnumCL ({#get cl_image_format.image_channel_data_type #} p)\n poke p (CLImageFormat a b) = do\n {#set cl_image_format.image_channel_order #} p (getCLValue a)\n {#set cl_image_format.image_channel_data_type #} p (getCLValue b)\n\n-- -----------------------------------------------------------------------------\n{-| Creates a 2D image object.\n\n'clCreateImage2D' returns a valid non-zero image object created if the image\nobject is created successfully. Otherwise, it throws one of the following\n'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_INVALID_VALUE' if values specified in flags are not valid.\n\n * 'CL_INVALID_IMAGE_FORMAT_DESCRIPTOR' if values specified in image_format are\nnot valid.\n\n * 'CL_INVALID_IMAGE_SIZE' if image_width or image_height are 0 or if they\nexceed values specified in 'CL_DEVICE_IMAGE2D_MAX_WIDTH' or\n'CL_DEVICE_IMAGE2D_MAX_HEIGHT' respectively for all devices in context or if\nvalues specified by image_row_pitch do not follow rules described in the\nargument description above.\n\n * 'CL_INVALID_HOST_PTR' if host_ptr is 'nullPtr' and 'CL_MEM_USE_HOST_PTR' or\n'CL_MEM_COPY_HOST_PTR' are set in flags or if host_ptr is not 'nullPtr' but\n'CL_MEM_COPY_HOST_PTR' or 'CL_MEM_USE_HOST_PTR' are not set in flags.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED' if the image_format is not supported.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor image object.\n\n * 'CL_INVALID_OPERATION' if there are no devices in context that support images\n(i.e. 'CL_DEVICE_IMAGE_SUPPORT' (specified in the table of OpenCL Device Queries\nfor 'clGetDeviceInfo') is 'False').\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n\n-}\n\nclCreateImage2D :: Integral a => CLContext -- ^ A valid OpenCL context on which\n -- the image object is to be created.\n -> [CLMemFlag] -- ^ A list of flags that is used to specify\n -- allocation and usage information about the\n -- image memory object being created.\n -> CLImageFormat -- ^ Structure that describes format\n -- properties of the image to be allocated.\n -> a -- ^ The width of the image in pixels. It must be values\n -- greater than or equal to 1.\n -> a -- ^ The height of the image in pixels. It must be\n -- values greater than or equal to 1.\n -> a -- ^ The scan-line pitch in bytes. This must be 0 if\n -- host_ptr is 'nullPtr' and can be either 0 or greater\n -- than or equal to image_width * size of element in\n -- bytes if host_ptr is not 'nullPtr'. If host_ptr is\n -- not 'nullPtr' and image_row_pitch is equal to 0,\n -- image_row_pitch is calculated as image_width * size\n -- of element in bytes. If image_row_pitch is not 0, it\n -- must be a multiple of the image element size in\n -- bytes.\n -> Ptr () -- ^ A pointer to the image data that may already\n -- be allocated by the application. The size of the\n -- buffer that host_ptr points to must be greater\n -- than or equal to image_row_pitch *\n -- image_height. The size of each element in bytes\n -- must be a power of 2. The image data specified\n -- by host_ptr is stored as a linear sequence of\n -- adjacent scanlines. Each scanline is stored as a\n -- linear sequence of image elements.\n -> IO CLMem\nclCreateImage2D ctx xs fmt iw ih irp ptr = wrapPError $ \\perr -> with fmt $ \\pfmt -> do\n raw_clCreateImage2D ctx flags pfmt ciw cih cirp ptr perr\n where\n flags = bitmaskFromFlags xs\n ciw = fromIntegral iw\n cih = fromIntegral ih\n cirp = fromIntegral irp\n\n{-| Creates a 3D image object.\n\n'clCreateImage3D' returns a valid non-zero image object created if the image\nobject is created successfully. Otherwise, it throws one of the following\n'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_INVALID_VALUE' if values specified in flags are not valid.\n\n * 'CL_INVALID_IMAGE_FORMAT_DESCRIPTOR' if values specified in image_format are\nnot valid.\n\n * 'CL_INVALID_IMAGE_SIZE' if image_width, image_height are 0 or if image_depth\nless than or equal to 1 or if they exceed values specified in\n'CL_DEVICE_IMAGE3D_MAX_WIDTH', CL_DEVICE_IMAGE3D_MAX_HEIGHT' or\n'CL_DEVICE_IMAGE3D_MAX_DEPTH' respectively for all devices in context or if\nvalues specified by image_row_pitch and image_slice_pitch do not follow rules\ndescribed in the argument description above.\n\n * 'CL_INVALID_HOST_PTR' if host_ptr is 'nullPtr' and 'CL_MEM_USE_HOST_PTR' or\n'CL_MEM_COPY_HOST_PTR' are set in flags or if host_ptr is not 'nullPtr' but\n'CL_MEM_COPY_HOST_PTR' or 'CL_MEM_USE_HOST_PTR' are not set in flags.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED' if the image_format is not supported.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor image object.\n\n * 'CL_INVALID_OPERATION' if there are no devices in context that support images\n(i.e. 'CL_DEVICE_IMAGE_SUPPORT' (specified in the table of OpenCL Device Queries\nfor clGetDeviceInfo) is 'False').\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n\n-}\nclCreateImage3D :: Integral a => CLContext -- ^ A valid OpenCL context on which\n -- the image object is to be created.\n -> [CLMemFlag] -- ^ A list of flags that is used to specify\n -- allocation and usage information about the\n -- image memory object being created.\n -> CLImageFormat -- ^ Structure that describes format\n -- properties of the image to be allocated.\n -> a -- ^ The width of the image in pixels. It must be values\n -- greater than or equal to 1.\n -> a -- ^ The height of the image in pixels. It must be\n -- values greater than or equal to 1.\n -> a -- ^ The depth of the image in pixels. This must be a\n -- value greater than 1.\n -> a -- ^ The scan-line pitch in bytes. This must be 0 if\n -- host_ptr is 'nullPtr' and can be either 0 or greater\n -- than or equal to image_width * size of element in\n -- bytes if host_ptr is not 'nullPtr'. If host_ptr is\n -- not 'nullPtr' and image_row_pitch is equal to 0,\n -- image_row_pitch is calculated as image_width * size\n -- of element in bytes. If image_row_pitch is not 0, it\n -- must be a multiple of the image element size in\n -- bytes.\n -> a -- ^ The size in bytes of each 2D slice in the 3D\n -- image. This must be 0 if host_ptr is 'nullPtr' and\n -- can be either 0 or greater than or equal to\n -- image_row_pitch * image_height if host_ptr is not\n -- 'nullPtr'. If host_ptr is not 'nullPtr' and\n -- image_slice_pitch equal to 0, image_slice_pitch is\n -- calculated as image_row_pitch * image_height. If\n -- image_slice_pitch is not 0, it must be a multiple of\n -- the image_row_pitch.\n -> Ptr () -- ^ A pointer to the image data that may already\n -- be allocated by the application. The size of the\n -- buffer that host_ptr points to must be greater\n -- than or equal to image_slice_pitch *\n -- image_depth. The size of each element in bytes\n -- must be a power of 2. The image data specified\n -- by host_ptr is stored as a linear sequence of\n -- adjacent 2D slices. Each 2D slice is a linear\n -- sequence of adjacent scanlines. Each scanline is\n -- a linear sequence of image elements.\n -> IO CLMem\nclCreateImage3D ctx xs fmt iw ih idepth irp isp ptr = wrapPError $ \\perr -> with fmt $ \\pfmt -> do\n raw_clCreateImage3D ctx flags pfmt ciw cih cid cirp cisp ptr perr\n where\n flags = bitmaskFromFlags xs\n ciw = fromIntegral iw\n cih = fromIntegral ih\n cid = fromIntegral idepth\n cirp = fromIntegral irp\n cisp = fromIntegral isp \n\n{-| Creates a 2D OpenCL image object from an existing OpenGL texture.\n\n'clCreateFromGLTexture2D' returns a non-zero image object if the image\nobject is created successfully. Otherwise, it throws one of the\nfollowing 'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context or was not\ncreated from a GL context.\n\n * 'CL_INVALID_VALUE' if values specified in flags are not valid or if\nvalue specified in texture_target is not one of the values specified\nin the description of texture_target.\n\n * 'CL_INVALID_MIPLEVEL' if miplevel is less than the value of\nlevelbase (for OpenGL implementations) or zero (for OpenGL ES\nimplementations); or greater than the value of q (for both OpenGL and\nOpenGL ES). levelbase and q are defined for the texture in section\n3.8.10 (Texture Completeness) of the OpenGL 2.1 specification and\nsection 3.7.10 of the OpenGL ES 2.0 specification.\n\n * 'CL_INVALID_MIPLEVEL' if miplevel is greater than zero and the\nOpenGL implementation does not support creating from non-zero mipmap\nlevels.\n\n * 'CL_INVALID_GL_OBJECT' if texture is not a GL texture object whose\ntype matches texture_target, if the specified miplevel of texture is\nnot defined, or if the width or height of the specified miplevel is\nzero.\n\n * 'CL_INVALID_IMAGE_FORMAT_DESCRIPTOR' if the OpenGL texture internal\nformat does not map to a supported OpenCL image format.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources\nrequired by the OpenCL implementation on the host.\n\n-}\nclCreateFromGLTexture2D :: (Integral a, Integral b, Integral c) =>\n CLContext -- ^ A valid OpenCL context in\n -- which the image object is to\n -- be created.\n -> [CLMemFlag] -- ^ A list of flags that is\n -- used to specify usage\n -- information about the image\n -- memory object being created.\n -> a -- ^ The OpenGL image type of the texture\n -- (e.g. GL_TEXTURE_2D)\n -> b -- ^ The mipmap level to be used.\n -> c -- ^ The GL texture object name.\n -> IO CLMem\nclCreateFromGLTexture2D ctx xs texType mipLevel tex = \n wrapPError $ raw_clCreateFromGLTexture2D ctx flags cTexType cMip cTex\n where flags = bitmaskFromFlags xs\n cTexType = fromIntegral texType\n cMip = fromIntegral mipLevel\n cTex = fromIntegral tex\n \ngetNumSupportedImageFormats :: CLContext -> [CLMemFlag] -> CLMemObjectType -> IO CLuint\ngetNumSupportedImageFormats ctx xs mtype = alloca $ \\(value_size :: Ptr CLuint) -> do\n whenSuccess (raw_clGetSupportedImageFormats ctx flags (getCLValue mtype) 0 nullPtr value_size)\n $ peek value_size\n where\n flags = bitmaskFromFlags xs\n \n{-| Get the list of image formats supported by an OpenCL\nimplementation. 'clGetSupportedImageFormats' can be used to get the list of\nimage formats supported by an OpenCL implementation when the following\ninformation about an image memory object is specified:\n\n * Context\n * Image type - 2D or 3D image\n * Image object allocation information\n\nThrows 'CL_INVALID_CONTEXT' if context is not a valid context, throws\n'CL_INVALID_VALUE' if flags or image_type are not valid.\n\n-}\nclGetSupportedImageFormats :: CLContext -- ^ A valid OpenCL context on which the\n -- image object(s) will be created.\n -> [CLMemFlag] -- ^ A bit-field that is used to\n -- specify allocation and usage\n -- information about the image\n -- memory object.\n -> CLMemObjectType -- ^ Describes the image type\n -- and must be either\n -- 'CL_MEM_OBJECT_IMAGE2D' or\n -- 'CL_MEM_OBJECT_IMAGE3D'.\n -> IO [CLImageFormat]\nclGetSupportedImageFormats ctx xs mtype = do\n num <- getNumSupportedImageFormats ctx xs mtype\n allocaArray (fromIntegral num) $ \\(buff :: Ptr CLImageFormat) -> do\n whenSuccess (raw_clGetSupportedImageFormats ctx flags (getCLValue mtype) num (castPtr buff) nullPtr)\n $ peekArray (fromIntegral num) buff\n where\n flags = bitmaskFromFlags xs\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLImageInfo {\n cL_IMAGE_FORMAT=CL_IMAGE_FORMAT,\n cL_IMAGE_ELEMENT_SIZE=CL_IMAGE_ELEMENT_SIZE,\n cL_IMAGE_ROW_PITCH=CL_IMAGE_ROW_PITCH,\n cL_IMAGE_SLICE_PITCH=CL_IMAGE_SLICE_PITCH,\n cL_IMAGE_WIDTH=CL_IMAGE_WIDTH,\n cL_IMAGE_HEIGHT=CL_IMAGE_HEIGHT,\n cL_IMAGE_DEPTH=CL_IMAGE_DEPTH,\n };\n#endc\n{#enum CLImageInfo {upcaseFirstLetter} #}\n\n-- | Return image format descriptor specified when image is created with\n-- clCreateImage2D or clCreateImage3D.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_FORMAT'.\nclGetImageFormat :: CLMem -> IO CLImageFormat\nclGetImageFormat mem =\n wrapGetInfo (\\(dat :: Ptr CLImageFormat) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_FORMAT\n size = fromIntegral $ sizeOf (undefined :: CLImageFormat)\n \n-- | Return size of each element of the image memory object given by image. An\n-- element is made up of n channels. The value of n is given in 'CLImageFormat'\n-- descriptor.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_ELEMENT_SIZE'.\nclGetImageElementSize :: CLMem -> IO CSize \nclGetImageElementSize mem =\n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_ELEMENT_SIZE\n size = fromIntegral $ sizeOf (undefined :: CSize)\n \n-- | Return size in bytes of a row of elements of the image object given by\n-- image.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_ROW_PITCH'.\nclGetImageRowPitch :: CLMem -> IO CSize \nclGetImageRowPitch mem = \n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_ROW_PITCH\n size = fromIntegral $ sizeOf (undefined :: CSize)\n \n-- | Return size in bytes of a 2D slice for the 3D image object given by\n-- image. For a 2D image object this value will be 0.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_SLICE_PITCH'.\nclGetImageSlicePitch :: CLMem -> IO CSize \nclGetImageSlicePitch mem = \n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_SLICE_PITCH\n size = fromIntegral $ sizeOf (undefined :: CSize) \n \n-- | Return width of image in pixels.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_WIDTH'.\nclGetImageWidth :: CLMem -> IO CSize \nclGetImageWidth mem = \n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_WIDTH\n size = fromIntegral $ sizeOf (undefined :: CSize)\n \n-- | Return height of image in pixels.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_HEIGHT'.\nclGetImageHeight :: CLMem -> IO CSize \nclGetImageHeight mem = \n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_HEIGHT\n size = fromIntegral $ sizeOf (undefined :: CSize)\n\n-- | Return depth of the image in pixels. For a 2D image, depth equals 0.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_DEPTH'.\nclGetImageDepth :: CLMem -> IO CSize \nclGetImageDepth mem = \n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_DEPTH\n size = fromIntegral $ sizeOf (undefined :: CSize)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemInfo {\n cL_MEM_TYPE=CL_MEM_TYPE,\n cL_MEM_FLAGS=CL_MEM_FLAGS,\n cL_MEM_SIZE=CL_MEM_SIZE,\n cL_MEM_HOST_PTR=CL_MEM_HOST_PTR,\n cL_MEM_MAP_COUNT=CL_MEM_MAP_COUNT,\n cL_MEM_REFERENCE_COUNT=CL_MEM_REFERENCE_COUNT,\n cL_MEM_CONTEXT=CL_MEM_CONTEXT,\n };\n#endc\n{#enum CLMemInfo {upcaseFirstLetter} #}\n\n-- | Returns the mem object type.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_TYPE'.\nclGetMemType :: CLMem -> IO CLMemObjectType\nclGetMemType mem =\n wrapGetInfo (\\(dat :: Ptr CLMemObjectType_) ->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_MEM_TYPE\n size = fromIntegral $ sizeOf (0::CLMemObjectType_)\n\n-- | Return the flags argument value specified when memobj was created.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_FLAGS'.\nclGetMemFlags :: CLMem -> IO [CLMemFlag]\nclGetMemFlags mem =\n wrapGetInfo (\\(dat :: Ptr CLMemFlags_)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) bitmaskToMemFlags\n where \n infoid = getCLValue CL_MEM_FLAGS\n size = fromIntegral $ sizeOf (0::CLMemFlags_)\n\n-- | Return actual size of memobj in bytes.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_SIZE'.\nclGetMemSize :: CLMem -> IO CSize\nclGetMemSize mem =\n wrapGetInfo (\\(dat :: Ptr CSize)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_SIZE\n size = fromIntegral $ sizeOf (0::CSize)\n\n-- | Return the host_ptr argument value specified when memobj is created.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_HOST_PTR'.\nclGetMemHostPtr :: CLMem -> IO (Ptr ())\nclGetMemHostPtr mem =\n wrapGetInfo (\\(dat :: Ptr (Ptr ()))->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_HOST_PTR\n size = fromIntegral $ sizeOf (nullPtr::Ptr ())\n\n-- | Map count. The map count returned should be considered immediately\n-- stale. It is unsuitable for general use in applications. This feature is\n-- provided for debugging.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_MAP_COUNT'.\nclGetMemMapCount :: CLMem -> IO CLuint\nclGetMemMapCount mem =\n wrapGetInfo (\\(dat :: Ptr CLuint)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_MAP_COUNT\n size = fromIntegral $ sizeOf (0 :: CLuint)\n\n-- | Return memobj reference count. The reference count returned should be\n-- considered immediately stale. It is unsuitable for general use in\n-- applications. This feature is provided for identifying memory leaks.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_REFERENCE_COUNT'.\nclGetMemReferenceCount :: CLMem -> IO CLuint\nclGetMemReferenceCount mem =\n wrapGetInfo (\\(dat :: Ptr CLuint)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0 :: CLuint)\n\n-- | Return context specified when memory object is created.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_CONTEXT'.\nclGetMemContext :: CLMem -> IO CLContext\nclGetMemContext mem =\n wrapGetInfo (\\(dat :: Ptr CLContext)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_CONTEXT\n size = fromIntegral $ sizeOf (0 :: CLuint)\n\n-- -----------------------------------------------------------------------------\n{-| Creates a sampler object. A sampler object describes how to sample an image\nwhen the image is read in the kernel. The built-in functions to read from an\nimage in a kernel take a sampler as an argument. The sampler arguments to the\nimage read function can be sampler objects created using OpenCL functions and\npassed as argument values to the kernel or can be samplers declared inside a\nkernel. In this section we discuss how sampler objects are created using OpenCL\nfunctions.\n\nReturns a valid non-zero sampler object if the sampler object is created\nsuccessfully. Otherwise, it throws one of the following 'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_INVALID_VALUE' if addressing_mode, filter_mode, or normalized_coords or a\ncombination of these argument values are not valid.\n\n * 'CL_INVALID_OPERATION' if images are not supported by any device associated\nwith context (i.e. 'CL_DEVICE_IMAGE_SUPPORT' specified in the table of OpenCL\nDevice Queries for clGetDeviceInfo is 'False').\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n-}\nclCreateSampler :: CLContext -> Bool -> CLAddressingMode -> CLFilterMode \n -> IO CLSampler\nclCreateSampler ctx norm am fm = wrapPError $ \\perr -> do\n raw_clCreateSampler ctx (fromBool norm) (getCLValue am) (getCLValue fm) perr\n\n-- | Increments the sampler reference count. 'clCreateSampler' does an implicit\n-- retain. Returns 'True' if the function is executed successfully. It returns\n-- 'False' if sampler is not a valid sampler object.\nclRetainSampler :: CLSampler -> IO Bool\nclRetainSampler mem = wrapCheckSuccess $ raw_clRetainSampler mem\n\n-- | Decrements the sampler reference count. The sampler object is deleted after\n-- the reference count becomes zero and commands queued for execution on a\n-- command-queue(s) that use sampler have finished. 'clReleaseSampler' returns\n-- 'True' if the function is executed successfully. It returns 'False' if\n-- sampler is not a valid sampler object.\nclReleaseSampler :: CLSampler -> IO Bool\nclReleaseSampler mem = wrapCheckSuccess $ raw_clReleaseSampler mem\n\n#c\nenum CLSamplerInfo {\n cL_SAMPLER_REFERENCE_COUNT=CL_SAMPLER_REFERENCE_COUNT,\n cL_SAMPLER_CONTEXT=CL_SAMPLER_CONTEXT,\n cL_SAMPLER_ADDRESSING_MODE=CL_SAMPLER_ADDRESSING_MODE,\n cL_SAMPLER_FILTER_MODE=CL_SAMPLER_FILTER_MODE,\n cL_SAMPLER_NORMALIZED_COORDS=CL_SAMPLER_NORMALIZED_COORDS\n };\n#endc\n{#enum CLSamplerInfo {upcaseFirstLetter} #}\n\n-- | Return the sampler reference count. The reference count returned should be\n-- considered immediately stale. It is unsuitable for general use in\n-- applications. This feature is provided for identifying memory leaks.\n--\n-- This function execute OpenCL clGetSamplerInfo with\n-- 'CL_SAMPLER_REFERENCE_COUNT'.\nclGetSamplerReferenceCount :: CLSampler -> IO CLuint\nclGetSamplerReferenceCount sam =\n wrapGetInfo (\\(dat :: Ptr CLuint)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_SAMPLER_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0 :: CLuint)\n\n-- | Return the context specified when the sampler is created.\n--\n-- This function execute OpenCL clGetSamplerInfo with 'CL_SAMPLER_CONTEXT'.\nclGetSamplerContext :: CLSampler -> IO CLContext\nclGetSamplerContext sam =\n wrapGetInfo (\\(dat :: Ptr CLContext)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_SAMPLER_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr :: CLContext)\n\n-- | Return the value specified by addressing_mode argument to clCreateSampler.\n--\n-- This function execute OpenCL clGetSamplerInfo with\n-- 'CL_SAMPLER_ADDRESSING_MODE'.\nclGetSamplerAddressingMode :: CLSampler -> IO CLAddressingMode\nclGetSamplerAddressingMode sam =\n wrapGetInfo (\\(dat :: Ptr CLAddressingMode_)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_SAMPLER_ADDRESSING_MODE\n size = fromIntegral $ sizeOf (0 :: CLAddressingMode_)\n\n-- | Return the value specified by filter_mode argument to clCreateSampler.\n--\n-- This function execute OpenCL clGetSamplerInfo with 'CL_SAMPLER_FILTER_MODE'.\nclGetSamplerFilterMode :: CLSampler -> IO CLFilterMode\nclGetSamplerFilterMode sam =\n wrapGetInfo (\\(dat :: Ptr CLFilterMode_)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_SAMPLER_FILTER_MODE\n size = fromIntegral $ sizeOf (0 :: CLFilterMode_)\n\n-- | Return the value specified by normalized_coords argument to\n-- clCreateSampler.\n--\n-- This function execute OpenCL clGetSamplerInfo with\n-- 'CL_SAMPLER_NORMALIZED_COORDS'.\nclGetSamplerNormalizedCoords :: CLSampler -> IO Bool\nclGetSamplerNormalizedCoords sam =\n wrapGetInfo (\\(dat :: Ptr CLbool)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) (\/=0)\n where \n infoid = getCLValue CL_SAMPLER_NORMALIZED_COORDS\n size = fromIntegral $ sizeOf (0 :: CLbool)\n\n-- -----------------------------------------------------------------------------\n","old_contents":"{- Copyright (c) 2011 Luis Cabellos,\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided\n with the distribution.\n\n * Neither the name of nor the names of other\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n-}\n{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables, CPP #-}\nmodule Control.Parallel.OpenCL.Memory(\n -- * Types\n CLMem, CLSampler, CLMemFlag(..), CLMemObjectType(..), CLAddressingMode(..), \n CLFilterMode(..), CLImageFormat(..),\n -- * Memory Functions\n clCreateBuffer, clRetainMemObject, clReleaseMemObject, clGetMemType, \n clGetMemFlags, clGetMemSize, clGetMemHostPtr, clGetMemMapCount, \n clGetMemReferenceCount, clGetMemContext, clCreateFromGLBuffer,\n -- * Image Functions\n clCreateImage2D, clCreateImage3D, clCreateFromGLTexture2D,\n clGetSupportedImageFormats, clGetImageFormat, clGetImageElementSize, \n clGetImageRowPitch, clGetImageSlicePitch, clGetImageWidth, clGetImageHeight, \n clGetImageDepth,\n -- * Sampler Functions\n clCreateSampler, clRetainSampler, clReleaseSampler, clGetSamplerReferenceCount, \n clGetSamplerContext, clGetSamplerAddressingMode, clGetSamplerFilterMode, \n clGetSamplerNormalizedCoords\n ) where\n\n-- -----------------------------------------------------------------------------\nimport Foreign\nimport Foreign.C.Types\nimport Control.Applicative( (<$>), (<*>) )\nimport Control.Parallel.OpenCL.Types( \n CLMem, CLContext, CLSampler, CLint, CLuint, CLbool, CLMemFlags_,\n CLMemInfo_, CLAddressingMode_, CLFilterMode_, CLSamplerInfo_, CLImageInfo_,\n CLAddressingMode(..), CLFilterMode(..), CLMemFlag(..), CLMemObjectType_, \n CLMemObjectType(..), \n wrapPError, wrapCheckSuccess, wrapGetInfo, whenSuccess, getEnumCL, \n bitmaskFromFlags, bitmaskToMemFlags, getCLValue )\n\n#ifdef __APPLE__\n#include \n#else\n#include \n#endif\n\n-- -----------------------------------------------------------------------------\nforeign import CALLCONV \"clCreateBuffer\" raw_clCreateBuffer :: \n CLContext -> CLMemFlags_ -> CSize -> Ptr () -> Ptr CLint -> IO CLMem\nforeign import CALLCONV \"clCreateImage2D\" raw_clCreateImage2D :: \n CLContext -> CLMemFlags_ -> CLImageFormat_p -> CSize -> CSize -> CSize \n -> Ptr () -> Ptr CLint -> IO CLMem\nforeign import CALLCONV \"clCreateImage3D\" raw_clCreateImage3D :: \n CLContext -> CLMemFlags_-> CLImageFormat_p -> CSize -> CSize -> CSize -> CSize \n -> CSize -> Ptr () -> Ptr CLint -> IO CLMem\nforeign import CALLCONV \"clCreateFromGLTexture2D\" raw_clCreateFromGLTexture2D ::\n CLContext -> CLMemFlags_ -> CLuint -> CLint -> CLuint -> Ptr CLint -> IO CLMem\nforeign import CALLCONV \"clCreateFromGLBuffer\" raw_clCreateFromGLBuffer ::\n CLContext -> CLMemFlags_ -> CLuint -> Ptr CLint -> IO CLMem\nforeign import CALLCONV \"clRetainMemObject\" raw_clRetainMemObject :: \n CLMem -> IO CLint\nforeign import CALLCONV \"clReleaseMemObject\" raw_clReleaseMemObject :: \n CLMem -> IO CLint\nforeign import CALLCONV \"clGetSupportedImageFormats\" raw_clGetSupportedImageFormats :: \n CLContext -> CLMemFlags_ -> CLMemObjectType_ -> CLuint -> CLImageFormat_p \n -> Ptr CLuint -> IO CLint\nforeign import CALLCONV \"clGetMemObjectInfo\" raw_clGetMemObjectInfo :: \n CLMem -> CLMemInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clGetImageInfo\" raw_clGetImageInfo ::\n CLMem -> CLImageInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\nforeign import CALLCONV \"clCreateSampler\" raw_clCreateSampler :: \n CLContext -> CLbool -> CLAddressingMode_ -> CLFilterMode_ -> Ptr CLint -> IO CLSampler\nforeign import CALLCONV \"clRetainSampler\" raw_clRetainSampler :: \n CLSampler -> IO CLint\nforeign import CALLCONV \"clReleaseSampler\" raw_clReleaseSampler :: \n CLSampler -> IO CLint\nforeign import CALLCONV \"clGetSamplerInfo\" raw_clGetSamplerInfo :: \n CLSampler -> CLSamplerInfo_ -> CSize -> Ptr () -> Ptr CSize -> IO CLint\n\n-- -----------------------------------------------------------------------------\n{-| Creates a buffer object. Returns a valid non-zero buffer object if the\nbuffer object is created successfully. Otherwise, it throws the 'CLError': \n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_INVALID_VALUE' if values specified in flags are not valid.\n\n * 'CL_INVALID_BUFFER_SIZE' if size is 0 or is greater than\n'clDeviceMaxMemAllocSize' value for all devices in context.\n\n * 'CL_INVALID_HOST_PTR' if host_ptr is NULL and 'CL_MEM_USE_HOST_PTR' or\n'CL_MEM_COPY_HOST_PTR' are set in flags or if host_ptr is not NULL but\n'CL_MEM_COPY_HOST_PTR' or 'CL_MEM_USE_HOST_PTR' are not set in flags.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor buffer object.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n-}\nclCreateBuffer :: Integral a => CLContext -> [CLMemFlag] -> (a, Ptr ()) -> IO CLMem\nclCreateBuffer ctx xs (sbuff,buff) = wrapPError $ \\perr -> do\n raw_clCreateBuffer ctx flags (fromIntegral sbuff) buff perr\n where\n flags = bitmaskFromFlags xs\n\n{-| Creates an OpenCL buffer object from an OpenGL buffer object. Returns a valid non-zero OpenCL buffer object if the buffer object is created successfully. Otherwise it throws the 'CLError':\n * 'CL_INVALID_CONTEXT' if context is not a valid context or was not created from a GL context.\n\n * 'CL_INVALID_VALUE' if values specified in flags are not valid.\n\n * 'CL_INVALID_GL_OBJECT' if bufobj is not a GL buffer object or is a GL buffer object but does not have an existing data store.\n\n * 'CL_OUT_OF_RESOURCES' if there is a failure to allocate resources required by the OpenCL implementation on the device.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required by the OpenCL implementation on the host.\n-}\nclCreateFromGLBuffer :: Integral a => CLContext -> [CLMemFlag] -> a -> IO CLMem\nclCreateFromGLBuffer ctx xs glObj = wrapPError $ \\perr -> do\n raw_clCreateFromGLBuffer ctx flags cglObj perr\n where flags = bitmaskFromFlags xs\n cglObj = fromIntegral glObj\n \n-- | Increments the memory object reference count. returns 'True' if the\n-- function is executed successfully. After the memobj reference count becomes\n-- zero and commands queued for execution on a command-queue(s) that use memobj\n-- have finished, the memory object is deleted. It returns 'False' if memobj is\n-- not a valid memory object.\nclRetainMemObject :: CLMem -> IO Bool\nclRetainMemObject mem = wrapCheckSuccess $ raw_clRetainMemObject mem\n\n-- | Decrements the memory object reference count. After the memobj reference\n-- count becomes zero and commands queued for execution on a command-queue(s)\n-- that use memobj have finished, the memory object is deleted. Returns 'True'\n-- if the function is executed successfully. It returns 'False' if memobj is not\n-- a valid memory object.\nclReleaseMemObject :: CLMem -> IO Bool\nclReleaseMemObject mem = wrapCheckSuccess $ raw_clReleaseMemObject mem\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLChannelOrder {\n cL_R=CL_R,\n cL_A=CL_A,\n cL_INTENSITY=CL_INTENSITY,\n cL_LUMINANCE=CL_LUMINANCE,\n cL_RG=CL_RG,\n cL_RA=CL_RA,\n cL_RGB=CL_RGB,\n cL_RGBA=CL_RGBA,\n cL_ARGB=CL_ARGB,\n cL_BGRA=CL_BGRA,\n };\n#endc\n{-| Specifies the number of channels and the channel layout i.e. the memory\nlayout in which channels are stored in the image. Valid values are described in\nthe table below.\n \n * 'CL_R', 'CL_A'.\n\n * 'CL_INTENSITY', This format can only be used if channel data type =\n'CL_UNORM_INT8', 'CL_UNORM_INT16', 'CL_SNORM_INT8', 'CL_SNORM_INT16',\n'CL_HALF_FLOAT', or 'CL_FLOAT'.\n\n * 'CL_LUMINANCE', This format can only be used if channel data type =\n'CL_UNORM_INT8', 'CL_UNORM_INT16', 'CL_SNORM_INT8', 'CL_SNORM_INT16',\n'CL_HALF_FLOAT', or 'CL_FLOAT'.\n\n * 'CL_RG', 'CL_RA'.\n\n * 'CL_RGB', This format can only be used if channel data type =\n'CL_UNORM_SHORT_565', 'CL_UNORM_SHORT_555' or 'CL_UNORM_INT101010'.\n\n * 'CL_RGBA'.\n\n * 'CL_ARGB', 'CL_BGRA'. This format can only be used if channel data type =\n'CL_UNORM_INT8', 'CL_SNORM_INT8', 'CL_SIGNED_INT8' or 'CL_UNSIGNED_INT8'. \n-}\n{#enum CLChannelOrder {upcaseFirstLetter} deriving(Show)#}\n\n#c\nenum CLChannelType {\n cL_SNORM_INT8=CL_SNORM_INT8,\n cL_SNORM_INT16=CL_SNORM_INT16,\n cL_UNORM_INT8=CL_UNORM_INT8,\n cL_UNORM_INT16=CL_UNORM_INT16,\n cL_UNORM_SHORT_565=CL_UNORM_SHORT_565,\n cL_UNORM_SHORT_555=CL_UNORM_SHORT_555,\n cL_UNORM_INT_101010=CL_UNORM_INT_101010,\n cL_SIGNED_INT8=CL_SIGNED_INT8,\n cL_SIGNED_INT16=CL_SIGNED_INT16,\n cL_SIGNED_INT32=CL_SIGNED_INT32,\n cL_UNSIGNED_INT8=CL_UNSIGNED_INT8,\n cL_UNSIGNED_INT16=CL_UNSIGNED_INT16,\n cL_UNSIGNED_INT32=CL_UNSIGNED_INT32,\n cL_HALF_FLOAT=CL_HALF_FLOAT,\n cL_FLOAT=CL_FLOAT,\n };\n#endc\n{-| Describes the size of the channel data type. The number of bits per element\ndetermined by the image_channel_data_type and image_channel_order must be a\npower of two. The list of supported values is described in the table below.\n\n * 'CL_SNORM_INT8', Each channel component is a normalized signed 8-bit integer\nvalue.\n\n * 'CL_SNORM_INT16', Each channel component is a normalized signed 16-bit\ninteger value.\n\n * 'CL_UNORM_INT8', Each channel component is a normalized unsigned 8-bit\ninteger value.\n\n * 'CL_UNORM_INT16', Each channel component is a normalized unsigned 16-bit\ninteger value.\n\n * 'CL_UNORM_SHORT_565', Represents a normalized 5-6-5 3-channel RGB image. The\nchannel order must be 'CL_RGB'.\n\n * 'CL_UNORM_SHORT_555', Represents a normalized x-5-5-5 4-channel xRGB\nimage. The channel order must be 'CL_RGB'.\n\n * 'CL_UNORM_INT_101010', Represents a normalized x-10-10-10 4-channel xRGB\nimage. The channel order must be 'CL_RGB'.\n\n * 'CL_SIGNED_INT8', Each channel component is an unnormalized signed 8-bit\ninteger value.\n\n * 'CL_SIGNED_INT16', Each channel component is an unnormalized signed 16-bit\ninteger value.\n\n * 'CL_SIGNED_INT32', Each channel component is an unnormalized signed 32-bit\ninteger value.\n\n * 'CL_UNSIGNED_INT8', Each channel component is an unnormalized unsigned 8-bit\ninteger value.\n\n * 'CL_UNSIGNED_INT16', Each channel component is an unnormalized unsigned\n16-bit integer value.\n\n * 'CL_UNSIGNED_INT32', Each channel component is an unnormalized unsigned\n32-bit integer value.\n\n * 'CL_HALF_FLOAT', Each channel component is a 16-bit half-float value.\n\n * 'CL_FLOAT', Each channel component is a single precision floating-point\nvalue.\n-}\n{#enum CLChannelType {upcaseFirstLetter} deriving(Show)#}\n\ndata CLImageFormat = CLImageFormat\n { image_channel_order :: ! CLChannelOrder\n , image_channel_data_type :: ! CLChannelType }\n deriving( Show )\n{#pointer *cl_image_format as CLImageFormat_p -> CLImageFormat#}\ninstance Storable CLImageFormat where\n alignment _ = alignment (undefined :: CDouble)\n sizeOf _ = {#sizeof cl_image_format #}\n peek p =\n CLImageFormat <$> fmap getEnumCL ({#get cl_image_format.image_channel_order #} p)\n <*> fmap getEnumCL ({#get cl_image_format.image_channel_data_type #} p)\n poke p (CLImageFormat a b) = do\n {#set cl_image_format.image_channel_order #} p (getCLValue a)\n {#set cl_image_format.image_channel_data_type #} p (getCLValue b)\n\n-- -----------------------------------------------------------------------------\n{-| Creates a 2D image object.\n\n'clCreateImage2D' returns a valid non-zero image object created if the image\nobject is created successfully. Otherwise, it throws one of the following\n'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_INVALID_VALUE' if values specified in flags are not valid.\n\n * 'CL_INVALID_IMAGE_FORMAT_DESCRIPTOR' if values specified in image_format are\nnot valid.\n\n * 'CL_INVALID_IMAGE_SIZE' if image_width or image_height are 0 or if they\nexceed values specified in 'CL_DEVICE_IMAGE2D_MAX_WIDTH' or\n'CL_DEVICE_IMAGE2D_MAX_HEIGHT' respectively for all devices in context or if\nvalues specified by image_row_pitch do not follow rules described in the\nargument description above.\n\n * 'CL_INVALID_HOST_PTR' if host_ptr is 'nullPtr' and 'CL_MEM_USE_HOST_PTR' or\n'CL_MEM_COPY_HOST_PTR' are set in flags or if host_ptr is not 'nullPtr' but\n'CL_MEM_COPY_HOST_PTR' or 'CL_MEM_USE_HOST_PTR' are not set in flags.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED' if the image_format is not supported.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor image object.\n\n * 'CL_INVALID_OPERATION' if there are no devices in context that support images\n(i.e. 'CL_DEVICE_IMAGE_SUPPORT' (specified in the table of OpenCL Device Queries\nfor 'clGetDeviceInfo') is 'False').\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n\n-}\n\nclCreateImage2D :: Integral a => CLContext -- ^ A valid OpenCL context on which\n -- the image object is to be created.\n -> [CLMemFlag] -- ^ A list of flags that is used to specify\n -- allocation and usage information about the\n -- image memory object being created.\n -> CLImageFormat -- ^ Structure that describes format\n -- properties of the image to be allocated.\n -> a -- ^ The width of the image in pixels. It must be values\n -- greater than or equal to 1.\n -> a -- ^ The height of the image in pixels. It must be\n -- values greater than or equal to 1.\n -> a -- ^ The scan-line pitch in bytes. This must be 0 if\n -- host_ptr is 'nullPtr' and can be either 0 or greater\n -- than or equal to image_width * size of element in\n -- bytes if host_ptr is not 'nullPtr'. If host_ptr is\n -- not 'nullPtr' and image_row_pitch is equal to 0,\n -- image_row_pitch is calculated as image_width * size\n -- of element in bytes. If image_row_pitch is not 0, it\n -- must be a multiple of the image element size in\n -- bytes.\n -> Ptr () -- ^ A pointer to the image data that may already\n -- be allocated by the application. The size of the\n -- buffer that host_ptr points to must be greater\n -- than or equal to image_row_pitch *\n -- image_height. The size of each element in bytes\n -- must be a power of 2. The image data specified\n -- by host_ptr is stored as a linear sequence of\n -- adjacent scanlines. Each scanline is stored as a\n -- linear sequence of image elements.\n -> IO CLMem\nclCreateImage2D ctx xs fmt iw ih irp ptr = wrapPError $ \\perr -> with fmt $ \\pfmt -> do\n raw_clCreateImage2D ctx flags pfmt ciw cih cirp ptr perr\n where\n flags = bitmaskFromFlags xs\n ciw = fromIntegral iw\n cih = fromIntegral ih\n cirp = fromIntegral irp\n\n{-| Creates a 3D image object.\n\n'clCreateImage3D' returns a valid non-zero image object created if the image\nobject is created successfully. Otherwise, it throws one of the following\n'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_INVALID_VALUE' if values specified in flags are not valid.\n\n * 'CL_INVALID_IMAGE_FORMAT_DESCRIPTOR' if values specified in image_format are\nnot valid.\n\n * 'CL_INVALID_IMAGE_SIZE' if image_width, image_height are 0 or if image_depth\nless than or equal to 1 or if they exceed values specified in\n'CL_DEVICE_IMAGE3D_MAX_WIDTH', CL_DEVICE_IMAGE3D_MAX_HEIGHT' or\n'CL_DEVICE_IMAGE3D_MAX_DEPTH' respectively for all devices in context or if\nvalues specified by image_row_pitch and image_slice_pitch do not follow rules\ndescribed in the argument description above.\n\n * 'CL_INVALID_HOST_PTR' if host_ptr is 'nullPtr' and 'CL_MEM_USE_HOST_PTR' or\n'CL_MEM_COPY_HOST_PTR' are set in flags or if host_ptr is not 'nullPtr' but\n'CL_MEM_COPY_HOST_PTR' or 'CL_MEM_USE_HOST_PTR' are not set in flags.\n\n * 'CL_IMAGE_FORMAT_NOT_SUPPORTED' if the image_format is not supported.\n\n * 'CL_MEM_OBJECT_ALLOCATION_FAILURE' if there is a failure to allocate memory\nfor image object.\n\n * 'CL_INVALID_OPERATION' if there are no devices in context that support images\n(i.e. 'CL_DEVICE_IMAGE_SUPPORT' (specified in the table of OpenCL Device Queries\nfor clGetDeviceInfo) is 'False').\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n\n-}\nclCreateImage3D :: Integral a => CLContext -- ^ A valid OpenCL context on which\n -- the image object is to be created.\n -> [CLMemFlag] -- ^ A list of flags that is used to specify\n -- allocation and usage information about the\n -- image memory object being created.\n -> CLImageFormat -- ^ Structure that describes format\n -- properties of the image to be allocated.\n -> a -- ^ The width of the image in pixels. It must be values\n -- greater than or equal to 1.\n -> a -- ^ The height of the image in pixels. It must be\n -- values greater than or equal to 1.\n -> a -- ^ The depth of the image in pixels. This must be a\n -- value greater than 1.\n -> a -- ^ The scan-line pitch in bytes. This must be 0 if\n -- host_ptr is 'nullPtr' and can be either 0 or greater\n -- than or equal to image_width * size of element in\n -- bytes if host_ptr is not 'nullPtr'. If host_ptr is\n -- not 'nullPtr' and image_row_pitch is equal to 0,\n -- image_row_pitch is calculated as image_width * size\n -- of element in bytes. If image_row_pitch is not 0, it\n -- must be a multiple of the image element size in\n -- bytes.\n -> a -- ^ The size in bytes of each 2D slice in the 3D\n -- image. This must be 0 if host_ptr is 'nullPtr' and\n -- can be either 0 or greater than or equal to\n -- image_row_pitch * image_height if host_ptr is not\n -- 'nullPtr'. If host_ptr is not 'nullPtr' and\n -- image_slice_pitch equal to 0, image_slice_pitch is\n -- calculated as image_row_pitch * image_height. If\n -- image_slice_pitch is not 0, it must be a multiple of\n -- the image_row_pitch.\n -> Ptr () -- ^ A pointer to the image data that may already\n -- be allocated by the application. The size of the\n -- buffer that host_ptr points to must be greater\n -- than or equal to image_slice_pitch *\n -- image_depth. The size of each element in bytes\n -- must be a power of 2. The image data specified\n -- by host_ptr is stored as a linear sequence of\n -- adjacent 2D slices. Each 2D slice is a linear\n -- sequence of adjacent scanlines. Each scanline is\n -- a linear sequence of image elements.\n -> IO CLMem\nclCreateImage3D ctx xs fmt iw ih idepth irp isp ptr = wrapPError $ \\perr -> with fmt $ \\pfmt -> do\n raw_clCreateImage3D ctx flags pfmt ciw cih cid cirp cisp ptr perr\n where\n flags = bitmaskFromFlags xs\n ciw = fromIntegral iw\n cih = fromIntegral ih\n cid = fromIntegral idepth\n cirp = fromIntegral irp\n cisp = fromIntegral isp \n\n{-| Creates a 2D OpenCL image object from an existing OpenGL texture.\n\n'clCreateFromGLTexture2D' returns a non-zero image object if the image\nobject is created successfully. Otherwise, it throws one of the\nfollowing 'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context or was not\ncreated from a GL context.\n\n * 'CL_INVALID_VALUE' if values specified in flags are not valid or if\nvalue specified in texture_target is not one of the values specified\nin the description of texture_target.\n\n * 'CL_INVALID_MIPLEVEL' if miplevel is less than the value of\nlevelbase (for OpenGL implementations) or zero (for OpenGL ES\nimplementations); or greater than the value of q (for both OpenGL and\nOpenGL ES). levelbase and q are defined for the texture in section\n3.8.10 (Texture Completeness) of the OpenGL 2.1 specification and\nsection 3.7.10 of the OpenGL ES 2.0 specification.\n\n * 'CL_INVALID_MIPLEVEL' if miplevel is greater than zero and the\nOpenGL implementation does not support creating from non-zero mipmap\nlevels.\n\n * 'CL_INVALID_GL_OBJECT' if texture is not a GL texture object whose\ntype matches texture_target, if the specified miplevel of texture is\nnot defined, or if the width or height of the specified miplevel is\nzero.\n\n * 'CL_INVALID_IMAGE_FORMAT_DESCRIPTOR' if the OpenGL texture internal\nformat does not map to a supported OpenCL image format.\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources\nrequired by the OpenCL implementation on the host.\n\n-}\nclCreateFromGLTexture2D :: (Integral a, Integral b, Integral c) =>\n CLContext -- ^ A valid OpenCL context in\n -- which the image object is to\n -- be created.\n -> [CLMemFlag] -- ^ A list of flags that is\n -- used to specify usage\n -- information about the image\n -- memory object being created.\n -> a -- ^ The OpenGL image type of the texture\n -- (e.g. GL_TEXTURE_2D)\n -> b -- ^ The mipmap level to be used.\n -> c -- ^ The GL texture object name.\n -> IO CLMem\nclCreateFromGLTexture2D ctx xs texType mipLevel tex = \n wrapPError $ raw_clCreateFromGLTexture2D ctx flags cTexType cMip cTex\n where flags = bitmaskFromFlags xs\n cTexType = fromIntegral texType\n cMip = fromIntegral mipLevel\n cTex = fromIntegral tex\n \ngetNumSupportedImageFormats :: CLContext -> [CLMemFlag] -> CLMemObjectType -> IO CLuint\ngetNumSupportedImageFormats ctx xs mtype = alloca $ \\(value_size :: Ptr CLuint) -> do\n whenSuccess (raw_clGetSupportedImageFormats ctx flags (getCLValue mtype) 0 nullPtr value_size)\n $ peek value_size\n where\n flags = bitmaskFromFlags xs\n \n{-| Get the list of image formats supported by an OpenCL\nimplementation. 'clGetSupportedImageFormats' can be used to get the list of\nimage formats supported by an OpenCL implementation when the following\ninformation about an image memory object is specified:\n\n * Context\n * Image type - 2D or 3D image\n * Image object allocation information\n\nThrows 'CL_INVALID_CONTEXT' if context is not a valid context, throws\n'CL_INVALID_VALUE' if flags or image_type are not valid.\n\n-}\nclGetSupportedImageFormats :: CLContext -- ^ A valid OpenCL context on which the\n -- image object(s) will be created.\n -> [CLMemFlag] -- ^ A bit-field that is used to\n -- specify allocation and usage\n -- information about the image\n -- memory object.\n -> CLMemObjectType -- ^ Describes the image type\n -- and must be either\n -- 'CL_MEM_OBJECT_IMAGE2D' or\n -- 'CL_MEM_OBJECT_IMAGE3D'.\n -> IO [CLImageFormat]\nclGetSupportedImageFormats ctx xs mtype = do\n num <- getNumSupportedImageFormats ctx xs mtype\n allocaArray (fromIntegral num) $ \\(buff :: Ptr CLImageFormat) -> do\n whenSuccess (raw_clGetSupportedImageFormats ctx flags (getCLValue mtype) num (castPtr buff) nullPtr)\n $ peekArray (fromIntegral num) buff\n where\n flags = bitmaskFromFlags xs\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLImageInfo {\n cL_IMAGE_FORMAT=CL_IMAGE_FORMAT,\n cL_IMAGE_ELEMENT_SIZE=CL_IMAGE_ELEMENT_SIZE,\n cL_IMAGE_ROW_PITCH=CL_IMAGE_ROW_PITCH,\n cL_IMAGE_SLICE_PITCH=CL_IMAGE_SLICE_PITCH,\n cL_IMAGE_WIDTH=CL_IMAGE_WIDTH,\n cL_IMAGE_HEIGHT=CL_IMAGE_HEIGHT,\n cL_IMAGE_DEPTH=CL_IMAGE_DEPTH,\n };\n#endc\n{#enum CLImageInfo {upcaseFirstLetter} #}\n\n-- | Return image format descriptor specified when image is created with\n-- clCreateImage2D or clCreateImage3D.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_FORMAT'.\nclGetImageFormat :: CLMem -> IO CLImageFormat\nclGetImageFormat mem =\n wrapGetInfo (\\(dat :: Ptr CLImageFormat) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_FORMAT\n size = fromIntegral $ sizeOf (undefined :: CLImageFormat)\n \n-- | Return size of each element of the image memory object given by image. An\n-- element is made up of n channels. The value of n is given in 'CLImageFormat'\n-- descriptor.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_ELEMENT_SIZE'.\nclGetImageElementSize :: CLMem -> IO CSize \nclGetImageElementSize mem =\n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_ELEMENT_SIZE\n size = fromIntegral $ sizeOf (undefined :: CSize)\n \n-- | Return size in bytes of a row of elements of the image object given by\n-- image.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_ROW_PITCH'.\nclGetImageRowPitch :: CLMem -> IO CSize \nclGetImageRowPitch mem = \n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_ROW_PITCH\n size = fromIntegral $ sizeOf (undefined :: CSize)\n \n-- | Return size in bytes of a 2D slice for the 3D image object given by\n-- image. For a 2D image object this value will be 0.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_SLICE_PITCH'.\nclGetImageSlicePitch :: CLMem -> IO CSize \nclGetImageSlicePitch mem = \n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_SLICE_PITCH\n size = fromIntegral $ sizeOf (undefined :: CSize) \n \n-- | Return width of image in pixels.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_WIDTH'.\nclGetImageWidth :: CLMem -> IO CSize \nclGetImageWidth mem = \n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_WIDTH\n size = fromIntegral $ sizeOf (undefined :: CSize)\n \n-- | Return height of image in pixels.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_HEIGHT'.\nclGetImageHeight :: CLMem -> IO CSize \nclGetImageHeight mem = \n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_HEIGHT\n size = fromIntegral $ sizeOf (undefined :: CSize)\n\n-- | Return depth of the image in pixels. For a 2D image, depth equals 0.\n--\n-- This function execute OpenCL clGetImageInfo with 'CL_IMAGE_DEPTH'.\nclGetImageDepth :: CLMem -> IO CSize \nclGetImageDepth mem = \n wrapGetInfo (\\(dat :: Ptr CSize) ->\n raw_clGetImageInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_IMAGE_DEPTH\n size = fromIntegral $ sizeOf (undefined :: CSize)\n\n-- -----------------------------------------------------------------------------\n#c\nenum CLMemInfo {\n cL_MEM_TYPE=CL_MEM_TYPE,\n cL_MEM_FLAGS=CL_MEM_FLAGS,\n cL_MEM_SIZE=CL_MEM_SIZE,\n cL_MEM_HOST_PTR=CL_MEM_HOST_PTR,\n cL_MEM_MAP_COUNT=CL_MEM_MAP_COUNT,\n cL_MEM_REFERENCE_COUNT=CL_MEM_REFERENCE_COUNT,\n cL_MEM_CONTEXT=CL_MEM_CONTEXT,\n };\n#endc\n{#enum CLMemInfo {upcaseFirstLetter} #}\n\n-- | Returns the mem object type.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_TYPE'.\nclGetMemType :: CLMem -> IO CLMemObjectType\nclGetMemType mem =\n wrapGetInfo (\\(dat :: Ptr CLMemObjectType_) ->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_MEM_TYPE\n size = fromIntegral $ sizeOf (0::CLMemObjectType_)\n\n-- | Return the flags argument value specified when memobj was created.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_FLAGS'.\nclGetMemFlags :: CLMem -> IO [CLMemFlag]\nclGetMemFlags mem =\n wrapGetInfo (\\(dat :: Ptr CLMemFlags_)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) bitmaskToMemFlags\n where \n infoid = getCLValue CL_MEM_FLAGS\n size = fromIntegral $ sizeOf (0::CLMemFlags_)\n\n-- | Return actual size of memobj in bytes.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_SIZE'.\nclGetMemSize :: CLMem -> IO CSize\nclGetMemSize mem =\n wrapGetInfo (\\(dat :: Ptr CSize)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_SIZE\n size = fromIntegral $ sizeOf (0::CSize)\n\n-- | Return the host_ptr argument value specified when memobj is created.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_HOST_PTR'.\nclGetMemHostPtr :: CLMem -> IO (Ptr ())\nclGetMemHostPtr mem =\n wrapGetInfo (\\(dat :: Ptr (Ptr ()))->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_HOST_PTR\n size = fromIntegral $ sizeOf (nullPtr::Ptr ())\n\n-- | Map count. The map count returned should be considered immediately\n-- stale. It is unsuitable for general use in applications. This feature is\n-- provided for debugging.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_MAP_COUNT'.\nclGetMemMapCount :: CLMem -> IO CLuint\nclGetMemMapCount mem =\n wrapGetInfo (\\(dat :: Ptr CLuint)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_MAP_COUNT\n size = fromIntegral $ sizeOf (0 :: CLuint)\n\n-- | Return memobj reference count. The reference count returned should be\n-- considered immediately stale. It is unsuitable for general use in\n-- applications. This feature is provided for identifying memory leaks.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_REFERENCE_COUNT'.\nclGetMemReferenceCount :: CLMem -> IO CLuint\nclGetMemReferenceCount mem =\n wrapGetInfo (\\(dat :: Ptr CLuint)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0 :: CLuint)\n\n-- | Return context specified when memory object is created.\n--\n-- This function execute OpenCL clGetMemObjectInfo with 'CL_MEM_CONTEXT'.\nclGetMemContext :: CLMem -> IO CLContext\nclGetMemContext mem =\n wrapGetInfo (\\(dat :: Ptr CLContext)->\n raw_clGetMemObjectInfo mem infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_MEM_CONTEXT\n size = fromIntegral $ sizeOf (0 :: CLuint)\n\n-- -----------------------------------------------------------------------------\n{-| Creates a sampler object. A sampler object describes how to sample an image\nwhen the image is read in the kernel. The built-in functions to read from an\nimage in a kernel take a sampler as an argument. The sampler arguments to the\nimage read function can be sampler objects created using OpenCL functions and\npassed as argument values to the kernel or can be samplers declared inside a\nkernel. In this section we discuss how sampler objects are created using OpenCL\nfunctions.\n\nReturns a valid non-zero sampler object if the sampler object is created\nsuccessfully. Otherwise, it throws one of the following 'CLError' exceptions:\n\n * 'CL_INVALID_CONTEXT' if context is not a valid context.\n\n * 'CL_INVALID_VALUE' if addressing_mode, filter_mode, or normalized_coords or a\ncombination of these argument values are not valid.\n\n * 'CL_INVALID_OPERATION' if images are not supported by any device associated\nwith context (i.e. 'CL_DEVICE_IMAGE_SUPPORT' specified in the table of OpenCL\nDevice Queries for clGetDeviceInfo is 'False').\n\n * 'CL_OUT_OF_HOST_MEMORY' if there is a failure to allocate resources required\nby the OpenCL implementation on the host.\n-}\nclCreateSampler :: CLContext -> Bool -> CLAddressingMode -> CLFilterMode \n -> IO CLSampler\nclCreateSampler ctx norm am fm = wrapPError $ \\perr -> do\n raw_clCreateSampler ctx (fromBool norm) (getCLValue am) (getCLValue fm) perr\n\n-- | Increments the sampler reference count. 'clCreateSampler' does an implicit\n-- retain. Returns 'True' if the function is executed successfully. It returns\n-- 'False' if sampler is not a valid sampler object.\nclRetainSampler :: CLSampler -> IO Bool\nclRetainSampler mem = wrapCheckSuccess $ raw_clRetainSampler mem\n\n-- | Decrements the sampler reference count. The sampler object is deleted after\n-- the reference count becomes zero and commands queued for execution on a\n-- command-queue(s) that use sampler have finished. 'clReleaseSampler' returns\n-- 'True' if the function is executed successfully. It returns 'False' if\n-- sampler is not a valid sampler object.\nclReleaseSampler :: CLSampler -> IO Bool\nclReleaseSampler mem = wrapCheckSuccess $ raw_clReleaseSampler mem\n\n#c\nenum CLSamplerInfo {\n cL_SAMPLER_REFERENCE_COUNT=CL_SAMPLER_REFERENCE_COUNT,\n cL_SAMPLER_CONTEXT=CL_SAMPLER_CONTEXT,\n cL_SAMPLER_ADDRESSING_MODE=CL_SAMPLER_ADDRESSING_MODE,\n cL_SAMPLER_FILTER_MODE=CL_SAMPLER_FILTER_MODE,\n cL_SAMPLER_NORMALIZED_COORDS=CL_SAMPLER_NORMALIZED_COORDS\n };\n#endc\n{#enum CLSamplerInfo {upcaseFirstLetter} #}\n\n-- | Return the sampler reference count. The reference count returned should be\n-- considered immediately stale. It is unsuitable for general use in\n-- applications. This feature is provided for identifying memory leaks.\n--\n-- This function execute OpenCL clGetSamplerInfo with\n-- 'CL_SAMPLER_REFERENCE_COUNT'.\nclGetSamplerReferenceCount :: CLSampler -> IO CLuint\nclGetSamplerReferenceCount sam =\n wrapGetInfo (\\(dat :: Ptr CLuint)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_SAMPLER_REFERENCE_COUNT\n size = fromIntegral $ sizeOf (0 :: CLuint)\n\n-- | Return the context specified when the sampler is created.\n--\n-- This function execute OpenCL clGetSamplerInfo with 'CL_SAMPLER_CONTEXT'.\nclGetSamplerContext :: CLSampler -> IO CLContext\nclGetSamplerContext sam =\n wrapGetInfo (\\(dat :: Ptr CLContext)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) id\n where \n infoid = getCLValue CL_SAMPLER_CONTEXT\n size = fromIntegral $ sizeOf (nullPtr :: CLContext)\n\n-- | Return the value specified by addressing_mode argument to clCreateSampler.\n--\n-- This function execute OpenCL clGetSamplerInfo with\n-- 'CL_SAMPLER_ADDRESSING_MODE'.\nclGetSamplerAddressingMode :: CLSampler -> IO CLAddressingMode\nclGetSamplerAddressingMode sam =\n wrapGetInfo (\\(dat :: Ptr CLAddressingMode_)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_SAMPLER_ADDRESSING_MODE\n size = fromIntegral $ sizeOf (0 :: CLAddressingMode_)\n\n-- | Return the value specified by filter_mode argument to clCreateSampler.\n--\n-- This function execute OpenCL clGetSamplerInfo with 'CL_SAMPLER_FILTER_MODE'.\nclGetSamplerFilterMode :: CLSampler -> IO CLFilterMode\nclGetSamplerFilterMode sam =\n wrapGetInfo (\\(dat :: Ptr CLFilterMode_)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) getEnumCL\n where \n infoid = getCLValue CL_SAMPLER_FILTER_MODE\n size = fromIntegral $ sizeOf (0 :: CLFilterMode_)\n\n-- | Return the value specified by normalized_coords argument to\n-- clCreateSampler.\n--\n-- This function execute OpenCL clGetSamplerInfo with\n-- 'CL_SAMPLER_NORMALIZED_COORDS'.\nclGetSamplerNormalizedCoords :: CLSampler -> IO Bool\nclGetSamplerNormalizedCoords sam =\n wrapGetInfo (\\(dat :: Ptr CLbool)->\n raw_clGetSamplerInfo sam infoid size (castPtr dat)) (\/=0)\n where \n infoid = getCLValue CL_SAMPLER_NORMALIZED_COORDS\n size = fromIntegral $ sizeOf (0 :: CLbool)\n\n-- -----------------------------------------------------------------------------\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"8ec4e80cd1b146adc0c26b3f610a72dc12ee0c34","subject":"Wrap image and font creation in Maybe","message":"Wrap image and font creation in Maybe\n","repos":"cocreature\/nanovg-hs","old_file":"src\/NanoVG\/Internal.chs","new_file":"src\/NanoVG\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RecordWildCards #-}\nmodule NanoVG.Internal where\n\nimport Data.Bits\nimport Data.ByteString hiding (null)\nimport qualified Data.Set as S\nimport qualified Data.Text as T\nimport qualified Data.Text.Encoding as T\nimport Data.Word\nimport Foreign.C.String (CString)\nimport Foreign.C.Types\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Linear.Matrix\nimport Linear.V2\nimport Linear.V3\nimport Linear.V4\nimport Prelude hiding (null)\n\n-- For now only the GL3 backend is supported\n#define NANOVG_GL3\n-- We need to include this to define GLuint\n#include \"GL\/glew.h\"\n#include \"nanovg.h\"\n#include \"nanovg_gl.h\"\n#include \"nanovg_wrapper.h\"\n\nwithCString :: T.Text -> (CString -> IO b) -> IO b\nwithCString t = useAsCString (T.encodeUtf8 t)\n\nuseAsCStringLen' :: ByteString -> ((Ptr CUChar,CInt) -> IO a) -> IO a\nuseAsCStringLen' bs f = useAsCStringLen bs (\\(ptr,len) -> f (castPtr ptr,fromIntegral len))\n\nuseAsPtr :: ByteString -> (Ptr CUChar -> IO a) -> IO a\nuseAsPtr bs f = useAsCStringLen bs (\\(ptr,_) -> f (castPtr ptr))\n\nzero :: Num a => (a -> b) -> b\nzero f = f 0\n\nnull :: (Ptr a -> b) -> b\nnull f = f nullPtr\n\nnewtype FileName = FileName { unwrapFileName :: T.Text }\n\nnewtype Image = Image {imageHandle :: CInt} deriving (Show,Read,Eq,Ord)\n\nnewtype Font = Font {fontHandle :: CInt} deriving (Show,Read,Eq,Ord)\n\n{#pointer *NVGcontext as Context newtype#}\n\nnewtype Transformation = Transformation (M23 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Transformation where\n sizeOf _ = sizeOf (0 :: CFloat) * 6\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peek p'\n b <- peekElemOff p' 1\n c <- peekElemOff p' 2\n d <- peekElemOff p' 3\n e <- peekElemOff p' 4\n f <- peekElemOff p' 5\n pure (Transformation\n (V2 (V3 a c e)\n (V3 b d f)))\n poke p (Transformation (V2 (V3 a c e) (V3 b d f))) =\n do let p' = castPtr p :: Ptr CFloat\n poke p' a\n pokeElemOff p' 1 b\n pokeElemOff p' 2 c\n pokeElemOff p' 3 d\n pokeElemOff p' 4 e\n pokeElemOff p' 5 f\n\nnewtype Extent = Extent (V2 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Extent where\n sizeOf _ = sizeOf (0 :: CFloat) * 4\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peekElemOff p' 0\n b <- peekElemOff p' 1\n pure (Extent (V2 a b))\n poke p (Extent (V2 a b)) =\n do let p' = castPtr p :: Ptr CFloat\n pokeElemOff p' 0 a\n pokeElemOff p' 1 b\n\n-- | rgba\ndata Color = Color !CFloat !CFloat !CFloat !CFloat deriving (Show,Read,Eq,Ord)\n\n{#pointer *NVGcolor as ColorPtr -> Color#}\n\ninstance Storable Color where\n sizeOf _ = sizeOf (0 :: CFloat) * 4\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n r <- peek p'\n g <- peekElemOff p' 1\n b <- peekElemOff p' 2\n a <- peekElemOff p' 3\n pure (Color r g b a)\n poke p (Color r g b a) =\n do let p' = castPtr p :: Ptr CFloat\n poke p' r\n pokeElemOff p' 1 g\n pokeElemOff p' 2 b\n pokeElemOff p' 3 a\n\ndata Paint =\n Paint {xform :: Transformation\n ,extent :: Extent\n ,radius :: !CFloat\n ,feather :: !CFloat\n ,innerColor :: !Color\n ,outerColor :: !Color\n ,image :: !Image} deriving (Show,Read,Eq,Ord)\n\n{#pointer *NVGpaint as PaintPtr -> Paint#}\n\ninstance Storable Paint where\n sizeOf _ = 76\n alignment _ = 4\n peek p =\n do xform <- peek (castPtr (p `plusPtr` {#offsetof NVGpaint->xform#}))\n extent <- peek (castPtr (p `plusPtr` {#offsetof NVGpaint->extent#}))\n radius <- {#get NVGpaint->radius#} p\n feather <- {#get NVGpaint->feather#} p\n innerColor <- peek (castPtr (p `plusPtr` 40))\n outerColor <- peek (castPtr (p `plusPtr` 56))\n image <- peek (castPtr (p `plusPtr` 72))\n pure (Paint xform extent radius feather innerColor outerColor (Image image))\n poke p (Paint{..}) =\n do poke (castPtr (p `plusPtr` {#offsetof NVGpaint->xform#})) xform\n poke (castPtr (p `plusPtr` {#offsetof NVGpaint->extent#})) extent\n {#set NVGpaint->radius#} p radius\n {#set NVGpaint->feather#} p feather\n poke (castPtr (p `plusPtr` 40)) innerColor\n poke (castPtr (p `plusPtr` 56)) outerColor\n poke (castPtr (p `plusPtr` 72)) (imageHandle image)\n\n{#enum NVGwinding as Winding\n {} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGsolidity as Solidity\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGlineCap as LineCap\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGalign as Align \n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\ndata GlyphPosition =\n GlyphPosition { str :: !(Ptr CChar)\n , glyphX :: !CFloat\n -- Remove prefix once GHC 8 is released\n , glyphPosMinX :: !CFloat\n , glyphPosMaxX :: !CFloat}\n\n{#pointer *NVGglyphPosition as GlyphPositionPtr -> GlyphPosition#}\n\ninstance Storable GlyphPosition where\n sizeOf _ = 24\n alignment _ = {#alignof NVGglyphPosition#}\n peek p =\n do str <- {#get NVGglyphPosition->str#} p\n x <- {#get NVGglyphPosition->x#} p\n minx <- {#get NVGglyphPosition->minx#} p\n maxx <- {#get NVGglyphPosition->maxx#} p\n pure (GlyphPosition str x minx maxx)\n poke p (GlyphPosition str x minx maxx) =\n do {#set NVGglyphPosition->str#} p str\n {#set NVGglyphPosition->x#} p x\n {#set NVGglyphPosition->minx#} p minx\n {#set NVGglyphPosition->maxx#} p maxx\n\ndata TextRow =\n TextRow {start :: !(Ptr CChar)\n ,end :: !(Ptr CChar)\n ,next :: !(Ptr CChar)\n ,width :: !CFloat\n -- Remove prefix once GHC 8 is released\n ,textRowMinX :: !CFloat\n ,textRowMaxX :: !CFloat} deriving (Show,Eq,Ord)\n\ninstance Storable TextRow where\n sizeOf _ = 40\n alignment _ = {#alignof NVGtextRow#}\n peek p =\n do start <- {#get NVGtextRow->start#} p\n end <- {#get NVGtextRow->end#} p\n next <- {#get NVGtextRow->next#} p\n width <- {#get NVGtextRow->width#} p\n minX <- {#get NVGtextRow->minx#} p\n maxX <- {#get NVGtextRow->maxx#} p\n pure (TextRow start end next width minX maxX)\n poke p (TextRow {..}) =\n do {#set NVGtextRow->start#} p start\n {#set NVGtextRow->end#} p end\n {#set NVGtextRow->next#} p next\n {#set NVGtextRow->width#} p width\n {#set NVGtextRow->minx#} p textRowMinX\n {#set NVGtextRow->maxx#} p textRowMaxX\n\n{#pointer *NVGtextRow as TextRowPtr -> TextRow#}\n\n{#enum NVGimageFlags as ImageFlags\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#fun unsafe nvgBeginFrame as beginFrame\n {`Context',`CInt',`CInt',`Float'} -> `()'#}\n\n{#fun unsafe nvgCancelFrame as canelFrame\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgEndFrame as endFrame\n {`Context'} -> `()'#}\n\n{#fun pure unsafe nvgRGB_ as rgb\n {id`CUChar',id`CUChar',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgRGBf_ as rgbf\n {`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgRGBA_ as rgba\n {id`CUChar',id`CUChar',id`CUChar',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgRGBAf_ as rgbaf\n {`CFloat',`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgLerpRGBA_ as lerpRGBA\n {with*`Color',with*`Color',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgTransRGBA_ as transRGBA\n {with*`Color',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgTransRGBAf_ as transRGBAf\n {with*`Color',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgHSL_ as hsl\n {`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgHSLA_ as hsla\n {`CFloat',`CFloat',`CFloat',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun unsafe nvgSave as save\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgRestore as restore\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgReset as reset\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgStrokeColor_ as strokeColor\n {`Context',with*`Color'} -> `()'#}\n\n{#fun unsafe nvgStrokePaint_ as strokePaint\n {`Context',with*`Paint'} -> `()'#}\n\n{#fun unsafe nvgFillColor_ as fillColor\n {`Context',with*`Color'} -> `()'#}\n\n{#fun unsafe nvgFillPaint_ as fillPaint\n {`Context',with*`Paint'} -> `()'#}\n\n{#fun unsafe nvgMiterLimit as miterLimit\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgStrokeWidth as strokeWidth\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgLineCap as lineCap\n {`Context',`LineCap'} -> `()'#}\n\n{#fun unsafe nvgLineJoin as lineJoin\n {`Context',`LineCap'} -> `()'#}\n\n{#fun unsafe nvgGlobalAlpha as globalAlpha\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgResetTransform as resetTransform\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgTransform as transform\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTranslate as translate\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgRotate as rotate\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgSkewX as skewX\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgSkewY as skewY\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgScale as scale\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\npeekTransformation :: Ptr CFloat -> IO Transformation\npeekTransformation = peek . castPtr\n\nallocaTransformation :: (Ptr CFloat -> IO b) -> IO b\nallocaTransformation f = alloca (\\(p :: Ptr Transformation) -> f (castPtr p))\n\nwithTransformation :: Transformation -> (Ptr CFloat -> IO b) -> IO b\nwithTransformation t f = with t (\\p -> f (castPtr p)) \n\n{#fun unsafe nvgCurrentTransform as currentTransform\n {`Context',allocaTransformation-`Transformation'peekTransformation*} -> `()'#}\n\n{#fun unsafe nvgTransformIdentity as transformIdentity\n {allocaTransformation-`Transformation'peekTransformation*} -> `()'#}\n\n{#fun unsafe nvgTransformTranslate as transformTranslate\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformScale as transformScale\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformRotate as transformRotate\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformSkewX as transformSkewX\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformSkewY as transformSkewY\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformMultiply as transformMultiply\n {allocaTransformation-`Transformation'peekTransformation*,withTransformation*`Transformation'} -> `()'#}\n\n{#fun unsafe nvgTransformInverse as transformInverse\n {allocaTransformation-`Transformation'peekTransformation*,withTransformation*`Transformation'} -> `()'#}\n\n{#fun pure unsafe nvgTransformPoint as transformPoint\n {alloca-`CFloat'peek*,alloca-`CFloat'peek*,withTransformation*`Transformation',`CFloat',`CFloat'} -> `()'#}\n\n{#fun pure unsafe nvgDegToRad as degToRad\n {`CFloat'} -> `CFloat'#}\n\n{#fun pure unsafe nvgRadToDeg as radToDeg\n {`CFloat'} -> `CFloat'#}\n\nsafeImage :: CInt -> Maybe Image\nsafeImage i\n | i < 0 = Nothing\n | otherwise = Just (Image i)\n\n{#fun unsafe nvgCreateImage as createImage\n {`Context','withCString.unwrapFileName'*`FileName',`CInt'} -> `Maybe Image'safeImage#}\n\n{#fun unsafe nvgCreateImageMem as createImageMem\n {`Context',`ImageFlags',useAsCStringLen'*`ByteString'&} -> `Maybe cImage'safeImage#}\n\n{#fun unsafe nvgCreateImageRGBA as createImageRGBA\n {`Context',`CInt',`CInt',`ImageFlags',useAsPtr*`ByteString'} -> `Maybe Image'safeImage#}\n\n{#fun unsafe nvgUpdateImage as updateImage\n {`Context',imageHandle`Image',useAsPtr*`ByteString'} -> `()'#}\n\n{#fun unsafe nvgImageSize as imageSize\n {`Context',imageHandle`Image',alloca-`CInt'peek*,alloca-`CInt'peek*} -> `()'#}\n\n{#fun unsafe nvgDeleteImage as deleteImage\n {`Context',imageHandle`Image'} -> `()'#}\n\n{#fun unsafe nvgLinearGradient_ as linearGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgBoxGradient_ as boxGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgRadialGradient_ as radialGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgImagePattern_ as imagePattern\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',imageHandle`Image',`CFloat',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgScissor as scissor\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgIntersectScissor as intersectScissor\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgResetScissor as resetScissor\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgBeginPath as beginPath\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgMoveTo as moveTo\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgLineTo as lineTo\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgBezierTo as bezierTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgQuadTo as quadTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgArcTo as arcTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgClosePath as closePath\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgPathWinding as pathWinding\n {`Context', `CInt'} -> `()'#}\n\n{#fun unsafe nvgArc as arc\n {`Context',`CFloat',`CFloat', `CFloat', `CFloat', `CFloat', `Winding'} -> `()'#}\n\n{#fun unsafe nvgRect as rect\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgRoundedRect as roundedRect\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgEllipse as ellipse\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgCircle as circle\n {`Context',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgFill as fill\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgStroke as stroke\n {`Context'} -> `()'#}\n\nsafeFont :: CInt -> Maybe Font\nsafeFont i\n | i < 0 = Nothing\n | otherwise = Just (Font i)\n\n{#fun unsafe nvgCreateFont as createFont\n {`Context',withCString*`T.Text','withCString.unwrapFileName'*`FileName'} -> `Maybe Font'safeFont#}\n\n{#fun unsafe nvgCreateFontMem as createFontMem\n {`Context',withCString*`T.Text',useAsCStringLen'*`ByteString'&,zero-`CInt'} -> `Maybe Font'safeFont#}\n\n{#fun unsafe nvgFindFont as findFont\n {`Context', withCString*`T.Text'} -> `Maybe Font'safeFont#}\n\n{#fun unsafe nvgFontSize as fontSize\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgFontBlur as fontBlur\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTextLetterSpacing as textLetterSpacing\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTextLineHeight as textLineHeight\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTextAlign as textAlign\n {`Context',bitMask`S.Set Align'} -> `()'#}\n\n{#fun unsafe nvgFontFaceId as fontFaceId\n {`Context',fontHandle`Font'} -> `()'#}\n\n{#fun unsafe nvgFontFace as fontFace\n {`Context',withCString*`T.Text'} -> `()'#}\n\n{#fun unsafe nvgText as text\n {`Context',`CFloat',`CFloat',id`Ptr CChar',id`Ptr CChar'} -> `()'#}\n\n{#fun unsafe nvgTextBox as textBox\n {`Context',`CFloat',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar'} -> `()'#}\n\nnewtype Bounds = Bounds (V4 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Bounds where\n sizeOf _ = sizeOf (0 :: CFloat) * 4\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peekElemOff p' 0\n b <- peekElemOff p' 1\n c <- peekElemOff p' 2\n d <- peekElemOff p' 3\n pure (Bounds (V4 a b c d))\n poke p (Bounds (V4 a b c d)) =\n do let p' = castPtr p :: Ptr CFloat\n pokeElemOff p' 0 a\n pokeElemOff p' 1 b\n pokeElemOff p' 2 c\n pokeElemOff p' 3 d\n\npeekBounds :: Ptr CFloat -> IO Bounds\npeekBounds = peek . castPtr\n\nallocaBounds :: (Ptr CFloat -> IO b) -> IO b\nallocaBounds f = alloca (\\(p :: Ptr Bounds) -> f (castPtr p))\n\nwithBounds :: Bounds -> (Ptr CFloat -> IO b) -> IO b\nwithBounds t f = with t (\\p -> f (castPtr p)) \n\n{#fun unsafe nvgTextBounds as textBounds\n {`Context',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar', allocaBounds-`Bounds'peekBounds*} -> `()'#}\n\n{#fun unsafe nvgTextBoxBounds as textBoxBounds\n {`Context',`CFloat',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar',allocaBounds-`Bounds'peekBounds*} -> `()'#}\n\n-- TODO: This should probably take a vector\n{#fun unsafe nvgTextGlyphPositions as textGlyphPositions\n {`Context',`CFloat',`CFloat',id`Ptr CChar',id`Ptr CChar',`GlyphPositionPtr', `CInt'} -> `CInt'#}\n\n{#fun unsafe nvgTextMetrics as textMetrics\n {`Context',alloca-`CFloat'peek*,alloca-`CFloat'peek*,alloca-`CFloat'peek*} -> `()'#}\n\n-- TODO: This should probably take a vector\n{#fun unsafe nvgTextBreakLines as textBreakLines\n {`Context',id`Ptr CChar',id`Ptr CChar',`CFloat',`TextRowPtr',`CInt'} -> `CInt'#}\n\n{#enum NVGcreateFlags as CreateFlags\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\nbitMask :: Enum a => S.Set a -> CInt\nbitMask = S.fold (.|.) 0 . S.map (fromIntegral . fromEnum)\n\n{#fun unsafe nvgCreateGL3 as createGL3\n {bitMask`S.Set CreateFlags'} -> `Context'#}\n{#fun unsafe nvgDeleteGL3 as deleteGL3\n {`Context'} -> `()'#}\n\ntype GLuint = Word32\n\n{#fun unsafe nvglCreateImageFromHandleGL3 as createImageFromHandleGL3\n {`Context',fromIntegral`GLuint',`CInt',`CInt',`CreateFlags'} -> `Image'Image#}\n\n{#fun unsafe nvglImageHandleGL3 as imageHandleGL3\n {`Context',imageHandle`Image'} -> `GLuint'fromIntegral#}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RecordWildCards #-}\nmodule NanoVG.Internal where\n\nimport Data.Bits\nimport Data.ByteString hiding (null)\nimport qualified Data.Set as S\nimport qualified Data.Text as T\nimport qualified Data.Text.Encoding as T\nimport Data.Word\nimport Foreign.C.String (CString)\nimport Foreign.C.Types\nimport Foreign.Marshal.Alloc\nimport Foreign.Marshal.Utils\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Linear.Matrix\nimport Linear.V2\nimport Linear.V3\nimport Linear.V4\nimport Prelude hiding (null)\n\n-- For now only the GL3 backend is supported\n#define NANOVG_GL3\n-- We need to include this to define GLuint\n#include \"GL\/glew.h\"\n#include \"nanovg.h\"\n#include \"nanovg_gl.h\"\n#include \"nanovg_wrapper.h\"\n\nwithCString :: T.Text -> (CString -> IO b) -> IO b\nwithCString t = useAsCString (T.encodeUtf8 t)\n\nuseAsCStringLen' :: ByteString -> ((Ptr CUChar,CInt) -> IO a) -> IO a\nuseAsCStringLen' bs f = useAsCStringLen bs (\\(ptr,len) -> f (castPtr ptr,fromIntegral len))\n\nuseAsPtr :: ByteString -> (Ptr CUChar -> IO a) -> IO a\nuseAsPtr bs f = useAsCStringLen bs (\\(ptr,_) -> f (castPtr ptr))\n\nzero :: Num a => (a -> b) -> b\nzero f = f 0\n\nnull :: (Ptr a -> b) -> b\nnull f = f nullPtr\n\nnewtype FileName = FileName { unwrapFileName :: T.Text }\n\nnewtype Image = Image {imageHandle :: CInt} deriving (Show,Read,Eq,Ord)\n\nnewtype Font = Font {fontHandle :: CInt} deriving (Show,Read,Eq,Ord)\n\n{#pointer *NVGcontext as Context newtype#}\n\nnewtype Transformation = Transformation (M23 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Transformation where\n sizeOf _ = sizeOf (0 :: CFloat) * 6\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peek p'\n b <- peekElemOff p' 1\n c <- peekElemOff p' 2\n d <- peekElemOff p' 3\n e <- peekElemOff p' 4\n f <- peekElemOff p' 5\n pure (Transformation\n (V2 (V3 a c e)\n (V3 b d f)))\n poke p (Transformation (V2 (V3 a c e) (V3 b d f))) =\n do let p' = castPtr p :: Ptr CFloat\n poke p' a\n pokeElemOff p' 1 b\n pokeElemOff p' 2 c\n pokeElemOff p' 3 d\n pokeElemOff p' 4 e\n pokeElemOff p' 5 f\n\nnewtype Extent = Extent (V2 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Extent where\n sizeOf _ = sizeOf (0 :: CFloat) * 4\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peekElemOff p' 0\n b <- peekElemOff p' 1\n pure (Extent (V2 a b))\n poke p (Extent (V2 a b)) =\n do let p' = castPtr p :: Ptr CFloat\n pokeElemOff p' 0 a\n pokeElemOff p' 1 b\n\n-- | rgba\ndata Color = Color !CFloat !CFloat !CFloat !CFloat deriving (Show,Read,Eq,Ord)\n\n{#pointer *NVGcolor as ColorPtr -> Color#}\n\ninstance Storable Color where\n sizeOf _ = sizeOf (0 :: CFloat) * 4\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n r <- peek p'\n g <- peekElemOff p' 1\n b <- peekElemOff p' 2\n a <- peekElemOff p' 3\n pure (Color r g b a)\n poke p (Color r g b a) =\n do let p' = castPtr p :: Ptr CFloat\n poke p' r\n pokeElemOff p' 1 g\n pokeElemOff p' 2 b\n pokeElemOff p' 3 a\n\ndata Paint =\n Paint {xform :: Transformation\n ,extent :: Extent\n ,radius :: !CFloat\n ,feather :: !CFloat\n ,innerColor :: !Color\n ,outerColor :: !Color\n ,image :: !Image} deriving (Show,Read,Eq,Ord)\n\n{#pointer *NVGpaint as PaintPtr -> Paint#}\n\ninstance Storable Paint where\n sizeOf _ = 76\n alignment _ = 4\n peek p =\n do xform <- peek (castPtr (p `plusPtr` {#offsetof NVGpaint->xform#}))\n extent <- peek (castPtr (p `plusPtr` {#offsetof NVGpaint->extent#}))\n radius <- {#get NVGpaint->radius#} p\n feather <- {#get NVGpaint->feather#} p\n innerColor <- peek (castPtr (p `plusPtr` 40))\n outerColor <- peek (castPtr (p `plusPtr` 56))\n image <- peek (castPtr (p `plusPtr` 72))\n pure (Paint xform extent radius feather innerColor outerColor (Image image))\n poke p (Paint{..}) =\n do poke (castPtr (p `plusPtr` {#offsetof NVGpaint->xform#})) xform\n poke (castPtr (p `plusPtr` {#offsetof NVGpaint->extent#})) extent\n {#set NVGpaint->radius#} p radius\n {#set NVGpaint->feather#} p feather\n poke (castPtr (p `plusPtr` 40)) innerColor\n poke (castPtr (p `plusPtr` 56)) outerColor\n poke (castPtr (p `plusPtr` 72)) (imageHandle image)\n\n{#enum NVGwinding as Winding\n {} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGsolidity as Solidity\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGlineCap as LineCap\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#enum NVGalign as Align \n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\ndata GlyphPosition =\n GlyphPosition { str :: !(Ptr CChar)\n , glyphX :: !CFloat\n -- Remove prefix once GHC 8 is released\n , glyphPosMinX :: !CFloat\n , glyphPosMaxX :: !CFloat}\n\n{#pointer *NVGglyphPosition as GlyphPositionPtr -> GlyphPosition#}\n\ninstance Storable GlyphPosition where\n sizeOf _ = 24\n alignment _ = {#alignof NVGglyphPosition#}\n peek p =\n do str <- {#get NVGglyphPosition->str#} p\n x <- {#get NVGglyphPosition->x#} p\n minx <- {#get NVGglyphPosition->minx#} p\n maxx <- {#get NVGglyphPosition->maxx#} p\n pure (GlyphPosition str x minx maxx)\n poke p (GlyphPosition str x minx maxx) =\n do {#set NVGglyphPosition->str#} p str\n {#set NVGglyphPosition->x#} p x\n {#set NVGglyphPosition->minx#} p minx\n {#set NVGglyphPosition->maxx#} p maxx\n\ndata TextRow =\n TextRow {start :: !(Ptr CChar)\n ,end :: !(Ptr CChar)\n ,next :: !(Ptr CChar)\n ,width :: !CFloat\n -- Remove prefix once GHC 8 is released\n ,textRowMinX :: !CFloat\n ,textRowMaxX :: !CFloat} deriving (Show,Eq,Ord)\n\ninstance Storable TextRow where\n sizeOf _ = 40\n alignment _ = {#alignof NVGtextRow#}\n peek p =\n do start <- {#get NVGtextRow->start#} p\n end <- {#get NVGtextRow->end#} p\n next <- {#get NVGtextRow->next#} p\n width <- {#get NVGtextRow->width#} p\n minX <- {#get NVGtextRow->minx#} p\n maxX <- {#get NVGtextRow->maxx#} p\n pure (TextRow start end next width minX maxX)\n poke p (TextRow {..}) =\n do {#set NVGtextRow->start#} p start\n {#set NVGtextRow->end#} p end\n {#set NVGtextRow->next#} p next\n {#set NVGtextRow->width#} p width\n {#set NVGtextRow->minx#} p textRowMinX\n {#set NVGtextRow->maxx#} p textRowMaxX\n\n{#pointer *NVGtextRow as TextRowPtr -> TextRow#}\n\n{#enum NVGimageFlags as ImageFlags\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\n{#fun unsafe nvgBeginFrame as beginFrame\n {`Context',`CInt',`CInt',`Float'} -> `()'#}\n\n{#fun unsafe nvgCancelFrame as canelFrame\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgEndFrame as endFrame\n {`Context'} -> `()'#}\n\n{#fun pure unsafe nvgRGB_ as rgb\n {id`CUChar',id`CUChar',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgRGBf_ as rgbf\n {`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgRGBA_ as rgba\n {id`CUChar',id`CUChar',id`CUChar',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgRGBAf_ as rgbaf\n {`CFloat',`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgLerpRGBA_ as lerpRGBA\n {with*`Color',with*`Color',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgTransRGBA_ as transRGBA\n {with*`Color',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgTransRGBAf_ as transRGBAf\n {with*`Color',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgHSL_ as hsl\n {`CFloat',`CFloat',`CFloat',alloca-`Color'peek*} -> `()'#}\n\n{#fun pure unsafe nvgHSLA_ as hsla\n {`CFloat',`CFloat',`CFloat',id`CUChar',alloca-`Color'peek*} -> `()'#}\n\n{#fun unsafe nvgSave as save\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgRestore as restore\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgReset as reset\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgStrokeColor_ as strokeColor\n {`Context',with*`Color'} -> `()'#}\n\n{#fun unsafe nvgStrokePaint_ as strokePaint\n {`Context',with*`Paint'} -> `()'#}\n\n{#fun unsafe nvgFillColor_ as fillColor\n {`Context',with*`Color'} -> `()'#}\n\n{#fun unsafe nvgFillPaint_ as fillPaint\n {`Context',with*`Paint'} -> `()'#}\n\n{#fun unsafe nvgMiterLimit as miterLimit\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgStrokeWidth as strokeWidth\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgLineCap as lineCap\n {`Context',`LineCap'} -> `()'#}\n\n{#fun unsafe nvgLineJoin as lineJoin\n {`Context',`LineCap'} -> `()'#}\n\n{#fun unsafe nvgGlobalAlpha as globalAlpha\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgResetTransform as resetTransform\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgTransform as transform\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTranslate as translate\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgRotate as rotate\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgSkewX as skewX\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgSkewY as skewY\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgScale as scale\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\npeekTransformation :: Ptr CFloat -> IO Transformation\npeekTransformation = peek . castPtr\n\nallocaTransformation :: (Ptr CFloat -> IO b) -> IO b\nallocaTransformation f = alloca (\\(p :: Ptr Transformation) -> f (castPtr p))\n\nwithTransformation :: Transformation -> (Ptr CFloat -> IO b) -> IO b\nwithTransformation t f = with t (\\p -> f (castPtr p)) \n\n{#fun unsafe nvgCurrentTransform as currentTransform\n {`Context',allocaTransformation-`Transformation'peekTransformation*} -> `()'#}\n\n{#fun unsafe nvgTransformIdentity as transformIdentity\n {allocaTransformation-`Transformation'peekTransformation*} -> `()'#}\n\n{#fun unsafe nvgTransformTranslate as transformTranslate\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformScale as transformScale\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformRotate as transformRotate\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformSkewX as transformSkewX\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformSkewY as transformSkewY\n {allocaTransformation-`Transformation'peekTransformation*,`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTransformMultiply as transformMultiply\n {allocaTransformation-`Transformation'peekTransformation*,withTransformation*`Transformation'} -> `()'#}\n\n{#fun unsafe nvgTransformInverse as transformInverse\n {allocaTransformation-`Transformation'peekTransformation*,withTransformation*`Transformation'} -> `()'#}\n\n{#fun pure unsafe nvgTransformPoint as transformPoint\n {alloca-`CFloat'peek*,alloca-`CFloat'peek*,withTransformation*`Transformation',`CFloat',`CFloat'} -> `()'#}\n\n{#fun pure unsafe nvgDegToRad as degToRad\n {`CFloat'} -> `CFloat'#}\n\n{#fun pure unsafe nvgRadToDeg as radToDeg\n {`CFloat'} -> `CFloat'#}\n\n{#fun unsafe nvgCreateImage as createImage\n {`Context','withCString.unwrapFileName'*`FileName',`CInt'} -> `Image'Image#}\n\n{#fun unsafe nvgCreateImageMem as createImageMem\n {`Context',`ImageFlags',useAsCStringLen'*`ByteString'&} -> `Image'Image#}\n\n{#fun unsafe nvgCreateImageRGBA as createImageRGBA\n {`Context',`CInt',`CInt',`ImageFlags',useAsPtr*`ByteString'} -> `Image'Image#}\n\n{#fun unsafe nvgUpdateImage as updateImage\n {`Context',imageHandle`Image',useAsPtr*`ByteString'} -> `()'#}\n\n{#fun unsafe nvgImageSize as imageSize\n {`Context',imageHandle`Image',alloca-`CInt'peek*,alloca-`CInt'peek*} -> `()'#}\n\n{#fun unsafe nvgDeleteImage as deleteImage\n {`Context',imageHandle`Image'} -> `()'#}\n\n{#fun unsafe nvgLinearGradient_ as linearGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgBoxGradient_ as boxGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgRadialGradient_ as radialGradient\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',with*`Color',with*`Color',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgImagePattern_ as imagePattern\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',imageHandle`Image',`CFloat',alloca-`Paint'peek*} -> `()'#}\n\n{#fun unsafe nvgScissor as scissor\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgIntersectScissor as intersectScissor\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgResetScissor as resetScissor\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgBeginPath as beginPath\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgMoveTo as moveTo\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgLineTo as lineTo\n {`Context',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgBezierTo as bezierTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgQuadTo as quadTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgArcTo as arcTo\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgClosePath as closePath\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgPathWinding as pathWinding\n {`Context', `CInt'} -> `()'#}\n\n{#fun unsafe nvgArc as arc\n {`Context',`CFloat',`CFloat', `CFloat', `CFloat', `CFloat', `Winding'} -> `()'#}\n\n{#fun unsafe nvgRect as rect\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgRoundedRect as roundedRect\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgEllipse as ellipse\n {`Context',`CFloat',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgCircle as circle\n {`Context',`CFloat',`CFloat',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgFill as fill\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgStroke as stroke\n {`Context'} -> `()'#}\n\n{#fun unsafe nvgCreateFont as createFont\n {`Context',withCString*`T.Text','withCString.unwrapFileName'*`FileName'} -> `Font'Font#}\n\n{#fun unsafe nvgCreateFontMem as createFontMem\n {`Context',withCString*`T.Text',useAsCStringLen'*`ByteString'&,zero-`CInt'} -> `Font'Font#}\n\n{#fun unsafe nvgFindFont as findFont\n {`Context', withCString*`T.Text'} -> `Font'Font#}\n\n{#fun unsafe nvgFontSize as fontSize\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgFontBlur as fontBlur\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTextLetterSpacing as textLetterSpacing\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTextLineHeight as textLineHeight\n {`Context',`CFloat'} -> `()'#}\n\n{#fun unsafe nvgTextAlign as textAlign\n {`Context',bitMask`S.Set Align'} -> `()'#}\n\n{#fun unsafe nvgFontFaceId as fontFaceId\n {`Context',fontHandle`Font'} -> `()'#}\n\n{#fun unsafe nvgFontFace as fontFace\n {`Context',withCString*`T.Text'} -> `()'#}\n\n{#fun unsafe nvgText as text\n {`Context',`CFloat',`CFloat',id`Ptr CChar',id`Ptr CChar'} -> `()'#}\n\n{#fun unsafe nvgTextBox as textBox\n {`Context',`CFloat',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar'} -> `()'#}\n\nnewtype Bounds = Bounds (V4 CFloat) deriving (Show,Read,Eq,Ord)\n\ninstance Storable Bounds where\n sizeOf _ = sizeOf (0 :: CFloat) * 4\n alignment _ = alignment (0 :: CFloat)\n peek p =\n do let p' = castPtr p :: Ptr CFloat\n a <- peekElemOff p' 0\n b <- peekElemOff p' 1\n c <- peekElemOff p' 2\n d <- peekElemOff p' 3\n pure (Bounds (V4 a b c d))\n poke p (Bounds (V4 a b c d)) =\n do let p' = castPtr p :: Ptr CFloat\n pokeElemOff p' 0 a\n pokeElemOff p' 1 b\n pokeElemOff p' 2 c\n pokeElemOff p' 3 d\n\npeekBounds :: Ptr CFloat -> IO Bounds\npeekBounds = peek . castPtr\n\nallocaBounds :: (Ptr CFloat -> IO b) -> IO b\nallocaBounds f = alloca (\\(p :: Ptr Bounds) -> f (castPtr p))\n\nwithBounds :: Bounds -> (Ptr CFloat -> IO b) -> IO b\nwithBounds t f = with t (\\p -> f (castPtr p)) \n\n{#fun unsafe nvgTextBounds as textBounds\n {`Context',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar', allocaBounds-`Bounds'peekBounds*} -> `()'#}\n\n{#fun unsafe nvgTextBoxBounds as textBoxBounds\n {`Context',`CFloat',`CFloat',`CFloat',withCString*`T.Text',null-`Ptr CUChar',allocaBounds-`Bounds'peekBounds*} -> `()'#}\n\n-- TODO: This should probably take a vector\n{#fun unsafe nvgTextGlyphPositions as textGlyphPositions\n {`Context',`CFloat',`CFloat',id`Ptr CChar',id`Ptr CChar',`GlyphPositionPtr', `CInt'} -> `CInt'#}\n\n{#fun unsafe nvgTextMetrics as textMetrics\n {`Context',alloca-`CFloat'peek*,alloca-`CFloat'peek*,alloca-`CFloat'peek*} -> `()'#}\n\n-- TODO: This should probably take a vector\n{#fun unsafe nvgTextBreakLines as textBreakLines\n {`Context',id`Ptr CChar',id`Ptr CChar',`CFloat',`TextRowPtr',`CInt'} -> `CInt'#}\n\n{#enum NVGcreateFlags as CreateFlags\n {underscoreToCase} with prefix = \"NVG_\"\n deriving (Show,Read,Eq,Ord)#}\n\nbitMask :: Enum a => S.Set a -> CInt\nbitMask = S.fold (.|.) 0 . S.map (fromIntegral . fromEnum)\n\n{#fun unsafe nvgCreateGL3 as createGL3\n {bitMask`S.Set CreateFlags'} -> `Context'#}\n{#fun unsafe nvgDeleteGL3 as deleteGL3\n {`Context'} -> `()'#}\n\ntype GLuint = Word32\n\n{#fun unsafe nvglCreateImageFromHandleGL3 as createImageFromHandleGL3\n {`Context',fromIntegral`GLuint',`CInt',`CInt',`CreateFlags'} -> `Image'Image#}\n\n{#fun unsafe nvglImageHandleGL3 as imageHandleGL3\n {`Context',imageHandle`Image'} -> `GLuint'fromIntegral#}\n","returncode":0,"stderr":"","license":"isc","lang":"C2hs Haskell"}
{"commit":"6669b1ab3bae0a878edd963ba253ca3b490ab8fa","subject":"Slightly nicer code.","message":"Slightly nicer code.\n","repos":"noteed\/curved","old_file":"Data\/Whisper.chs","new_file":"Data\/Whisper.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE RecordWildCards #-}\nmodule Data.Whisper\n ( closeWhisper, openWhisper, createWhisper\n , readHeader, readMetaData, readArchiveInfo\n , readArchive, readPoint\n , readArchives\n , updateWhisper\n , aiRetention, aiSize\n , AggregationType(..)\n , Header(..), MetaData(..), ArchiveInfo(..), Archive(..), Point(..)\n ) where\n\nimport Prelude hiding (Enum, fromEnum)\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Exception (finally)\nimport Data.Bits ((.|.))\nimport Data.Function (on)\nimport Data.List (sortBy)\nimport Data.Word (Word32, Word64)\nimport Data.Storable.Endian (peekBE, pokeBE)\nimport Foreign.C.Types\nimport Foreign.Marshal.Utils (with)\nimport Foreign.Ptr (castPtr, nullPtr, plusPtr, Ptr)\nimport Foreign.Storable\nimport System.IO (SeekMode(..))\nimport System.IO.Unsafe (unsafePerformIO)\nimport System.Posix (closeFd, defaultFileFlags, fileSize, getFdStatus, openFd, OpenMode(..))\nimport System.Posix.IO (fdSeek, fdWrite)\nimport System.Posix.Files (ownerReadMode, ownerWriteMode, unionFileModes)\nimport System.Posix.Types (Fd)\n\n-- TODO Some Int are used for unsigned long, which is not correct.\n-- TODO Replace peekElemOff with plusPtr by peekByteOff.\n-- TODO Use fcntl to lock the file.\n-- TODO Probably the header can be directly available in the Whisper data type\n-- (probably it is almost always necessary to know the complete file layout (as\n-- provided by the ArchiveInfo) to do any meaningful operation).\n\n#include \n\nclass Enum a where\n toEnum :: Integer -> a\n fromEnum :: a -> Integer\n\n#c\nenum curved_MMAP_WRAPPER\n{ curved_MAP_SHARED = MAP_SHARED\n};\n#endc\n\n{# enum curved_MMAP_WRAPPER as MMAP_WRAPPER {} with prefix = \"curved_\" #}\n\n#c\nenum curved_PROT_WRAPPER\n{ curved_PROT_READ = PROT_READ\n, curved_PROT_WRITE = PROT_WRITE\n};\n#endc\n\n{# enum curved_PROT_WRAPPER as PROT_WRAPPER {} with prefix = \"curved_\" #}\n\ndata Whisper = Whisper { whisperPtr :: Ptr (), whisperFd :: Fd }\n\ndata Header = Header\n { hMetaData :: MetaData\n , hArchiveInfo :: [ArchiveInfo]\n }\n deriving Show\n\ndata MetaData = MetaData\n { mdAggregationType :: AggregationType\n , mdMaxRetention :: Int\n , mdXFilesFactor :: Float\n , mdArchiveCount :: Int\n }\n deriving Show\n\ndata ArchiveInfo = ArchiveInfo\n { aiOffset :: Int\n , aiSecondsPerPoint :: Int\n , aiPoints :: Int\n }\n deriving Show\n\naiRetention :: ArchiveInfo -> Int\naiRetention ArchiveInfo{..} = aiSecondsPerPoint * aiPoints\n\naiSize :: ArchiveInfo -> Int\naiSize ArchiveInfo{..} = aiPoints * sizeOf (undefined :: Point)\n\ndata AggregationType = Average | Sum | Last | Max | Min\n deriving Show\n\ndata Archive = Archive [Point]\n deriving Show\n\ndata Point = Point Int Double\n deriving Show\n\n-- | Open a memory-mapped file.\nopenWhisper :: FilePath -> IO Whisper\nopenWhisper path = do\n fd <- openFd path ReadWrite Nothing defaultFileFlags\n flip finally (closeFd fd) $ do -- TODO Can we close the fd before unmmap'ing it ?\n stat <- getFdStatus fd\n let size = fileSize stat\n ptr <- {# call mmap #} nullPtr (fromIntegral size) (fromInteger $ fromEnum PROT_READ .|. fromEnum PROT_WRITE) (fromInteger $ fromEnum MAP_SHARED) (fromIntegral fd) 0\n if ptr == nullPtr\n then error \"Data.Whisper.openWhisper: unable to mmap file.\"\n else return $ Whisper (castPtr ptr) fd\n\ncloseWhisper :: Whisper -> IO ()\ncloseWhisper (Whisper ptr fd) = do\n _ <- {# call munmap #} ptr (fromIntegral fd) -- TODO check error code\n return ()\n\n-- | Create a memory-mapped file of the given size.\nopenWhisperSize :: FilePath -> Int -> IO Whisper\nopenWhisperSize path size = do\n fd <- openFd path ReadWrite (Just $ ownerReadMode `unionFileModes` ownerWriteMode) defaultFileFlags\n -- Write a dummy byte to size correctly the underlying file befor\n -- memory-mapping it.\n fdSeek fd AbsoluteSeek (fromIntegral $ size - 1) >>= print --TODO check return value ? check size > 0 ?\n fdWrite fd \"\\0\" >>= print\n flip finally (closeFd fd) $ do -- TODO Can we close the fd before unmmap'ing it ?\n ptr <- {# call mmap #} nullPtr (fromIntegral size) (fromInteger $ fromEnum PROT_WRITE) (fromInteger $ fromEnum MAP_SHARED) (fromIntegral fd) 0 -- TODO | PROT_READ\n print ptr\n if ptr == nullPtr\n then error \"Data.Whisper.openWhisperSize: unable to mmap file.\"\n else return $ Whisper ptr fd\n\nreadHeader :: Whisper -> IO Header\nreadHeader w = do\n md <- readMetaData w\n ai <- mapM (readArchiveInfo w) [0..fromIntegral (mdArchiveCount md) - 1]\n return $ Header md ai\n\nreadMetaData :: Whisper -> IO MetaData\nreadMetaData Whisper{..} = peek (castPtr whisperPtr)\n\nreadArchiveInfo :: Whisper -> Int -> IO ArchiveInfo\nreadArchiveInfo Whisper{..} n =\n peekElemOff (castPtr whisperPtr `plusPtr` sizeOf (undefined :: MetaData)) n\n\n-- | Read the nth archive, considering it as a window ending at `timestamp`.\nreadArchive :: Whisper -> Int -> Timestamp -> IO Archive\nreadArchive w@Whisper{..} n timestamp = do\n ai@ArchiveInfo{..} <- readArchiveInfo w n -- TODO the archiveInfo is usually already read.\n if aiPoints <= 0\n then return $ Archive []\n else do\n -- The very first point presence indicates if data are present.\n Point ts _ <- readPoint w aiOffset 0\n if ts == 0\n then return $ Archive []\n else do\n -- The first point in the archive is used as a base point\n -- to index into the archive data.\n ps <- mapM (readPoint w aiOffset) [0..aiPoints - 1]\n let (after, before) = splitAt (slot ai ts timestamp) ps\n return . Archive $ lockstep ai timestamp $ before ++ after\n\n-- TODO instead of passing the aiOffset, we could just pass the ArchiveInfo.\nreadPoint :: Whisper -> Int -> Int -> IO Point\nreadPoint Whisper{..} archiveOffset n =\n peekElemOff (castPtr whisperPtr `plusPtr` archiveOffset) n\n\nreadArchives :: Whisper -> Timestamp -> IO [Archive]\nreadArchives w timestamp = do\n Header{..} <- readHeader w\n mapM (flip (readArchive w) timestamp) [0..length hArchiveInfo - 1]\n\nwriteHeader :: Whisper -> Header -> IO ()\nwriteHeader w Header{..} = do\n writeMetaData w hMetaData\n mapM_ (uncurry $ writeArchiveInfo w) $ zip [0..] hArchiveInfo\n\nwriteMetaData :: Whisper -> MetaData -> IO ()\nwriteMetaData Whisper{..} = poke (castPtr whisperPtr)\n\nwriteArchiveInfo :: Whisper -> Int -> ArchiveInfo -> IO ()\nwriteArchiveInfo Whisper{..} n =\n pokeElemOff (castPtr whisperPtr `plusPtr` sizeOf (undefined :: MetaData)) n\n\nwriteArchive :: Whisper -> ArchiveInfo -> Archive -> IO ()\nwriteArchive w@Whisper{..} ArchiveInfo{..} (Archive points) =\n mapM_ (uncurry $ writePoint w aiOffset) $ zip [0..] points\n\nwritePoint :: Whisper -> Int -> Int -> Point -> IO ()\nwritePoint Whisper{..} archiveOffset n =\n pokeElemOff (castPtr whisperPtr `plusPtr` archiveOffset) n\n\nwriteArchives :: Whisper -> [ArchiveInfo] -> [Archive] -> IO ()\nwriteArchives w infos archives =\n mapM_ (uncurry $ writeArchive w) $ zip infos archives\n\ncreateWhisper :: FilePath -> [(Int, Int)] -> Float -> AggregationType -> IO ()\ncreateWhisper filename archiveInfos_ factor aggregation = do\n -- TODO archiveInfos_ can't be null.\n\n let archiveInfos = sortBy (compare `on` fst) archiveInfos_\n archiveInfos' = tail $ scanl toAI (ArchiveInfo (headerSize $ length archiveInfos) 1 0) archiveInfos\n retention = aiRetention $ last archiveInfos'\n meta = MetaData aggregation retention factor (length archiveInfos)\n header = Header meta archiveInfos'\n archives = map (Archive . flip replicate (Point 0 0) . snd) archiveInfos\n\n w@Whisper{..} <- openWhisperSize filename (headerSize (length archiveInfos) + sum (map snd archiveInfos) * sizeOf (undefined :: Point))\n writeHeader w header\n writeArchives w archiveInfos' archives\n closeWhisper w\n\n-- | Given an ArchiveInfo and a timestamp, return its slot in the archive.\nslot ArchiveInfo{..} base timestamp = (((timestamp - base) `div` aiSecondsPerPoint) + 1) `mod` aiPoints\n\nslot' ArchiveInfo{..} base timestamp = ((timestamp - base) `div` aiSecondsPerPoint) `mod` aiPoints\n\nstart ai timestamp = timestamp - (timestamp `mod` aiSecondsPerPoint ai) - aiRetention ai + aiSecondsPerPoint ai\n\nslotTimestamp ai timestamp = timestamp - (timestamp `mod` aiSecondsPerPoint ai)\n\nlockstep ai@ArchiveInfo{..} timestamp points = zipWith f [s, s + aiSecondsPerPoint ..] points\n where s = start ai timestamp\n f ts (Point ts' value) | ts == ts' = Point ts value\n | otherwise = Point 0 0\n\n-- | sizeOf a complete header, given the number of archives.\nheaderSize :: Int -> Int\nheaderSize n = sizeOf (undefined :: MetaData) + sizeOf (undefined :: ArchiveInfo) * n\n\n-- | Given the precision and number of points of an archive (i.e. its\n-- ArchiveInfo without its offset), and its predecessor archive, create a\n-- complete ArchiveInfo (i.e. with its offset).\ntoAI :: ArchiveInfo -> (Int, Int) -> ArchiveInfo\ntoAI ArchiveInfo{..} (precision, points) =\n ArchiveInfo (aiOffset + sizeOf (undefined :: Point) * aiPoints) precision points\n\ntype Timestamp = Int\n\nupdateWhisper :: Whisper -> Header -> Int -> Double -> IO ()\nupdateWhisper w@Whisper{..} header timestamp value = do\n let archiveIndex = 0 -- TODO correctly select thearchive to update and propagate the value.\n ai = hArchiveInfo header !! archiveIndex\n offset = aiOffset ai\n Point ts _ <- readPoint w offset 0\n -- TODO then patter of reading the first point and decide if the archive has already some data is reused in readArchive.\n -- (B.t.w. I don't think it was necessary: only the modulo (without the base timestamp) was enough. Any gain\n -- exists only for empty or almost emtpy files.\n if ts == 0\n then writePoint w offset 0 (Point (slotTimestamp ai timestamp) value)\n else do\n let i = slot' (hArchiveInfo header !! archiveIndex) ts timestamp\n writePoint w offset i (Point (slotTimestamp ai timestamp )value)\n\ninstance Storable MetaData where\n sizeOf _ =\n sizeOf (undefined :: Word32)\n + sizeOf (undefined :: Word32)\n + sizeOf (undefined :: CFloat)\n + sizeOf (undefined :: Word32)\n\n alignment _ = alignment (undefined :: Word32)\n\n peek ptr = MetaData\n <$> peek (castPtr ptr)\n <*> peekWord32beAsNum (castPtr ptr `plusPtr` 4)\n <*> peekWord32beAsFloat (castPtr ptr `plusPtr` 8)\n <*> peekWord32beAsNum (castPtr ptr `plusPtr` 12)\n\n poke ptr MetaData{..} = do\n poke (castPtr ptr) mdAggregationType\n pokeBE (castPtr ptr `plusPtr` 4) (fromIntegral mdMaxRetention :: Word32)\n pokeBE (castPtr ptr `plusPtr` 8) (coerce mdXFilesFactor)\n pokeBE (castPtr ptr `plusPtr` 12) (fromIntegral mdArchiveCount :: Word32)\n where\n coerce :: Float -> Word32\n coerce x = unsafePerformIO $ with x $ \\p ->\n peek (castPtr p) :: IO Word32\n\ninstance Storable ArchiveInfo where\n sizeOf _ =\n sizeOf (undefined :: Word32)\n + sizeOf (undefined :: Word32)\n + sizeOf (undefined :: Word32)\n\n alignment _ = alignment (undefined :: Word32)\n\n peek ptr = ArchiveInfo\n <$> peekWord32beAsNum (castPtr ptr)\n <*> peekWord32beAsNum (castPtr ptr `plusPtr` 4)\n <*> peekWord32beAsNum (castPtr ptr `plusPtr` 8)\n\n poke ptr ArchiveInfo{..} = do\n pokeBE (castPtr ptr) (fromIntegral aiOffset :: Word32)\n pokeBE (castPtr ptr `plusPtr` 4) (fromIntegral aiSecondsPerPoint :: Word32)\n pokeBE (castPtr ptr `plusPtr` 8) (fromIntegral aiPoints :: Word32)\n\ninstance Storable AggregationType where\n sizeOf _ = sizeOf (undefined :: Word32)\n\n alignment _ = alignment (undefined :: Word32)\n\n peek ptr = agg <$> peekBE (castPtr ptr :: Ptr Word32)\n where\n agg 1 = Average\n agg 2 = Sum\n agg 3 = Last\n agg 4 = Max\n agg 5 = Min\n agg _ = Average\n\n poke ptr a = pokeBE (castPtr ptr) $ agg a\n where\n agg Average = 1 :: Word32\n agg Sum = 2\n agg Last = 3\n agg Max = 4\n agg Min = 5\n\ninstance Storable Point where\n sizeOf _ = sizeOf (undefined :: Word32)\n + sizeOf (undefined :: CDouble)\n\n alignment _ = alignment (undefined :: Word32)\n\n peek ptr = Point\n <$> peekWord32beAsNum (castPtr ptr)\n <*> peekWord64beAsDouble (castPtr ptr `plusPtr` 4)\n\n poke ptr (Point a b) = do\n pokeBE (castPtr ptr) (fromIntegral a :: Word32)\n pokeBE (castPtr ptr `plusPtr` 4) (coerce b)\n where\n coerce :: Double -> Word64\n coerce x = unsafePerformIO $ with x $ \\p ->\n peek (castPtr p) :: IO Word64\n\npeekWord32beAsNum :: Num a => Ptr Word32 -> IO a\npeekWord32beAsNum ptr = fromIntegral <$> peekBE ptr\n\npeekWord32beAsFloat :: Ptr Word32 -> IO Float\npeekWord32beAsFloat ptr = coerce <$> peekBE ptr\n where\n coerce :: Word32 -> Float\n coerce x = unsafePerformIO $ with x $ \\p ->\n peek (castPtr p) :: IO Float\n\npeekWord64beAsDouble :: Ptr Word64 -> IO Double\npeekWord64beAsDouble ptr = coerce <$> peekBE ptr\n where\n coerce :: Word64 -> Double\n coerce x = unsafePerformIO $ with x $ \\p ->\n peek (castPtr p) :: IO Double\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE RecordWildCards #-}\nmodule Data.Whisper\n ( closeWhisper, openWhisper, createWhisper\n , readHeader, readMetaData, readArchiveInfo\n , readArchive, readPoint\n , readArchives\n , updateWhisper\n , aiRetention, aiSize\n , AggregationType(..)\n , Header(..), MetaData(..), ArchiveInfo(..), Archive(..), Point(..)\n ) where\n\nimport Prelude hiding (Enum, fromEnum)\n\nimport Control.Exception (finally)\nimport Data.Bits ((.|.))\nimport Data.Function (on)\nimport Data.List (sortBy)\nimport Data.Word (Word32, Word64)\nimport Data.Storable.Endian (peekBE, pokeBE)\nimport Foreign.C.Types\nimport Foreign.Marshal.Utils (with)\nimport Foreign.Ptr (castPtr, nullPtr, plusPtr, Ptr)\nimport Foreign.Storable\nimport System.IO (SeekMode(..))\nimport System.IO.Unsafe (unsafePerformIO)\nimport System.Posix (closeFd, defaultFileFlags, fileSize, getFdStatus, openFd, OpenMode(..))\nimport System.Posix.IO (fdSeek, fdWrite)\nimport System.Posix.Files (ownerReadMode, ownerWriteMode, unionFileModes)\nimport System.Posix.Types (Fd)\n\n-- TODO Some Int are used for unsigned long, which is not correct.\n-- TODO Replace peekElemOff with plusPtr by peekByteOff.\n-- TODO Use fcntl to lock the file.\n-- TODO Probably the header can be directly available in the Whisper data type\n-- (probably it is almost always necessary to know the complete file layout (as\n-- provided by the ArchiveInfo) to do any meaningful operation).\n\n#include \n\nclass Enum a where\n toEnum :: Integer -> a\n fromEnum :: a -> Integer\n\n#c\nenum curved_MMAP_WRAPPER\n{ curved_MAP_SHARED = MAP_SHARED\n};\n#endc\n\n{# enum curved_MMAP_WRAPPER as MMAP_WRAPPER {} with prefix = \"curved_\" #}\n\n#c\nenum curved_PROT_WRAPPER\n{ curved_PROT_READ = PROT_READ\n, curved_PROT_WRITE = PROT_WRITE\n};\n#endc\n\n{# enum curved_PROT_WRAPPER as PROT_WRAPPER {} with prefix = \"curved_\" #}\n\ndata Whisper = Whisper { whisperPtr :: Ptr (), whisperFd :: Fd }\n\ndata Header = Header\n { hMetaData :: MetaData\n , hArchiveInfo :: [ArchiveInfo]\n }\n deriving Show\n\ndata MetaData = MetaData\n { mdAggregationType :: AggregationType\n , mdMaxRetention :: Int\n , mdXFilesFactor :: Float\n , mdArchiveCount :: Int\n }\n deriving Show\n\ndata ArchiveInfo = ArchiveInfo\n { aiOffset :: Int\n , aiSecondsPerPoint :: Int\n , aiPoints :: Int\n }\n deriving Show\n\naiRetention :: ArchiveInfo -> Int\naiRetention ArchiveInfo{..} = aiSecondsPerPoint * aiPoints\n\naiSize :: ArchiveInfo -> Int\naiSize ArchiveInfo{..} = aiPoints * sizeOf (undefined :: Point)\n\ndata AggregationType = Average | Sum | Last | Max | Min\n deriving Show\n\ndata Archive = Archive [Point]\n deriving Show\n\ndata Point = Point Int Double\n deriving Show\n\n-- | Open a memory-mapped file.\nopenWhisper :: FilePath -> IO Whisper\nopenWhisper path = do\n fd <- openFd path ReadWrite Nothing defaultFileFlags\n flip finally (closeFd fd) $ do -- TODO Can we close the fd before unmmap'ing it ?\n stat <- getFdStatus fd\n let size = fileSize stat\n ptr <- {# call mmap #} nullPtr (fromIntegral size) (fromInteger $ fromEnum PROT_READ .|. fromEnum PROT_WRITE) (fromInteger $ fromEnum MAP_SHARED) (fromIntegral fd) 0\n if ptr == nullPtr\n then error \"Data.Whisper.openWhisper: unable to mmap file.\"\n else return $ Whisper (castPtr ptr) fd\n\ncloseWhisper :: Whisper -> IO ()\ncloseWhisper (Whisper ptr fd) = do\n _ <- {# call munmap #} ptr (fromIntegral fd) -- TODO check error code\n return ()\n\n-- | Create a memory-mapped file of the given size.\nopenWhisperSize :: FilePath -> Int -> IO Whisper\nopenWhisperSize path size = do\n fd <- openFd path ReadWrite (Just $ ownerReadMode `unionFileModes` ownerWriteMode) defaultFileFlags\n -- Write a dummy byte to size correctly the underlying file befor\n -- memory-mapping it.\n fdSeek fd AbsoluteSeek (fromIntegral $ size - 1) >>= print --TODO check return value ? check size > 0 ?\n fdWrite fd \"\\0\" >>= print\n flip finally (closeFd fd) $ do -- TODO Can we close the fd before unmmap'ing it ?\n ptr <- {# call mmap #} nullPtr (fromIntegral size) (fromInteger $ fromEnum PROT_WRITE) (fromInteger $ fromEnum MAP_SHARED) (fromIntegral fd) 0 -- TODO | PROT_READ\n print ptr\n if ptr == nullPtr\n then error \"Data.Whisper.openWhisperSize: unable to mmap file.\"\n else return $ Whisper ptr fd\n\nreadHeader :: Whisper -> IO Header\nreadHeader w = do\n md <- readMetaData w\n ai <- mapM (readArchiveInfo w) [0..fromIntegral (mdArchiveCount md) - 1]\n return $ Header md ai\n\nreadMetaData :: Whisper -> IO MetaData\nreadMetaData Whisper{..} = peek (castPtr whisperPtr)\n\nreadArchiveInfo :: Whisper -> Int -> IO ArchiveInfo\nreadArchiveInfo Whisper{..} n =\n peekElemOff (castPtr whisperPtr `plusPtr` sizeOf (undefined :: MetaData)) n\n\n-- | Read the nth archive, considering it as a window ending at `timestamp`.\nreadArchive :: Whisper -> Int -> Timestamp -> IO Archive\nreadArchive w@Whisper{..} n timestamp = do\n ai@ArchiveInfo{..} <- readArchiveInfo w n -- TODO the archiveInfo is usually already read.\n if aiPoints <= 0\n then return $ Archive []\n else do\n -- The very first point presence indicates if data are present.\n Point ts _ <- readPoint w aiOffset 0\n if ts == 0\n then return $ Archive []\n else do\n -- The first point in the archive is used as a base point\n -- to index into the archive data.\n ps <- mapM (readPoint w aiOffset) [0..aiPoints - 1]\n let (after, before) = splitAt (slot ai ts timestamp) ps\n return . Archive $ lockstep ai timestamp $ before ++ after\n\n-- TODO instead of passing the aiOffset, we could just pass the ArchiveInfo.\nreadPoint :: Whisper -> Int -> Int -> IO Point\nreadPoint Whisper{..} archiveOffset n =\n peekElemOff (castPtr whisperPtr `plusPtr` archiveOffset) n\n\nreadArchives :: Whisper -> Timestamp -> IO [Archive]\nreadArchives w timestamp = do\n Header{..} <- readHeader w\n mapM (flip (readArchive w) timestamp) [0..length hArchiveInfo - 1]\n\nwriteHeader :: Whisper -> Header -> IO ()\nwriteHeader w Header{..} = do\n writeMetaData w hMetaData\n mapM_ (uncurry $ writeArchiveInfo w) $ zip [0..] hArchiveInfo\n\nwriteMetaData :: Whisper -> MetaData -> IO ()\nwriteMetaData Whisper{..} = poke (castPtr whisperPtr)\n\nwriteArchiveInfo :: Whisper -> Int -> ArchiveInfo -> IO ()\nwriteArchiveInfo Whisper{..} n =\n pokeElemOff (castPtr whisperPtr `plusPtr` sizeOf (undefined :: MetaData)) n\n\nwriteArchive :: Whisper -> ArchiveInfo -> Archive -> IO ()\nwriteArchive w@Whisper{..} ArchiveInfo{..} (Archive points) =\n mapM_ (uncurry $ writePoint w aiOffset) $ zip [0..] points\n\nwritePoint :: Whisper -> Int -> Int -> Point -> IO ()\nwritePoint Whisper{..} archiveOffset n =\n pokeElemOff (castPtr whisperPtr `plusPtr` archiveOffset) n\n\nwriteArchives :: Whisper -> [ArchiveInfo] -> [Archive] -> IO ()\nwriteArchives w infos archives =\n mapM_ (uncurry $ writeArchive w) $ zip infos archives\n\ncreateWhisper :: FilePath -> [(Int, Int)] -> Float -> AggregationType -> IO ()\ncreateWhisper filename archiveInfos_ factor aggregation = do\n -- TODO archiveInfos_ can't be null.\n\n let archiveInfos = sortBy (compare `on` fst) archiveInfos_\n archiveInfos' = tail $ scanl toAI (ArchiveInfo (headerSize $ length archiveInfos) 1 0) archiveInfos\n retention = aiRetention $ last archiveInfos'\n meta = MetaData aggregation retention factor (length archiveInfos)\n header = Header meta archiveInfos'\n archives = map (Archive . flip replicate (Point 0 0) . snd) archiveInfos\n\n w@Whisper{..} <- openWhisperSize filename (headerSize (length archiveInfos) + sum (map snd archiveInfos) * sizeOf (undefined :: Point))\n writeHeader w header\n writeArchives w archiveInfos' archives\n closeWhisper w\n\n-- | Given an ArchiveInfo and a timestamp, return its slot in the archive.\nslot ArchiveInfo{..} base timestamp = (((timestamp - base) `div` aiSecondsPerPoint) + 1) `mod` aiPoints\n\nslot' ArchiveInfo{..} base timestamp = ((timestamp - base) `div` aiSecondsPerPoint) `mod` aiPoints\n\nstart ai timestamp = timestamp - (timestamp `mod` aiSecondsPerPoint ai) - aiRetention ai + aiSecondsPerPoint ai\n\nslotTimestamp ai timestamp = timestamp - (timestamp `mod` aiSecondsPerPoint ai)\n\nlockstep ai@ArchiveInfo{..} timestamp points = zipWith f [s, s + aiSecondsPerPoint ..] points\n where s = start ai timestamp\n f ts (Point ts' value) | ts == ts' = Point ts value\n | otherwise = Point 0 0\n\n-- | sizeOf a complete header, given the number of archives.\nheaderSize :: Int -> Int\nheaderSize n = sizeOf (undefined :: MetaData) + sizeOf (undefined :: ArchiveInfo) * n\n\n-- | Given the precision and number of points of an archive (i.e. its\n-- ArchiveInfo without its offset), and its predecessor archive, create a\n-- complete ArchiveInfo (i.e. with its offset).\ntoAI :: ArchiveInfo -> (Int, Int) -> ArchiveInfo\ntoAI ArchiveInfo{..} (precision, points) =\n ArchiveInfo (aiOffset + sizeOf (undefined :: Point) * aiPoints) precision points\n\ntype Timestamp = Int\n\nupdateWhisper :: Whisper -> Header -> Int -> Double -> IO ()\nupdateWhisper w@Whisper{..} header timestamp value = do\n let archiveIndex = 0 -- TODO correctly select thearchive to update and propagate the value.\n ai = hArchiveInfo header !! archiveIndex\n offset = aiOffset ai\n Point ts _ <- readPoint w offset 0\n -- TODO then patter of reading the first point and decide if the archive has already some data is reused in readArchive.\n -- (B.t.w. I don't think it was necessary: only the modulo (without the base timestamp) was enough. Any gain\n -- exists only for empty or almost emtpy files.\n if ts == 0\n then writePoint w offset 0 (Point (slotTimestamp ai timestamp) value)\n else do\n let i = slot' (hArchiveInfo header !! archiveIndex) ts timestamp\n writePoint w offset i (Point (slotTimestamp ai timestamp )value)\n\ninstance Storable MetaData where\n sizeOf _ =\n sizeOf (undefined :: Word32)\n + sizeOf (undefined :: Word32)\n + sizeOf (undefined :: CFloat)\n + sizeOf (undefined :: Word32)\n\n alignment _ = alignment (undefined :: Word32)\n\n peek ptr = do\n a <- peek (castPtr ptr)\n b <- fromIntegral `fmap` peekBE (castPtr ptr `plusPtr` 4 :: Ptr Word32)\n c <- coerce `fmap` peekBE (castPtr ptr `plusPtr` 8)\n d <- fromIntegral `fmap` peekBE (castPtr ptr `plusPtr` 12 :: Ptr Word32)\n return $ MetaData a b c d\n where\n coerce :: Word32 -> Float\n coerce x = unsafePerformIO $ with x $ \\p ->\n peek (castPtr p) :: IO Float\n\n poke ptr MetaData{..} = do\n poke (castPtr ptr) mdAggregationType\n pokeBE (castPtr ptr `plusPtr` 4) (fromIntegral mdMaxRetention :: Word32)\n pokeBE (castPtr ptr `plusPtr` 8) (coerce mdXFilesFactor)\n pokeBE (castPtr ptr `plusPtr` 12) (fromIntegral mdArchiveCount :: Word32)\n where\n coerce :: Float -> Word32\n coerce x = unsafePerformIO $ with x $ \\p ->\n peek (castPtr p) :: IO Word32\n\ninstance Storable ArchiveInfo where\n sizeOf _ =\n sizeOf (undefined :: Word32)\n + sizeOf (undefined :: Word32)\n + sizeOf (undefined :: Word32)\n\n alignment _ = alignment (undefined :: Word32)\n\n peek ptr = do\n a <- fromIntegral `fmap` peekBE (castPtr ptr :: Ptr Word32)\n b <- fromIntegral `fmap` peekBE (castPtr ptr `plusPtr` 4 :: Ptr Word32)\n c <- fromIntegral `fmap` peekBE (castPtr ptr `plusPtr` 8 :: Ptr Word32)\n return $ ArchiveInfo a b c\n\n poke ptr ArchiveInfo{..} = do\n pokeBE (castPtr ptr) (fromIntegral aiOffset :: Word32)\n pokeBE (castPtr ptr `plusPtr` 4) (fromIntegral aiSecondsPerPoint :: Word32)\n pokeBE (castPtr ptr `plusPtr` 8) (fromIntegral aiPoints :: Word32)\n\ninstance Storable AggregationType where\n sizeOf _ = sizeOf (undefined :: Word32)\n\n alignment _ = alignment (undefined :: Word32)\n\n peek ptr = agg `fmap` peekBE (castPtr ptr :: Ptr Word32)\n where\n agg 1 = Average\n agg 2 = Sum\n agg 3 = Last\n agg 4 = Max\n agg 5 = Min\n agg _ = Average\n\n poke ptr a = pokeBE (castPtr ptr) $ agg a\n where\n agg Average = 1 :: Word32\n agg Sum = 2\n agg Last = 3\n agg Max = 4\n agg Min = 5\n\ninstance Storable Point where\n sizeOf _ = sizeOf (undefined :: Word32)\n + sizeOf (undefined :: CDouble)\n\n alignment _ = alignment (undefined :: Word32)\n\n peek ptr = do\n a <- fromIntegral `fmap` peekBE (castPtr ptr :: Ptr Word32)\n b <- coerce `fmap` peekBE (castPtr ptr `plusPtr` 4)\n return $ Point a b\n where\n coerce :: Word64 -> Double\n coerce x = unsafePerformIO $ with x $ \\p ->\n peek (castPtr p) :: IO Double\n\n poke ptr (Point a b) = do\n pokeBE (castPtr ptr) (fromIntegral a :: Word32)\n pokeBE (castPtr ptr `plusPtr` 4) (coerce b)\n where\n coerce :: Double -> Word64\n coerce x = unsafePerformIO $ with x $ \\p ->\n peek (castPtr p) :: IO Word64\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"0ad825a28251a3594c81c36a5ea9f0c608c7f64b","subject":"SVG: provide implementation for GObjectClass","message":"SVG: provide implementation for GObjectClass\n\ndarcs-hash:20071031135016-ef904-ae7d2cb50b83f130196b7d9f6363402d04675cb3.gz\n","repos":"thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs,thiagoarrais\/gtk2hs","old_file":"svgcairo\/Graphics\/Rendering\/Cairo\/SVG.chs","new_file":"svgcairo\/Graphics\/Rendering\/Cairo\/SVG.chs","new_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.SVG\n-- Copyright : (c) 2005 Duncan Coutts, Paolo Martini \n-- License : BSD-style (see cairo\/COPYRIGHT)\n--\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : experimental\n-- Portability : portable\n--\n-- The SVG extension to the Cairo 2D graphics library.\n--\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.SVG (\n -- * Convenience API\n\n -- | These operations render an SVG image directly in the current 'Render'\n -- contect. Because they operate in the cairo 'Render' monad they are\n -- affected by the current transformation matrix. So it is possible, for\n -- example, to scale or rotate an SVG image.\n --\n -- In the following example we scale an SVG image to a unit square:\n --\n -- > let (width, height) = svgGetSize in\n -- > do scale (1\/width) (1\/height)\n -- > svgRender svg\n\n svgRenderFromFile,\n svgRenderFromHandle,\n svgRenderFromString,\n\n -- * Standard API\n\n -- | With this API there are seperate functions for loading the SVG and\n -- rendering it. This allows us to be more effecient in the case that an SVG\n -- image is used many times - since it can be loaded just once and rendered\n -- many times. With the convenience API above the SVG would be parsed and\n -- processed each time it is drawn.\n\n SVG,\n svgRender,\n svgGetSize,\n\n -- ** Block scoped versions\n\n -- | These versions of the SVG loading operations give temporary access\n -- to the 'SVG' object within the scope of the handler function. These\n -- operations guarantee that the resources for the SVG object are deallocated\n -- at the end of the handler block. If this form of resource allocation is\n -- too restrictive you can use the GC-managed versions below.\n --\n -- These versions are ofen used in the following style:\n --\n -- > withSvgFromFile \"foo.svg\" $ \\svg -> do\n -- > ...\n -- > svgRender svg\n -- > ...\n\n withSvgFromFile,\n withSvgFromHandle,\n withSvgFromString,\n\n -- ** GC-managed versions\n\n -- | These versions of the SVG loading operations use the standard Haskell\n -- garbage collector to manage the resources associated with the 'SVG' object.\n -- As such they are more convenient to use but the GC cannot give\n -- strong guarantees about when the resources associated with the 'SVG' object\n -- will be released. In most circumstances this is not a problem, especially\n -- if the SVG files being used are not very big.\n\n svgNewFromFile,\n svgNewFromHandle,\n svgNewFromString,\n ) where\n\nimport Control.Monad (when)\nimport Foreign\nimport Foreign.C\nimport Control.Monad.Reader (ask, liftIO)\nimport System.IO (Handle, openFile, IOMode(ReadMode), hGetBuf)\n\nimport System.Glib.GError (GError(GError), checkGError)\nimport System.Glib.GObject (GObjectClass(..), constructNewGObject, unGObject, mkGObject)\n\nimport Graphics.Rendering.Cairo.Internal (Render, bracketR)\n{# import Graphics.Rendering.Cairo.Types #} (Cairo(Cairo))\n\n{# context lib=\"librsvg\" prefix=\"rsvg_handle\" #}\n\n---------------------\n-- Types\n-- \n\n{# pointer *RsvgHandle as SVG foreign newtype #}\n\nmkSVG = SVG\nunSVG (SVG o) = o\n\ninstance GObjectClass SVG where\n toGObject = mkGObject . castForeignPtr . unSVG\n unsafeCastGObject = mkSVG . castForeignPtr . unGObject\n\n---------------------\n-- Basic API\n-- \n\n-- block scoped versions\n\nwithSvgFromFile :: FilePath -> (SVG -> Render a) -> Render a\nwithSvgFromFile file action =\n withSVG $ \\svg -> do \n liftIO $ svgParseFromFile file svg\n action svg\n\nwithSvgFromHandle :: Handle -> (SVG -> Render a) -> Render a\nwithSvgFromHandle hnd action =\n withSVG $ \\svg -> do \n liftIO $ svgParseFromHandle hnd svg\n action svg\n\nwithSvgFromString :: String -> (SVG -> Render a) -> Render a\nwithSvgFromString str action =\n withSVG $ \\svg -> do\n liftIO $ svgParseFromString str svg\n action svg\n\nwithSVG :: (SVG -> Render a) -> Render a\nwithSVG =\n bracketR (do\n {# call g_type_init #}\n svgPtr <- {# call unsafe new #}\n svgPtr' <- newForeignPtr_ svgPtr\n return (SVG svgPtr')) \n (\\(SVG fptr) -> withForeignPtr fptr $ \\ptr ->\n {# call unsafe g_object_unref #} (castPtr ptr))\n\n-- GC managed versions\n\nsvgNewFromFile :: FilePath -> IO SVG\nsvgNewFromFile file = do\n svg <- svgNew\n svgParseFromFile file svg\n return svg\n\nsvgNewFromHandle :: Handle -> IO SVG\nsvgNewFromHandle hnd = do\n svg <- svgNew\n svgParseFromHandle hnd svg\n return svg\n\nsvgNewFromString :: String -> IO SVG\nsvgNewFromString str = do\n svg <- svgNew\n svgParseFromString str svg\n return svg\n\nsvgNew :: IO SVG\nsvgNew = do\n {# call g_type_init #}\n constructNewGObject SVG {# call unsafe new #}\n\n\n-- internal implementation\n\nsvgParseFromFile :: FilePath -> SVG -> IO ()\nsvgParseFromFile file svg = do\n hnd <- openFile file ReadMode\n svgParseFromHandle hnd svg\n\nsvgParseFromHandle :: Handle -> SVG -> IO ()\nsvgParseFromHandle hnd svg =\n allocaBytes 4096 $ \\bufferPtr -> do\n let loop = do\n count <- hGetBuf hnd bufferPtr 4096\n when (count > 0)\n (checkStatus $ {# call unsafe rsvg_handle_write #}\n svg (castPtr bufferPtr) (fromIntegral count))\n when (count == 4096) loop\n loop\n checkStatus $ {# call unsafe rsvg_handle_close #} svg\n\nsvgParseFromString :: String -> SVG -> IO ()\nsvgParseFromString str svg = do\n let loop \"\" = return ()\n loop str =\n case splitAt 4096 str of\n (chunk, str') -> do\n withCStringLen chunk $ \\(chunkPtr, len) ->\n checkStatus $ {# call unsafe rsvg_handle_write #}\n svg (castPtr chunkPtr) (fromIntegral len)\n loop str'\n loop str\n checkStatus $ {# call unsafe rsvg_handle_close #} svg\n\n-- actually render it\n\nsvgRender :: SVG -> Render ()\nsvgRender svg = do\n cr <- ask\n liftIO $ {# call unsafe render_cairo #} svg cr\n\n-- | Get the width and height of the SVG image.\n--\nsvgGetSize :: \n SVG\n -> (Int, Int) -- ^ @(width, height)@\nsvgGetSize svg = unsafePerformIO $\n allocaBytes {# sizeof RsvgDimensionData #} $ \\dimentionsPtr -> do\n {# call unsafe get_dimensions #} svg dimentionsPtr\n width <- {# get RsvgDimensionData->width #} dimentionsPtr\n height <- {# get RsvgDimensionData->height #} dimentionsPtr\n return (fromIntegral width, fromIntegral height)\n\n---------------------\n-- Convenience API\n-- \n\nsvgRenderFromFile :: FilePath -> Render ()\nsvgRenderFromFile file = withSvgFromFile file svgRender\n\nsvgRenderFromHandle :: Handle -> Render ()\nsvgRenderFromHandle hnd = withSvgFromHandle hnd svgRender\n\nsvgRenderFromString :: String -> Render ()\nsvgRenderFromString str = withSvgFromString str svgRender\n\n---------------------\n-- Utils\n-- \n\ncheckStatus :: (Ptr (Ptr ()) -> IO CInt) -> IO ()\ncheckStatus action =\n checkGError (\\ptr -> action ptr >> return ())\n (\\(GError domain code msg) -> fail (\"svg cairo error: \" ++ msg))\n","old_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.SVG\n-- Copyright : (c) 2005 Duncan Coutts, Paolo Martini \n-- License : BSD-style (see cairo\/COPYRIGHT)\n--\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : experimental\n-- Portability : portable\n--\n-- The SVG extension to the Cairo 2D graphics library.\n--\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.SVG (\n -- * Convenience API\n\n -- | These operations render an SVG image directly in the current 'Render'\n -- contect. Because they operate in the cairo 'Render' monad they are\n -- affected by the current transformation matrix. So it is possible, for\n -- example, to scale or rotate an SVG image.\n --\n -- In the following example we scale an SVG image to a unit square:\n --\n -- > let (width, height) = svgGetSize in\n -- > do scale (1\/width) (1\/height)\n -- > svgRender svg\n\n svgRenderFromFile,\n svgRenderFromHandle,\n svgRenderFromString,\n\n -- * Standard API\n\n -- | With this API there are seperate functions for loading the SVG and\n -- rendering it. This allows us to be more effecient in the case that an SVG\n -- image is used many times - since it can be loaded just once and rendered\n -- many times. With the convenience API above the SVG would be parsed and\n -- processed each time it is drawn.\n\n SVG,\n svgRender,\n svgGetSize,\n\n -- ** Block scoped versions\n\n -- | These versions of the SVG loading operations give temporary access\n -- to the 'SVG' object within the scope of the handler function. These\n -- operations guarantee that the resources for the SVG object are deallocated\n -- at the end of the handler block. If this form of resource allocation is\n -- too restrictive you can use the GC-managed versions below.\n --\n -- These versions are ofen used in the following style:\n --\n -- > withSvgFromFile \"foo.svg\" $ \\svg -> do\n -- > ...\n -- > svgRender svg\n -- > ...\n\n withSvgFromFile,\n withSvgFromHandle,\n withSvgFromString,\n\n -- ** GC-managed versions\n\n -- | These versions of the SVG loading operations use the standard Haskell\n -- garbage collector to manage the resources associated with the 'SVG' object.\n -- As such they are more convenient to use but the GC cannot give\n -- strong guarantees about when the resources associated with the 'SVG' object\n -- will be released. In most circumstances this is not a problem, especially\n -- if the SVG files being used are not very big.\n\n svgNewFromFile,\n svgNewFromHandle,\n svgNewFromString,\n ) where\n\nimport Control.Monad (when)\nimport Foreign\nimport Foreign.C\nimport Control.Monad.Reader (ask, liftIO)\nimport System.IO (Handle, openFile, IOMode(ReadMode), hGetBuf)\n\nimport System.Glib.GError (GError(GError), checkGError)\nimport System.Glib.GObject (GObjectClass, constructNewGObject)\n\nimport Graphics.Rendering.Cairo.Internal (Render, bracketR)\n{# import Graphics.Rendering.Cairo.Types #} (Cairo(Cairo))\n\n{# context lib=\"librsvg\" prefix=\"rsvg_handle\" #}\n\n---------------------\n-- Types\n-- \n\n{# pointer *RsvgHandle as SVG foreign newtype #}\n\ninstance GObjectClass SVG\n\n---------------------\n-- Basic API\n-- \n\n-- block scoped versions\n\nwithSvgFromFile :: FilePath -> (SVG -> Render a) -> Render a\nwithSvgFromFile file action =\n withSVG $ \\svg -> do \n liftIO $ svgParseFromFile file svg\n action svg\n\nwithSvgFromHandle :: Handle -> (SVG -> Render a) -> Render a\nwithSvgFromHandle hnd action =\n withSVG $ \\svg -> do \n liftIO $ svgParseFromHandle hnd svg\n action svg\n\nwithSvgFromString :: String -> (SVG -> Render a) -> Render a\nwithSvgFromString str action =\n withSVG $ \\svg -> do\n liftIO $ svgParseFromString str svg\n action svg\n\nwithSVG :: (SVG -> Render a) -> Render a\nwithSVG =\n bracketR (do\n {# call g_type_init #}\n svgPtr <- {# call unsafe new #}\n svgPtr' <- newForeignPtr_ svgPtr\n return (SVG svgPtr')) \n (\\(SVG fptr) -> withForeignPtr fptr $ \\ptr ->\n {# call unsafe g_object_unref #} (castPtr ptr))\n\n-- GC managed versions\n\nsvgNewFromFile :: FilePath -> IO SVG\nsvgNewFromFile file = do\n svg <- svgNew\n svgParseFromFile file svg\n return svg\n\nsvgNewFromHandle :: Handle -> IO SVG\nsvgNewFromHandle hnd = do\n svg <- svgNew\n svgParseFromHandle hnd svg\n return svg\n\nsvgNewFromString :: String -> IO SVG\nsvgNewFromString str = do\n svg <- svgNew\n svgParseFromString str svg\n return svg\n\nsvgNew :: IO SVG\nsvgNew = do\n {# call g_type_init #}\n constructNewGObject SVG {# call unsafe new #}\n\n\n-- internal implementation\n\nsvgParseFromFile :: FilePath -> SVG -> IO ()\nsvgParseFromFile file svg = do\n hnd <- openFile file ReadMode\n svgParseFromHandle hnd svg\n\nsvgParseFromHandle :: Handle -> SVG -> IO ()\nsvgParseFromHandle hnd svg =\n allocaBytes 4096 $ \\bufferPtr -> do\n let loop = do\n count <- hGetBuf hnd bufferPtr 4096\n when (count > 0)\n (checkStatus $ {# call unsafe rsvg_handle_write #}\n svg (castPtr bufferPtr) (fromIntegral count))\n when (count == 4096) loop\n loop\n checkStatus $ {# call unsafe rsvg_handle_close #} svg\n\nsvgParseFromString :: String -> SVG -> IO ()\nsvgParseFromString str svg = do\n let loop \"\" = return ()\n loop str =\n case splitAt 4096 str of\n (chunk, str') -> do\n withCStringLen chunk $ \\(chunkPtr, len) ->\n checkStatus $ {# call unsafe rsvg_handle_write #}\n svg (castPtr chunkPtr) (fromIntegral len)\n loop str'\n loop str\n checkStatus $ {# call unsafe rsvg_handle_close #} svg\n\n-- actually render it\n\nsvgRender :: SVG -> Render ()\nsvgRender svg = do\n cr <- ask\n liftIO $ {# call unsafe render_cairo #} svg cr\n\n-- | Get the width and height of the SVG image.\n--\nsvgGetSize :: \n SVG\n -> (Int, Int) -- ^ @(width, height)@\nsvgGetSize svg = unsafePerformIO $\n allocaBytes {# sizeof RsvgDimensionData #} $ \\dimentionsPtr -> do\n {# call unsafe get_dimensions #} svg dimentionsPtr\n width <- {# get RsvgDimensionData->width #} dimentionsPtr\n height <- {# get RsvgDimensionData->height #} dimentionsPtr\n return (fromIntegral width, fromIntegral height)\n\n---------------------\n-- Convenience API\n-- \n\nsvgRenderFromFile :: FilePath -> Render ()\nsvgRenderFromFile file = withSvgFromFile file svgRender\n\nsvgRenderFromHandle :: Handle -> Render ()\nsvgRenderFromHandle hnd = withSvgFromHandle hnd svgRender\n\nsvgRenderFromString :: String -> Render ()\nsvgRenderFromString str = withSvgFromString str svgRender\n\n---------------------\n-- Utils\n-- \n\ncheckStatus :: (Ptr (Ptr ()) -> IO CInt) -> IO ()\ncheckStatus action =\n checkGError (\\ptr -> action ptr >> return ())\n (\\(GError domain code msg) -> fail (\"svg cairo error: \" ++ msg))\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"87d7b9e08a5d31cd8ceb10816e286e0f7bcb656d","subject":"SVG: provide implementation for GObjectClass","message":"SVG: provide implementation for GObjectClass\n","repos":"gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/vte","old_file":"svgcairo\/Graphics\/Rendering\/Cairo\/SVG.chs","new_file":"svgcairo\/Graphics\/Rendering\/Cairo\/SVG.chs","new_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.SVG\n-- Copyright : (c) 2005 Duncan Coutts, Paolo Martini \n-- License : BSD-style (see cairo\/COPYRIGHT)\n--\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : experimental\n-- Portability : portable\n--\n-- The SVG extension to the Cairo 2D graphics library.\n--\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.SVG (\n -- * Convenience API\n\n -- | These operations render an SVG image directly in the current 'Render'\n -- contect. Because they operate in the cairo 'Render' monad they are\n -- affected by the current transformation matrix. So it is possible, for\n -- example, to scale or rotate an SVG image.\n --\n -- In the following example we scale an SVG image to a unit square:\n --\n -- > let (width, height) = svgGetSize in\n -- > do scale (1\/width) (1\/height)\n -- > svgRender svg\n\n svgRenderFromFile,\n svgRenderFromHandle,\n svgRenderFromString,\n\n -- * Standard API\n\n -- | With this API there are seperate functions for loading the SVG and\n -- rendering it. This allows us to be more effecient in the case that an SVG\n -- image is used many times - since it can be loaded just once and rendered\n -- many times. With the convenience API above the SVG would be parsed and\n -- processed each time it is drawn.\n\n SVG,\n svgRender,\n svgGetSize,\n\n -- ** Block scoped versions\n\n -- | These versions of the SVG loading operations give temporary access\n -- to the 'SVG' object within the scope of the handler function. These\n -- operations guarantee that the resources for the SVG object are deallocated\n -- at the end of the handler block. If this form of resource allocation is\n -- too restrictive you can use the GC-managed versions below.\n --\n -- These versions are ofen used in the following style:\n --\n -- > withSvgFromFile \"foo.svg\" $ \\svg -> do\n -- > ...\n -- > svgRender svg\n -- > ...\n\n withSvgFromFile,\n withSvgFromHandle,\n withSvgFromString,\n\n -- ** GC-managed versions\n\n -- | These versions of the SVG loading operations use the standard Haskell\n -- garbage collector to manage the resources associated with the 'SVG' object.\n -- As such they are more convenient to use but the GC cannot give\n -- strong guarantees about when the resources associated with the 'SVG' object\n -- will be released. In most circumstances this is not a problem, especially\n -- if the SVG files being used are not very big.\n\n svgNewFromFile,\n svgNewFromHandle,\n svgNewFromString,\n ) where\n\nimport Control.Monad (when)\nimport Foreign\nimport Foreign.C\nimport Control.Monad.Reader (ask, liftIO)\nimport System.IO (Handle, openFile, IOMode(ReadMode), hGetBuf)\n\nimport System.Glib.GError (GError(GError), checkGError)\nimport System.Glib.GObject (GObjectClass(..), constructNewGObject, unGObject, mkGObject)\n\nimport Graphics.Rendering.Cairo.Internal (Render, bracketR)\n{# import Graphics.Rendering.Cairo.Types #} (Cairo(Cairo))\n\n{# context lib=\"librsvg\" prefix=\"rsvg_handle\" #}\n\n---------------------\n-- Types\n-- \n\n{# pointer *RsvgHandle as SVG foreign newtype #}\n\nmkSVG = SVG\nunSVG (SVG o) = o\n\ninstance GObjectClass SVG where\n toGObject = mkGObject . castForeignPtr . unSVG\n unsafeCastGObject = mkSVG . castForeignPtr . unGObject\n\n---------------------\n-- Basic API\n-- \n\n-- block scoped versions\n\nwithSvgFromFile :: FilePath -> (SVG -> Render a) -> Render a\nwithSvgFromFile file action =\n withSVG $ \\svg -> do \n liftIO $ svgParseFromFile file svg\n action svg\n\nwithSvgFromHandle :: Handle -> (SVG -> Render a) -> Render a\nwithSvgFromHandle hnd action =\n withSVG $ \\svg -> do \n liftIO $ svgParseFromHandle hnd svg\n action svg\n\nwithSvgFromString :: String -> (SVG -> Render a) -> Render a\nwithSvgFromString str action =\n withSVG $ \\svg -> do\n liftIO $ svgParseFromString str svg\n action svg\n\nwithSVG :: (SVG -> Render a) -> Render a\nwithSVG =\n bracketR (do\n {# call g_type_init #}\n svgPtr <- {# call unsafe new #}\n svgPtr' <- newForeignPtr_ svgPtr\n return (SVG svgPtr')) \n (\\(SVG fptr) -> withForeignPtr fptr $ \\ptr ->\n {# call unsafe g_object_unref #} (castPtr ptr))\n\n-- GC managed versions\n\nsvgNewFromFile :: FilePath -> IO SVG\nsvgNewFromFile file = do\n svg <- svgNew\n svgParseFromFile file svg\n return svg\n\nsvgNewFromHandle :: Handle -> IO SVG\nsvgNewFromHandle hnd = do\n svg <- svgNew\n svgParseFromHandle hnd svg\n return svg\n\nsvgNewFromString :: String -> IO SVG\nsvgNewFromString str = do\n svg <- svgNew\n svgParseFromString str svg\n return svg\n\nsvgNew :: IO SVG\nsvgNew = do\n {# call g_type_init #}\n constructNewGObject SVG {# call unsafe new #}\n\n\n-- internal implementation\n\nsvgParseFromFile :: FilePath -> SVG -> IO ()\nsvgParseFromFile file svg = do\n hnd <- openFile file ReadMode\n svgParseFromHandle hnd svg\n\nsvgParseFromHandle :: Handle -> SVG -> IO ()\nsvgParseFromHandle hnd svg =\n allocaBytes 4096 $ \\bufferPtr -> do\n let loop = do\n count <- hGetBuf hnd bufferPtr 4096\n when (count > 0)\n (checkStatus $ {# call unsafe rsvg_handle_write #}\n svg (castPtr bufferPtr) (fromIntegral count))\n when (count == 4096) loop\n loop\n checkStatus $ {# call unsafe rsvg_handle_close #} svg\n\nsvgParseFromString :: String -> SVG -> IO ()\nsvgParseFromString str svg = do\n let loop \"\" = return ()\n loop str =\n case splitAt 4096 str of\n (chunk, str') -> do\n withCStringLen chunk $ \\(chunkPtr, len) ->\n checkStatus $ {# call unsafe rsvg_handle_write #}\n svg (castPtr chunkPtr) (fromIntegral len)\n loop str'\n loop str\n checkStatus $ {# call unsafe rsvg_handle_close #} svg\n\n-- actually render it\n\nsvgRender :: SVG -> Render ()\nsvgRender svg = do\n cr <- ask\n liftIO $ {# call unsafe render_cairo #} svg cr\n\n-- | Get the width and height of the SVG image.\n--\nsvgGetSize :: \n SVG\n -> (Int, Int) -- ^ @(width, height)@\nsvgGetSize svg = unsafePerformIO $\n allocaBytes {# sizeof RsvgDimensionData #} $ \\dimentionsPtr -> do\n {# call unsafe get_dimensions #} svg dimentionsPtr\n width <- {# get RsvgDimensionData->width #} dimentionsPtr\n height <- {# get RsvgDimensionData->height #} dimentionsPtr\n return (fromIntegral width, fromIntegral height)\n\n---------------------\n-- Convenience API\n-- \n\nsvgRenderFromFile :: FilePath -> Render ()\nsvgRenderFromFile file = withSvgFromFile file svgRender\n\nsvgRenderFromHandle :: Handle -> Render ()\nsvgRenderFromHandle hnd = withSvgFromHandle hnd svgRender\n\nsvgRenderFromString :: String -> Render ()\nsvgRenderFromString str = withSvgFromString str svgRender\n\n---------------------\n-- Utils\n-- \n\ncheckStatus :: (Ptr (Ptr ()) -> IO CInt) -> IO ()\ncheckStatus action =\n checkGError (\\ptr -> action ptr >> return ())\n (\\(GError domain code msg) -> fail (\"svg cairo error: \" ++ msg))\n","old_contents":"-----------------------------------------------------------------------------\n-- |\n-- Module : Graphics.Rendering.Cairo.SVG\n-- Copyright : (c) 2005 Duncan Coutts, Paolo Martini \n-- License : BSD-style (see cairo\/COPYRIGHT)\n--\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : experimental\n-- Portability : portable\n--\n-- The SVG extension to the Cairo 2D graphics library.\n--\n-----------------------------------------------------------------------------\n\nmodule Graphics.Rendering.Cairo.SVG (\n -- * Convenience API\n\n -- | These operations render an SVG image directly in the current 'Render'\n -- contect. Because they operate in the cairo 'Render' monad they are\n -- affected by the current transformation matrix. So it is possible, for\n -- example, to scale or rotate an SVG image.\n --\n -- In the following example we scale an SVG image to a unit square:\n --\n -- > let (width, height) = svgGetSize in\n -- > do scale (1\/width) (1\/height)\n -- > svgRender svg\n\n svgRenderFromFile,\n svgRenderFromHandle,\n svgRenderFromString,\n\n -- * Standard API\n\n -- | With this API there are seperate functions for loading the SVG and\n -- rendering it. This allows us to be more effecient in the case that an SVG\n -- image is used many times - since it can be loaded just once and rendered\n -- many times. With the convenience API above the SVG would be parsed and\n -- processed each time it is drawn.\n\n SVG,\n svgRender,\n svgGetSize,\n\n -- ** Block scoped versions\n\n -- | These versions of the SVG loading operations give temporary access\n -- to the 'SVG' object within the scope of the handler function. These\n -- operations guarantee that the resources for the SVG object are deallocated\n -- at the end of the handler block. If this form of resource allocation is\n -- too restrictive you can use the GC-managed versions below.\n --\n -- These versions are ofen used in the following style:\n --\n -- > withSvgFromFile \"foo.svg\" $ \\svg -> do\n -- > ...\n -- > svgRender svg\n -- > ...\n\n withSvgFromFile,\n withSvgFromHandle,\n withSvgFromString,\n\n -- ** GC-managed versions\n\n -- | These versions of the SVG loading operations use the standard Haskell\n -- garbage collector to manage the resources associated with the 'SVG' object.\n -- As such they are more convenient to use but the GC cannot give\n -- strong guarantees about when the resources associated with the 'SVG' object\n -- will be released. In most circumstances this is not a problem, especially\n -- if the SVG files being used are not very big.\n\n svgNewFromFile,\n svgNewFromHandle,\n svgNewFromString,\n ) where\n\nimport Control.Monad (when)\nimport Foreign\nimport Foreign.C\nimport Control.Monad.Reader (ask, liftIO)\nimport System.IO (Handle, openFile, IOMode(ReadMode), hGetBuf)\n\nimport System.Glib.GError (GError(GError), checkGError)\nimport System.Glib.GObject (GObjectClass, constructNewGObject)\n\nimport Graphics.Rendering.Cairo.Internal (Render, bracketR)\n{# import Graphics.Rendering.Cairo.Types #} (Cairo(Cairo))\n\n{# context lib=\"librsvg\" prefix=\"rsvg_handle\" #}\n\n---------------------\n-- Types\n-- \n\n{# pointer *RsvgHandle as SVG foreign newtype #}\n\ninstance GObjectClass SVG\n\n---------------------\n-- Basic API\n-- \n\n-- block scoped versions\n\nwithSvgFromFile :: FilePath -> (SVG -> Render a) -> Render a\nwithSvgFromFile file action =\n withSVG $ \\svg -> do \n liftIO $ svgParseFromFile file svg\n action svg\n\nwithSvgFromHandle :: Handle -> (SVG -> Render a) -> Render a\nwithSvgFromHandle hnd action =\n withSVG $ \\svg -> do \n liftIO $ svgParseFromHandle hnd svg\n action svg\n\nwithSvgFromString :: String -> (SVG -> Render a) -> Render a\nwithSvgFromString str action =\n withSVG $ \\svg -> do\n liftIO $ svgParseFromString str svg\n action svg\n\nwithSVG :: (SVG -> Render a) -> Render a\nwithSVG =\n bracketR (do\n {# call g_type_init #}\n svgPtr <- {# call unsafe new #}\n svgPtr' <- newForeignPtr_ svgPtr\n return (SVG svgPtr')) \n (\\(SVG fptr) -> withForeignPtr fptr $ \\ptr ->\n {# call unsafe g_object_unref #} (castPtr ptr))\n\n-- GC managed versions\n\nsvgNewFromFile :: FilePath -> IO SVG\nsvgNewFromFile file = do\n svg <- svgNew\n svgParseFromFile file svg\n return svg\n\nsvgNewFromHandle :: Handle -> IO SVG\nsvgNewFromHandle hnd = do\n svg <- svgNew\n svgParseFromHandle hnd svg\n return svg\n\nsvgNewFromString :: String -> IO SVG\nsvgNewFromString str = do\n svg <- svgNew\n svgParseFromString str svg\n return svg\n\nsvgNew :: IO SVG\nsvgNew = do\n {# call g_type_init #}\n constructNewGObject SVG {# call unsafe new #}\n\n\n-- internal implementation\n\nsvgParseFromFile :: FilePath -> SVG -> IO ()\nsvgParseFromFile file svg = do\n hnd <- openFile file ReadMode\n svgParseFromHandle hnd svg\n\nsvgParseFromHandle :: Handle -> SVG -> IO ()\nsvgParseFromHandle hnd svg =\n allocaBytes 4096 $ \\bufferPtr -> do\n let loop = do\n count <- hGetBuf hnd bufferPtr 4096\n when (count > 0)\n (checkStatus $ {# call unsafe rsvg_handle_write #}\n svg (castPtr bufferPtr) (fromIntegral count))\n when (count == 4096) loop\n loop\n checkStatus $ {# call unsafe rsvg_handle_close #} svg\n\nsvgParseFromString :: String -> SVG -> IO ()\nsvgParseFromString str svg = do\n let loop \"\" = return ()\n loop str =\n case splitAt 4096 str of\n (chunk, str') -> do\n withCStringLen chunk $ \\(chunkPtr, len) ->\n checkStatus $ {# call unsafe rsvg_handle_write #}\n svg (castPtr chunkPtr) (fromIntegral len)\n loop str'\n loop str\n checkStatus $ {# call unsafe rsvg_handle_close #} svg\n\n-- actually render it\n\nsvgRender :: SVG -> Render ()\nsvgRender svg = do\n cr <- ask\n liftIO $ {# call unsafe render_cairo #} svg cr\n\n-- | Get the width and height of the SVG image.\n--\nsvgGetSize :: \n SVG\n -> (Int, Int) -- ^ @(width, height)@\nsvgGetSize svg = unsafePerformIO $\n allocaBytes {# sizeof RsvgDimensionData #} $ \\dimentionsPtr -> do\n {# call unsafe get_dimensions #} svg dimentionsPtr\n width <- {# get RsvgDimensionData->width #} dimentionsPtr\n height <- {# get RsvgDimensionData->height #} dimentionsPtr\n return (fromIntegral width, fromIntegral height)\n\n---------------------\n-- Convenience API\n-- \n\nsvgRenderFromFile :: FilePath -> Render ()\nsvgRenderFromFile file = withSvgFromFile file svgRender\n\nsvgRenderFromHandle :: Handle -> Render ()\nsvgRenderFromHandle hnd = withSvgFromHandle hnd svgRender\n\nsvgRenderFromString :: String -> Render ()\nsvgRenderFromString str = withSvgFromString str svgRender\n\n---------------------\n-- Utils\n-- \n\ncheckStatus :: (Ptr (Ptr ()) -> IO CInt) -> IO ()\ncheckStatus action =\n checkGError (\\ptr -> action ptr >> return ())\n (\\(GError domain code msg) -> fail (\"svg cairo error: \" ++ msg))\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"a8effbc3dc9365d5aaa884079c37a552c6785c56","subject":"","message":"\nfix typo\n\n\n","repos":"ccasin\/hpuz","old_file":"Codec\/Game\/Puz\/Internal.chs","new_file":"Codec\/Game\/Puz\/Internal.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \"puz.h\"\n\nmodule Codec.Game.Puz.Internal where\n\nimport Foreign\nimport Foreign.Ptr\nimport Foreign.C\n\n{# pointer *puz_head_t as PuzHead foreign newtype #}\n{# pointer *puzzle_t as Puz foreign newtype #}\n\n{# enum define PuzType\n { PUZ_FILE_BINARY as PuzTypeBinary\n , PUZ_FILE_TEXT as PuzTypeText\n , PUZ_FILE_UNKNOWN as PuzTypeUnknown\n }\n deriving (Eq,Show)\n #}\n\n\n-- XXX is this really freeing the right thing? How could I tell?\nmarshallPuz :: Ptr Puz -> IO Puz\nmarshallPuz pp = do fp <- newForeignPtr finalizerFree pp\n return $ Puz fp\n\n-- custom marshallers\n-- IN\nalwaysUseIn :: a -> (a -> b) -> b\nalwaysUseIn a f = f a\n\nnullIn :: (Ptr a -> IO b) -> IO b\nnullIn = alwaysUseIn nullPtr\n\npuzTypeIn :: (CInt -> IO b) -> IO b\npuzTypeIn = alwaysUseIn $ cIntConv $ fromEnum PuzTypeUnknown\n\npuzIn :: Puz -> (Ptr Puz -> IO b) -> IO b\npuzIn (Puz fp) = withForeignPtr fp\n\n-- OUT\ncerrToBool :: CInt -> Bool\ncerrToBool = (0 ==)\n\ncintToBool :: CInt -> Bool\ncintToBool = (1 ==)\n\n{- puz struct creation, initialization -}\n\n-- XXX I think we don't actually need puz_init because puz_load also mallocs\n-- and accepts null\n{# fun puz_init as puzCreate\n {nullIn- `Ptr Puz'} -> `Puz' marshallPuz* #}\n\n{# fun puz_load as puzLoad\n { nullIn- `Ptr Puz'\n , puzTypeIn- `PuzType'\n , id `Ptr CUChar'\n , `Int'\n } ->\n `Puz' marshallPuz* \n #}\n\n{- check sum checking, generation -}\n{# fun puz_cksums_calc as puzCksumsCalc\n { id `Ptr Puz' } -> `()' \n #}\n\n{# fun puz_cksums_check as puzCksumsCheck\n { id `Ptr Puz' } -> `Bool' cerrToBool\n #}\n\n{# fun puz_cksums_commit as puzCksumsCommit\n { id `Ptr Puz' } -> `()'\n #}\n\n{- accessors -}\n-- XXX actually the return guys on the sets check errors\n\n{# fun puz_width_get as puzGetWidth\n { puzIn* `Puz' } -> `Int'\n #}\n\n{# fun puz_width_set as puzSetWidth\n { puzIn* `Puz'\n , `Int'\n } -> \n `()'\n #}\n\n\n{# fun puz_height_get as puzGetHeight\n { puzIn* `Puz' } -> `Int'\n #}\n\n{# fun puz_height_set as puzSetHeight\n { puzIn* `Puz'\n , `Int'\n } -> \n `()'\n #}\n\n\n{# fun puz_solution_get as puzGetSolution\n { puzIn* `Puz' } -> `Ptr CUChar' id\n #}\n\n{# fun puz_solution_set as puzSetSolution\n { puzIn* `Puz' \n , id `Ptr CUChar' \n } -> \n `()'\n #}\n\n\n{# fun puz_grid_get as puzGetGrid\n { puzIn* `Puz' } -> `Ptr CUChar' id\n #}\n\n{# fun puz_grid_set as puzSetGrid\n { puzIn* `Puz' \n , id `Ptr CUChar' \n } -> \n `()'\n #}\n\n\n{# fun puz_title_get as puzGetTitle\n { puzIn* `Puz' } -> `Ptr CUChar' id\n #}\n\n{# fun puz_title_set as puzSetTitle\n { puzIn* `Puz'\n , id `Ptr CUChar'\n } -> \n `()'\n #}\n\n\n{# fun puz_author_get as puzGetAuthor\n { puzIn* `Puz' } -> `Ptr CUChar' id\n #}\n\n{# fun puz_author_set as puzSetAuthor\n { puzIn* `Puz'\n , id `Ptr CUChar'\n } -> \n `()'\n #}\n\n\n{# fun puz_copyright_get as puzGetCopyright\n { puzIn* `Puz'} -> `Ptr CUChar' id\n #}\n\n{# fun puz_copyright_set as puzSetCopyright\n { puzIn* `Puz'\n , id `Ptr CUChar' \n } -> \n `()'\n #}\n\n\n{# fun puz_clue_count_get as puzGetClueCount\n { puzIn* `Puz' } -> `Int'\n #}\n\n{# fun puz_clue_count_set as puzSetClueCount\n { puzIn* `Puz'\n , `Int'\n } -> \n `()'\n #}\n\n\n{# fun puz_clue_get as puzGetClue\n { puzIn* `Puz'\n , `Int' \n } -> \n `Ptr CUChar' id\n #}\n\n{# fun puz_clue_set as puzSetClue\n { puzIn* `Puz'\n , `Int' \n , id `Ptr CUChar'\n } -> \n `()'\n #}\n\n\n{# fun puz_notes_get as puzGetNotes\n { puzIn* `Puz' } -> `Ptr CUChar' id\n #}\n\n{# fun puz_notes_set as puzSetNotes\n { puzIn* `Puz'\n , id `Ptr CUChar' } \n -> \n `()'\n #}\n\n\n\n------\n------ C2HS stuff - why isn't there a C2HS module\n------\n\ncIntConv :: (Integral a, Integral b) => a -> b\ncIntConv = fromIntegral\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \"puz.h\"\n\nmodule Codec.Game.Puz.Internal where\n\nimport Foreign\nimport Foreign.Ptr\nimport Foreign.C\n\n{# pointer *puz_head_t as PuzHead foreign newtype #}\n{# pointer *puzzle_t as Puz foreign newtype #}\n\n{# enum define PuzType\n { PUZ_FILE_BINARY as PuzTypeBinary\n , PUZ_FILE_TEXT as PuzTypeText\n , PUZ_FILE_UNKNOWN as PuzTypeUnknown\n }\n deriving (Eq,Show)\n #}\n\n\n-- XXX is this really freeing the right thing? How could I tell?\nmarshallPuz :: Ptr Puz -> IO Puz\nmarshallPuz pp = do fp <- newForeignPtr finalizerFree pp\n return $ Puz fp\n\n-- custom marshallers\n-- IN\nalwaysUseIn :: a -> (a -> b) -> b\nalwaysUseIn a f = f a\n\nnullIn :: (Ptr a -> IO b) -> IO b\nnullIn = alwaysUseIn nullPtr\n\npuzTypeIn :: (CInt -> IO b) -> IO b\npuzTypeIn = alwaysUseIn $ cIntConv $ fromEnum PuzTypeUnknown\n\npuzIn :: Puz -> (Ptr Puz -> IO b) -> IO b\npuzIn (Puz fp) = withForeignPtr fp\n\n-- OUT\ncerrToBool :: CInt -> Bool\ncerrToBool = (0 ==)\n\ncintToBool :: Cint -> Bool\ncintToBool = (1 ==)\n\n{- puz struct creation, initialization -}\n\n-- XXX I think we don't actually need puz_init because puz_load also mallocs\n-- and accepts null\n{# fun puz_init as puzCreate\n {nullIn- `Ptr Puz'} -> `Puz' marshallPuz* #}\n\n{# fun puz_load as puzLoad\n { nullIn- `Ptr Puz'\n , puzTypeIn- `PuzType'\n , id `Ptr CUChar'\n , `Int'\n } ->\n `Puz' marshallPuz* \n #}\n\n{- check sum checking, generation -}\n{# fun puz_cksums_calc as puzCksumsCalc\n { id `Ptr Puz' } -> `()' \n #}\n\n{# fun puz_cksums_check as puzCksumsCheck\n { id `Ptr Puz' } -> `Bool' cerrToBool\n #}\n\n{# fun puz_cksums_commit as puzCksumsCommit\n { id `Ptr Puz' } -> `()'\n #}\n\n{- accessors -}\n-- XXX actually the return guys on the sets check errors\n\n{# fun puz_width_get as puzGetWidth\n { puzIn* `Puz' } -> `Int'\n #}\n\n{# fun puz_width_set as puzSetWidth\n { puzIn* `Puz'\n , `Int'\n } -> \n `()'\n #}\n\n\n{# fun puz_height_get as puzGetHeight\n { puzIn* `Puz' } -> `Int'\n #}\n\n{# fun puz_height_set as puzSetHeight\n { puzIn* `Puz'\n , `Int'\n } -> \n `()'\n #}\n\n\n{# fun puz_solution_get as puzGetSolution\n { puzIn* `Puz' } -> `Ptr CUChar' id\n #}\n\n{# fun puz_solution_set as puzSetSolution\n { puzIn* `Puz' \n , id `Ptr CUChar' \n } -> \n `()'\n #}\n\n\n{# fun puz_grid_get as puzGetGrid\n { puzIn* `Puz' } -> `Ptr CUChar' id\n #}\n\n{# fun puz_grid_set as puzSetGrid\n { puzIn* `Puz' \n , id `Ptr CUChar' \n } -> \n `()'\n #}\n\n\n{# fun puz_title_get as puzGetTitle\n { puzIn* `Puz' } -> `Ptr CUChar' id\n #}\n\n{# fun puz_title_set as puzSetTitle\n { puzIn* `Puz'\n , id `Ptr CUChar'\n } -> \n `()'\n #}\n\n\n{# fun puz_author_get as puzGetAuthor\n { puzIn* `Puz' } -> `Ptr CUChar' id\n #}\n\n{# fun puz_author_set as puzSetAuthor\n { puzIn* `Puz'\n , id `Ptr CUChar'\n } -> \n `()'\n #}\n\n\n{# fun puz_copyright_get as puzGetCopyright\n { puzIn* `Puz'} -> `Ptr CUChar' id\n #}\n\n{# fun puz_copyright_set as puzSetCopyright\n { puzIn* `Puz'\n , id `Ptr CUChar' \n } -> \n `()'\n #}\n\n\n{# fun puz_clue_count_get as puzGetClueCount\n { puzIn* `Puz' } -> `Int'\n #}\n\n{# fun puz_clue_count_set as puzSetClueCount\n { puzIn* `Puz'\n , `Int'\n } -> \n `()'\n #}\n\n\n{# fun puz_clue_get as puzGetClue\n { puzIn* `Puz'\n , `Int' \n } -> \n `Ptr CUChar' id\n #}\n\n{# fun puz_clue_set as puzSetClue\n { puzIn* `Puz'\n , `Int' \n , id `Ptr CUChar'\n } -> \n `()'\n #}\n\n\n{# fun puz_notes_get as puzGetNotes\n { puzIn* `Puz' } -> `Ptr CUChar' id\n #}\n\n{# fun puz_notes_set as puzSetNotes\n { puzIn* `Puz'\n , id `Ptr CUChar' } \n -> \n `()'\n #}\n\n\n\n------\n------ C2HS stuff - why isn't there a C2HS module\n------\n\ncIntConv :: (Integral a, Integral b) => a -> b\ncIntConv = fromIntegral\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"}
{"commit":"74d870a028c21d2ba7660393196ec4b9c41a9da5","subject":"[project @ 2002-07-17 16:02:09 by juhp] (scrolledWindowNew): Make it maybe take Adjustments, passing a null ptr when Nothing is given.","message":"[project @ 2002-07-17 16:02:09 by juhp]\n(scrolledWindowNew): Make it maybe take Adjustments, passing\na null ptr when Nothing is given.\n\n","repos":"gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/gstreamer","old_file":"gtk\/scrolling\/ScrolledWindow.chs","new_file":"gtk\/scrolling\/ScrolledWindow.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget ScrolledWindow@\n--\n-- Author : Axel Simon\n-- \n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/07\/17 16:02:09 $\n--\n-- Copyright (c) 1999..2002 Axel Simon\n--\n-- This file is free software; you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation; either version 2 of the License, or\n-- (at your option) any later version.\n--\n-- This file is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- * @ScrolledWindow is a container that adds scroll bars to its child. Some\n-- widgets have native scrolling support, in which case the scrolling action\n-- is performed by the child itself (e.g. a TreeView widget does this by only\n-- moving the table part and not the titles of a table). If a widget does\n-- not support native scrolling it has to be put into a @TreeView widget.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n\nmodule ScrolledWindow(\n ScrolledWindow,\n ScrolledWindowClass,\n castToScrolledWindow,\n scrolledWindowNew,\n scrolledWindowGetHAdjustment,\n scrolledWindowGetVAdjustment,\n PolicyType(..),\n scrolledWindowSetPolicy,\n scrolledWindowAddWithViewport,\n CornerType(..),\n scrolledWindowSetPlacement,\n ShadowType(..),\n scrolledWindowSetShadowType,\n scrolledWindowSetHAdjustment,\n scrolledWindowSetVAdjustment,\n ) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Enums\t(PolicyType(..), CornerType(..), ShadowType(..))\nimport Maybe (fromMaybe)\nimport Structs (nullForeignPtr)\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- @constructor scrolledWindowNew@ Create a new @ref type ScrolledWindow@.\n--\nscrolledWindowNew :: Maybe Adjustment -> Maybe Adjustment -> IO ScrolledWindow\nscrolledWindowNew hAdj vAdj = makeNewObject mkScrolledWindow $ liftM castPtr $\n {#call unsafe scrolled_window_new#} (fromMAdj hAdj) (fromMAdj vAdj)\n where\n fromMAdj :: Maybe Adjustment -> Adjustment\n fromMAdj = fromMaybe $ mkAdjustment nullForeignPtr\n\n-- @method scrolledWindowGetHAdjustment@ Retrieve the horizontal\n-- @ref arg Adjustment@ of the @ref type ScrolledWindow@.\n--\nscrolledWindowGetHAdjustment :: ScrolledWindowClass w => w -> IO Adjustment\nscrolledWindowGetHAdjustment w = makeNewObject mkAdjustment $\n {#call unsafe scrolled_window_get_hadjustment#} (toScrolledWindow w)\n\n-- @method scrolledWindowGetVAdjustment@ Retrieve the vertical\n-- @ref arg Adjustment@ of the @ref type ScrolledWindow@.\n--\nscrolledWindowGetVAdjustment :: ScrolledWindowClass w => w -> IO Adjustment\nscrolledWindowGetVAdjustment w = makeNewObject mkAdjustment $\n {#call unsafe scrolled_window_get_vadjustment#} (toScrolledWindow w)\n\n-- @method scrolledWindowSetPolicy@ Specify if the scrollbars should vanish if\n-- the child size is sufficiently small.\n--\nscrolledWindowSetPolicy :: ScrolledWindowClass w => w -> PolicyType ->\n PolicyType -> IO ()\nscrolledWindowSetPolicy w hPol vPol = {#call scrolled_window_set_policy#}\n (toScrolledWindow w) ((fromIntegral.fromEnum) hPol) \n ((fromIntegral.fromEnum) vPol)\n\n-- @method scrolledWindowAddWithViewport@ Add a child widget without native\n-- scrolling support to this @ref type ScrolledWindow@.\n--\nscrolledWindowAddWithViewport :: (ScrolledWindowClass w, WidgetClass wid) => \n w -> wid -> IO ()\nscrolledWindowAddWithViewport w wid = \n {#call scrolled_window_add_with_viewport#} (toScrolledWindow w) \n (toWidget wid)\n\n-- @method scrolledWindowSetPlacement@ Specify where the scrollbars should be\n-- placed.\n--\nscrolledWindowSetPlacement :: ScrolledWindowClass w => w -> CornerType -> IO ()\nscrolledWindowSetPlacement w ct =\n {#call scrolled_window_set_placement#} (toScrolledWindow w)\n ((fromIntegral.fromEnum) ct)\n\n-- @method scrolledWindowSetShadowType@ Specify if and how an outer frame\n-- should be drawn around the child.\n--\nscrolledWindowSetShadowType :: ScrolledWindowClass w => w -> ShadowType ->\n IO ()\nscrolledWindowSetShadowType w st = {#call scrolled_window_set_shadow_type#}\n (toScrolledWindow w) ((fromIntegral.fromEnum) st)\n\n-- @method scrolledWindowSetHAdjustment@ Set the horizontal\n-- @ref arg Adjustment@ of the @ref type ScrolledWindow@.\n--\nscrolledWindowSetHAdjustment :: ScrolledWindowClass w => w -> Adjustment ->\n IO ()\nscrolledWindowSetHAdjustment w adj = {#call scrolled_window_set_hadjustment#}\n (toScrolledWindow w) adj\n\n-- @method scrolledWindowSetVAdjustment@ Set the vertical @ref arg Adjustment@\n-- of the @ref type ScrolledWindow@.\n--\nscrolledWindowSetVAdjustment :: ScrolledWindowClass w => w -> Adjustment ->\n IO ()\nscrolledWindowSetVAdjustment w adj = {#call scrolled_window_set_hadjustment#}\n (toScrolledWindow w) adj\n\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget ScrolledWindow@\n--\n-- Author : Axel Simon\n-- \n-- Created: 23 May 2001\n--\n-- Version $Revision: 1.2 $ from $Date: 2002\/05\/24 09:43:25 $\n--\n-- Copyright (c) 1999..2002 Axel Simon\n--\n-- This file is free software; you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation; either version 2 of the License, or\n-- (at your option) any later version.\n--\n-- This file is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- * @ScrolledWindow is a container that adds scroll bars to its child. Some\n-- widgets have native scrolling support, in which case the scrolling action\n-- is performed by the child itself (e.g. a TreeView widget does this by only\n-- moving the table part and not the titles of a table). If a widget does\n-- not support native scrolling it has to be put into a @TreeView widget.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n\nmodule ScrolledWindow(\n ScrolledWindow,\n ScrolledWindowClass,\n castToScrolledWindow,\n scrolledWindowNew,\n scrolledWindowGetHAdjustment,\n scrolledWindowGetVAdjustment,\n PolicyType(..),\n scrolledWindowSetPolicy,\n scrolledWindowAddWithViewport,\n CornerType(..),\n scrolledWindowSetPlacement,\n ShadowType(..),\n scrolledWindowSetShadowType,\n scrolledWindowSetHAdjustment,\n scrolledWindowSetVAdjustment,\n ) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Enums\t(PolicyType(..), CornerType(..), ShadowType(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n-- @constructor scrolledWindowNew@ Create a new @ref type ScrolledWindow@.\n--\nscrolledWindowNew :: Adjustment -> Adjustment -> IO ScrolledWindow\nscrolledWindowNew vAdj hAdj = makeNewObject mkScrolledWindow $ liftM castPtr $\n {#call unsafe scrolled_window_new#} hAdj vAdj\n\n-- @method scrolledWindowGetHAdjustment@ Retrieve the horizontal\n-- @ref arg Adjustment@ of the @ref type ScrolledWindow@.\n--\nscrolledWindowGetHAdjustment :: ScrolledWindowClass w => w -> IO Adjustment\nscrolledWindowGetHAdjustment w = makeNewObject mkAdjustment $\n {#call unsafe scrolled_window_get_hadjustment#} (toScrolledWindow w)\n\n-- @method scrolledWindowGetVAdjustment@ Retrieve the vertical\n-- @ref arg Adjustment@ of the @ref type ScrolledWindow@.\n--\nscrolledWindowGetVAdjustment :: ScrolledWindowClass w => w -> IO Adjustment\nscrolledWindowGetVAdjustment w = makeNewObject mkAdjustment $\n {#call unsafe scrolled_window_get_vadjustment#} (toScrolledWindow w)\n\n-- @method scrolledWindowSetPolicy@ Specify if the scrollbars should vanish if\n-- the child size is sufficiently small.\n--\nscrolledWindowSetPolicy :: ScrolledWindowClass w => w -> PolicyType ->\n PolicyType -> IO ()\nscrolledWindowSetPolicy w hPol vPol = {#call scrolled_window_set_policy#}\n (toScrolledWindow w) ((fromIntegral.fromEnum) hPol) \n ((fromIntegral.fromEnum) vPol)\n\n-- @method scrolledWindowAddWithViewport@ Add a child widget without native\n-- scrolling support to this @ref type ScrolledWindow@.\n--\nscrolledWindowAddWithViewport :: (ScrolledWindowClass w, WidgetClass wid) => \n w -> wid -> IO ()\nscrolledWindowAddWithViewport w wid = \n {#call scrolled_window_add_with_viewport#} (toScrolledWindow w) \n (toWidget wid)\n\n-- @method scrolledWindowSetPlacement@ Specify where the scrollbars should be\n-- placed.\n--\nscrolledWindowSetPlacement :: ScrolledWindowClass w => w -> CornerType -> IO ()\nscrolledWindowSetPlacement w ct =\n {#call scrolled_window_set_placement#} (toScrolledWindow w)\n ((fromIntegral.fromEnum) ct)\n\n-- @method scrolledWindowSetShadowType@ Specify if and how an outer frame\n-- should be drawn around the child.\n--\nscrolledWindowSetShadowType :: ScrolledWindowClass w => w -> ShadowType ->\n IO ()\nscrolledWindowSetShadowType w st = {#call scrolled_window_set_shadow_type#}\n (toScrolledWindow w) ((fromIntegral.fromEnum) st)\n\n-- @method scrolledWindowSetHAdjustment@ Set the horizontal\n-- @ref arg Adjustment@ of the @ref type ScrolledWindow@.\n--\nscrolledWindowSetHAdjustment :: ScrolledWindowClass w => w -> Adjustment ->\n IO ()\nscrolledWindowSetHAdjustment w adj = {#call scrolled_window_set_hadjustment#}\n (toScrolledWindow w) adj\n\n-- @method scrolledWindowSetVAdjustment@ Set the vertical @ref arg Adjustment@\n-- of the @ref type ScrolledWindow@.\n--\nscrolledWindowSetVAdjustment :: ScrolledWindowClass w => w -> Adjustment ->\n IO ()\nscrolledWindowSetVAdjustment w adj = {#call scrolled_window_set_hadjustment#}\n (toScrolledWindow w) adj\n\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"8d0768c0e1d9e0b8895642e0ef3f7079354d9a1f","subject":"MINOR: Stylistic Changes","message":"MINOR: Stylistic Changes\n","repos":"weissi\/hs-shonky-crypt","old_file":"src-hs\/Codec\/ShonkyCrypt\/ShonkyCryptFFI.chs","new_file":"src-hs\/Codec\/ShonkyCrypt\/ShonkyCryptFFI.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -fno-cse -fno-full-laziness #-} -- recommended by GHC manual\n\nmodule Codec.ShonkyCrypt.ShonkyCryptFFI where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (liftM)\nimport Data.ByteString (ByteString)\nimport Data.Word (Word8)\nimport Foreign.C.String (CStringLen, CString)\nimport Foreign.C.Types (CChar(..), CULong(..), CDouble(..))\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Alloc (mallocBytes, free)\nimport Foreign.Marshal.Utils (with, fromBool, toBool)\nimport Foreign.Ptr\nimport Foreign.Storable (Storable(..))\nimport System.IO.Unsafe (unsafePerformIO)\nimport qualified Data.ByteString.Internal as BSI\nimport qualified Data.ByteString.Unsafe as BSU\n\n#include \"shonky-crypt.h\"\n\ndata ShonkyCryptKey = ShonkyCryptKey\n { sckKeyStart :: !Word8\n , sckKeyInc :: !Word8\n , sckOnlyAlnum :: !Bool\n } deriving Show\n\ninstance Storable ShonkyCryptKey where\n sizeOf _ = {#sizeof shonky_crypt_key_t #}\n alignment _ = 4\n peek p = ShonkyCryptKey\n <$> liftM fromIntegral ({#get shonky_crypt_key_t->key_start #} p)\n <*> liftM fromIntegral ({#get shonky_crypt_key_t->key_inc #} p)\n <*> liftM toBool ({#get shonky_crypt_key_t->only_alnum #} p)\n poke p x =\n do {#set shonky_crypt_key_t.key_start #} p (fromIntegral $ sckKeyStart x)\n {#set shonky_crypt_key_t.key_inc #} p (fromIntegral $ sckKeyInc x)\n {#set shonky_crypt_key_t.only_alnum #} p (fromBool $ sckOnlyAlnum x)\n\n{#pointer shonky_crypt_key_t as ShonkyCryptKeyPtr -> ShonkyCryptKey #}\n\nfromMallocedStorable :: Storable a => Ptr a -> IO a\nfromMallocedStorable p =\n do key <- peek p\n free p\n return key\n\nnewShonkyCryptContextPointer :: Ptr ShonkyCryptContext -> IO ShonkyCryptContext\nnewShonkyCryptContextPointer p =\n do fp <- newForeignPtr scReleaseContextPtr p\n return $! ShonkyCryptContext fp\n\nunsafePackMallocCStringLen :: CStringLen -> IO ByteString\nunsafePackMallocCStringLen (cstr, len) = do\n fp <- newForeignPtr BSI.c_free_finalizer (castPtr cstr)\n return $! BSI.PS fp 0 len\n\nwithShonkyCryptContext :: ShonkyCryptContext -> (Ptr ShonkyCryptContext -> IO b) -> IO b\n{#pointer shonky_crypt_context_t as ShonkyCryptContext foreign newtype #}\n\nforeign import ccall \"shonky-crypt.h &sc_release_context\"\n scReleaseContextPtr :: FunPtr (Ptr ShonkyCryptContext -> IO ())\n\nwithTrickC2HS :: Storable a => a -> (Ptr a -> IO b) -> IO b\nwithTrickC2HS = with\n\n{#fun pure unsafe sc_alloc_context_with_key as\n ^ { withTrickC2HS *`ShonkyCryptKey' }\n -> `ShonkyCryptContext' newShonkyCryptContextPointer * #}\n\nwithByteStringLen :: ByteString -> ((CString, CULong) -> IO a) -> IO a\nwithByteStringLen str f = BSU.unsafeUseAsCStringLen str (\\(cstr, len) ->\n f (cstr, fromIntegral len))\n\n{#fun pure unsafe sc_entropy as\n ^ { withByteStringLen *`ByteString'& } -> `Double' #}\n\n{#fun pure unsafe sc_copy_context as\n ^ { withShonkyCryptContext *`ShonkyCryptContext' }\n -> `ShonkyCryptContext' newShonkyCryptContextPointer * #}\n\ntype InPlaceEnDeCryptFun =\n Ptr ShonkyCryptContext -> Ptr CChar -> Ptr CChar -> CULong -> IO ()\ntype NewEnDeCryptFun =\n Ptr ShonkyCryptKey -> Ptr CChar -> CULong -> IO CString\n\nscEnDeCryptInplace :: InPlaceEnDeCryptFun\n -> ShonkyCryptContext\n -> ByteString\n -> (ByteString, ShonkyCryptContext)\nscEnDeCryptInplace f ctx input =\n unsafePerformIO $\n BSU.unsafeUseAsCStringLen input $ \\(inputBytes, inputLen) ->\n withShonkyCryptContext ctx $ \\ctx' ->\n do\n newContext' <- {#call sc_copy_context #} ctx'\n outBuffer <- mallocBytes inputLen\n f newContext' inputBytes outBuffer (fromIntegral inputLen)\n out <- unsafePackMallocCStringLen (outBuffer, inputLen)\n newContext <- newShonkyCryptContextPointer newContext'\n return (out, newContext)\n\nencryptS :: ShonkyCryptContext -> ByteString -> (ByteString, ShonkyCryptContext)\nencryptS = scEnDeCryptInplace {#call unsafe sc_encrypt_inplace #}\ndecryptS :: ShonkyCryptContext -> ByteString -> (ByteString, ShonkyCryptContext)\ndecryptS = scEnDeCryptInplace {#call unsafe sc_decrypt_inplace #}\n\nscEnDecryptNew :: NewEnDeCryptFun -> ShonkyCryptKey -> ByteString -> ByteString\nscEnDecryptNew f key input =\n unsafePerformIO $\n BSU.unsafeUseAsCStringLen input $ \\(inputBytes, inputLen) ->\n with key $ \\key' ->\n do outputC <- f key' inputBytes (fromIntegral inputLen)\n unsafePackMallocCStringLen (outputC, inputLen)\n\nencrypt :: ShonkyCryptKey -> ByteString -> ByteString\nencrypt = scEnDecryptNew {#call unsafe sc_encrypt_new #}\n\ndecrypt :: ShonkyCryptKey -> ByteString -> ByteString\ndecrypt = scEnDecryptNew {#call unsafe sc_decrypt_new #}\n\n{#fun pure unsafe sc_new_crypt_key_with as\n ^ { `Word8', `Word8', `Bool' } -> `ShonkyCryptKey' fromMallocedStorable * #}\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE BangPatterns #-}\n{-# OPTIONS_GHC -fno-cse -fno-full-laziness #-} -- recommended by GHC manual\n\nmodule Codec.ShonkyCrypt.ShonkyCryptFFI where\n\nimport Control.Applicative ((<$>), (<*>))\nimport Control.Monad (liftM)\nimport Data.ByteString (ByteString)\nimport Data.Word (Word8)\nimport Foreign.C.String (CStringLen, CString)\nimport Foreign.C.Types (CChar(..), CULong(..), CDouble(..))\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Alloc (mallocBytes, free)\nimport Foreign.Marshal.Utils (with, fromBool, toBool)\nimport Foreign.Ptr\nimport Foreign.Storable (Storable(..))\nimport System.IO.Unsafe (unsafePerformIO)\nimport qualified Data.ByteString.Internal as BSI\nimport qualified Data.ByteString.Unsafe as BSU\n\n#include \"shonky-crypt.h\"\n\ndata ShonkyCryptKey = ShonkyCryptKey\n { sckKeyStart :: !Word8\n , sckKeyInc :: !Word8\n , sckOnlyAlnum :: !Bool\n } deriving Show\n\ninstance Storable ShonkyCryptKey where\n sizeOf _ = {#sizeof shonky_crypt_key_t #}\n alignment _ = 4\n peek p = ShonkyCryptKey\n <$> liftM fromIntegral ({#get shonky_crypt_key_t->key_start #} p)\n <*> liftM fromIntegral ({#get shonky_crypt_key_t->key_inc #} p)\n <*> liftM toBool ({#get shonky_crypt_key_t->only_alnum #} p)\n poke p x =\n do {#set shonky_crypt_key_t.key_start #} p (fromIntegral $ sckKeyStart x)\n {#set shonky_crypt_key_t.key_inc #} p (fromIntegral $ sckKeyInc x)\n {#set shonky_crypt_key_t.only_alnum #} p (fromBool $ sckOnlyAlnum x)\n\n{#pointer shonky_crypt_key_t as ShonkyCryptKeyPtr -> ShonkyCryptKey #}\n\nfromMallocedStorable :: Storable a => Ptr a -> IO a\nfromMallocedStorable p =\n do key <- peek p\n free p\n return key\n\nnewShonkyCryptContextPointer :: Ptr ShonkyCryptContext -> IO ShonkyCryptContext\nnewShonkyCryptContextPointer p =\n do fp <- newForeignPtr scReleaseContextPtr p\n return $ ShonkyCryptContext fp\n\nunsafePackMallocCStringLen :: CStringLen -> IO ByteString\nunsafePackMallocCStringLen (cstr, len) = do\n fp <- newForeignPtr BSI.c_free_finalizer (castPtr cstr)\n return $! BSI.PS fp 0 len\n\nwithShonkyCryptContext :: ShonkyCryptContext -> (Ptr ShonkyCryptContext -> IO b) -> IO b\n{#pointer shonky_crypt_context_t as ShonkyCryptContext foreign newtype #}\n\nforeign import ccall \"shonky-crypt.h &sc_release_context\"\n scReleaseContextPtr :: FunPtr (Ptr ShonkyCryptContext -> IO ())\n\nwithTrickC2HS :: Storable a => a -> (Ptr a -> IO b) -> IO b\nwithTrickC2HS = with\n\n{#fun pure unsafe sc_alloc_context_with_key as\n ^ { withTrickC2HS* `ShonkyCryptKey' }\n -> `ShonkyCryptContext' newShonkyCryptContextPointer* #}\n\nwithByteStringLen :: ByteString -> ((CString, CULong) -> IO a) -> IO a\nwithByteStringLen str f = BSU.unsafeUseAsCStringLen str (\\(cstr, len) ->\n f (cstr, fromIntegral len))\n\n{#fun pure unsafe sc_entropy as\n ^ { withByteStringLen *`ByteString'& } -> `Double' #}\n\n{#fun pure unsafe sc_copy_context as\n ^ { withShonkyCryptContext* `ShonkyCryptContext' }\n -> `ShonkyCryptContext' newShonkyCryptContextPointer* #}\n\ntype InPlaceEnDeCryptFun =\n Ptr ShonkyCryptContext -> Ptr CChar -> Ptr CChar -> CULong -> IO ()\ntype NewEnDeCryptFun =\n Ptr ShonkyCryptKey -> Ptr CChar -> CULong -> IO CString\n\nscEnDeCryptInplace :: InPlaceEnDeCryptFun\n -> ShonkyCryptContext\n -> ByteString\n -> (ByteString, ShonkyCryptContext)\nscEnDeCryptInplace f ctx input =\n unsafePerformIO $\n BSU.unsafeUseAsCStringLen input $ \\(inputBytes, inputLen) ->\n withShonkyCryptContext ctx $ \\ctx' ->\n do\n newContext' <- {#call sc_copy_context #} ctx'\n outBuffer <- mallocBytes inputLen\n f newContext' inputBytes outBuffer (fromIntegral inputLen)\n out <- unsafePackMallocCStringLen (outBuffer, inputLen)\n newContext <- newShonkyCryptContextPointer newContext'\n return (out, newContext)\n\nencryptS :: ShonkyCryptContext -> ByteString -> (ByteString, ShonkyCryptContext)\nencryptS = scEnDeCryptInplace {#call unsafe sc_encrypt_inplace #}\ndecryptS :: ShonkyCryptContext -> ByteString -> (ByteString, ShonkyCryptContext)\ndecryptS = scEnDeCryptInplace {#call unsafe sc_decrypt_inplace #}\n\nscEnDecryptNew :: NewEnDeCryptFun -> ShonkyCryptKey -> ByteString -> ByteString\nscEnDecryptNew f key input =\n unsafePerformIO $\n BSU.unsafeUseAsCStringLen input $ \\(inputBytes, inputLen) ->\n with key $ \\key' ->\n do outputC <- f key' inputBytes (fromIntegral inputLen)\n unsafePackMallocCStringLen (outputC, inputLen)\n\nencrypt :: ShonkyCryptKey -> ByteString -> ByteString\nencrypt = scEnDecryptNew {#call unsafe sc_encrypt_new #}\n\ndecrypt :: ShonkyCryptKey -> ByteString -> ByteString\ndecrypt = scEnDecryptNew {#call unsafe sc_decrypt_new #}\n\n{#fun pure unsafe sc_new_crypt_key_with as\n ^ { `Word8', `Word8', `Bool' } -> `ShonkyCryptKey' fromMallocedStorable* #}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"211ebc1f1a915c0615b68d37330ffcd12bfe20d4","subject":"Don't export valueUnset since it's not used outside of the module","message":"Don't export valueUnset since it's not used outside of the module\n","repos":"gtk2hs\/webkit,gtk2hs\/gtksourceview,gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/gtksourceview,gtk2hs\/webkit,gtk2hs\/webkit,gtk2hs\/gstreamer","old_file":"glib\/System\/Glib\/GValue.chs","new_file":"glib\/System\/Glib\/GValue.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GValue\n--\n-- Author : Axel Simon\n--\n-- Created: 1 June 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2005\/11\/16 13:14:16 $\n--\n-- Copyright (c) 1999..2002 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- This module implements only the necessities for the GTK binding.\n--\n-- * Everything here is only used by \"Graphics.UI.Gtk.TreeList.TreeModel\" and\n-- friends.\n--\nmodule System.Glib.GValue (\n GValue(GValue),\n valueInit,\n valueGetType,\n allocaGValue\n ) where\n\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.GType\t(GType)\n\n{# context lib=\"glib\" prefix=\"g\" #}\n\n{# pointer *GValue newtype #}\n\n-- | Clear a GValue.\n--\nvalueInit :: GValue -> GType -> IO ()\nvalueInit gv gt = do\n -- The g_type field of the value must be zero or g_value_init will fail.\n {# call unsafe value_init #} gv gt\n return ()\n\n-- | Get the type of the value stored in the GValue\n--\nvalueGetType :: GValue -> IO GType\nvalueGetType (GValue gvPtr) = {# get GValue->g_type #} gvPtr\n\n-- | Temporarily allocate a GValue.\n--\nallocaGValue :: (GValue -> IO b) -> IO b\nallocaGValue body =\n -- c2hs is broken in that it can't handle arrays of compound arrays in the\n -- sizeof hook\n allocaBytes ({# sizeof GType #}+ 2* {# sizeof guint64 #}) $ \\gvPtr -> do\n -- The g_type field of the value must be zero or g_value_init will fail.\n {# set GValue->g_type #} gvPtr (0 :: GType)\n result <- body (GValue gvPtr)\n {#call unsafe value_unset#} (GValue gvPtr)\n return result\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) GValue\n--\n-- Author : Axel Simon\n--\n-- Created: 1 June 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2005\/11\/16 13:14:16 $\n--\n-- Copyright (c) 1999..2002 Axel Simon\n--\n-- This library is free software; you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public\n-- License as published by the Free Software Foundation; either\n-- version 2.1 of the License, or (at your option) any later version.\n--\n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n--\n-- |\n-- Maintainer : gtk2hs-users@lists.sourceforge.net\n-- Stability : provisional\n-- Portability : portable (depends on GHC)\n--\n-- This module implements only the necessities for the GTK binding.\n--\n-- * Everything here is only used by \"Graphics.UI.Gtk.TreeList.TreeModel\" and\n-- friends.\n--\nmodule System.Glib.GValue (\n GValue(GValue),\n valueInit,\n valueUnset,\n valueGetType,\n allocaGValue\n ) where\n\nimport Monad\t(liftM)\n\nimport System.Glib.FFI\nimport System.Glib.GType\t(GType)\n\n{# context lib=\"glib\" prefix=\"g\" #}\n\n{# pointer *GValue newtype #}\n\n-- | Clear a GValue.\n--\nvalueInit :: GValue -> GType -> IO ()\nvalueInit gv gt = do\n -- The g_type field of the value must be zero or g_value_init will fail.\n {# call unsafe value_init #} gv gt\n return ()\n\n-- | Free the data in a GValue.\n--\nvalueUnset :: GValue -> IO ()\nvalueUnset = {#call unsafe value_unset#}\n\n-- | Get the type of the value stored in the GValue\n--\nvalueGetType :: GValue -> IO GType\nvalueGetType (GValue gvPtr) = {# get GValue->g_type #} gvPtr\n\n-- | Temporarily allocate a GValue.\n--\nallocaGValue :: (GValue -> IO b) -> IO b\nallocaGValue body =\n -- c2hs is broken in that it can't handle arrays of compound arrays in the\n -- sizeof hook\n allocaBytes ({# sizeof GType #}+ 2* {# sizeof guint64 #}) $ \\gvPtr -> do\n -- The g_type field of the value must be zero or g_value_init will fail.\n {# set GValue->g_type #} gvPtr (0 :: GType)\n result <- body (GValue gvPtr)\n valueUnset (GValue gvPtr)\n return result\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"8c2f2f137fcba9c667b93b804e8fcb8df5d9708b","subject":"[project @ 2002-07-12 13:06:08 by dg22] Fixed references that used the old names for packing widgets.","message":"[project @ 2002-07-12 13:06:08 by dg22]\nFixed references that used the old names for packing widgets.\n","repos":"vincenthz\/webkit","old_file":"gtk\/abstract\/Box.chs","new_file":"gtk\/abstract\/Box.chs","new_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget Box@\n--\n-- Author : Axel Simon\n-- \n-- Created: 15 May 2001\n--\n-- Version $Revision: 1.4 $ from $Date: 2002\/07\/12 13:06:08 $\n--\n-- Copyright (c) 1999..2002 Axel Simon\n--\n-- This file is free software; you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation; either version 2 of the License, or\n-- (at your option) any later version.\n--\n-- This file is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- * This abstract container class is instatiated by using HBox or VBox. It \n-- supplies all methods to add and remove children.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n\nmodule Box(\n Box,\n BoxClass,\n castToBox,\n Packing(..),\n boxPackStart,\n boxPackEnd,\n boxPackStartDefaults,\n boxPackEndDefaults,\n boxSetHomogeneous,\n boxGetSpacing,\n boxSetSpacing,\n boxReorderChild,\n boxQueryChildPacking,\n boxSetChildPacking\n ) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Enums\t(PackType(..), Packing(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n\n-- @method boxPackStart@ Insert a widget at the beginning of the box\n-- container.\n--\n-- * The @ref arg Packing@ parameter determines how the child behaves in the\n-- horizontal or vertical way in an HBox or VBox, respectively.\n-- @ref arg Natural@ means the child is as big as it reqests. All children\n-- that have choosen @ref arg Repel@ for @ref arg p@ will be padded with\n-- the remaining space. @ref arg Grow@ is the same as @ref arg Expand@\n-- except that the child will receive the superfluous space.\n--\nboxPackStart :: (BoxClass b, WidgetClass w) => b -> w -> Packing -> Int ->\n IO ()\nboxPackStart b w p pad = {#call box_pack_start#} (toBox b) (toWidget w)\n (fromBool $ p\/=PackNatural) (fromBool $ p==PackGrow) (fromIntegral pad)\n\n-- @method boxPackEnd@ Insert a widget at the end of the box container.\n--\n-- * See @ref method boxPackStart@.\n--\nboxPackEnd :: (BoxClass b, WidgetClass w) => b -> w -> Packing -> Int -> IO ()\nboxPackEnd b w p pad = {#call box_pack_end#} (toBox b) (toWidget w)\n (fromBool $ p\/=PackNatural) (fromBool $ p==PackGrow) (fromIntegral pad)\n\n\n-- @method boxPackStartDefaults@ Like @ref method boxPackStart@ but uses the\n-- default parameters @ref arg Fill@ and 0 for @ref arg Padding@.\n--\nboxPackStartDefaults :: (BoxClass b, WidgetClass w) => b -> w -> IO ()\nboxPackStartDefaults b w = \n {#call box_pack_start_defaults#} (toBox b) (toWidget w)\n\n-- @method boxPackEndDefaults@ Like @ref method boxPackEnd@ but uses the\n-- default parameters @ref arg Fill@ and 0 for @ref arg Padding@.\n--\nboxPackEndDefaults :: (BoxClass b, WidgetClass w) => b -> w -> IO ()\nboxPackEndDefaults b w = \n {#call box_pack_end_defaults#} (toBox b) (toWidget w)\n\n-- @method boxSetHomogeneous@ Set if all children should be spread homogeneous\n-- withing the box.\n--\nboxSetHomogeneous :: BoxClass b => b -> Bool -> IO ()\nboxSetHomogeneous b homo = \n {#call box_set_homogeneous#} (toBox b) (fromBool homo)\n\n-- @method boxSetSpacing@ Set the standard spacing between two children.\n--\n-- * This space is in addition to the padding parameter that is given for each\n-- child.\n--\nboxSetSpacing :: BoxClass b => b -> Int -> IO ()\nboxSetSpacing b spacing =\n {#call box_set_spacing#} (toBox b) (fromIntegral spacing)\n\n-- @method boxReorderChild@ Move @ref arg child@ to a new @ref arg position@\n-- (counted from 0) in the box.\n--\nboxReorderChild :: (BoxClass b, WidgetClass w) => b -> w -> Int -> IO ()\nboxReorderChild b w position = \n {#call box_reorder_child#} (toBox b) (toWidget w) (fromIntegral position)\n\n-- @method boxQueryChildPacking@ Query the packing parameter of a child.\n-- Returns the behavious if free space is available (@Packing), the additional\n-- padding for this widget (@Int) and if the widget was inserted at the start\n-- or end of the container (@PackType).\n--\nboxQueryChildPacking :: (BoxClass b, WidgetClass w) => b -> w ->\n IO (Packing,Int,PackType)\nboxQueryChildPacking b w = alloca $ \\expandPtr -> alloca $ \\fillPtr ->\n alloca $ \\paddingPtr -> alloca $ \\packPtr -> do\n {#call unsafe box_query_child_packing#} (toBox b) (toWidget w)\n expandPtr fillPtr paddingPtr packPtr\n expand <- liftM toBool $ peek expandPtr\n fill <- liftM toBool $ peek fillPtr\n padding <- liftM fromIntegral $ peek paddingPtr\n pack <- liftM (toEnum.fromIntegral) $ peek packPtr\n return (if fill then PackGrow else \n (if expand then PackRepel else PackNatural),\n\t padding,pack)\n\n-- @method boxSetChildPacking@ Set the packing parameter of a child.\n--\nboxSetChildPacking :: (BoxClass b, WidgetClass w) => b -> w -> Packing ->\n Int -> PackType -> IO ()\nboxSetChildPacking b w pack pad pt = {#call box_set_child_packing#} (toBox b) \n (toWidget w) (fromBool $ pack\/=PackNatural) (fromBool $ pack==PackGrow) \n (fromIntegral pad) ((fromIntegral.fromEnum) pt)\n\n\n-- @method boxGetSpacing@ Retrieves the standard spacing between widgets.\n--\nboxGetSpacing :: BoxClass b => b -> IO Int\nboxGetSpacing b = \n liftM fromIntegral $ {#call unsafe box_get_spacing#} (toBox b)\n\n\n\n\n","old_contents":"-- -*-haskell-*-\n-- GIMP Toolkit (GTK) @entry Widget Box@\n--\n-- Author : Axel Simon\n-- \n-- Created: 15 May 2001\n--\n-- Version $Revision: 1.3 $ from $Date: 2002\/07\/11 12:15:22 $\n--\n-- Copyright (c) 1999..2002 Axel Simon\n--\n-- This file is free software; you can redistribute it and\/or modify\n-- it under the terms of the GNU General Public License as published by\n-- the Free Software Foundation; either version 2 of the License, or\n-- (at your option) any later version.\n--\n-- This file is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n-- GNU General Public License for more details.\n--\n-- @description@ --------------------------------------------------------------\n--\n-- * This abstract container class is instatiated by using HBox or VBox. It \n-- supplies all methods to add and remove children.\n--\n-- @documentation@ ------------------------------------------------------------\n--\n--\n-- @todo@ ---------------------------------------------------------------------\n\nmodule Box(\n Box,\n BoxClass,\n castToBox,\n Packing(..),\n boxPackStart,\n boxPackEnd,\n boxPackStartDefaults,\n boxPackEndDefaults,\n boxSetHomogeneous,\n boxGetSpacing,\n boxSetSpacing,\n boxReorderChild,\n boxQueryChildPacking,\n boxSetChildPacking\n ) where\n\nimport Monad\t(liftM)\nimport Foreign\nimport UTFCForeign\nimport Object\t(makeNewObject)\n{#import Hierarchy#}\n{#import Signal#}\nimport Enums\t(PackType(..), Packing(..))\n\n{# context lib=\"gtk\" prefix=\"gtk\" #}\n\n-- methods\n\n\n-- @method boxPackStart@ Insert a widget at the beginning of the box\n-- container.\n--\n-- * The @ref arg Packing@ parameter determines how the child behaves in the\n-- horizontal or vertical way in an HBox or VBox, respectively.\n-- @ref arg Natural@ means the child is as big as it reqests. All children\n-- that have choosen @ref arg Repel@ for @ref arg p@ will be padded with\n-- the remaining space. @ref arg Grow@ is the same as @ref arg Expand@\n-- except that the child will receive the superfluous space.\n--\nboxPackStart :: (BoxClass b, WidgetClass w) => b -> w -> Packing -> Int ->\n IO ()\nboxPackStart b w p pad = {#call box_pack_start#} (toBox b) (toWidget w)\n (fromBool $ p\/=PackNatural) (fromBool $ p==PackGrow) (fromIntegral pad)\n\n-- @method boxPackEnd@ Insert a widget at the end of the box container.\n--\n-- * See @ref method boxPackStart@.\n--\nboxPackEnd :: (BoxClass b, WidgetClass w) => b -> w -> Packing -> Int -> IO ()\nboxPackEnd b w p pad = {#call box_pack_end#} (toBox b) (toWidget w)\n (fromBool $ p\/=PackNatural) (fromBool $ p==PackFill) (fromIntegral pad)\n\n\n-- @method boxPackStartDefaults@ Like @ref method boxPackStart@ but uses the\n-- default parameters @ref arg Fill@ and 0 for @ref arg Padding@.\n--\nboxPackStartDefaults :: (BoxClass b, WidgetClass w) => b -> w -> IO ()\nboxPackStartDefaults b w = \n {#call box_pack_start_defaults#} (toBox b) (toWidget w)\n\n-- @method boxPackEndDefaults@ Like @ref method boxPackEnd@ but uses the\n-- default parameters @ref arg Fill@ and 0 for @ref arg Padding@.\n--\nboxPackEndDefaults :: (BoxClass b, WidgetClass w) => b -> w -> IO ()\nboxPackEndDefaults b w = \n {#call box_pack_end_defaults#} (toBox b) (toWidget w)\n\n-- @method boxSetHomogeneous@ Set if all children should be spread homogeneous\n-- withing the box.\n--\nboxSetHomogeneous :: BoxClass b => b -> Bool -> IO ()\nboxSetHomogeneous b homo = \n {#call box_set_homogeneous#} (toBox b) (fromBool homo)\n\n-- @method boxSetSpacing@ Set the standard spacing between two children.\n--\n-- * This space is in addition to the padding parameter that is given for each\n-- child.\n--\nboxSetSpacing :: BoxClass b => b -> Int -> IO ()\nboxSetSpacing b spacing =\n {#call box_set_spacing#} (toBox b) (fromIntegral spacing)\n\n-- @method boxReorderChild@ Move @ref arg child@ to a new @ref arg position@\n-- (counted from 0) in the box.\n--\nboxReorderChild :: (BoxClass b, WidgetClass w) => b -> w -> Int -> IO ()\nboxReorderChild b w position = \n {#call box_reorder_child#} (toBox b) (toWidget w) (fromIntegral position)\n\n-- @method boxQueryChildPacking@ Query the packing parameter of a child.\n-- Returns the behavious if free space is available (@Packing), the additional\n-- padding for this widget (@Int) and if the widget was inserted at the start\n-- or end of the container (@PackType).\n--\nboxQueryChildPacking :: (BoxClass b, WidgetClass w) => b -> w ->\n IO (Packing,Int,PackType)\nboxQueryChildPacking b w = alloca $ \\expandPtr -> alloca $ \\fillPtr ->\n alloca $ \\paddingPtr -> alloca $ \\packPtr -> do\n {#call unsafe box_query_child_packing#} (toBox b) (toWidget w)\n expandPtr fillPtr paddingPtr packPtr\n expand <- liftM toBool $ peek expandPtr\n fill <- liftM toBool $ peek fillPtr\n padding <- liftM fromIntegral $ peek paddingPtr\n pack <- liftM (toEnum.fromIntegral) $ peek packPtr\n return (if fill then PackFill else \n (if expand then PackExpand else PackNatural),\n\t padding,pack)\n\n-- @method boxSetChildPacking@ Set the packing parameter of a child.\n--\nboxSetChildPacking :: (BoxClass b, WidgetClass w) => b -> w -> Packing ->\n Int -> PackType -> IO ()\nboxSetChildPacking b w pack pad pt = {#call box_set_child_packing#} (toBox b) \n (toWidget w) (fromBool $ pack\/=PackNatural) (fromBool $ pack==PackFill) \n (fromIntegral pad) ((fromIntegral.fromEnum) pt)\n\n\n-- @method boxGetSpacing@ Retrieves the standard spacing between widgets.\n--\nboxGetSpacing :: BoxClass b => b -> IO Int\nboxGetSpacing b = \n liftM fromIntegral $ {#call unsafe box_get_spacing#} (toBox b)\n\n\n\n\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"3cf3c73c4d5438d49a2b5ea0a9eeb464b3d58093","subject":"support for Integer64 ogr types","message":"support for Integer64 ogr types\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/OGRFeature.chs","new_file":"src\/GDAL\/Internal\/OGRFeature.chs","new_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGRFeature (\n FieldType (..)\n , Field\n , Feature (..)\n , FeatureH\n , FieldDefnH (..)\n , FeatureDefnH (..)\n , Justification (..)\n\n , FeatureDef (..)\n , GeomFieldDef (..)\n , FieldDef (..)\n\n , fieldDef\n , featureToHandle\n , featureFromHandle\n\n , withFeatureH\n , withFieldDefnH\n , fieldDefFromHandle\n , featureDefFromHandle\n#if MULTI_GEOM_FIELDS\n , GeomFieldDefnH (..)\n , withGeomFieldDefnH\n#endif\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\" #}\n\nimport Control.Applicative ((<$>), (<*>), pure)\nimport Control.Monad (liftM, (>=>), (<=<), when)\nimport Control.Monad.Catch (bracket)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Data.ByteString (ByteString)\nimport Data.ByteString.Char8 (packCStringLen)\nimport Data.Int (Int32, Int64)\nimport Data.Monoid (mempty)\nimport Data.Text (Text)\nimport Data.Time.LocalTime (\n LocalTime(..)\n , TimeOfDay(..)\n , ZonedTime(..)\n , getCurrentTimeZone\n , minutesToTimeZone\n , utc\n )\nimport Data.Time ()\nimport Data.Time.Calendar (Day, fromGregorian)\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport qualified Data.Vector as V\n\nimport Foreign.C.Types (CInt(..), CDouble(..), CChar(..), CUChar(..))\nimport Foreign.ForeignPtr (\n ForeignPtr\n , FinalizerPtr\n , withForeignPtr\n )\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (copyBytes)\nimport Foreign.Ptr (Ptr, castPtr)\nimport Foreign.Storable (Storable, sizeOf, peek, peekElemOff)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.Util (\n toEnumC\n , fromEnumC\n , peekEncodedCString\n , useAsEncodedCString\n )\n{#import GDAL.Internal.OSR #}\n{#import GDAL.Internal.CPLError #}\n{#import GDAL.Internal.OGRGeometry #}\n{#import GDAL.Internal.OGRError #}\n\n#include \"gdal.h\"\n#include \"ogr_core.h\"\n#include \"ogr_api.h\"\n#include \"cpl_string.h\"\n\n{#enum FieldType {} omit (OFTMaxType) deriving (Eq,Show,Read,Bounded) #}\n\n{#enum Justification {}\n omit (JustifyUndefined)\n with prefix = \"OJ\"\n add prefix = \"Justify\"\n deriving (Eq,Show,Read,Bounded) #}\n\ndata Field\n = OGRInteger {-# UNPACK #-} !Int32\n | OGRIntegerList {-# UNPACK #-} !(St.Vector Int32)\n | OGRInteger64 {-# UNPACK #-} !Int64\n | OGRInteger64List {-# UNPACK #-} !(St.Vector Int64)\n | OGRReal {-# UNPACK #-} !Double\n | OGRRealList {-# UNPACK #-} !(St.Vector Double)\n | OGRString {-# UNPACK #-} !Text\n | OGRStringList {-# UNPACK #-} !(V.Vector Text)\n | OGRBinary {-# UNPACK #-} !ByteString\n | OGRDateTime {-# UNPACK #-} !ZonedTime\n | OGRDate {-# UNPACK #-} !Day\n | OGRTime {-# UNPACK #-} !TimeOfDay\n deriving (Show)\n\ndata FieldDef\n = FieldDef {\n fldName :: {-# UNPACK #-} !Text\n , fldType :: {-# UNPACK #-} !FieldType\n , fldWidth :: {-# UNPACK #-} !(Maybe Int)\n , fldPrec :: {-# UNPACK #-} !(Maybe Int)\n , fldJust :: {-# UNPACK #-} !(Maybe Justification)\n } deriving (Show, Eq)\n\nfieldDef :: FieldType -> Text -> FieldDef\nfieldDef ftype name = FieldDef name ftype Nothing Nothing Nothing\n\ndata Feature\n = Feature {\n fId :: {-# UNPACK #-} !Int64\n , fFields :: {-# UNPACK #-} !(V.Vector Field)\n , fGeoms :: {-# UNPACK #-} !(V.Vector Geometry)\n } deriving (Show)\n\ndata FeatureDef\n = FeatureDef {\n fdName :: {-# UNPACK #-} !Text\n , fdFields :: {-# UNPACK #-} !(V.Vector FieldDef)\n , fdGeom :: {-# UNPACK #-} !GeomFieldDef\n , fdGeoms :: {-# UNPACK #-} !(V.Vector GeomFieldDef)\n } deriving (Show, Eq)\n\ndata GeomFieldDef\n = GeomFieldDef {\n gfdName :: {-# UNPACK #-} !Text\n , gfdType :: {-# UNPACK #-} !GeometryType\n , gfdSrs :: {-# UNPACK #-} !(Maybe SpatialReference)\n } deriving (Show, Eq)\n\n\n{#pointer FeatureH foreign finalizer OGR_F_Destroy as ^ newtype#}\n{#pointer FieldDefnH newtype#}\n{#pointer FeatureDefnH newtype#}\n\n\n\nwithFieldDefnH :: FieldDef -> (FieldDefnH -> IO a) -> IO a\nwithFieldDefnH FieldDef{..} f =\n useAsEncodedCString fldName $ \\pName ->\n bracket ({#call unsafe OGR_Fld_Create as ^#} pName (fromEnumC fldType))\n ({#call unsafe OGR_Fld_Destroy as ^#}) (\\p -> populate p >> f p)\n where\n populate h = do\n case fldWidth of\n Just w -> {#call unsafe OGR_Fld_SetWidth as ^#} h (fromIntegral w)\n Nothing -> return ()\n case fldPrec of\n Just p -> {#call unsafe OGR_Fld_SetPrecision as ^#} h (fromIntegral p)\n Nothing -> return ()\n case fldJust of\n Just j -> {#call unsafe OGR_Fld_SetJustify as ^#} h (fromEnumC j)\n Nothing -> return ()\n\nfieldDefFromHandle :: FieldDefnH -> IO FieldDef\nfieldDefFromHandle p =\n FieldDef\n <$> getFieldName p\n <*> liftM toEnumC ({#call unsafe OGR_Fld_GetType as ^#} p)\n <*> liftM iToMaybe ({#call unsafe OGR_Fld_GetWidth as ^#} p)\n <*> liftM iToMaybe ({#call unsafe OGR_Fld_GetPrecision as ^#} p)\n <*> liftM jToMaybe ({#call unsafe OGR_Fld_GetJustify as ^#} p)\n where\n iToMaybe = (\\v -> if v==0 then Nothing else Just (fromIntegral v))\n jToMaybe = (\\j -> if j==0 then Nothing else Just (toEnumC j))\n\nfeatureDefFromHandle :: GeomFieldDef -> FeatureDefnH -> IO FeatureDef\nfeatureDefFromHandle gfd p =\n FeatureDef\n <$> ({#call unsafe OGR_FD_GetName as ^#} p >>= peekEncodedCString)\n <*> fieldDefsFromFeatureDefnH p\n <*> pure gfd\n <*> geomFieldDefsFromFeatureDefnH p\n where\n\nfieldDefsFromFeatureDefnH :: FeatureDefnH -> IO (V.Vector FieldDef)\nfieldDefsFromFeatureDefnH p = do\n nFields <- {#call unsafe OGR_FD_GetFieldCount as ^#} p\n V.generateM (fromIntegral nFields) $\n fieldDefFromHandle <=<\n ({#call unsafe OGR_FD_GetFieldDefn as ^#} p . fromIntegral)\n\n\ngeomFieldDefsFromFeatureDefnH :: FeatureDefnH -> IO (V.Vector GeomFieldDef)\n\n#if MULTI_GEOM_FIELDS\n\n{#pointer GeomFieldDefnH newtype#}\n\ngeomFieldDefsFromFeatureDefnH p = do\n nFields <- {#call unsafe OGR_FD_GetGeomFieldCount as ^#} p\n V.generateM (fromIntegral (nFields-1)) $\n gFldDef <=< ( {#call unsafe OGR_FD_GetGeomFieldDefn as ^#} p\n . (+1)\n . fromIntegral\n )\n where\n gFldDef g =\n GeomFieldDef\n <$> ({#call unsafe OGR_GFld_GetNameRef as ^#} g >>= peekEncodedCString)\n <*> liftM toEnumC ({#call unsafe OGR_GFld_GetType as ^#} g)\n <*> ({#call unsafe OGR_GFld_GetSpatialRef as ^#} g >>=\n maybeNewSpatialRefBorrowedHandle)\n\nwithGeomFieldDefnH :: GeomFieldDef -> (GeomFieldDefnH -> IO a) -> IO a\nwithGeomFieldDefnH GeomFieldDef{..} f =\n useAsEncodedCString gfdName $ \\pName ->\n bracket ({#call unsafe OGR_GFld_Create as ^#} pName (fromEnumC gfdType))\n ({#call unsafe OGR_GFld_Destroy as ^#}) (\\p -> populate p >> f p)\n where\n populate = withMaybeSpatialReference gfdSrs .\n {#call unsafe OGR_GFld_SetSpatialRef as ^#}\n#else\n-- | GDAL < 1.11 only supports 1 geometry field and associates it the layer\ngeomFieldDefsFromFeatureDefnH = const (return V.empty)\n#endif\n\n\nfeatureToHandle :: FeatureDef -> Feature -> GDAL s FeatureH\nfeatureToHandle = undefined\n\nfeatureFromHandle :: FeatureDef -> FeatureH -> GDAL s Feature\nfeatureFromHandle = undefined\n\n\ngetFieldBy :: FieldType -> Text -> CInt -> Ptr FeatureH -> IO Field\n\ngetFieldBy OFTInteger _ ix f\n = liftM (OGRInteger . fromIntegral)\n ({#call unsafe OGR_F_GetFieldAsInteger as ^#} f ix)\n\ngetFieldBy OFTIntegerList _ ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsIntegerList as ^#} f ix lenP\n nElems <- peekIntegral lenP\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CInt) (nElems * sizeOf (undefined :: CInt))\n liftM OGRIntegerList (St.unsafeFreeze (Stm.unsafeCast vec))\n\n#if (GDAL_VERSION_MAJOR >= 2)\ngetFieldBy OFTInteger64 _ ix f\n = liftM (OGRInteger64 . fromIntegral)\n ({#call unsafe OGR_F_GetFieldAsInteger64 as ^#} f ix)\n\ngetFieldBy OFTInteger64List _ ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsInteger64List as ^#} f ix lenP\n nElems <- peekIntegral lenP\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CLong) (nElems * sizeOf (undefined :: CLong))\n liftM OGRInteger64List (St.unsafeFreeze (Stm.unsafeCast vec))\n#endif\n\ngetFieldBy OFTReal _ ix f\n = liftM (OGRReal . realToFrac)\n ({#call unsafe OGR_F_GetFieldAsDouble as ^#} f ix)\n\ngetFieldBy OFTRealList _ ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsDoubleList as ^#} f ix lenP\n nElems <- peekIntegral lenP\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CDouble) (nElems * sizeOf (undefined :: CDouble))\n liftM OGRRealList (St.unsafeFreeze (Stm.unsafeCast vec))\n\ngetFieldBy OFTString _ ix f = liftM OGRString\n (({#call unsafe OGR_F_GetFieldAsString as ^#} f ix) >>= peekEncodedCString)\n\ngetFieldBy OFTWideString fname ix f = getFieldBy OFTString fname ix f\n\ngetFieldBy OFTStringList _ ix f = liftM OGRStringList $ do\n ptr <- {#call unsafe OGR_F_GetFieldAsStringList as ^#} f ix\n nElems <- liftM fromIntegral ({#call unsafe CSLCount as ^#} ptr)\n V.generateM nElems (peekElemOff ptr >=> peekEncodedCString)\n\ngetFieldBy OFTWideStringList fname ix f = getFieldBy OFTStringList fname ix f\n\ngetFieldBy OFTBinary _ ix f = alloca $ \\lenP -> do\n buf <- liftM castPtr ({#call unsafe OGR_F_GetFieldAsBinary as ^#} f ix lenP)\n nElems <- peekIntegral lenP\n liftM OGRBinary (packCStringLen (buf, nElems))\n\ngetFieldBy OFTDateTime fname ix f\n = liftM OGRDateTime $ alloca $ \\y -> alloca $ \\m -> alloca $ \\d ->\n alloca $ \\h -> alloca $ \\mn -> alloca $ \\s -> alloca $ \\tz -> do\n ret <- {#call unsafe OGR_F_GetFieldAsDateTime as ^#} f ix y m d h mn s tz\n when (ret==0) $ throwBindingException (FieldParseError fname)\n day <- fromGregorian <$> peekIntegral y\n <*> peekIntegral m\n <*> peekIntegral d\n tod <- TimeOfDay <$> peekIntegral h\n <*> peekIntegral mn\n <*> peekIntegral s\n let lt = return . ZonedTime (LocalTime day tod)\n tzV <- peekIntegral tz\n case tzV of\n -- Unknown timezone, assume utc\n 0 -> lt utc\n 1 -> getCurrentTimeZone >>= lt\n 100 -> lt utc\n n -> lt (minutesToTimeZone ((n-100) * 15))\n\ngetFieldBy OFTDate fname ix f\n = liftM (OGRDate . localDay . zonedTimeToLocalTime . unDateTime)\n (getFieldBy OFTDateTime fname ix f)\n\ngetFieldBy OFTTime fname ix f\n = liftM (OGRTime . localTimeOfDay . zonedTimeToLocalTime. unDateTime)\n (getFieldBy OFTDateTime fname ix f)\n\nunDateTime :: Field -> ZonedTime\nunDateTime (OGRDateTime f) = f\nunDateTime _ = error \"GDAL.Internal.OGRFeature.unDateTime\"\n\n\npeekIntegral :: (Storable a, Integral a, Num b) => Ptr a -> IO b\npeekIntegral = liftM fromIntegral . peek\n\ngetFieldName :: FieldDefnH -> IO Text\ngetFieldName =\n {#call unsafe OGR_Fld_GetNameRef as ^#} >=> peekEncodedCString\n\n\ngeometryByName :: Text -> FeatureH -> GDAL s Geometry\ngeometryByName = undefined\n\ngeometryByIndex :: FeatureH -> Int -> GDAL s Geometry\ngeometryByIndex = undefined\n","old_contents":"{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.OGRFeature (\n FieldType (..)\n , Field\n , Feature (..)\n , FeatureH\n , FieldDefnH (..)\n , FeatureDefnH (..)\n , Justification (..)\n\n , FeatureDef (..)\n , GeomFieldDef (..)\n , FieldDef (..)\n\n , fieldDef\n , featureToHandle\n , featureFromHandle\n\n , withFeatureH\n , withFieldDefnH\n , fieldDefFromHandle\n , featureDefFromHandle\n#if MULTI_GEOM_FIELDS\n , GeomFieldDefnH (..)\n , withGeomFieldDefnH\n#endif\n) where\n\n{#context lib = \"gdal\" prefix = \"OGR\" #}\n\nimport Control.Applicative ((<$>), (<*>), pure)\nimport Control.Monad (liftM, (>=>), (<=<), when)\nimport Control.Monad.Catch (bracket)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Data.ByteString (ByteString)\nimport Data.ByteString.Char8 (packCStringLen)\nimport Data.Int (Int64)\nimport Data.Monoid (mempty)\nimport Data.Text (Text)\nimport Data.Time.LocalTime (\n LocalTime(..)\n , TimeOfDay(..)\n , ZonedTime(..)\n , getCurrentTimeZone\n , minutesToTimeZone\n , utc\n )\nimport Data.Time ()\nimport Data.Time.Calendar (Day, fromGregorian)\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport qualified Data.Vector as V\n\nimport Foreign.C.Types (CInt(..), CDouble(..), CChar(..), CUChar(..))\nimport Foreign.ForeignPtr (\n ForeignPtr\n , FinalizerPtr\n , withForeignPtr\n )\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Utils (copyBytes)\nimport Foreign.Ptr (Ptr, castPtr)\nimport Foreign.Storable (Storable, sizeOf, peek, peekElemOff)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.Util (\n toEnumC\n , fromEnumC\n , peekEncodedCString\n , useAsEncodedCString\n )\n{#import GDAL.Internal.OSR #}\n{#import GDAL.Internal.CPLError #}\n{#import GDAL.Internal.OGRGeometry #}\n{#import GDAL.Internal.OGRError #}\n\n#include \"gdal.h\"\n#include \"ogr_core.h\"\n#include \"ogr_api.h\"\n#include \"cpl_string.h\"\n\n{#enum FieldType {} omit (OFTMaxType) deriving (Eq,Show,Read,Bounded) #}\n\n{#enum Justification {}\n omit (JustifyUndefined)\n with prefix = \"OJ\"\n add prefix = \"Justify\"\n deriving (Eq,Show,Read,Bounded) #}\n\ndata Field\n = OGRInteger {-# UNPACK #-} !Int\n | OGRIntegerList {-# UNPACK #-} !(St.Vector Int)\n | OGRReal {-# UNPACK #-} !Double\n | OGRRealList {-# UNPACK #-} !(St.Vector Double)\n | OGRString {-# UNPACK #-} !Text\n | OGRStringList {-# UNPACK #-} !(V.Vector Text)\n | OGRBinary {-# UNPACK #-} !ByteString\n | OGRDateTime {-# UNPACK #-} !ZonedTime\n | OGRDate {-# UNPACK #-} !Day\n | OGRTime {-# UNPACK #-} !TimeOfDay\n deriving (Show)\n\ndata FieldDef\n = FieldDef {\n fldName :: {-# UNPACK #-} !Text\n , fldType :: {-# UNPACK #-} !FieldType\n , fldWidth :: {-# UNPACK #-} !(Maybe Int)\n , fldPrec :: {-# UNPACK #-} !(Maybe Int)\n , fldJust :: {-# UNPACK #-} !(Maybe Justification)\n } deriving (Show, Eq)\n\nfieldDef :: FieldType -> Text -> FieldDef\nfieldDef ftype name = FieldDef name ftype Nothing Nothing Nothing\n\ndata Feature\n = Feature {\n fId :: {-# UNPACK #-} !Int64\n , fFields :: {-# UNPACK #-} !(V.Vector Field)\n , fGeoms :: {-# UNPACK #-} !(V.Vector Geometry)\n } deriving (Show)\n\ndata FeatureDef\n = FeatureDef {\n fdName :: {-# UNPACK #-} !Text\n , fdFields :: {-# UNPACK #-} !(V.Vector FieldDef)\n , fdGeom :: {-# UNPACK #-} !GeomFieldDef\n , fdGeoms :: {-# UNPACK #-} !(V.Vector GeomFieldDef)\n } deriving (Show, Eq)\n\ndata GeomFieldDef\n = GeomFieldDef {\n gfdName :: {-# UNPACK #-} !Text\n , gfdType :: {-# UNPACK #-} !GeometryType\n , gfdSrs :: {-# UNPACK #-} !(Maybe SpatialReference)\n } deriving (Show, Eq)\n\n\n{#pointer FeatureH foreign finalizer OGR_F_Destroy as ^ newtype#}\n{#pointer FieldDefnH newtype#}\n{#pointer FeatureDefnH newtype#}\n\n\n\nwithFieldDefnH :: FieldDef -> (FieldDefnH -> IO a) -> IO a\nwithFieldDefnH FieldDef{..} f =\n useAsEncodedCString fldName $ \\pName ->\n bracket ({#call unsafe OGR_Fld_Create as ^#} pName (fromEnumC fldType))\n ({#call unsafe OGR_Fld_Destroy as ^#}) (\\p -> populate p >> f p)\n where\n populate h = do\n case fldWidth of\n Just w -> {#call unsafe OGR_Fld_SetWidth as ^#} h (fromIntegral w)\n Nothing -> return ()\n case fldPrec of\n Just p -> {#call unsafe OGR_Fld_SetPrecision as ^#} h (fromIntegral p)\n Nothing -> return ()\n case fldJust of\n Just j -> {#call unsafe OGR_Fld_SetJustify as ^#} h (fromEnumC j)\n Nothing -> return ()\n\nfieldDefFromHandle :: FieldDefnH -> IO FieldDef\nfieldDefFromHandle p =\n FieldDef\n <$> getFieldName p\n <*> liftM toEnumC ({#call unsafe OGR_Fld_GetType as ^#} p)\n <*> liftM iToMaybe ({#call unsafe OGR_Fld_GetWidth as ^#} p)\n <*> liftM iToMaybe ({#call unsafe OGR_Fld_GetPrecision as ^#} p)\n <*> liftM jToMaybe ({#call unsafe OGR_Fld_GetJustify as ^#} p)\n where\n iToMaybe = (\\v -> if v==0 then Nothing else Just (fromIntegral v))\n jToMaybe = (\\j -> if j==0 then Nothing else Just (toEnumC j))\n\nfeatureDefFromHandle :: GeomFieldDef -> FeatureDefnH -> IO FeatureDef\nfeatureDefFromHandle gfd p =\n FeatureDef\n <$> ({#call unsafe OGR_FD_GetName as ^#} p >>= peekEncodedCString)\n <*> fieldDefsFromFeatureDefnH p\n <*> pure gfd\n <*> geomFieldDefsFromFeatureDefnH p\n where\n\nfieldDefsFromFeatureDefnH :: FeatureDefnH -> IO (V.Vector FieldDef)\nfieldDefsFromFeatureDefnH p = do\n nFields <- {#call unsafe OGR_FD_GetFieldCount as ^#} p\n V.generateM (fromIntegral nFields) $\n fieldDefFromHandle <=<\n ({#call unsafe OGR_FD_GetFieldDefn as ^#} p . fromIntegral)\n\n\ngeomFieldDefsFromFeatureDefnH :: FeatureDefnH -> IO (V.Vector GeomFieldDef)\n\n#if MULTI_GEOM_FIELDS\n\n{#pointer GeomFieldDefnH newtype#}\n\ngeomFieldDefsFromFeatureDefnH p = do\n nFields <- {#call unsafe OGR_FD_GetGeomFieldCount as ^#} p\n V.generateM (fromIntegral (nFields-1)) $\n gFldDef <=< ( {#call unsafe OGR_FD_GetGeomFieldDefn as ^#} p\n . (+1)\n . fromIntegral\n )\n where\n gFldDef g =\n GeomFieldDef\n <$> ({#call unsafe OGR_GFld_GetNameRef as ^#} g >>= peekEncodedCString)\n <*> liftM toEnumC ({#call unsafe OGR_GFld_GetType as ^#} g)\n <*> ({#call unsafe OGR_GFld_GetSpatialRef as ^#} g >>=\n maybeNewSpatialRefBorrowedHandle)\n\nwithGeomFieldDefnH :: GeomFieldDef -> (GeomFieldDefnH -> IO a) -> IO a\nwithGeomFieldDefnH GeomFieldDef{..} f =\n useAsEncodedCString gfdName $ \\pName ->\n bracket ({#call unsafe OGR_GFld_Create as ^#} pName (fromEnumC gfdType))\n ({#call unsafe OGR_GFld_Destroy as ^#}) (\\p -> populate p >> f p)\n where\n populate = withMaybeSpatialReference gfdSrs .\n {#call unsafe OGR_GFld_SetSpatialRef as ^#}\n#else\n-- | GDAL < 1.11 only supports 1 geometry field and associates it the layer\ngeomFieldDefsFromFeatureDefnH = const (return V.empty)\n#endif\n\n\nfeatureToHandle :: FeatureDef -> Feature -> GDAL s FeatureH\nfeatureToHandle = undefined\n\nfeatureFromHandle :: FeatureDef -> FeatureH -> GDAL s Feature\nfeatureFromHandle = undefined\n\n\ngetFieldBy :: FieldType -> Text -> CInt -> Ptr FeatureH -> IO Field\n\ngetFieldBy OFTInteger _ ix f\n = liftM (OGRInteger . fromIntegral)\n ({#call unsafe OGR_F_GetFieldAsInteger as ^#} f ix)\n\ngetFieldBy OFTIntegerList _ ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsIntegerList as ^#} f ix lenP\n nElems <- peekIntegral lenP\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CInt) (nElems * sizeOf (undefined :: CInt))\n liftM OGRIntegerList (St.unsafeFreeze (Stm.unsafeCast vec))\n\ngetFieldBy OFTReal _ ix f\n = liftM (OGRReal . realToFrac)\n ({#call unsafe OGR_F_GetFieldAsDouble as ^#} f ix)\n\ngetFieldBy OFTRealList _ ix f = alloca $ \\lenP -> do\n buf <- {#call unsafe OGR_F_GetFieldAsDoubleList as ^#} f ix lenP\n nElems <- peekIntegral lenP\n vec <- Stm.new nElems\n Stm.unsafeWith vec $ \\vP ->\n copyBytes vP (buf :: Ptr CDouble) (nElems * sizeOf (undefined :: CDouble))\n liftM OGRRealList (St.unsafeFreeze (Stm.unsafeCast vec))\n\ngetFieldBy OFTString _ ix f = liftM OGRString\n (({#call unsafe OGR_F_GetFieldAsString as ^#} f ix) >>= peekEncodedCString)\n\ngetFieldBy OFTWideString fname ix f = getFieldBy OFTString fname ix f\n\ngetFieldBy OFTStringList _ ix f = liftM OGRStringList $ do\n ptr <- {#call unsafe OGR_F_GetFieldAsStringList as ^#} f ix\n nElems <- liftM fromIntegral ({#call unsafe CSLCount as ^#} ptr)\n V.generateM nElems (peekElemOff ptr >=> peekEncodedCString)\n\ngetFieldBy OFTWideStringList fname ix f = getFieldBy OFTStringList fname ix f\n\ngetFieldBy OFTBinary _ ix f = alloca $ \\lenP -> do\n buf <- liftM castPtr ({#call unsafe OGR_F_GetFieldAsBinary as ^#} f ix lenP)\n nElems <- peekIntegral lenP\n liftM OGRBinary (packCStringLen (buf, nElems))\n\ngetFieldBy OFTDateTime fname ix f\n = liftM OGRDateTime $ alloca $ \\y -> alloca $ \\m -> alloca $ \\d ->\n alloca $ \\h -> alloca $ \\mn -> alloca $ \\s -> alloca $ \\tz -> do\n ret <- {#call unsafe OGR_F_GetFieldAsDateTime as ^#} f ix y m d h mn s tz\n when (ret==0) $ throwBindingException (FieldParseError fname)\n day <- fromGregorian <$> peekIntegral y\n <*> peekIntegral m\n <*> peekIntegral d\n tod <- TimeOfDay <$> peekIntegral h\n <*> peekIntegral mn\n <*> peekIntegral s\n let lt = return . ZonedTime (LocalTime day tod)\n tzV <- peekIntegral tz\n case tzV of\n -- Unknown timezone, assume utc\n 0 -> lt utc\n 1 -> getCurrentTimeZone >>= lt\n 100 -> lt utc\n n -> lt (minutesToTimeZone ((n-100) * 15))\n\ngetFieldBy OFTDate fname ix f\n = liftM (OGRDate . localDay . zonedTimeToLocalTime . unDateTime)\n (getFieldBy OFTDateTime fname ix f)\n\ngetFieldBy OFTTime fname ix f\n = liftM (OGRTime . localTimeOfDay . zonedTimeToLocalTime. unDateTime)\n (getFieldBy OFTDateTime fname ix f)\n\nunDateTime :: Field -> ZonedTime\nunDateTime (OGRDateTime f) = f\nunDateTime _ = error \"GDAL.Internal.OGRFeature.unDateTime\"\n\n\npeekIntegral :: (Storable a, Integral a, Num b) => Ptr a -> IO b\npeekIntegral = liftM fromIntegral . peek\n\ngetFieldName :: FieldDefnH -> IO Text\ngetFieldName =\n {#call unsafe OGR_Fld_GetNameRef as ^#} >=> peekEncodedCString\n\n\ngeometryByName :: Text -> FeatureH -> GDAL s Geometry\ngeometryByName = undefined\n\ngeometryByIndex :: FeatureH -> Int -> GDAL s Geometry\ngeometryByIndex = undefined\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"3c54b39403cc4322550084424a6e3e95267766af","subject":"export bandMask","message":"export bandMask\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/GDAL.chs","new_file":"src\/GDAL\/Internal\/GDAL.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE LambdaCase #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.GDAL (\n GDALRasterException (..)\n , Geotransform (..)\n , OverviewResampling (..)\n , Driver (..)\n , Dataset\n , DatasetH (..)\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , RasterBandH (..)\n , MaskType (..)\n\n , northUpGeotransform\n , gcpGeotransform\n , applyGeotransform\n , (|$|)\n , invertGeotransform\n , inv\n , composeGeotransforms\n , (|.|)\n , geoEnvelopeTransformer\n\n , nullDatasetH\n , allRegister\n , destroyDriverManager\n , create\n , createMem\n , delete\n , rename\n , copyFiles\n , flushCache\n , closeDataset\n , openReadOnly\n , openReadWrite\n , unsafeToReadOnly\n , createCopy\n , buildOverviews\n , driverCreationOptionList\n\n , bandAs\n\n , datasetDriver\n , datasetSize\n , datasetFileList\n , datasetProjection\n , datasetProjectionIO\n , setDatasetProjection\n , datasetGeotransform\n , datasetGeotransformIO\n , setDatasetGeotransform\n , datasetGCPs\n , setDatasetGCPs\n , datasetBandCount\n\n , bandDataType\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandHasOverviews\n , allBand\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , addBand\n , fillBand\n , fmapBand\n , readBand\n , createBandMask\n , bandMask\n , readBandBlock\n , writeBand\n , writeBandBlock\n , copyBand\n , bandConduit\n , unsafeBandConduit\n , bandSink\n , bandSinkGeo\n\n , metadataDomains\n , metadata\n , metadataItem\n , setMetadataItem\n , description\n , setDescription\n\n , foldl'\n , ifoldl'\n , foldlWindow'\n , ifoldlWindow'\n , blockConduit\n , unsafeBlockConduit\n , blockSource\n , unsafeBlockSource\n , blockSink\n , allBlocks\n , zipBlocks\n , getZipBlocks\n\n , unDataset\n , unBand\n , version\n , newDatasetHandle\n , openDatasetCount\n\n , module GDAL.Internal.DataType\n) where\n\n{#context lib = \"gdal\" prefix = \"GDAL\" #}\n\nimport Control.Arrow (second)\nimport Control.Applicative (Applicative(..), (<$>), liftA2)\nimport Control.Exception (Exception(..))\nimport Control.Monad (liftM, liftM2, when, (>=>), void, forever)\nimport Control.Monad.Trans (lift)\nimport Control.Monad.Catch (bracket)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Data.Bits ((.&.))\nimport Data.ByteString.Char8 (ByteString, packCString, useAsCString)\nimport Data.ByteString.Unsafe (unsafeUseAsCString)\nimport Data.Coerce (coerce)\nimport qualified Data.Conduit.List as CL\nimport Data.Conduit\nimport Data.Conduit.Internal (Pipe(..), ConduitM(..), injectLeftovers)\nimport Data.Maybe (fromMaybe, fromJust)\nimport Data.String (IsString)\nimport Data.Proxy\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport Data.Typeable (Typeable)\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport qualified Data.Vector.Generic.Mutable as M\nimport qualified Data.Vector.Unboxed.Mutable as UM\nimport qualified Data.Vector.Unboxed as U\nimport Data.Word (Word8)\n\nimport Foreign.C.String (withCString, CString)\nimport Foreign.C.Types\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrBytes)\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (withArrayLen)\nimport Foreign.Marshal.Utils (toBool, fromBool, with)\n\nimport GHC.Types (SPEC(..))\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.Types.Value\nimport GDAL.Internal.DataType\nimport GDAL.Internal.Common\nimport GDAL.Internal.Util\n{#import GDAL.Internal.GCP#}\n{#import GDAL.Internal.CPLError#}\n{#import GDAL.Internal.CPLString#}\n{#import GDAL.Internal.CPLProgress#}\nimport GDAL.Internal.OSR\nimport GDAL.Internal.OGRGeometry (Envelope(..), envelopeSize)\n\n\n#include \"gdal.h\"\n\nnewtype Driver = Driver ByteString\n deriving (Eq, IsString)\n\ninstance Show Driver where\n show (Driver s) = show s\n\nversion :: (Int, Int)\nversion = ({#const GDAL_VERSION_MAJOR#} , {#const GDAL_VERSION_MINOR#})\n\ndata GDALRasterException\n = InvalidRasterSize !Size\n | InvalidBlockSize !Int\n | InvalidDriverOptions\n | UnknownRasterDataType\n | NullDataset\n | NullBand\n | UnknownDriver !ByteString\n | BandDoesNotAllowNoData\n | CannotInvertGeotransform\n | NotImplemented !ByteString\n deriving (Typeable, Show, Eq)\n\ninstance Exception GDALRasterException where\n toException = bindingExceptionToException\n fromException = bindingExceptionFromException\n\n\n{#enum GDALAccess {} deriving (Eq, Show) #}\n\n{#enum RWFlag {} deriving (Eq, Show) #}\n\n{#pointer MajorObjectH newtype#}\n\nclass MajorObject o (t::AccessMode) where\n majorObject :: o t -> MajorObjectH\n\n\n{#pointer DatasetH newtype #}\n\n\nnullDatasetH :: DatasetH\nnullDatasetH = DatasetH nullPtr\n\nderiving instance Eq DatasetH\n\nnewtype Dataset s a (t::AccessMode) =\n Dataset (ReleaseKey, DatasetH)\n\ninstance MajorObject (Dataset s a) t where\n majorObject ds =\n let DatasetH p = unDataset ds\n in MajorObjectH (castPtr p)\n\nunDataset :: Dataset s a t -> DatasetH\nunDataset (Dataset (_,s)) = s\n\ncloseDataset :: MonadIO m => Dataset s a t -> m ()\ncloseDataset (Dataset (rk,_)) = release rk\n\ntype RODataset s a = Dataset s a ReadOnly\ntype RWDataset s a = Dataset s a ReadWrite\n\n{#pointer RasterBandH newtype #}\n\nnullBandH :: RasterBandH\nnullBandH = RasterBandH nullPtr\n\nderiving instance Eq RasterBandH\n\nnewtype Band s a (t::AccessMode) = Band (RasterBandH, DataTypeK)\n\nunBand :: Band s a t -> RasterBandH\nunBand (Band (p,_)) = p\n{-# INLINE unBand #-}\n\nbandDataType :: Band s a t -> DataTypeK\nbandDataType (Band (_,t)) = t\n{-# INLINE bandDataType #-}\n\nbandAs :: Band s a t -> DataType d -> Band s (HsType d) t\nbandAs = const . coerce\n{-# INLINE bandAs #-}\n\ninstance MajorObject (Band s a) t where\n majorObject b =\n let RasterBandH p = unBand b\n in MajorObjectH (castPtr p)\n\ntype ROBand s a = Band s a ReadOnly\ntype RWBand s a = Band s a ReadWrite\n\n\n{#pointer DriverH #}\n\n{#fun AllRegister as ^ {} -> `()' #}\n\n{#fun DestroyDriverManager as ^ {} -> `()'#}\n\ndriverByName :: Driver -> IO DriverH\ndriverByName (Driver s) = do\n d <- useAsCString s {#call unsafe GetDriverByName as ^#}\n if d == nullPtr\n then throwBindingException (UnknownDriver s)\n else return d\n\ndriverCreationOptionList :: Driver -> ByteString\ndriverCreationOptionList driver = unsafePerformIO $ do\n d <- driverByName driver\n {#call GetDriverCreationOptionList\tas ^#} d >>= packCString\n\nvalidateCreationOptions :: DriverH -> Ptr CString -> IO ()\nvalidateCreationOptions d o = do\n valid <- liftM toBool ({#call GDALValidateCreationOptions as ^ #} d o)\n when (not valid) (throwBindingException InvalidDriverOptions)\n\ncreate\n :: Driver -> String -> Size -> Int -> DataType d -> OptionList\n -> GDAL s (Dataset s (HsType d) ReadWrite)\ncreate drv path (nx :+: ny) bands dtype options =\n newDatasetHandle $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC dtype\n d <- driverByName drv\n withOptionList options $ \\opts -> do\n validateCreationOptions d opts\n {#call GDALCreate as ^#} d path' nx' ny' bands' dtype' opts\n\ndelete :: Driver -> String -> GDAL s ()\ndelete driver path =\n liftIO $\n checkCPLError \"deleteDataset\" $ do\n d <- driverByName driver\n withCString path ({#call DeleteDataset as ^#} d)\n\nrename :: Driver -> String -> String -> GDAL s ()\nrename driver newName oldName =\n liftIO $\n checkCPLError \"renameDataset\" $ do\n d <- driverByName driver\n withCString newName $\n withCString oldName . ({#call RenameDataset as ^#} d)\n\ncopyFiles :: Driver -> String -> String -> GDAL s ()\ncopyFiles driver newName oldName =\n liftIO $\n checkCPLError \"copyFiles\" $ do\n d <- driverByName driver\n withCString newName $\n withCString oldName . ({#call CopyDatasetFiles as ^#} d)\n\nopenReadOnly :: String -> DataType d -> GDAL s (RODataset s (HsType d))\nopenReadOnly p _ = openWithMode GA_ReadOnly p\n\nopenReadWrite :: String -> DataType d -> GDAL s (RWDataset s (HsType d))\nopenReadWrite p _ = openWithMode GA_Update p\n\nopenWithMode :: GDALAccess -> String -> GDAL s (Dataset s a t)\nopenWithMode m path =\n newDatasetHandle $\n withCString path $\n flip {#call GDALOpen as ^#} (fromEnumC m)\n\nunsafeToReadOnly :: RWDataset s a -> GDAL s (RODataset s a)\nunsafeToReadOnly ds = flushCache ds >> return (coerce ds)\n\ncreateCopy\n :: Driver -> String -> Dataset s a t -> Bool -> OptionList\n -> Maybe ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy driver path ds strict options progressFun =\n newDatasetHandle $\n withProgressFun \"createCopy\" progressFun $ \\pFunc -> do\n d <- driverByName driver\n withOptionList options $ \\o -> do\n validateCreationOptions d o\n withCString path $ \\p ->\n {#call GDALCreateCopy as ^#}\n d p (unDataset ds) (fromBool strict) o pFunc nullPtr\n\n\n\nnewDatasetHandle :: IO DatasetH -> GDAL s (Dataset s a t)\nnewDatasetHandle act =\n liftM Dataset $ allocate (checkGDALCall checkit act) free\n where\n checkit exc p\n | p==nullDatasetH = Just (fromMaybe\n (GDALBindingException NullDataset) exc)\n | otherwise = Nothing\n free ds = do\n refCount <- {#call unsafe DereferenceDataset as ^#} ds\n when (refCount<=0) ({#call GDALClose as ^#} ds)\n\ncreateMem\n :: Size -> Int -> DataType d -> OptionList\n -> GDAL s (Dataset s (HsType d) ReadWrite)\ncreateMem = create \"Mem\" \"\"\n\nflushCache :: RWDataset s a -> GDAL s ()\nflushCache = liftIO . {#call GDALFlushCache as ^#} . unDataset\n\ndatasetDriver :: Dataset s a t -> Driver\ndatasetDriver ds =\n unsafePerformIO $\n liftM Driver $ do\n driver <-{#call unsafe GetDatasetDriver as ^#} (unDataset ds)\n {#call unsafe GetDriverShortName as ^#} driver >>= packCString\n\ndatasetSize :: Dataset s a t -> Size\ndatasetSize ds =\n fmap fromIntegral $\n ({#call pure unsafe GetRasterXSize as ^#} (unDataset ds))\n :+: ({#call pure unsafe GetRasterYSize as ^#} (unDataset ds))\n\ndatasetFileList :: Dataset s a t -> GDAL s [Text]\ndatasetFileList =\n liftIO .\n fromCPLStringList .\n {#call unsafe GetFileList as ^#} .\n unDataset\n\ndatasetProjectionIO :: Dataset s a t -> IO (Maybe SpatialReference)\ndatasetProjectionIO =\n {#call unsafe GetProjectionRef as ^#} . unDataset\n >=> maybeSpatialReferenceFromCString\n\ndatasetProjection :: Dataset s a t -> GDAL s (Maybe SpatialReference)\ndatasetProjection = liftIO . datasetProjectionIO\n\n\nsetDatasetProjection :: SpatialReference -> RWDataset s a -> GDAL s ()\nsetDatasetProjection srs ds =\n liftIO $ checkCPLError \"SetProjection\" $\n useAsCString (srsToWkt srs)\n ({#call unsafe SetProjection as ^#} (unDataset ds))\n\nsetDatasetGCPs\n :: [GroundControlPoint] -> Maybe SpatialReference -> RWDataset s a\n -> GDAL s ()\nsetDatasetGCPs gcps mSrs ds =\n liftIO $\n checkCPLError \"setDatasetGCPs\" $\n withGCPArrayLen gcps $ \\nGcps pGcps ->\n withMaybeSRAsCString mSrs $\n {#call unsafe GDALSetGCPs as ^#}\n (unDataset ds)\n (fromIntegral nGcps)\n pGcps\n\ndatasetGCPs\n :: Dataset s a t\n -> GDAL s ([GroundControlPoint], Maybe SpatialReference)\ndatasetGCPs ds =\n liftIO $ do\n let pDs = unDataset ds\n srs <- maybeSpatialReferenceFromCString\n =<< {#call unsafe GetGCPProjection as ^#} pDs\n nGcps <- liftM fromIntegral ({#call unsafe GetGCPCount as ^#} pDs)\n gcps <- {#call unsafe GetGCPs as ^#} pDs >>= fromGCPArray nGcps\n return (gcps, srs)\n\n\ndata OverviewResampling\n = OvNearest\n | OvGauss\n | OvCubic\n | OvAverage\n | OvMode\n | OvAverageMagphase\n | OvNone\n\nbuildOverviews\n :: RWDataset s a -> OverviewResampling -> [Int] -> [Int] -> Maybe ProgressFun\n -> GDAL s ()\nbuildOverviews ds resampling overviews bands progressFun =\n liftIO $\n withResampling resampling $ \\pResampling ->\n withArrayLen (map fromIntegral overviews) $ \\nOverviews pOverviews ->\n withArrayLen (map fromIntegral bands) $ \\nBands pBands ->\n withProgressFun \"buildOverviews\" progressFun $ \\pFunc ->\n checkCPLError \"buildOverviews\" $\n {#call GDALBuildOverviews as ^#}\n (unDataset ds)\n pResampling\n (fromIntegral nOverviews)\n pOverviews\n (fromIntegral nBands)\n pBands\n pFunc\n nullPtr\n where\n withResampling OvNearest = unsafeUseAsCString \"NEAREST\\0\"\n withResampling OvGauss = unsafeUseAsCString \"GAUSS\\0\"\n withResampling OvCubic = unsafeUseAsCString \"CUBIC\\0\"\n withResampling OvAverage = unsafeUseAsCString \"AVERAGE\\0\"\n withResampling OvMode = unsafeUseAsCString \"MODE\\0\"\n withResampling OvAverageMagphase = unsafeUseAsCString \"AVERAGE_MAGPHASE\\0\"\n withResampling OvNone = unsafeUseAsCString \"NONE\\0\"\n\ndata Geotransform\n = Geotransform {\n gtXOff :: {-# UNPACK #-} !Double\n , gtXDelta :: {-# UNPACK #-} !Double\n , gtXRot :: {-# UNPACK #-} !Double\n , gtYOff :: {-# UNPACK #-} !Double\n , gtYRot :: {-# UNPACK #-} !Double\n , gtYDelta :: {-# UNPACK #-} !Double\n } deriving (Eq, Show)\n\nnorthUpGeotransform :: Size -> Envelope Double -> Geotransform\nnorthUpGeotransform size envelope =\n Geotransform {\n gtXOff = pFst (envelopeMin envelope)\n , gtXDelta = pFst (envelopeSize envelope \/ fmap fromIntegral size)\n , gtXRot = 0\n , gtYOff = pSnd (envelopeMax envelope)\n , gtYRot = 0\n , gtYDelta = negate (pSnd (envelopeSize envelope \/ fmap fromIntegral size))\n }\n\ngcpGeotransform :: [GroundControlPoint] -> ApproxOK -> Maybe Geotransform\ngcpGeotransform gcps approxOk =\n unsafePerformIO $\n alloca $ \\pGt ->\n withGCPArrayLen gcps $ \\nGcps pGcps -> do\n ret <- liftM toBool $\n {#call unsafe GCPsToGeoTransform as ^#}\n (fromIntegral nGcps)\n pGcps\n (castPtr pGt)\n (fromEnumC approxOk)\n if ret then liftM Just (peek pGt) else return Nothing\n\napplyGeotransform :: Geotransform -> Pair Double -> Pair Double\napplyGeotransform Geotransform{..} (x :+: y) =\n (gtXOff + gtXDelta*x + gtXRot * y) :+: (gtYOff + gtYRot *x + gtYDelta * y)\n{-# INLINE applyGeotransform #-}\n\ninfixr 5 |$|\n(|$|) :: Geotransform -> Pair Double -> Pair Double\n(|$|) = applyGeotransform\n\ninvertGeotransform :: Geotransform -> Maybe Geotransform\ninvertGeotransform (Geotransform g0 g1 g2 g3 g4 g5)\n | g2==0 && g4==0 && g1\/=0 && g5\/=0 -- No rotation\n = Just $! Geotransform (-g0\/g1) (1\/g1) 0 (-g3\/g5) 0 (1\/g5)\n | abs det < 1e-15 = Nothing -- not invertible\n | otherwise\n = Just $! Geotransform ((g2*g3 - g0*g5) * idet)\n (g5*idet)\n (-g2*idet)\n ((-g1*g3 + g0*g4) * idet)\n (-g4*idet)\n (g1*idet)\n where\n idet = 1\/det\n det = g1*g5 - g2*g4\n{-# INLINE invertGeotransform #-}\n\ninv :: Geotransform -> Geotransform\ninv = fromMaybe (error \"Could not invert geotransform\") . invertGeotransform\n\n-- | Creates a Geotransform equivalent to applying a and then b\ncomposeGeotransforms :: Geotransform -> Geotransform -> Geotransform\nb `composeGeotransforms` a =\n Geotransform (b1*a0 + b2*a3 + b0)\n (b1*a1 + b2*a4)\n (b1*a2 + b2*a5)\n (b4*a0 + b5*a3 + b3)\n (b4*a1 + b5*a4)\n (b4*a2 + b5*a5)\n\n where\n Geotransform a0 a1 a2 a3 a4 a5 = a\n Geotransform b0 b1 b2 b3 b4 b5 = b\n{-# INLINE composeGeotransforms #-}\n\ninfixr 9 |.|\n(|.|) :: Geotransform -> Geotransform -> Geotransform\n(|.|) = composeGeotransforms\n\ninstance Storable Geotransform where\n sizeOf _ = sizeOf (undefined :: CDouble) * 6\n alignment _ = alignment (undefined :: CDouble)\n poke pGt (Geotransform g0 g1 g2 g3 g4 g5) = do\n let p = castPtr pGt :: Ptr CDouble\n pokeElemOff p 0 (realToFrac g0)\n pokeElemOff p 1 (realToFrac g1)\n pokeElemOff p 2 (realToFrac g2)\n pokeElemOff p 3 (realToFrac g3)\n pokeElemOff p 4 (realToFrac g4)\n pokeElemOff p 5 (realToFrac g5)\n peek pGt = do\n let p = castPtr pGt :: Ptr CDouble\n Geotransform <$> liftM realToFrac (peekElemOff p 0)\n <*> liftM realToFrac (peekElemOff p 1)\n <*> liftM realToFrac (peekElemOff p 2)\n <*> liftM realToFrac (peekElemOff p 3)\n <*> liftM realToFrac (peekElemOff p 4)\n <*> liftM realToFrac (peekElemOff p 5)\n\n\ndatasetGeotransformIO :: Dataset s a t -> IO (Maybe Geotransform)\ndatasetGeotransformIO ds = alloca $ \\p -> do\n ret <- {#call unsafe GetGeoTransform as ^#} (unDataset ds) (castPtr p)\n if toEnumC ret == CE_None\n then liftM Just (peek p)\n else return Nothing\n\ndatasetGeotransform :: Dataset s a t -> GDAL s (Maybe Geotransform)\ndatasetGeotransform = liftIO . datasetGeotransformIO\n\n\nsetDatasetGeotransform :: Geotransform -> RWDataset s a -> GDAL s ()\nsetDatasetGeotransform gt ds = liftIO $\n checkCPLError \"SetGeoTransform\" $\n with gt ({#call unsafe SetGeoTransform as ^#} (unDataset ds) . castPtr)\n\n\ndatasetBandCount :: Dataset s a t -> GDAL s Int\ndatasetBandCount =\n liftM fromIntegral . liftIO . {#call unsafe GetRasterCount as ^#} . unDataset\n\ngetBand :: Int -> Dataset s a t -> GDAL s (Band s a t)\ngetBand b ds = liftIO $ do\n pB <- checkGDALCall checkit $\n {#call GetRasterBand as ^#} (unDataset ds) (fromIntegral b)\n dt <- liftM toEnumC ({#call unsafe GetRasterDataType as ^#} pB)\n return (Band (pB, dt))\n where\n checkit exc p\n | p == nullBandH = Just (fromMaybe (GDALBindingException NullBand) exc)\n | otherwise = Nothing\n\naddBand\n :: forall s a. GDALType a\n => OptionList -> RWDataset s a -> GDAL s (RWBand s a)\naddBand options ds = do\n liftIO $\n checkCPLError \"addBand\" $\n withOptionList options $\n {#call GDALAddBand as ^#} (unDataset ds) (fromEnumC dt)\n ix <- datasetBandCount ds\n getBand ix ds\n where dt = hsDataType (Proxy :: Proxy a)\n\nbandDataset :: Band s a t -> GDAL s (Dataset s a t)\nbandDataset b = newDatasetHandle $ do\n hDs <- {#call unsafe GDALGetBandDataset as ^#} (unBand b)\n void $ {#call unsafe GDALReferenceDataset as ^#} hDs\n return hDs\n\n\nbandBlockSize :: (Band s a t) -> Size\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n {#call unsafe GetBlockSize as ^#} (unBand band) xPtr yPtr\n liftM (fmap fromIntegral) (liftM2 (:+:) (peek xPtr) (peek yPtr))\n{-# NOINLINE bandBlockSize #-}\n\nbandBlockLen :: Band s a t -> Int\nbandBlockLen = (\\(x :+: y) -> x*y) . bandBlockSize\n\nbandSize :: Band s a t -> Size\nbandSize band =\n fmap fromIntegral $\n ({#call pure unsafe GetRasterBandXSize as ^#} (unBand band))\n :+: ({#call pure unsafe GetRasterBandYSize as ^#} (unBand band))\n{-# NOINLINE bandSize #-}\n\nallBand :: Band s a t -> Envelope Int\nallBand = Envelope (pure 0) . bandSize\n\nbandBlockCount :: Band s a t -> Pair Int\nbandBlockCount b = fmap ceiling $ liftA2 ((\/) :: Double -> Double -> Double)\n (fmap fromIntegral (bandSize b))\n (fmap fromIntegral (bandBlockSize b))\n\nbandHasOverviews :: Band s a t -> GDAL s Bool\nbandHasOverviews =\n liftIO . liftM toBool . {#call unsafe HasArbitraryOverviews as ^#} . unBand\n\nbandNodataValue :: GDALType a => Band s a t -> GDAL s (Maybe a)\nbandNodataValue b =\n liftIO $\n alloca $ \\p -> do\n value <- {#call unsafe GetRasterNoDataValue as ^#} (unBand b) p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just (fromCDouble value) else Nothing)\n{-# NOINLINE bandNodataValue #-}\n\n\nsetBandNodataValue :: GDALType a => a -> RWBand s a -> GDAL s ()\nsetBandNodataValue v b =\n liftIO $\n checkCPLError \"SetRasterNoDataValue\" $\n {#call unsafe SetRasterNoDataValue as ^#} (unBand b) (toCDouble v)\n\ncreateBandMask :: MaskType -> RWBand s a -> GDAL s ()\ncreateBandMask maskType band = liftIO $\n checkCPLError \"createBandMask\" $\n {#call CreateMaskBand as ^#} (unBand band) cflags\n where cflags = maskFlagsForType maskType\n\nreadBand :: forall s t a. GDALType a\n => (Band s a t)\n -> Envelope Int\n -> Size\n -> GDAL s (U.Vector (Value a))\nreadBand band win sz = liftM fromJust $ runConduit $\n yield win =$= unsafeBandConduit sz band =$= CL.head\n{-# INLINE readBand #-}\n\nbandConduit\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (U.Vector (Value a))\nbandConduit sz band =\n unsafeBandConduitM sz band =$= CL.mapM (liftIO . U.freeze)\n{-# INLINE bandConduit #-}\n\nunsafeBandConduit\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (U.Vector (Value a))\nunsafeBandConduit sz band =\n unsafeBandConduitM sz band =$= CL.mapM (liftIO . U.unsafeFreeze)\n{-# INLINE unsafeBandConduit #-}\n\n\nunsafeBandConduitM\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (UM.IOVector (Value a))\nunsafeBandConduitM (bx :+: by) band = do\n buf <- liftIO (M.new (bx*by))\n lift (bandMaskType band) >>= \\case\n MaskNoData -> do\n nd <- lift (noDataOrFail band)\n let vec = mkValueUMVector nd buf\n awaitForever $ \\win -> do\n liftIO (read_ band buf win)\n yield vec\n MaskAllValid -> do\n let vec = mkAllValidValueUMVector buf\n awaitForever $ \\win -> do\n liftIO (read_ band buf win)\n yield vec\n _ -> do\n mBuf <- liftIO $ M.replicate (bx*by) 0\n mask <- lift $ bandMask band\n let vec = mkMaskedValueUMVector mBuf buf\n awaitForever $ \\win -> do\n liftIO (read_ band buf win >> read_ mask mBuf win)\n yield vec\n where\n read_ :: forall a'. GDALType a'\n => Band s a' t -> Stm.IOVector a' -> Envelope Int -> IO ()\n read_ b vec win = do\n let sx :+: sy = envelopeSize win\n xoff :+: yoff = envelopeMin win\n Stm.unsafeWith vec $ \\ptr -> do\n checkCPLError \"RasterAdviseRead\" $\n {#call unsafe RasterAdviseRead as ^#}\n (unBand b)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n nullPtr\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand b)\n (fromEnumC GF_Read)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n 0\n 0\n{-# INLINE unsafeBandConduitM #-}\n\ngeoEnvelopeTransformer\n :: Geotransform -> Maybe (Envelope Double -> Envelope Int)\ngeoEnvelopeTransformer gt =\n case (gtXDelta gt < 0, gtYDelta gt<0, invertGeotransform gt) of\n (_,_,Nothing) -> Nothing\n (False,False,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let e0' = fmap round (applyGeotransform iGt e0)\n e1' = fmap round (applyGeotransform iGt e1)\n in Envelope e0' e1'\n (True,False,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x1 :+: y0 = fmap round (applyGeotransform iGt e0)\n x0 :+: y1 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n (False,True,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x0 :+: y1 = fmap round (applyGeotransform iGt e0)\n x1 :+: y0 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n (True,True,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x1 :+: y1 = fmap round (applyGeotransform iGt e0)\n x0 :+: y0 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n{-# INLINE geoEnvelopeTransformer #-}\n\n\nwriteBand\n :: forall s a. GDALType a\n => RWBand s a\n -> Envelope Int\n -> Size\n -> U.Vector (Value a)\n -> GDAL s ()\nwriteBand band win sz uvec =\n runConduit (yield (win, sz, uvec) =$= bandSink band)\n{-# INLINE writeBand #-}\n\n\n\nbandSink\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (Envelope Int, Size, U.Vector (Value a)) (GDAL s) ()\nbandSink band = lift (bandMaskType band) >>= \\case\n MaskNoData -> do\n nd <- lift (noDataOrFail band)\n awaitForever $ \\(win, sz, uvec) -> lift $\n write band win sz (toGVecWithNodata nd uvec)\n MaskAllValid ->\n awaitForever $ \\(win, sz, uvec) -> lift $\n maybe (throwBindingException BandDoesNotAllowNoData)\n (write band win sz)\n (toGVec uvec)\n _ -> do\n mBand <- lift (bandMask band)\n awaitForever $ \\(win, sz, uvec) -> lift $ do\n let (mask, vec) = toGVecWithMask uvec\n write band win sz vec\n write mBand win sz mask\n where\n\n write :: forall a'. GDALType a'\n => RWBand s a' -> Envelope Int -> Size -> St.Vector a' -> GDAL s ()\n write band' win sz@(bx :+: by) vec = do\n let sx :+: sy = envelopeSize win\n xoff :+: yoff = envelopeMin win\n if sizeLen sz \/= G.length vec\n then throwBindingException (InvalidRasterSize sz)\n else liftIO $\n St.unsafeWith vec $ \\ptr ->\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand band')\n (fromEnumC GF_Write)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n 0\n 0\n{-# INLINE bandSink #-}\n\nbandSinkGeo\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (Envelope Double, Size, U.Vector (Value a)) (GDAL s) ()\nbandSinkGeo band = do\n mGt <- lift (bracket (bandDataset band) closeDataset datasetGeotransform)\n case mGt >>= geoEnvelopeTransformer of\n Just trans -> CL.map (\\(e,s,v) -> (trans e,s,v)) =$= bandSink band\n Nothing -> lift (throwBindingException CannotInvertGeotransform)\n{-# INLINE bandSinkGeo #-}\n\nnoDataOrFail :: GDALType a => Band s a t -> GDAL s a\nnoDataOrFail = liftM (fromMaybe err) . bandNodataValue\n where\n err = error (\"GDAL.readMasked: band has GMF_NODATA flag but did \" ++\n \"not return a nodata value\")\n\nbandMask :: Band s a t -> GDAL s (Band s Word8 t)\nbandMask =\n liftIO . liftM (\\p -> Band (p,GByte)) . {#call GetMaskBand as ^#}\n . unBand\n\ndata MaskType\n = MaskNoData\n | MaskAllValid\n |\u00a0MaskPerBand\n |\u00a0MaskPerDataset\n\nbandMaskType :: Band s a t -> GDAL s MaskType\nbandMaskType band = do\n flags <- liftIO ({#call unsafe GetMaskFlags as ^#} (unBand band))\n let testFlag f = (fromEnumC f .&. flags) \/= 0\n return $ case () of\n () | testFlag GMF_NODATA -> MaskNoData\n () | testFlag GMF_ALL_VALID -> MaskAllValid\n () | testFlag GMF_PER_DATASET -> MaskPerDataset\n _ -> MaskPerBand\n\nmaskFlagsForType :: MaskType -> CInt\nmaskFlagsForType MaskNoData = fromEnumC GMF_NODATA\nmaskFlagsForType MaskAllValid = fromEnumC GMF_ALL_VALID\nmaskFlagsForType MaskPerBand = 0\nmaskFlagsForType MaskPerDataset = fromEnumC GMF_PER_DATASET\n\n{#enum define MaskFlag { GMF_ALL_VALID as GMF_ALL_VALID\n , GMF_PER_DATASET as GMF_PER_DATASET\n , GMF_ALPHA as GMF_ALPHA\n , GMF_NODATA as GMF_NODATA\n } deriving (Eq,Bounded,Show) #}\n\ncopyBand\n :: Band s a t -> RWBand s a -> OptionList\n -> Maybe ProgressFun -> GDAL s ()\ncopyBand src dst options progressFun =\n liftIO $\n withProgressFun \"copyBand\" progressFun $ \\pFunc ->\n withOptionList options $ \\o ->\n checkCPLError \"copyBand\" $\n {#call RasterBandCopyWholeRaster as ^#}\n (unBand src) (unBand dst) o pFunc nullPtr\n\nfillBand :: GDALType a => Value a -> RWBand s a -> GDAL s ()\nfillBand val b =\n runConduit (allBlocks b =$= CL.map (\\i -> (i,v)) =$= blockSink b)\n where v = G.replicate (bandBlockLen b) val\n\n\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s a t -> GDAL s b\nfoldl' f = ifoldl' (\\z _ v -> f z v)\n{-# INLINE foldl' #-}\n\nifoldl'\n :: forall s t a b. GDALType a\n => (b -> Pair Int -> Value a -> b) -> b -> Band s a t -> GDAL s b\nifoldl' f z band =\n runConduit (unsafeBlockSource band =$= CL.fold folder z)\n where\n !(mx :+: my) = liftA2 mod (bandSize band) (bandBlockSize band)\n !(nx :+: ny) = bandBlockCount band\n !(sx :+: sy) = bandBlockSize band\n {-# INLINE folder #-}\n folder !acc !(!(iB :+: jB), !vec) = go SPEC 0 0 acc\n where\n go !_ !i !j !acc'\n | i < stopx = go SPEC (i+1) j\n (f acc' ix (vec `G.unsafeIndex` (j*sx+i)))\n | j+1 < stopy = go SPEC 0 (j+1) acc'\n | otherwise = acc'\n where ix = iB*sx+i :+: jB*sy+j\n !stopx\n | mx \/= 0 && iB==nx-1 = mx\n | otherwise = sx\n !stopy\n | my \/= 0 && jB==ny-1 = my\n | otherwise = sy\n{-# INLINE ifoldl' #-}\n\nfoldlWindow'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s a t -> Envelope Int -> GDAL s b\nfoldlWindow' f b = ifoldlWindow' (\\z _ v -> f z v) b\n{-# INLINE foldlWindow' #-}\n\nifoldlWindow'\n :: forall s t a b. GDALType a\n => (b -> Pair Int -> Value a -> b)\n -> b -> Band s a t -> Envelope Int -> GDAL s b\nifoldlWindow' f z band (Envelope (x0 :+: y0) (x1 :+: y1)) = runConduit $\n allBlocks band =$= CL.filter inRange\n =$= decorate (unsafeBlockConduit band)\n =$= CL.fold folder z\n where\n inRange bIx = bx0 < x1 && x0 < bx1 && by0 < y1 && y0 < by1\n where\n !b0@(bx0 :+: by0) = bIx * bSize\n !(bx1 :+: by1) = b0 + bSize\n !(mx :+: my) = liftA2 mod (bandSize band) (bandBlockSize band)\n !(nx :+: ny) = bandBlockCount band\n !bSize@(sx :+: sy) = bandBlockSize band\n {-# INLINE folder #-}\n folder !acc !(!(iB :+: jB), !vec) = go SPEC 0 0 acc\n where\n go !_ !i !j !acc'\n | i < stopx = go SPEC (i+1) j acc''\n | j+1 < stopy = go SPEC 0 (j+1) acc'\n | otherwise = acc'\n where\n !ix@(ixx :+: ixy) = iB*sx+i :+: jB*sy+j\n acc''\n | x0 <= ixx && ixx < x1 && y0 <= ixy && ixy < y1\n = f acc' ix (vec `G.unsafeIndex` (j*sx+i))\n | otherwise = acc'\n !stopx\n | mx \/= 0 && iB==nx-1 = mx\n | otherwise = sx\n !stopy\n | my \/= 0 && jB==ny-1 = my\n | otherwise = sy\n{-# INLINE ifoldlWindow' #-}\n\nunsafeBlockSource\n :: GDALType a\n => Band s a t -> Source (GDAL s) (BlockIx, U.Vector (Value a))\nunsafeBlockSource band = allBlocks band =$= decorate (unsafeBlockConduit band)\n{-# INLINE unsafeBlockSource #-}\n\nblockSource\n :: GDALType a\n => Band s a t -> Source (GDAL s) (BlockIx, U.Vector (Value a))\nblockSource band = allBlocks band =$= decorate (blockConduit band)\n{-# INLINE blockSource #-}\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> BlockIx -> U.Vector (Value a) -> GDAL s ()\nwriteBandBlock band blockIx uvec =\n runConduit (yield (blockIx, uvec) =$= blockSink band)\n{-# INLINE writeBandBlock #-}\n\nfmapBand\n :: forall s a b t. (GDALType a, GDALType b)\n => (Value a -> Value b)\n -> Band s a t\n -> RWBand s b \n -> GDAL s ()\nfmapBand f src dst\n | bandSize src \/= bandSize dst\n = throwBindingException (InvalidRasterSize (bandSize src))\n | bandBlockSize src \/= bandBlockSize dst\n = throwBindingException notImplementedErr\n | otherwise = runConduit\n (unsafeBlockSource src =$= CL.map (second (U.map f)) =$= blockSink dst)\n where\n notImplementedErr = NotImplemented\n \"fmapBand: Not implemented for bands of different block size\"\n{-# INLINE fmapBand #-}\n\n\nblockSink\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (BlockIx, U.Vector (Value a)) (GDAL s) ()\nblockSink band = do\n writeBlock <-\n if dtBand==dtBuf\n then return writeNative\n else do tempBuf <- liftIO (mallocForeignPtrBytes (len*szBand))\n return (writeTranslated tempBuf)\n lift (bandMaskType band) >>= \\case\n MaskNoData -> lift (noDataOrFail band) >>= sinkNodata writeBlock\n MaskAllValid -> sinkAllValid writeBlock\n _ -> lift (bandMask band) >>= sinkMask writeBlock\n\n where\n len = bandBlockLen band\n dtBand = bandDataType (band)\n szBand = sizeOfDataType dtBand\n dtBuf = hsDataType (Proxy :: Proxy a)\n szBuf = sizeOfDataType dtBuf\n\n sinkNodata writeBlock nd = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n St.unsafeWith (toGVecWithNodata nd vec) (writeBlock ix)\n\n\n sinkAllValid writeBlock = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n case toGVec vec of\n Just buf -> St.unsafeWith buf (writeBlock ix)\n Nothing -> throwBindingException BandDoesNotAllowNoData\n\n sinkMask writeBlock bMask = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n let (mask, vec') = toGVecWithMask vec\n off = bi * bs\n win = liftA2 min bs (rs - off)\n bi = fmap fromIntegral ix\n bs = fmap fromIntegral (bandBlockSize band)\n rs = fmap fromIntegral (bandSize band)\n St.unsafeWith vec' (writeBlock ix)\n St.unsafeWith mask $ \\pBuf ->\n checkCPLError \"WriteBlock\" $\n {#call RasterIO as ^#}\n (unBand bMask)\n (fromEnumC GF_Write)\n (pFst off)\n (pSnd off)\n (pFst win)\n (pSnd win)\n (castPtr pBuf)\n (pFst win)\n (pSnd win)\n (fromEnumC GByte)\n 0\n (pFst bs * fromIntegral (sizeOfDataType GByte))\n\n checkLen v\n | len \/= G.length v\n = throwBindingException (InvalidBlockSize (G.length v))\n | otherwise = return ()\n\n writeTranslated temp blockIx pBuf =\n withForeignPtr temp $ \\pTemp -> do\n {#call unsafe CopyWords as ^#}\n (castPtr pTemp)\n (fromEnumC dtBand)\n (fromIntegral szBand)\n (castPtr pBuf)\n (fromEnumC dtBuf)\n (fromIntegral szBuf)\n (fromIntegral len)\n writeNative blockIx pTemp\n\n writeNative blockIx pBuf =\n checkCPLError \"WriteBlock\" $\n {#call GDALWriteBlock as ^#}\n (unBand band)\n (pFst bi)\n (pSnd bi)\n (castPtr pBuf)\n where bi = fmap fromIntegral blockIx\n{-# INLINE blockSink #-}\n\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s a t -> BlockIx -> GDAL s (U.Vector (Value a))\nreadBandBlock band blockIx = liftM fromJust $ runConduit $\n yield blockIx =$= unsafeBlockConduit band =$= CL.head\n{-# INLINE readBandBlock #-}\n\n\nallBlocks :: Monad m => Band s a t -> Producer m BlockIx\nallBlocks band = CL.sourceList [x :+: y | y <- [0..ny-1], x <- [0..nx-1]]\n where\n !(nx :+: ny) = bandBlockCount band\n{-# INLINE allBlocks #-}\n\nblockConduit\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (U.Vector (Value a))\nblockConduit band =\n unsafeBlockConduitM band =$= CL.mapM (liftIO . U.freeze)\n{-# INLINE blockConduit #-}\n\nunsafeBlockConduit\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (U.Vector (Value a))\nunsafeBlockConduit band =\n unsafeBlockConduitM band =$= CL.mapM (liftIO . U.unsafeFreeze)\n{-# INLINE unsafeBlockConduit #-}\n\n\nunsafeBlockConduitM\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (UM.IOVector (Value a))\nunsafeBlockConduitM band = do\n buf <- liftIO (M.new len)\n maskType <- lift $ bandMaskType band\n case maskType of\n MaskNoData -> do\n noData <- lift $ noDataOrFail band\n blockReader (mkValueUMVector noData buf) buf (const (return ()))\n MaskAllValid ->\n blockReader (mkAllValidValueUMVector buf) buf (const (return ()))\n _ -> do\n mBuf <- liftIO $ M.replicate len 0\n mask <- lift $ bandMask band\n blockReader (mkMaskedValueUMVector mBuf buf) buf (readMask mask mBuf)\n where\n isNative = dtBand == dtBuf\n len = bandBlockLen band\n dtBand = bandDataType band\n dtBuf = hsDataType (Proxy :: Proxy a)\n\n {-# INLINE blockReader #-}\n blockReader vec buf extra\n | isNative = awaitForever $ \\ix -> do\n liftIO (Stm.unsafeWith buf (loadBlock ix))\n extra ix\n yield vec\n | otherwise = do\n temp <- liftIO $ mallocForeignPtrBytes (len*szBand)\n awaitForever $ \\ix -> do\n liftIO $ withForeignPtr temp $ \\pTemp -> do\n loadBlock ix pTemp\n Stm.unsafeWith buf (translateBlock pTemp)\n extra ix\n yield vec\n\n {-# INLINE loadBlock #-}\n loadBlock ix pBuf = \n checkCPLError \"ReadBlock\" $\n {#call ReadBlock as ^#}\n (unBand band)\n (fromIntegral (pFst ix))\n (fromIntegral (pSnd ix))\n (castPtr pBuf)\n\n {-# INLINE translateBlock #-}\n translateBlock pTemp pBuf = \n {#call unsafe CopyWords as ^#}\n (castPtr pTemp)\n (fromEnumC dtBand)\n (fromIntegral szBand)\n (castPtr pBuf)\n (fromEnumC dtBuf)\n (fromIntegral szBuf)\n (fromIntegral len)\n szBand = sizeOfDataType dtBand\n szBuf = sizeOfDataType dtBuf\n\n {-# INLINE readMask #-}\n readMask mask vMask ix =\n liftIO $\n Stm.unsafeWith vMask $ \\pMask ->\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand mask)\n (fromEnumC GF_Read)\n (pFst off)\n (pSnd off)\n (pFst win)\n (pSnd win)\n (castPtr pMask)\n (pFst win)\n (pSnd win)\n (fromEnumC GByte)\n 0\n (pFst bs)\n where\n bi = fmap fromIntegral ix\n off = bi * bs\n win = liftA2 min bs (rs - off)\n bs = fmap fromIntegral (bandBlockSize band)\n rs = fmap fromIntegral (bandSize band)\n{-# INLINE unsafeBlockConduitM #-}\n\nopenDatasetCount :: IO Int\nopenDatasetCount =\n alloca $ \\ppDs ->\n alloca $ \\pCount -> do\n {#call unsafe GetOpenDatasets as ^#} ppDs pCount\n liftM fromIntegral (peek pCount)\n\n-----------------------------------------------------------------------------\n-- Metadata\n-----------------------------------------------------------------------------\n\nmetadataDomains :: MajorObject o t => o t -> GDAL s [Text]\n#if SUPPORTS_METADATA_DOMAINS\nmetadataDomains o =\n liftIO $\n fromCPLStringList $\n {#call unsafe GetMetadataDomainList as ^#} (majorObject o)\n#else\nmetadataDomains = const (return [])\n#endif\n\nmetadata\n :: MajorObject o t\n => Maybe ByteString -> o t -> GDAL s [(Text,Text)]\nmetadata domain o =\n liftIO $\n withMaybeByteString domain\n ({#call unsafe GetMetadata as ^#} (majorObject o)\n >=> liftM (map breakIt) . fromBorrowedCPLStringList)\n where\n breakIt s =\n case T.break (=='=') s of\n (k,\"\") -> (k,\"\")\n (k, v) -> (k, T.tail v)\n\nmetadataItem\n :: MajorObject o t\n => Maybe ByteString -> ByteString -> o t -> GDAL s (Maybe ByteString)\nmetadataItem domain key o =\n liftIO $\n useAsCString key $ \\pKey ->\n withMaybeByteString domain $\n {#call unsafe GetMetadataItem as ^#} (majorObject o) pKey >=>\n maybePackCString\n\nsetMetadataItem\n :: (MajorObject o t, t ~ ReadWrite)\n => Maybe ByteString -> ByteString -> ByteString -> o t -> GDAL s ()\nsetMetadataItem domain key val o =\n liftIO $\n checkCPLError \"setMetadataItem\" $\n useAsCString key $ \\pKey ->\n useAsCString val $ \\pVal ->\n withMaybeByteString domain $\n {#call unsafe GDALSetMetadataItem as ^#} (majorObject o) pKey pVal\n\ndescription :: MajorObject o t => o t -> GDAL s ByteString\ndescription =\n liftIO . ({#call unsafe GetDescription as ^#} . majorObject >=> packCString)\n\nsetDescription\n :: (MajorObject o t, t ~ ReadWrite)\n => ByteString -> o t -> GDAL s ()\nsetDescription val =\n liftIO . checkGDALCall_ const .\n useAsCString val . {#call unsafe GDALSetDescription as ^#} . majorObject\n\n\n\n-----------------------------------------------------------------------------\n-- Conduit utils\n-----------------------------------------------------------------------------\n\n-- | Parallel zip of two conduits\npZipConduitApp\n :: Monad m\n => Conduit a m (b -> c)\n -> Conduit a m b\n -> Conduit a m c\npZipConduitApp (ConduitM l0) (ConduitM r0) = ConduitM $ \\rest -> let\n go (HaveOutput p c o) (HaveOutput p' c' o') =\n HaveOutput (go p p') (c>>c') (o o')\n go (NeedInput p c) (NeedInput p' c') =\n NeedInput (\\i -> go (p i) (p' i)) (\\u -> go (c u) (c' u))\n go (Done ()) (Done ()) = rest ()\n go (PipeM m) (PipeM m') = PipeM (liftM2 go m m')\n go (Leftover p i) (Leftover p' _) = Leftover (go p p') i\n go _ _ = error \"pZipConduitApp: not parallel\"\n in go (injectLeftovers $ l0 Done) (injectLeftovers $ r0 Done)\n\nnewtype PZipConduit i m o =\n PZipConduit { getPZipConduit :: Conduit i m o}\n\ninstance Monad m => Functor (PZipConduit i m) where\n fmap f = PZipConduit . mapOutput f . getPZipConduit\n\ninstance Monad m => Applicative (PZipConduit i m) where\n pure = PZipConduit . forever . yield\n PZipConduit l <*> PZipConduit r = PZipConduit (pZipConduitApp l r)\n\nzipBlocks\n :: GDALType a\n => Band s a t -> PZipConduit BlockIx (GDAL s) (U.Vector (Value a))\nzipBlocks = PZipConduit . unsafeBlockConduit\n\ngetZipBlocks\n :: PZipConduit BlockIx (GDAL s) a\n -> Conduit BlockIx (GDAL s) (BlockIx, a)\ngetZipBlocks = decorate . getPZipConduit\n\ndecorate :: Monad m => Conduit a m b -> Conduit a m (a, b)\ndecorate (ConduitM c0) = ConduitM $ \\rest -> let\n go1 HaveOutput{} = error \"unexpected NeedOutput\"\n go1 (NeedInput p c) = NeedInput (\\i -> go2 i (p i)) (go1 . c)\n go1 (Done r) = rest r\n go1 (PipeM mp) = PipeM (liftM (go1) mp)\n go1 (Leftover p i) = Leftover (go1 p) i\n\n go2 i (HaveOutput p c o) = HaveOutput (go2 i p) c (i, o)\n go2 _ (NeedInput p c) = NeedInput (\\i -> go2 i (p i)) (go1 . c)\n go2 _ (Done r) = rest r\n go2 i (PipeM mp) = PipeM (liftM (go2 i) mp)\n go2 i (Leftover p i') = Leftover (go2 i p) i'\n in go1 (c0 Done)\n{-# INLINE decorate #-}\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE LambdaCase #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.GDAL (\n GDALRasterException (..)\n , Geotransform (..)\n , OverviewResampling (..)\n , Driver (..)\n , Dataset\n , DatasetH (..)\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , RasterBandH (..)\n , MaskType (..)\n\n , northUpGeotransform\n , gcpGeotransform\n , applyGeotransform\n , (|$|)\n , invertGeotransform\n , inv\n , composeGeotransforms\n , (|.|)\n , geoEnvelopeTransformer\n\n , nullDatasetH\n , allRegister\n , destroyDriverManager\n , create\n , createMem\n , delete\n , rename\n , copyFiles\n , flushCache\n , closeDataset\n , openReadOnly\n , openReadWrite\n , unsafeToReadOnly\n , createCopy\n , buildOverviews\n , driverCreationOptionList\n\n , bandAs\n\n , datasetDriver\n , datasetSize\n , datasetFileList\n , datasetProjection\n , datasetProjectionIO\n , setDatasetProjection\n , datasetGeotransform\n , datasetGeotransformIO\n , setDatasetGeotransform\n , datasetGCPs\n , setDatasetGCPs\n , datasetBandCount\n\n , bandDataType\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandHasOverviews\n , allBand\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , addBand\n , fillBand\n , fmapBand\n , readBand\n , createBandMask\n , readBandBlock\n , writeBand\n , writeBandBlock\n , copyBand\n , bandConduit\n , unsafeBandConduit\n , bandSink\n , bandSinkGeo\n\n , metadataDomains\n , metadata\n , metadataItem\n , setMetadataItem\n , description\n , setDescription\n\n , foldl'\n , ifoldl'\n , foldlWindow'\n , ifoldlWindow'\n , blockConduit\n , unsafeBlockConduit\n , blockSource\n , unsafeBlockSource\n , blockSink\n , allBlocks\n , zipBlocks\n , getZipBlocks\n\n , unDataset\n , unBand\n , version\n , newDatasetHandle\n , openDatasetCount\n\n , module GDAL.Internal.DataType\n) where\n\n{#context lib = \"gdal\" prefix = \"GDAL\" #}\n\nimport Control.Arrow (second)\nimport Control.Applicative (Applicative(..), (<$>), liftA2)\nimport Control.Exception (Exception(..))\nimport Control.Monad (liftM, liftM2, when, (>=>), void, forever)\nimport Control.Monad.Trans (lift)\nimport Control.Monad.Catch (bracket)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Data.Bits ((.&.))\nimport Data.ByteString.Char8 (ByteString, packCString, useAsCString)\nimport Data.ByteString.Unsafe (unsafeUseAsCString)\nimport Data.Coerce (coerce)\nimport qualified Data.Conduit.List as CL\nimport Data.Conduit\nimport Data.Conduit.Internal (Pipe(..), ConduitM(..), injectLeftovers)\nimport Data.Maybe (fromMaybe, fromJust)\nimport Data.String (IsString)\nimport Data.Proxy\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport Data.Typeable (Typeable)\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport qualified Data.Vector.Generic.Mutable as M\nimport qualified Data.Vector.Unboxed.Mutable as UM\nimport qualified Data.Vector.Unboxed as U\nimport Data.Word (Word8)\n\nimport Foreign.C.String (withCString, CString)\nimport Foreign.C.Types\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrBytes)\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (withArrayLen)\nimport Foreign.Marshal.Utils (toBool, fromBool, with)\n\nimport GHC.Types (SPEC(..))\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.Types.Value\nimport GDAL.Internal.DataType\nimport GDAL.Internal.Common\nimport GDAL.Internal.Util\n{#import GDAL.Internal.GCP#}\n{#import GDAL.Internal.CPLError#}\n{#import GDAL.Internal.CPLString#}\n{#import GDAL.Internal.CPLProgress#}\nimport GDAL.Internal.OSR\nimport GDAL.Internal.OGRGeometry (Envelope(..), envelopeSize)\n\n\n#include \"gdal.h\"\n\nnewtype Driver = Driver ByteString\n deriving (Eq, IsString)\n\ninstance Show Driver where\n show (Driver s) = show s\n\nversion :: (Int, Int)\nversion = ({#const GDAL_VERSION_MAJOR#} , {#const GDAL_VERSION_MINOR#})\n\ndata GDALRasterException\n = InvalidRasterSize !Size\n | InvalidBlockSize !Int\n | InvalidDriverOptions\n | UnknownRasterDataType\n | NullDataset\n | NullBand\n | UnknownDriver !ByteString\n | BandDoesNotAllowNoData\n | CannotInvertGeotransform\n | NotImplemented !ByteString\n deriving (Typeable, Show, Eq)\n\ninstance Exception GDALRasterException where\n toException = bindingExceptionToException\n fromException = bindingExceptionFromException\n\n\n{#enum GDALAccess {} deriving (Eq, Show) #}\n\n{#enum RWFlag {} deriving (Eq, Show) #}\n\n{#pointer MajorObjectH newtype#}\n\nclass MajorObject o (t::AccessMode) where\n majorObject :: o t -> MajorObjectH\n\n\n{#pointer DatasetH newtype #}\n\n\nnullDatasetH :: DatasetH\nnullDatasetH = DatasetH nullPtr\n\nderiving instance Eq DatasetH\n\nnewtype Dataset s a (t::AccessMode) =\n Dataset (ReleaseKey, DatasetH)\n\ninstance MajorObject (Dataset s a) t where\n majorObject ds =\n let DatasetH p = unDataset ds\n in MajorObjectH (castPtr p)\n\nunDataset :: Dataset s a t -> DatasetH\nunDataset (Dataset (_,s)) = s\n\ncloseDataset :: MonadIO m => Dataset s a t -> m ()\ncloseDataset (Dataset (rk,_)) = release rk\n\ntype RODataset s a = Dataset s a ReadOnly\ntype RWDataset s a = Dataset s a ReadWrite\n\n{#pointer RasterBandH newtype #}\n\nnullBandH :: RasterBandH\nnullBandH = RasterBandH nullPtr\n\nderiving instance Eq RasterBandH\n\nnewtype Band s a (t::AccessMode) = Band (RasterBandH, DataTypeK)\n\nunBand :: Band s a t -> RasterBandH\nunBand (Band (p,_)) = p\n{-# INLINE unBand #-}\n\nbandDataType :: Band s a t -> DataTypeK\nbandDataType (Band (_,t)) = t\n{-# INLINE bandDataType #-}\n\nbandAs :: Band s a t -> DataType d -> Band s (HsType d) t\nbandAs = const . coerce\n{-# INLINE bandAs #-}\n\ninstance MajorObject (Band s a) t where\n majorObject b =\n let RasterBandH p = unBand b\n in MajorObjectH (castPtr p)\n\ntype ROBand s a = Band s a ReadOnly\ntype RWBand s a = Band s a ReadWrite\n\n\n{#pointer DriverH #}\n\n{#fun AllRegister as ^ {} -> `()' #}\n\n{#fun DestroyDriverManager as ^ {} -> `()'#}\n\ndriverByName :: Driver -> IO DriverH\ndriverByName (Driver s) = do\n d <- useAsCString s {#call unsafe GetDriverByName as ^#}\n if d == nullPtr\n then throwBindingException (UnknownDriver s)\n else return d\n\ndriverCreationOptionList :: Driver -> ByteString\ndriverCreationOptionList driver = unsafePerformIO $ do\n d <- driverByName driver\n {#call GetDriverCreationOptionList\tas ^#} d >>= packCString\n\nvalidateCreationOptions :: DriverH -> Ptr CString -> IO ()\nvalidateCreationOptions d o = do\n valid <- liftM toBool ({#call GDALValidateCreationOptions as ^ #} d o)\n when (not valid) (throwBindingException InvalidDriverOptions)\n\ncreate\n :: Driver -> String -> Size -> Int -> DataType d -> OptionList\n -> GDAL s (Dataset s (HsType d) ReadWrite)\ncreate drv path (nx :+: ny) bands dtype options =\n newDatasetHandle $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC dtype\n d <- driverByName drv\n withOptionList options $ \\opts -> do\n validateCreationOptions d opts\n {#call GDALCreate as ^#} d path' nx' ny' bands' dtype' opts\n\ndelete :: Driver -> String -> GDAL s ()\ndelete driver path =\n liftIO $\n checkCPLError \"deleteDataset\" $ do\n d <- driverByName driver\n withCString path ({#call DeleteDataset as ^#} d)\n\nrename :: Driver -> String -> String -> GDAL s ()\nrename driver newName oldName =\n liftIO $\n checkCPLError \"renameDataset\" $ do\n d <- driverByName driver\n withCString newName $\n withCString oldName . ({#call RenameDataset as ^#} d)\n\ncopyFiles :: Driver -> String -> String -> GDAL s ()\ncopyFiles driver newName oldName =\n liftIO $\n checkCPLError \"copyFiles\" $ do\n d <- driverByName driver\n withCString newName $\n withCString oldName . ({#call CopyDatasetFiles as ^#} d)\n\nopenReadOnly :: String -> DataType d -> GDAL s (RODataset s (HsType d))\nopenReadOnly p _ = openWithMode GA_ReadOnly p\n\nopenReadWrite :: String -> DataType d -> GDAL s (RWDataset s (HsType d))\nopenReadWrite p _ = openWithMode GA_Update p\n\nopenWithMode :: GDALAccess -> String -> GDAL s (Dataset s a t)\nopenWithMode m path =\n newDatasetHandle $\n withCString path $\n flip {#call GDALOpen as ^#} (fromEnumC m)\n\nunsafeToReadOnly :: RWDataset s a -> GDAL s (RODataset s a)\nunsafeToReadOnly ds = flushCache ds >> return (coerce ds)\n\ncreateCopy\n :: Driver -> String -> Dataset s a t -> Bool -> OptionList\n -> Maybe ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy driver path ds strict options progressFun =\n newDatasetHandle $\n withProgressFun \"createCopy\" progressFun $ \\pFunc -> do\n d <- driverByName driver\n withOptionList options $ \\o -> do\n validateCreationOptions d o\n withCString path $ \\p ->\n {#call GDALCreateCopy as ^#}\n d p (unDataset ds) (fromBool strict) o pFunc nullPtr\n\n\n\nnewDatasetHandle :: IO DatasetH -> GDAL s (Dataset s a t)\nnewDatasetHandle act =\n liftM Dataset $ allocate (checkGDALCall checkit act) free\n where\n checkit exc p\n | p==nullDatasetH = Just (fromMaybe\n (GDALBindingException NullDataset) exc)\n | otherwise = Nothing\n free ds = do\n refCount <- {#call unsafe DereferenceDataset as ^#} ds\n when (refCount<=0) ({#call GDALClose as ^#} ds)\n\ncreateMem\n :: Size -> Int -> DataType d -> OptionList\n -> GDAL s (Dataset s (HsType d) ReadWrite)\ncreateMem = create \"Mem\" \"\"\n\nflushCache :: RWDataset s a -> GDAL s ()\nflushCache = liftIO . {#call GDALFlushCache as ^#} . unDataset\n\ndatasetDriver :: Dataset s a t -> Driver\ndatasetDriver ds =\n unsafePerformIO $\n liftM Driver $ do\n driver <-{#call unsafe GetDatasetDriver as ^#} (unDataset ds)\n {#call unsafe GetDriverShortName as ^#} driver >>= packCString\n\ndatasetSize :: Dataset s a t -> Size\ndatasetSize ds =\n fmap fromIntegral $\n ({#call pure unsafe GetRasterXSize as ^#} (unDataset ds))\n :+: ({#call pure unsafe GetRasterYSize as ^#} (unDataset ds))\n\ndatasetFileList :: Dataset s a t -> GDAL s [Text]\ndatasetFileList =\n liftIO .\n fromCPLStringList .\n {#call unsafe GetFileList as ^#} .\n unDataset\n\ndatasetProjectionIO :: Dataset s a t -> IO (Maybe SpatialReference)\ndatasetProjectionIO =\n {#call unsafe GetProjectionRef as ^#} . unDataset\n >=> maybeSpatialReferenceFromCString\n\ndatasetProjection :: Dataset s a t -> GDAL s (Maybe SpatialReference)\ndatasetProjection = liftIO . datasetProjectionIO\n\n\nsetDatasetProjection :: SpatialReference -> RWDataset s a -> GDAL s ()\nsetDatasetProjection srs ds =\n liftIO $ checkCPLError \"SetProjection\" $\n useAsCString (srsToWkt srs)\n ({#call unsafe SetProjection as ^#} (unDataset ds))\n\nsetDatasetGCPs\n :: [GroundControlPoint] -> Maybe SpatialReference -> RWDataset s a\n -> GDAL s ()\nsetDatasetGCPs gcps mSrs ds =\n liftIO $\n checkCPLError \"setDatasetGCPs\" $\n withGCPArrayLen gcps $ \\nGcps pGcps ->\n withMaybeSRAsCString mSrs $\n {#call unsafe GDALSetGCPs as ^#}\n (unDataset ds)\n (fromIntegral nGcps)\n pGcps\n\ndatasetGCPs\n :: Dataset s a t\n -> GDAL s ([GroundControlPoint], Maybe SpatialReference)\ndatasetGCPs ds =\n liftIO $ do\n let pDs = unDataset ds\n srs <- maybeSpatialReferenceFromCString\n =<< {#call unsafe GetGCPProjection as ^#} pDs\n nGcps <- liftM fromIntegral ({#call unsafe GetGCPCount as ^#} pDs)\n gcps <- {#call unsafe GetGCPs as ^#} pDs >>= fromGCPArray nGcps\n return (gcps, srs)\n\n\ndata OverviewResampling\n = OvNearest\n | OvGauss\n | OvCubic\n | OvAverage\n | OvMode\n | OvAverageMagphase\n | OvNone\n\nbuildOverviews\n :: RWDataset s a -> OverviewResampling -> [Int] -> [Int] -> Maybe ProgressFun\n -> GDAL s ()\nbuildOverviews ds resampling overviews bands progressFun =\n liftIO $\n withResampling resampling $ \\pResampling ->\n withArrayLen (map fromIntegral overviews) $ \\nOverviews pOverviews ->\n withArrayLen (map fromIntegral bands) $ \\nBands pBands ->\n withProgressFun \"buildOverviews\" progressFun $ \\pFunc ->\n checkCPLError \"buildOverviews\" $\n {#call GDALBuildOverviews as ^#}\n (unDataset ds)\n pResampling\n (fromIntegral nOverviews)\n pOverviews\n (fromIntegral nBands)\n pBands\n pFunc\n nullPtr\n where\n withResampling OvNearest = unsafeUseAsCString \"NEAREST\\0\"\n withResampling OvGauss = unsafeUseAsCString \"GAUSS\\0\"\n withResampling OvCubic = unsafeUseAsCString \"CUBIC\\0\"\n withResampling OvAverage = unsafeUseAsCString \"AVERAGE\\0\"\n withResampling OvMode = unsafeUseAsCString \"MODE\\0\"\n withResampling OvAverageMagphase = unsafeUseAsCString \"AVERAGE_MAGPHASE\\0\"\n withResampling OvNone = unsafeUseAsCString \"NONE\\0\"\n\ndata Geotransform\n = Geotransform {\n gtXOff :: {-# UNPACK #-} !Double\n , gtXDelta :: {-# UNPACK #-} !Double\n , gtXRot :: {-# UNPACK #-} !Double\n , gtYOff :: {-# UNPACK #-} !Double\n , gtYRot :: {-# UNPACK #-} !Double\n , gtYDelta :: {-# UNPACK #-} !Double\n } deriving (Eq, Show)\n\nnorthUpGeotransform :: Size -> Envelope Double -> Geotransform\nnorthUpGeotransform size envelope =\n Geotransform {\n gtXOff = pFst (envelopeMin envelope)\n , gtXDelta = pFst (envelopeSize envelope \/ fmap fromIntegral size)\n , gtXRot = 0\n , gtYOff = pSnd (envelopeMax envelope)\n , gtYRot = 0\n , gtYDelta = negate (pSnd (envelopeSize envelope \/ fmap fromIntegral size))\n }\n\ngcpGeotransform :: [GroundControlPoint] -> ApproxOK -> Maybe Geotransform\ngcpGeotransform gcps approxOk =\n unsafePerformIO $\n alloca $ \\pGt ->\n withGCPArrayLen gcps $ \\nGcps pGcps -> do\n ret <- liftM toBool $\n {#call unsafe GCPsToGeoTransform as ^#}\n (fromIntegral nGcps)\n pGcps\n (castPtr pGt)\n (fromEnumC approxOk)\n if ret then liftM Just (peek pGt) else return Nothing\n\napplyGeotransform :: Geotransform -> Pair Double -> Pair Double\napplyGeotransform Geotransform{..} (x :+: y) =\n (gtXOff + gtXDelta*x + gtXRot * y) :+: (gtYOff + gtYRot *x + gtYDelta * y)\n{-# INLINE applyGeotransform #-}\n\ninfixr 5 |$|\n(|$|) :: Geotransform -> Pair Double -> Pair Double\n(|$|) = applyGeotransform\n\ninvertGeotransform :: Geotransform -> Maybe Geotransform\ninvertGeotransform (Geotransform g0 g1 g2 g3 g4 g5)\n | g2==0 && g4==0 && g1\/=0 && g5\/=0 -- No rotation\n = Just $! Geotransform (-g0\/g1) (1\/g1) 0 (-g3\/g5) 0 (1\/g5)\n | abs det < 1e-15 = Nothing -- not invertible\n | otherwise\n = Just $! Geotransform ((g2*g3 - g0*g5) * idet)\n (g5*idet)\n (-g2*idet)\n ((-g1*g3 + g0*g4) * idet)\n (-g4*idet)\n (g1*idet)\n where\n idet = 1\/det\n det = g1*g5 - g2*g4\n{-# INLINE invertGeotransform #-}\n\ninv :: Geotransform -> Geotransform\ninv = fromMaybe (error \"Could not invert geotransform\") . invertGeotransform\n\n-- | Creates a Geotransform equivalent to applying a and then b\ncomposeGeotransforms :: Geotransform -> Geotransform -> Geotransform\nb `composeGeotransforms` a =\n Geotransform (b1*a0 + b2*a3 + b0)\n (b1*a1 + b2*a4)\n (b1*a2 + b2*a5)\n (b4*a0 + b5*a3 + b3)\n (b4*a1 + b5*a4)\n (b4*a2 + b5*a5)\n\n where\n Geotransform a0 a1 a2 a3 a4 a5 = a\n Geotransform b0 b1 b2 b3 b4 b5 = b\n{-# INLINE composeGeotransforms #-}\n\ninfixr 9 |.|\n(|.|) :: Geotransform -> Geotransform -> Geotransform\n(|.|) = composeGeotransforms\n\ninstance Storable Geotransform where\n sizeOf _ = sizeOf (undefined :: CDouble) * 6\n alignment _ = alignment (undefined :: CDouble)\n poke pGt (Geotransform g0 g1 g2 g3 g4 g5) = do\n let p = castPtr pGt :: Ptr CDouble\n pokeElemOff p 0 (realToFrac g0)\n pokeElemOff p 1 (realToFrac g1)\n pokeElemOff p 2 (realToFrac g2)\n pokeElemOff p 3 (realToFrac g3)\n pokeElemOff p 4 (realToFrac g4)\n pokeElemOff p 5 (realToFrac g5)\n peek pGt = do\n let p = castPtr pGt :: Ptr CDouble\n Geotransform <$> liftM realToFrac (peekElemOff p 0)\n <*> liftM realToFrac (peekElemOff p 1)\n <*> liftM realToFrac (peekElemOff p 2)\n <*> liftM realToFrac (peekElemOff p 3)\n <*> liftM realToFrac (peekElemOff p 4)\n <*> liftM realToFrac (peekElemOff p 5)\n\n\ndatasetGeotransformIO :: Dataset s a t -> IO (Maybe Geotransform)\ndatasetGeotransformIO ds = alloca $ \\p -> do\n ret <- {#call unsafe GetGeoTransform as ^#} (unDataset ds) (castPtr p)\n if toEnumC ret == CE_None\n then liftM Just (peek p)\n else return Nothing\n\ndatasetGeotransform :: Dataset s a t -> GDAL s (Maybe Geotransform)\ndatasetGeotransform = liftIO . datasetGeotransformIO\n\n\nsetDatasetGeotransform :: Geotransform -> RWDataset s a -> GDAL s ()\nsetDatasetGeotransform gt ds = liftIO $\n checkCPLError \"SetGeoTransform\" $\n with gt ({#call unsafe SetGeoTransform as ^#} (unDataset ds) . castPtr)\n\n\ndatasetBandCount :: Dataset s a t -> GDAL s Int\ndatasetBandCount =\n liftM fromIntegral . liftIO . {#call unsafe GetRasterCount as ^#} . unDataset\n\ngetBand :: Int -> Dataset s a t -> GDAL s (Band s a t)\ngetBand b ds = liftIO $ do\n pB <- checkGDALCall checkit $\n {#call GetRasterBand as ^#} (unDataset ds) (fromIntegral b)\n dt <- liftM toEnumC ({#call unsafe GetRasterDataType as ^#} pB)\n return (Band (pB, dt))\n where\n checkit exc p\n | p == nullBandH = Just (fromMaybe (GDALBindingException NullBand) exc)\n | otherwise = Nothing\n\naddBand\n :: forall s a. GDALType a\n => OptionList -> RWDataset s a -> GDAL s (RWBand s a)\naddBand options ds = do\n liftIO $\n checkCPLError \"addBand\" $\n withOptionList options $\n {#call GDALAddBand as ^#} (unDataset ds) (fromEnumC dt)\n ix <- datasetBandCount ds\n getBand ix ds\n where dt = hsDataType (Proxy :: Proxy a)\n\nbandDataset :: Band s a t -> GDAL s (Dataset s a t)\nbandDataset b = newDatasetHandle $ do\n hDs <- {#call unsafe GDALGetBandDataset as ^#} (unBand b)\n void $ {#call unsafe GDALReferenceDataset as ^#} hDs\n return hDs\n\n\nbandBlockSize :: (Band s a t) -> Size\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n {#call unsafe GetBlockSize as ^#} (unBand band) xPtr yPtr\n liftM (fmap fromIntegral) (liftM2 (:+:) (peek xPtr) (peek yPtr))\n{-# NOINLINE bandBlockSize #-}\n\nbandBlockLen :: Band s a t -> Int\nbandBlockLen = (\\(x :+: y) -> x*y) . bandBlockSize\n\nbandSize :: Band s a t -> Size\nbandSize band =\n fmap fromIntegral $\n ({#call pure unsafe GetRasterBandXSize as ^#} (unBand band))\n :+: ({#call pure unsafe GetRasterBandYSize as ^#} (unBand band))\n{-# NOINLINE bandSize #-}\n\nallBand :: Band s a t -> Envelope Int\nallBand = Envelope (pure 0) . bandSize\n\nbandBlockCount :: Band s a t -> Pair Int\nbandBlockCount b = fmap ceiling $ liftA2 ((\/) :: Double -> Double -> Double)\n (fmap fromIntegral (bandSize b))\n (fmap fromIntegral (bandBlockSize b))\n\nbandHasOverviews :: Band s a t -> GDAL s Bool\nbandHasOverviews =\n liftIO . liftM toBool . {#call unsafe HasArbitraryOverviews as ^#} . unBand\n\nbandNodataValue :: GDALType a => Band s a t -> GDAL s (Maybe a)\nbandNodataValue b =\n liftIO $\n alloca $ \\p -> do\n value <- {#call unsafe GetRasterNoDataValue as ^#} (unBand b) p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just (fromCDouble value) else Nothing)\n{-# NOINLINE bandNodataValue #-}\n\n\nsetBandNodataValue :: GDALType a => a -> RWBand s a -> GDAL s ()\nsetBandNodataValue v b =\n liftIO $\n checkCPLError \"SetRasterNoDataValue\" $\n {#call unsafe SetRasterNoDataValue as ^#} (unBand b) (toCDouble v)\n\ncreateBandMask :: MaskType -> RWBand s a -> GDAL s ()\ncreateBandMask maskType band = liftIO $\n checkCPLError \"createBandMask\" $\n {#call CreateMaskBand as ^#} (unBand band) cflags\n where cflags = maskFlagsForType maskType\n\nreadBand :: forall s t a. GDALType a\n => (Band s a t)\n -> Envelope Int\n -> Size\n -> GDAL s (U.Vector (Value a))\nreadBand band win sz = liftM fromJust $ runConduit $\n yield win =$= unsafeBandConduit sz band =$= CL.head\n{-# INLINE readBand #-}\n\nbandConduit\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (U.Vector (Value a))\nbandConduit sz band =\n unsafeBandConduitM sz band =$= CL.mapM (liftIO . U.freeze)\n{-# INLINE bandConduit #-}\n\nunsafeBandConduit\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (U.Vector (Value a))\nunsafeBandConduit sz band =\n unsafeBandConduitM sz band =$= CL.mapM (liftIO . U.unsafeFreeze)\n{-# INLINE unsafeBandConduit #-}\n\n\nunsafeBandConduitM\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (UM.IOVector (Value a))\nunsafeBandConduitM (bx :+: by) band = do\n buf <- liftIO (M.new (bx*by))\n lift (bandMaskType band) >>= \\case\n MaskNoData -> do\n nd <- lift (noDataOrFail band)\n let vec = mkValueUMVector nd buf\n awaitForever $ \\win -> do\n liftIO (read_ band buf win)\n yield vec\n MaskAllValid -> do\n let vec = mkAllValidValueUMVector buf\n awaitForever $ \\win -> do\n liftIO (read_ band buf win)\n yield vec\n _ -> do\n mBuf <- liftIO $ M.replicate (bx*by) 0\n mask <- lift $ bandMask band\n let vec = mkMaskedValueUMVector mBuf buf\n awaitForever $ \\win -> do\n liftIO (read_ band buf win >> read_ mask mBuf win)\n yield vec\n where\n read_ :: forall a'. GDALType a'\n => Band s a' t -> Stm.IOVector a' -> Envelope Int -> IO ()\n read_ b vec win = do\n let sx :+: sy = envelopeSize win\n xoff :+: yoff = envelopeMin win\n Stm.unsafeWith vec $ \\ptr -> do\n checkCPLError \"RasterAdviseRead\" $\n {#call unsafe RasterAdviseRead as ^#}\n (unBand b)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n nullPtr\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand b)\n (fromEnumC GF_Read)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n 0\n 0\n{-# INLINE unsafeBandConduitM #-}\n\ngeoEnvelopeTransformer\n :: Geotransform -> Maybe (Envelope Double -> Envelope Int)\ngeoEnvelopeTransformer gt =\n case (gtXDelta gt < 0, gtYDelta gt<0, invertGeotransform gt) of\n (_,_,Nothing) -> Nothing\n (False,False,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let e0' = fmap round (applyGeotransform iGt e0)\n e1' = fmap round (applyGeotransform iGt e1)\n in Envelope e0' e1'\n (True,False,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x1 :+: y0 = fmap round (applyGeotransform iGt e0)\n x0 :+: y1 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n (False,True,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x0 :+: y1 = fmap round (applyGeotransform iGt e0)\n x1 :+: y0 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n (True,True,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x1 :+: y1 = fmap round (applyGeotransform iGt e0)\n x0 :+: y0 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n{-# INLINE geoEnvelopeTransformer #-}\n\n\nwriteBand\n :: forall s a. GDALType a\n => RWBand s a\n -> Envelope Int\n -> Size\n -> U.Vector (Value a)\n -> GDAL s ()\nwriteBand band win sz uvec =\n runConduit (yield (win, sz, uvec) =$= bandSink band)\n{-# INLINE writeBand #-}\n\n\n\nbandSink\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (Envelope Int, Size, U.Vector (Value a)) (GDAL s) ()\nbandSink band = lift (bandMaskType band) >>= \\case\n MaskNoData -> do\n nd <- lift (noDataOrFail band)\n awaitForever $ \\(win, sz, uvec) -> lift $\n write band win sz (toGVecWithNodata nd uvec)\n MaskAllValid ->\n awaitForever $ \\(win, sz, uvec) -> lift $\n maybe (throwBindingException BandDoesNotAllowNoData)\n (write band win sz)\n (toGVec uvec)\n _ -> do\n mBand <- lift (bandMask band)\n awaitForever $ \\(win, sz, uvec) -> lift $ do\n let (mask, vec) = toGVecWithMask uvec\n write band win sz vec\n write mBand win sz mask\n where\n\n write :: forall a'. GDALType a'\n => RWBand s a' -> Envelope Int -> Size -> St.Vector a' -> GDAL s ()\n write band' win sz@(bx :+: by) vec = do\n let sx :+: sy = envelopeSize win\n xoff :+: yoff = envelopeMin win\n if sizeLen sz \/= G.length vec\n then throwBindingException (InvalidRasterSize sz)\n else liftIO $\n St.unsafeWith vec $ \\ptr ->\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand band')\n (fromEnumC GF_Write)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n 0\n 0\n{-# INLINE bandSink #-}\n\nbandSinkGeo\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (Envelope Double, Size, U.Vector (Value a)) (GDAL s) ()\nbandSinkGeo band = do\n mGt <- lift (bracket (bandDataset band) closeDataset datasetGeotransform)\n case mGt >>= geoEnvelopeTransformer of\n Just trans -> CL.map (\\(e,s,v) -> (trans e,s,v)) =$= bandSink band\n Nothing -> lift (throwBindingException CannotInvertGeotransform)\n{-# INLINE bandSinkGeo #-}\n\nnoDataOrFail :: GDALType a => Band s a t -> GDAL s a\nnoDataOrFail = liftM (fromMaybe err) . bandNodataValue\n where\n err = error (\"GDAL.readMasked: band has GMF_NODATA flag but did \" ++\n \"not return a nodata value\")\n\nbandMask :: Band s a t -> GDAL s (Band s Word8 t)\nbandMask =\n liftIO . liftM (\\p -> Band (p,GByte)) . {#call GetMaskBand as ^#}\n . unBand\n\ndata MaskType\n = MaskNoData\n | MaskAllValid\n |\u00a0MaskPerBand\n |\u00a0MaskPerDataset\n\nbandMaskType :: Band s a t -> GDAL s MaskType\nbandMaskType band = do\n flags <- liftIO ({#call unsafe GetMaskFlags as ^#} (unBand band))\n let testFlag f = (fromEnumC f .&. flags) \/= 0\n return $ case () of\n () | testFlag GMF_NODATA -> MaskNoData\n () | testFlag GMF_ALL_VALID -> MaskAllValid\n () | testFlag GMF_PER_DATASET -> MaskPerDataset\n _ -> MaskPerBand\n\nmaskFlagsForType :: MaskType -> CInt\nmaskFlagsForType MaskNoData = fromEnumC GMF_NODATA\nmaskFlagsForType MaskAllValid = fromEnumC GMF_ALL_VALID\nmaskFlagsForType MaskPerBand = 0\nmaskFlagsForType MaskPerDataset = fromEnumC GMF_PER_DATASET\n\n{#enum define MaskFlag { GMF_ALL_VALID as GMF_ALL_VALID\n , GMF_PER_DATASET as GMF_PER_DATASET\n , GMF_ALPHA as GMF_ALPHA\n , GMF_NODATA as GMF_NODATA\n } deriving (Eq,Bounded,Show) #}\n\ncopyBand\n :: Band s a t -> RWBand s a -> OptionList\n -> Maybe ProgressFun -> GDAL s ()\ncopyBand src dst options progressFun =\n liftIO $\n withProgressFun \"copyBand\" progressFun $ \\pFunc ->\n withOptionList options $ \\o ->\n checkCPLError \"copyBand\" $\n {#call RasterBandCopyWholeRaster as ^#}\n (unBand src) (unBand dst) o pFunc nullPtr\n\nfillBand :: GDALType a => Value a -> RWBand s a -> GDAL s ()\nfillBand val b =\n runConduit (allBlocks b =$= CL.map (\\i -> (i,v)) =$= blockSink b)\n where v = G.replicate (bandBlockLen b) val\n\n\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s a t -> GDAL s b\nfoldl' f = ifoldl' (\\z _ v -> f z v)\n{-# INLINE foldl' #-}\n\nifoldl'\n :: forall s t a b. GDALType a\n => (b -> Pair Int -> Value a -> b) -> b -> Band s a t -> GDAL s b\nifoldl' f z band =\n runConduit (unsafeBlockSource band =$= CL.fold folder z)\n where\n !(mx :+: my) = liftA2 mod (bandSize band) (bandBlockSize band)\n !(nx :+: ny) = bandBlockCount band\n !(sx :+: sy) = bandBlockSize band\n {-# INLINE folder #-}\n folder !acc !(!(iB :+: jB), !vec) = go SPEC 0 0 acc\n where\n go !_ !i !j !acc'\n | i < stopx = go SPEC (i+1) j\n (f acc' ix (vec `G.unsafeIndex` (j*sx+i)))\n | j+1 < stopy = go SPEC 0 (j+1) acc'\n | otherwise = acc'\n where ix = iB*sx+i :+: jB*sy+j\n !stopx\n | mx \/= 0 && iB==nx-1 = mx\n | otherwise = sx\n !stopy\n | my \/= 0 && jB==ny-1 = my\n | otherwise = sy\n{-# INLINE ifoldl' #-}\n\nfoldlWindow'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s a t -> Envelope Int -> GDAL s b\nfoldlWindow' f b = ifoldlWindow' (\\z _ v -> f z v) b\n{-# INLINE foldlWindow' #-}\n\nifoldlWindow'\n :: forall s t a b. GDALType a\n => (b -> Pair Int -> Value a -> b)\n -> b -> Band s a t -> Envelope Int -> GDAL s b\nifoldlWindow' f z band (Envelope (x0 :+: y0) (x1 :+: y1)) = runConduit $\n allBlocks band =$= CL.filter inRange\n =$= decorate (unsafeBlockConduit band)\n =$= CL.fold folder z\n where\n inRange bIx = bx0 < x1 && x0 < bx1 && by0 < y1 && y0 < by1\n where\n !b0@(bx0 :+: by0) = bIx * bSize\n !(bx1 :+: by1) = b0 + bSize\n !(mx :+: my) = liftA2 mod (bandSize band) (bandBlockSize band)\n !(nx :+: ny) = bandBlockCount band\n !bSize@(sx :+: sy) = bandBlockSize band\n {-# INLINE folder #-}\n folder !acc !(!(iB :+: jB), !vec) = go SPEC 0 0 acc\n where\n go !_ !i !j !acc'\n | i < stopx = go SPEC (i+1) j acc''\n | j+1 < stopy = go SPEC 0 (j+1) acc'\n | otherwise = acc'\n where\n !ix@(ixx :+: ixy) = iB*sx+i :+: jB*sy+j\n acc''\n | x0 <= ixx && ixx < x1 && y0 <= ixy && ixy < y1\n = f acc' ix (vec `G.unsafeIndex` (j*sx+i))\n | otherwise = acc'\n !stopx\n | mx \/= 0 && iB==nx-1 = mx\n | otherwise = sx\n !stopy\n | my \/= 0 && jB==ny-1 = my\n | otherwise = sy\n{-# INLINE ifoldlWindow' #-}\n\nunsafeBlockSource\n :: GDALType a\n => Band s a t -> Source (GDAL s) (BlockIx, U.Vector (Value a))\nunsafeBlockSource band = allBlocks band =$= decorate (unsafeBlockConduit band)\n{-# INLINE unsafeBlockSource #-}\n\nblockSource\n :: GDALType a\n => Band s a t -> Source (GDAL s) (BlockIx, U.Vector (Value a))\nblockSource band = allBlocks band =$= decorate (blockConduit band)\n{-# INLINE blockSource #-}\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> BlockIx -> U.Vector (Value a) -> GDAL s ()\nwriteBandBlock band blockIx uvec =\n runConduit (yield (blockIx, uvec) =$= blockSink band)\n{-# INLINE writeBandBlock #-}\n\nfmapBand\n :: forall s a b t. (GDALType a, GDALType b)\n => (Value a -> Value b)\n -> Band s a t\n -> RWBand s b \n -> GDAL s ()\nfmapBand f src dst\n | bandSize src \/= bandSize dst\n = throwBindingException (InvalidRasterSize (bandSize src))\n | bandBlockSize src \/= bandBlockSize dst\n = throwBindingException notImplementedErr\n | otherwise = runConduit\n (unsafeBlockSource src =$= CL.map (second (U.map f)) =$= blockSink dst)\n where\n notImplementedErr = NotImplemented\n \"fmapBand: Not implemented for bands of different block size\"\n{-# INLINE fmapBand #-}\n\n\nblockSink\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (BlockIx, U.Vector (Value a)) (GDAL s) ()\nblockSink band = do\n writeBlock <-\n if dtBand==dtBuf\n then return writeNative\n else do tempBuf <- liftIO (mallocForeignPtrBytes (len*szBand))\n return (writeTranslated tempBuf)\n lift (bandMaskType band) >>= \\case\n MaskNoData -> lift (noDataOrFail band) >>= sinkNodata writeBlock\n MaskAllValid -> sinkAllValid writeBlock\n _ -> lift (bandMask band) >>= sinkMask writeBlock\n\n where\n len = bandBlockLen band\n dtBand = bandDataType (band)\n szBand = sizeOfDataType dtBand\n dtBuf = hsDataType (Proxy :: Proxy a)\n szBuf = sizeOfDataType dtBuf\n\n sinkNodata writeBlock nd = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n St.unsafeWith (toGVecWithNodata nd vec) (writeBlock ix)\n\n\n sinkAllValid writeBlock = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n case toGVec vec of\n Just buf -> St.unsafeWith buf (writeBlock ix)\n Nothing -> throwBindingException BandDoesNotAllowNoData\n\n sinkMask writeBlock bMask = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n let (mask, vec') = toGVecWithMask vec\n off = bi * bs\n win = liftA2 min bs (rs - off)\n bi = fmap fromIntegral ix\n bs = fmap fromIntegral (bandBlockSize band)\n rs = fmap fromIntegral (bandSize band)\n St.unsafeWith vec' (writeBlock ix)\n St.unsafeWith mask $ \\pBuf ->\n checkCPLError \"WriteBlock\" $\n {#call RasterIO as ^#}\n (unBand bMask)\n (fromEnumC GF_Write)\n (pFst off)\n (pSnd off)\n (pFst win)\n (pSnd win)\n (castPtr pBuf)\n (pFst win)\n (pSnd win)\n (fromEnumC GByte)\n 0\n (pFst bs * fromIntegral (sizeOfDataType GByte))\n\n checkLen v\n | len \/= G.length v\n = throwBindingException (InvalidBlockSize (G.length v))\n | otherwise = return ()\n\n writeTranslated temp blockIx pBuf =\n withForeignPtr temp $ \\pTemp -> do\n {#call unsafe CopyWords as ^#}\n (castPtr pTemp)\n (fromEnumC dtBand)\n (fromIntegral szBand)\n (castPtr pBuf)\n (fromEnumC dtBuf)\n (fromIntegral szBuf)\n (fromIntegral len)\n writeNative blockIx pTemp\n\n writeNative blockIx pBuf =\n checkCPLError \"WriteBlock\" $\n {#call GDALWriteBlock as ^#}\n (unBand band)\n (pFst bi)\n (pSnd bi)\n (castPtr pBuf)\n where bi = fmap fromIntegral blockIx\n{-# INLINE blockSink #-}\n\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s a t -> BlockIx -> GDAL s (U.Vector (Value a))\nreadBandBlock band blockIx = liftM fromJust $ runConduit $\n yield blockIx =$= unsafeBlockConduit band =$= CL.head\n{-# INLINE readBandBlock #-}\n\n\nallBlocks :: Monad m => Band s a t -> Producer m BlockIx\nallBlocks band = CL.sourceList [x :+: y | y <- [0..ny-1], x <- [0..nx-1]]\n where\n !(nx :+: ny) = bandBlockCount band\n{-# INLINE allBlocks #-}\n\nblockConduit\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (U.Vector (Value a))\nblockConduit band =\n unsafeBlockConduitM band =$= CL.mapM (liftIO . U.freeze)\n{-# INLINE blockConduit #-}\n\nunsafeBlockConduit\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (U.Vector (Value a))\nunsafeBlockConduit band =\n unsafeBlockConduitM band =$= CL.mapM (liftIO . U.unsafeFreeze)\n{-# INLINE unsafeBlockConduit #-}\n\n\nunsafeBlockConduitM\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (UM.IOVector (Value a))\nunsafeBlockConduitM band = do\n buf <- liftIO (M.new len)\n maskType <- lift $ bandMaskType band\n case maskType of\n MaskNoData -> do\n noData <- lift $ noDataOrFail band\n blockReader (mkValueUMVector noData buf) buf (const (return ()))\n MaskAllValid ->\n blockReader (mkAllValidValueUMVector buf) buf (const (return ()))\n _ -> do\n mBuf <- liftIO $ M.replicate len 0\n mask <- lift $ bandMask band\n blockReader (mkMaskedValueUMVector mBuf buf) buf (readMask mask mBuf)\n where\n isNative = dtBand == dtBuf\n len = bandBlockLen band\n dtBand = bandDataType band\n dtBuf = hsDataType (Proxy :: Proxy a)\n\n {-# INLINE blockReader #-}\n blockReader vec buf extra\n | isNative = awaitForever $ \\ix -> do\n liftIO (Stm.unsafeWith buf (loadBlock ix))\n extra ix\n yield vec\n | otherwise = do\n temp <- liftIO $ mallocForeignPtrBytes (len*szBand)\n awaitForever $ \\ix -> do\n liftIO $ withForeignPtr temp $ \\pTemp -> do\n loadBlock ix pTemp\n Stm.unsafeWith buf (translateBlock pTemp)\n extra ix\n yield vec\n\n {-# INLINE loadBlock #-}\n loadBlock ix pBuf = \n checkCPLError \"ReadBlock\" $\n {#call ReadBlock as ^#}\n (unBand band)\n (fromIntegral (pFst ix))\n (fromIntegral (pSnd ix))\n (castPtr pBuf)\n\n {-# INLINE translateBlock #-}\n translateBlock pTemp pBuf = \n {#call unsafe CopyWords as ^#}\n (castPtr pTemp)\n (fromEnumC dtBand)\n (fromIntegral szBand)\n (castPtr pBuf)\n (fromEnumC dtBuf)\n (fromIntegral szBuf)\n (fromIntegral len)\n szBand = sizeOfDataType dtBand\n szBuf = sizeOfDataType dtBuf\n\n {-# INLINE readMask #-}\n readMask mask vMask ix =\n liftIO $\n Stm.unsafeWith vMask $ \\pMask ->\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand mask)\n (fromEnumC GF_Read)\n (pFst off)\n (pSnd off)\n (pFst win)\n (pSnd win)\n (castPtr pMask)\n (pFst win)\n (pSnd win)\n (fromEnumC GByte)\n 0\n (pFst bs)\n where\n bi = fmap fromIntegral ix\n off = bi * bs\n win = liftA2 min bs (rs - off)\n bs = fmap fromIntegral (bandBlockSize band)\n rs = fmap fromIntegral (bandSize band)\n{-# INLINE unsafeBlockConduitM #-}\n\nopenDatasetCount :: IO Int\nopenDatasetCount =\n alloca $ \\ppDs ->\n alloca $ \\pCount -> do\n {#call unsafe GetOpenDatasets as ^#} ppDs pCount\n liftM fromIntegral (peek pCount)\n\n-----------------------------------------------------------------------------\n-- Metadata\n-----------------------------------------------------------------------------\n\nmetadataDomains :: MajorObject o t => o t -> GDAL s [Text]\n#if SUPPORTS_METADATA_DOMAINS\nmetadataDomains o =\n liftIO $\n fromCPLStringList $\n {#call unsafe GetMetadataDomainList as ^#} (majorObject o)\n#else\nmetadataDomains = const (return [])\n#endif\n\nmetadata\n :: MajorObject o t\n => Maybe ByteString -> o t -> GDAL s [(Text,Text)]\nmetadata domain o =\n liftIO $\n withMaybeByteString domain\n ({#call unsafe GetMetadata as ^#} (majorObject o)\n >=> liftM (map breakIt) . fromBorrowedCPLStringList)\n where\n breakIt s =\n case T.break (=='=') s of\n (k,\"\") -> (k,\"\")\n (k, v) -> (k, T.tail v)\n\nmetadataItem\n :: MajorObject o t\n => Maybe ByteString -> ByteString -> o t -> GDAL s (Maybe ByteString)\nmetadataItem domain key o =\n liftIO $\n useAsCString key $ \\pKey ->\n withMaybeByteString domain $\n {#call unsafe GetMetadataItem as ^#} (majorObject o) pKey >=>\n maybePackCString\n\nsetMetadataItem\n :: (MajorObject o t, t ~ ReadWrite)\n => Maybe ByteString -> ByteString -> ByteString -> o t -> GDAL s ()\nsetMetadataItem domain key val o =\n liftIO $\n checkCPLError \"setMetadataItem\" $\n useAsCString key $ \\pKey ->\n useAsCString val $ \\pVal ->\n withMaybeByteString domain $\n {#call unsafe GDALSetMetadataItem as ^#} (majorObject o) pKey pVal\n\ndescription :: MajorObject o t => o t -> GDAL s ByteString\ndescription =\n liftIO . ({#call unsafe GetDescription as ^#} . majorObject >=> packCString)\n\nsetDescription\n :: (MajorObject o t, t ~ ReadWrite)\n => ByteString -> o t -> GDAL s ()\nsetDescription val =\n liftIO . checkGDALCall_ const .\n useAsCString val . {#call unsafe GDALSetDescription as ^#} . majorObject\n\n\n\n-----------------------------------------------------------------------------\n-- Conduit utils\n-----------------------------------------------------------------------------\n\n-- | Parallel zip of two conduits\npZipConduitApp\n :: Monad m\n => Conduit a m (b -> c)\n -> Conduit a m b\n -> Conduit a m c\npZipConduitApp (ConduitM l0) (ConduitM r0) = ConduitM $ \\rest -> let\n go (HaveOutput p c o) (HaveOutput p' c' o') =\n HaveOutput (go p p') (c>>c') (o o')\n go (NeedInput p c) (NeedInput p' c') =\n NeedInput (\\i -> go (p i) (p' i)) (\\u -> go (c u) (c' u))\n go (Done ()) (Done ()) = rest ()\n go (PipeM m) (PipeM m') = PipeM (liftM2 go m m')\n go (Leftover p i) (Leftover p' _) = Leftover (go p p') i\n go _ _ = error \"pZipConduitApp: not parallel\"\n in go (injectLeftovers $ l0 Done) (injectLeftovers $ r0 Done)\n\nnewtype PZipConduit i m o =\n PZipConduit { getPZipConduit :: Conduit i m o}\n\ninstance Monad m => Functor (PZipConduit i m) where\n fmap f = PZipConduit . mapOutput f . getPZipConduit\n\ninstance Monad m => Applicative (PZipConduit i m) where\n pure = PZipConduit . forever . yield\n PZipConduit l <*> PZipConduit r = PZipConduit (pZipConduitApp l r)\n\nzipBlocks\n :: GDALType a\n => Band s a t -> PZipConduit BlockIx (GDAL s) (U.Vector (Value a))\nzipBlocks = PZipConduit . unsafeBlockConduit\n\ngetZipBlocks\n :: PZipConduit BlockIx (GDAL s) a\n -> Conduit BlockIx (GDAL s) (BlockIx, a)\ngetZipBlocks = decorate . getPZipConduit\n\ndecorate :: Monad m => Conduit a m b -> Conduit a m (a, b)\ndecorate (ConduitM c0) = ConduitM $ \\rest -> let\n go1 HaveOutput{} = error \"unexpected NeedOutput\"\n go1 (NeedInput p c) = NeedInput (\\i -> go2 i (p i)) (go1 . c)\n go1 (Done r) = rest r\n go1 (PipeM mp) = PipeM (liftM (go1) mp)\n go1 (Leftover p i) = Leftover (go1 p) i\n\n go2 i (HaveOutput p c o) = HaveOutput (go2 i p) c (i, o)\n go2 _ (NeedInput p c) = NeedInput (\\i -> go2 i (p i)) (go1 . c)\n go2 _ (Done r) = rest r\n go2 i (PipeM mp) = PipeM (liftM (go2 i) mp)\n go2 i (Leftover p i') = Leftover (go2 i p) i'\n in go1 (c0 Done)\n{-# INLINE decorate #-}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"2c09c2396f849e61f08b3f0a8490aa256c957d0e","subject":"Unhide CSize (unnecessary)","message":"Unhide CSize (unnecessary)\n","repos":"AaronFriel\/hyhac,AaronFriel\/hyhac,AaronFriel\/hyhac","old_file":"src\/Database\/HyperDex\/Internal\/Hyperclient.chs","new_file":"src\/Database\/HyperDex\/Internal\/Hyperclient.chs","new_contents":"module Database.HyperDex.Internal.Hyperclient where\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.Marshal.Utils\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Data.Int\n\nimport Control.Applicative ((<$>))\n\n#import \"hyperclient.h\"\n\ndata Hyperclient\n{#pointer *hyperclient as HyperclientPtr -> Hyperclient #}\n\ndata HyperclientAttribute\n{#pointer *hyperclient_attribute as HyperclientAttributePtr -> HyperclientAttribute #}\n\ndata HyperclientMapAttribute\n{#pointer *hyperclient_map_attribute as HyperclientMapAttributePtr -> HyperclientMapAttribute #}\n\ndata HyperclientAttributeCheck\n{#pointer *hyperclient_attribute_check as HyperclientAttributeCheckPtr -> HyperclientAttributeCheck #}\n\n{#enum hyperclient_returncode as HyperclientReturnCode {underscoreToCase} deriving (Eq, Show) #}\n\n-- struct hyperclient*\n-- hyperclient_create(const char* coordinator, uint16_t port);\nhyperclientCreate :: String -> Int16 -> IO HyperclientPtr\nhyperclientCreate host port = do\n inHost <- newCString host\n {# call hyperclient_create #} inHost (fromIntegral port)\n\n-- void\n-- hyperclient_destroy(struct hyperclient* client);\nhyperclientDestroy :: HyperclientPtr -> IO ()\nhyperclientDestroy client = {# call hyperclient_destroy #} client\n\n-- enum hyperclient_returncode\n-- hyperclient_add_space(struct hyperclient* client, const char* description);\nhyperclientAddSpace :: HyperclientPtr -> String -> IO HyperclientReturnCode\nhyperclientAddSpace client description = do\n inDescription <- newCString description\n toEnum . fromIntegral <$>\n {#call hyperclient_add_space #} client inDescription\n\n-- enum hyperclient_returncode\n-- hyperclient_rm_space(struct hyperclient* client, const char* space);\nhyperclientRemoveSpace :: HyperclientPtr -> String -> IO HyperclientReturnCode\nhyperclientRemoveSpace client space = do\n inSpace <- newCString space\n toEnum . fromIntegral <$>\n {#call hyperclient_rm_space #} client inSpace\n\n-- int64_t\n-- hyperclient_put(struct hyperclient* client, const char* space, const char* key,\n-- size_t key_sz, const struct hyperclient_attribute* attrs,\n-- size_t attrs_sz, enum hyperclient_returncode* status);\nhyperclientGet :: HyperclientPtr -> String -> String -> IO (Int64, HyperclientReturnCode, HyperclientAttributePtr, Int64) \nhyperclientGet client space key = do\n returnCodePtr <- malloc \n attributePtrPtr <- malloc \n attributeSizePtr <- malloc\n (inSpace) <- newCString space\n (inKey, inKeySize) <- newCStringLen key\n result <- {#call hyperclient_get#} \n client\n inSpace inKey (fromIntegral inKeySize)\n returnCodePtr attributePtrPtr attributeSizePtr\n returnCode <- toEnum . fromIntegral <$> peek returnCodePtr :: IO HyperclientReturnCode\n attributePtr <- peek attributePtrPtr\n attributeSize <- fromIntegral <$> peek attributeSizePtr :: IO Int64\n return (fromIntegral result, returnCode, attributePtr, attributeSize)\n\n-- int64_t\n-- hyperclient_put(struct hyperclient* client, const char* space, const char* key,\n-- size_t key_sz, const struct hyperclient_attribute* attrs,\n-- size_t attrs_sz, enum hyperclient_returncode* status);\nhyperclientPut :: HyperclientPtr -> String -> String -> HyperclientAttributePtr -> Int64 -> IO (Int64, HyperclientReturnCode)\nhyperclientPut client space key attributes attributeSize = do\n returnCodePtr <- malloc\n (inSpace) <- newCString space\n (inKey, inKeySize) <- newCStringLen key\n result <- {# call hyperclient_put #} \n client\n inSpace inKey (fromIntegral inKeySize)\n attributes (fromIntegral attributeSize) returnCodePtr\n returnCode <- toEnum . fromIntegral <$> peek returnCodePtr :: IO HyperclientReturnCode\n return (fromIntegral result, returnCode)\n\n-- int64_t\n-- hyperclient_put_if_not_exist(struct hyperclient* client, const char* space, const char* key,\n-- size_t key_sz, const struct hyperclient_attribute* attrs,\n-- size_t attrs_sz, enum hyperclient_returncode* status);\nhyperclientPutIfNotExist :: HyperclientPtr -> String -> String -> HyperclientAttributePtr -> Int64 -> IO (Int64, HyperclientReturnCode)\nhyperclientPutIfNotExist client space key attributes attributeSize = do\n returnCodePtr <- malloc\n (inSpace) <- newCString space\n (inKey, inKeySize) <- newCStringLen key\n result <- {# call hyperclient_put_if_not_exist #} \n client\n inSpace inKey (fromIntegral inKeySize)\n attributes (fromIntegral attributeSize) returnCodePtr\n returnCode <- toEnum . fromIntegral <$> peek returnCodePtr :: IO HyperclientReturnCode\n return (fromIntegral result, returnCode)\n\n-- int64_t\n-- hyperclient_del(struct hyperclient* client, const char* space, const char* key,\n-- size_t key_sz, enum hyperclient_returncode* status);\nhyperclientDelete :: HyperclientPtr -> String -> String -> IO (Int64, HyperclientReturnCode)\nhyperclientDelete client space key = do\n returnCodePtr <- malloc\n (inSpace) <- newCString space\n (inKey, inKeySize) <- newCStringLen key\n result <- {# call hyperclient_del #} \n client\n inSpace inKey (fromIntegral inKeySize)\n returnCodePtr\n returnCode <- toEnum . fromIntegral <$> peek returnCodePtr :: IO HyperclientReturnCode\n return (fromIntegral result, returnCode)\n","old_contents":"module Database.HyperDex.Internal.Hyperclient where\n\nimport Foreign.C.Types hiding (CSize)\nimport Foreign.C.String\nimport Foreign.Marshal.Utils\nimport Foreign.Marshal.Alloc\nimport Foreign.Ptr\nimport Foreign.Storable\nimport Data.Int\n\nimport Control.Applicative ((<$>))\n\ntype CSize = CULong\n\n#import \"hyperclient.h\"\n\ndata Hyperclient\n{#pointer *hyperclient as HyperclientPtr -> Hyperclient #}\n\ndata HyperclientAttribute\n{#pointer *hyperclient_attribute as HyperclientAttributePtr -> HyperclientAttribute #}\n\ndata HyperclientMapAttribute\n{#pointer *hyperclient_map_attribute as HyperclientMapAttributePtr -> HyperclientMapAttribute #}\n\ndata HyperclientAttributeCheck\n{#pointer *hyperclient_attribute_check as HyperclientAttributeCheckPtr -> HyperclientAttributeCheck #}\n\n{#enum hyperclient_returncode as HyperclientReturnCode {underscoreToCase} deriving (Eq, Show) #}\n\n-- struct hyperclient*\n-- hyperclient_create(const char* coordinator, uint16_t port);\nhyperclientCreate :: String -> Int16 -> IO HyperclientPtr\nhyperclientCreate host port = do\n inHost <- newCString host\n {# call hyperclient_create #} inHost (fromIntegral port)\n\n-- void\n-- hyperclient_destroy(struct hyperclient* client);\nhyperclientDestroy :: HyperclientPtr -> IO ()\nhyperclientDestroy client = {# call hyperclient_destroy #} client\n\n-- enum hyperclient_returncode\n-- hyperclient_add_space(struct hyperclient* client, const char* description);\nhyperclientAddSpace :: HyperclientPtr -> String -> IO HyperclientReturnCode\nhyperclientAddSpace client description = do\n inDescription <- newCString description\n toEnum . fromIntegral <$>\n {#call hyperclient_add_space #} client inDescription\n\n-- enum hyperclient_returncode\n-- hyperclient_rm_space(struct hyperclient* client, const char* space);\nhyperclientRemoveSpace :: HyperclientPtr -> String -> IO HyperclientReturnCode\nhyperclientRemoveSpace client space = do\n inSpace <- newCString space\n toEnum . fromIntegral <$>\n {#call hyperclient_rm_space #} client inSpace\n\n-- int64_t\n-- hyperclient_put(struct hyperclient* client, const char* space, const char* key,\n-- size_t key_sz, const struct hyperclient_attribute* attrs,\n-- size_t attrs_sz, enum hyperclient_returncode* status);\nhyperclientGet :: HyperclientPtr -> String -> String -> IO (Int64, HyperclientReturnCode, HyperclientAttributePtr, Int64) \nhyperclientGet client space key = do\n returnCodePtr <- malloc \n attributePtrPtr <- malloc \n attributeSizePtr <- malloc\n (inSpace) <- newCString space\n (inKey, inKeySize) <- newCStringLen key\n result <- {#call hyperclient_get#} \n client\n inSpace inKey (fromIntegral inKeySize)\n returnCodePtr attributePtrPtr attributeSizePtr\n returnCode <- toEnum . fromIntegral <$> peek returnCodePtr :: IO HyperclientReturnCode\n attributePtr <- peek attributePtrPtr\n attributeSize <- fromIntegral <$> peek attributeSizePtr :: IO Int64\n return (fromIntegral result, returnCode, attributePtr, attributeSize)\n\n-- int64_t\n-- hyperclient_put(struct hyperclient* client, const char* space, const char* key,\n-- size_t key_sz, const struct hyperclient_attribute* attrs,\n-- size_t attrs_sz, enum hyperclient_returncode* status);\nhyperclientPut :: HyperclientPtr -> String -> String -> HyperclientAttributePtr -> Int64 -> IO (Int64, HyperclientReturnCode)\nhyperclientPut client space key attributes attributeSize = do\n returnCodePtr <- malloc\n (inSpace) <- newCString space\n (inKey, inKeySize) <- newCStringLen key\n result <- {# call hyperclient_put #} \n client\n inSpace inKey (fromIntegral inKeySize)\n attributes (fromIntegral attributeSize) returnCodePtr\n returnCode <- toEnum . fromIntegral <$> peek returnCodePtr :: IO HyperclientReturnCode\n return (fromIntegral result, returnCode)\n\n-- int64_t\n-- hyperclient_put_if_not_exist(struct hyperclient* client, const char* space, const char* key,\n-- size_t key_sz, const struct hyperclient_attribute* attrs,\n-- size_t attrs_sz, enum hyperclient_returncode* status);\nhyperclientPutIfNotExist :: HyperclientPtr -> String -> String -> HyperclientAttributePtr -> Int64 -> IO (Int64, HyperclientReturnCode)\nhyperclientPutIfNotExist client space key attributes attributeSize = do\n returnCodePtr <- malloc\n (inSpace) <- newCString space\n (inKey, inKeySize) <- newCStringLen key\n result <- {# call hyperclient_put_if_not_exist #} \n client\n inSpace inKey (fromIntegral inKeySize)\n attributes (fromIntegral attributeSize) returnCodePtr\n returnCode <- toEnum . fromIntegral <$> peek returnCodePtr :: IO HyperclientReturnCode\n return (fromIntegral result, returnCode)\n\n-- int64_t\n-- hyperclient_del(struct hyperclient* client, const char* space, const char* key,\n-- size_t key_sz, enum hyperclient_returncode* status);\nhyperclientDelete :: HyperclientPtr -> String -> String -> IO (Int64, HyperclientReturnCode)\nhyperclientDelete client space key = do\n returnCodePtr <- malloc\n (inSpace) <- newCString space\n (inKey, inKeySize) <- newCStringLen key\n result <- {# call hyperclient_del #} \n client\n inSpace inKey (fromIntegral inKeySize)\n returnCodePtr\n returnCode <- toEnum . fromIntegral <$> peek returnCodePtr :: IO HyperclientReturnCode\n return (fromIntegral result, returnCode)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"bbc372a68fd4c7660ebb0a4b26898dece2b8e3d8","subject":"Pass a copy of the icon image since it is freed in the Fl_Window destructor.","message":"Pass a copy of the icon image since it is freed in the Fl_Window destructor.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Base\/Window.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Base\/Window.chs","new_contents":"{-# LANGUAGE CPP, UndecidableInstances, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ExistentialQuantification #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Base.Window\n (\n CustomWindowFuncs(..),\n OptionalSizeRangeArgs(..),\n PositionSpec(..),\n WindowType(..),\n defaultCustomWindowFuncs,\n fillCustomWidgetFunctionStruct,\n defaultOptionalSizeRangeArgs,\n windowCustom,\n windowNew,\n windowMaker,\n currentWindow\n , handleWindowBase\n , resizeWindowBase\n , hideWindowBase\n , showWidgetWindowBase\n , flushWindowBase\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Functions\n --\n -- $functions\n )\nwhere\n#include \"Fl_C.h\"\n#include \"Fl_WindowC.h\"\n#include \"Fl_WidgetC.h\"\n#include \"Fl_GroupC.h\"\nimport Foreign\nimport Foreign.C\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\nimport Graphics.UI.FLTK.LowLevel.Base.Widget\nimport Graphics.UI.FLTK.LowLevel.RGBImage()\nimport Control.Exception(throwIO)\nimport System.IO.Error(userError)\n\n#c\n enum WindowType {\n SingleWindowType = FL_WINDOWC,\n DoubleWindowType = FL_DOUBLE_WINDOWC\n};\n#endc\n{#enum WindowType {} deriving (Show, Eq) #}\n\ndata PositionSpec = ByPosition Position\n | forall a. (Parent a WidgetBase) => ByWidget (Ref a)\n\ndata CustomWindowFuncs a =\n CustomWindowFuncs {\n flushCustom :: Maybe (Ref a -> IO ())\n }\n\ndata OptionalSizeRangeArgs = OptionalSizeRangeArgs {\n maxw :: Maybe Int,\n maxh :: Maybe Int,\n dw :: Maybe Int,\n dh :: Maybe Int,\n aspect :: Maybe Bool\n }\n\noptionalSizeRangeArgsToStruct :: OptionalSizeRangeArgs -> IO (Ptr ())\noptionalSizeRangeArgsToStruct args = do\n p <- mallocBytes {#sizeof fl_Window_size_range_args #}\n {#set fl_Window_size_range_args->maxw #} p $ maybe 0 fromIntegral (maxw args)\n {#set fl_Window_size_range_args->maxh #} p $ maybe 0 fromIntegral (maxh args)\n {#set fl_Window_size_range_args->dw #} p $ maybe 0 fromIntegral (dw args)\n {#set fl_Window_size_range_args->dh #} p $ maybe 0 fromIntegral (dh args)\n {#set fl_Window_size_range_args->aspect #} p $ maybe 0 fromBool (aspect args)\n return p\n\ndefaultOptionalSizeRangeArgs :: OptionalSizeRangeArgs\ndefaultOptionalSizeRangeArgs = OptionalSizeRangeArgs Nothing Nothing Nothing Nothing Nothing\n\nfillCustomWindowFunctionStruct :: forall a. (Parent a WindowBase) =>\n Ptr () ->\n CustomWindowFuncs a ->\n IO ()\nfillCustomWindowFunctionStruct structPtr (CustomWindowFuncs _flush') =\n toCallbackPrim `orNullFunPtr` _flush' >>= {#set fl_Window_Virtual_Funcs->flush#} structPtr\n\ndefaultCustomWindowFuncs :: forall a. (Parent a WindowBase) => CustomWindowFuncs a\ndefaultCustomWindowFuncs = CustomWindowFuncs Nothing\n\n{# fun Fl_Window_default_virtual_funcs as virtualFuncs' {} -> `Ptr ()' id #}\nwindowMaker :: forall a b. (Parent a WindowBase, Parent b WidgetBase) =>\n Size ->\n Maybe Position ->\n Maybe T.Text ->\n Maybe (Ref b -> IO ()) ->\n CustomWidgetFuncs b ->\n CustomWindowFuncs a ->\n (Int -> Int -> Ptr () -> IO (Ptr ())) ->\n (Int -> Int -> CString -> Ptr () -> IO (Ptr ())) ->\n (Int -> Int -> Int -> Int -> Ptr () -> IO (Ptr ())) ->\n (Int -> Int -> Int -> Int -> CString -> Ptr () -> IO (Ptr ())) ->\n IO (Ref a)\nwindowMaker (Size (Width w) (Height h))\n position\n title\n draw'\n customWidgetFuncs'\n customWindowFuncs'\n custom'\n customWithLabel'\n customXY'\n customXYWithLabel' =\n do\n p <- virtualFuncs'\n fillCustomWidgetFunctionStruct p draw' customWidgetFuncs'\n fillCustomWindowFunctionStruct p customWindowFuncs'\n ref <- case (position, title) of\n (Nothing, Nothing) -> custom' w h p >>= toRef\n (Just (Position (X x) (Y y)), Nothing) -> customXY' x y w h p >>= toRef\n (Just (Position (X x) (Y y)), (Just l')) -> copyTextToCString l' >>= \\l'' -> customXYWithLabel' x y w h l'' p >>= toRef\n (Nothing, (Just l')) -> copyTextToCString l' >>= \\l'' -> customWithLabel' w h l'' p >>= toRef\n setFlag (safeCast ref :: Ref WindowBase) WidgetFlagCopiedLabel\n setFlag (safeCast ref :: Ref WindowBase) WidgetFlagCopiedTooltip\n return ref\n\n{# fun Fl_OverriddenWindow_New as overriddenWindowNew' {`Int',`Int', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenWindow_NewXY as overriddenWindowNewXY' {`Int',`Int', `Int', `Int', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenWindow_NewXY_WithLabel as overriddenWindowNewXYWithLabel' { `Int',`Int',`Int',`Int',`CString', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenWindow_New_WithLabel as overriddenWindowNewWithLabel' { `Int',`Int', `CString', id `Ptr ()'} -> `Ptr ()' id #}\nwindowCustom :: Size -- ^ Size of this window\n -> Maybe Position -- ^ Optional position of this window\n -> Maybe T.Text -- ^ Optional label\n -> Maybe (Ref Window -> IO ()) -- ^ Optional table drawing routine\n -> CustomWidgetFuncs Window -- ^ Custom widget overrides\n -> CustomWindowFuncs Window -- ^ Custom window overrides\n -> IO (Ref Window)\nwindowCustom size position title draw' customWidgetFuncs' customWindowFuncs' =\n windowMaker\n size\n position\n title\n draw'\n customWidgetFuncs'\n customWindowFuncs'\n overriddenWindowNew'\n overriddenWindowNewWithLabel'\n overriddenWindowNewXY'\n overriddenWindowNewXYWithLabel'\n\nwindowNew :: Size -> Maybe Position -> Maybe T.Text -> IO (Ref Window)\nwindowNew size position title =\n windowMaker\n size\n position\n title\n Nothing\n (defaultCustomWidgetFuncs :: CustomWidgetFuncs Window)\n (defaultCustomWindowFuncs :: CustomWindowFuncs Window)\n overriddenWindowNew'\n overriddenWindowNewWithLabel'\n overriddenWindowNewXY'\n overriddenWindowNewXYWithLabel'\n\n{# fun Fl_Window_Destroy as windowDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Destroy ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> windowDestroy' winPtr\n\n{# fun Fl_Window_set_callback as windowSetCallback' {id `Ptr ()' , id `FunPtr CallbackWithUserDataPrim'} -> `FunPtr CallbackWithUserDataPrim' id #}\ninstance (impl ~ ((Ref orig -> IO ()) -> IO ())) => Op (SetCallback ()) WindowBase orig impl where\n runOp _ _ window callback =\n withRef window $ (\\p -> do\n callbackPtr <- toCallbackPrimWithUserData callback\n oldCb <- windowSetCallback' (castPtr p) callbackPtr\n if (oldCb == nullFunPtr)\n then return ()\n else freeHaskellFunPtr oldCb)\n\n{# fun Fl_Window_changed as changed' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ ( IO (Bool))) => Op (Changed ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> changed' winPtr\n\n{# fun Fl_Window_fullscreen as fullscreen' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (MakeFullscreen ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> fullscreen' winPtr\n\n{# fun Fl_Window_fullscreen_off as fullscreenOff' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_fullscreen_off_with_resize as fullscreenOffWithResize' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Maybe Rectangle -> IO ())) => Op (FullscreenOff ()) WindowBase orig impl where\n runOp _ _ win (Just rectangle) =\n withRef win $ \\winPtr ->\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in fullscreenOffWithResize' winPtr x_pos y_pos width height\n runOp _ _ win Nothing =\n withRef win $ \\winPtr -> fullscreenOff' winPtr\n\n{# fun Fl_Window_set_border as setBorder' { id `Ptr ()', fromBool `Bool' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Bool -> IO ())) => Op (SetBorder ()) WindowBase orig impl where\n runOp _ _ win b = withRef win $ \\winPtr -> setBorder' winPtr b\n\n{# fun Fl_Window_clear_border as clearBorder' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (ClearBorder ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> clearBorder' winPtr\n\n{# fun Fl_Window_border as border' { id `Ptr ()' } -> `Bool' toBool#}\ninstance (impl ~ ( IO (Bool))) => Op (GetBorder ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> border' winPtr\n\n{# fun Fl_Window_set_override as setOverride' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (SetOverride ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> setOverride' winPtr\n\n{# fun Fl_Window_override as override' { id `Ptr ()' } -> `Bool' toBool #}\ninstance (impl ~ ( IO (Bool))) => Op (GetOverride ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> override' winPtr\n\n{# fun Fl_Window_set_modal as setModal' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (SetModal ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> setModal' winPtr\n\n{# fun Fl_Window_modal as modal' { id `Ptr ()' } -> `Bool' toBool #}\ninstance (impl ~ ( IO (Bool))) => Op (GetModal ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> modal' winPtr\n\n{# fun Fl_Window_set_non_modal as setNonModal' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (SetNonModal ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> setNonModal' winPtr\n\n{# fun Fl_Window_non_modal as nonModal' { id `Ptr ()' } -> `Bool' toBool #}\ninstance (impl ~ ( IO (Bool))) => Op (NonModal ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> nonModal' winPtr\n\n{# fun Fl_Window_set_menu_window as setMenuWindow' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (SetMenuWindow ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> setMenuWindow' winPtr\n\n{# fun Fl_Window_menu_window as menuWindow' { id `Ptr ()' } -> `Bool' toBool #}\ninstance (impl ~ ( IO (Bool))) => Op (GetMenuWindow ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> menuWindow' winPtr\n\n{# fun Fl_Window_set_tooltip_window as setTooltipWindow' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (SetTooltipWindow ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> setTooltipWindow' winPtr\n\n{# fun Fl_Window_tooltip_window as tooltipWindow' { id `Ptr ()' } -> `Bool' toBool #}\ninstance (impl ~ ( IO (Bool))) => Op (GetTooltipWindow ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> tooltipWindow' winPtr\n\n{# fun Fl_Window_hotspot_with_x_y as hotspotWithXY' { id `Ptr ()',`Int',`Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_hotspot_with_x_y_with_offscreen as hotspotWithXYWithOffscreen' { id `Ptr ()',`Int',`Int', fromBool `Bool' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_hotspot_with_widget as hotspotWithWidget' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_hotspot_with_widget_with_offscreen as hotspotWithWidgetWithOffscreen' { id `Ptr ()',id `Ptr ()',fromBool `Bool' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (PositionSpec -> Maybe Bool -> IO ())) => Op (HotSpot ()) WindowBase orig impl where\n runOp _ _ win positionSpec offscreen =\n withRef win $ \\winPtr ->\n case (positionSpec, offscreen) of\n ((ByPosition (Position (X x) (Y y))), (Just offscreen')) ->\n hotspotWithXYWithOffscreen' winPtr x y offscreen'\n ((ByPosition (Position (X x) (Y y))), Nothing) -> hotspotWithXY' winPtr x y\n ((ByWidget templateWidget), (Just offscreen')) ->\n withRef templateWidget $ \\templatePtr ->\n hotspotWithWidgetWithOffscreen' winPtr templatePtr offscreen'\n ((ByWidget templateWidget), Nothing) ->\n withRef templateWidget $ \\templatePtr ->\n hotspotWithWidget' winPtr templatePtr\n{# fun Fl_Window_free_position as freePosition' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (FreePosition ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> freePosition' winPtr\n\n{# fun Fl_Window_size_range as sizeRange' { id `Ptr ()',`Int',`Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_size_range_with_args as sizeRangeWithArgs' { id `Ptr ()',`Int',`Int', id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Size -> IO ())) => Op (SizeRange ()) WindowBase orig impl where\n runOp _ _ win (Size (Width minw') (Height minh')) =\n withRef win $ \\winPtr -> sizeRange' winPtr minw' minh'\ninstance (impl ~ (Size -> OptionalSizeRangeArgs -> IO ())) => Op (SizeRangeWithArgs ()) WindowBase orig impl where\n runOp _ _ win (Size (Width minw') (Height minh')) args =\n withRef win $ \\winPtr -> do\n structPtr <- optionalSizeRangeArgsToStruct args\n sizeRangeWithArgs' winPtr minw' minh' structPtr\n\n{# fun Fl_Window_label as label' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO T.Text)) => Op (GetLabel ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> label' winPtr >>= cStringToText\n\n{# fun Fl_Window_iconlabel as iconlabel' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO T.Text)) => Op (GetIconlabel ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> iconlabel' winPtr >>= cStringToText\n\n{# fun Fl_Window_set_label as setLabel' { id `Ptr ()',`CString' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetLabel ()) WindowBase orig impl where\n runOp _ _ win l' = withRef win $ \\winPtr -> copyTextToCString l' >>= setLabel' winPtr\n\n{# fun Fl_Window_set_iconlabel as setIconlabel' { id `Ptr ()',`CString' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetIconlabel ()) WindowBase orig impl where\n runOp _ _ win l' = withRef win $ \\winPtr -> copyTextToCString l' >>= setIconlabel' winPtr\n\n{# fun Fl_Window_set_label_with_iconlabel as setLabelWithIconlabel' { id `Ptr ()',`CString',`CString' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> T.Text -> IO ())) => Op (SetLabelWithIconlabel ()) WindowBase orig impl where\n runOp _ _ win label iconlabel = withRef win $ \\winPtr -> do\n l' <- copyTextToCString label\n il' <- copyTextToCString iconlabel\n setLabelWithIconlabel' winPtr l' il'\n\n{# fun Fl_Window_copy_label as copyLabel' { id `Ptr ()',`CString' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (CopyLabel ()) WindowBase orig impl where\n runOp _ _ win a = withRef win $ \\winPtr -> withText a (copyLabel' winPtr)\n\n{# fun Fl_Window_xclass as xclass' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO T.Text)) => Op (GetXclass ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> xclass' winPtr >>= cStringToText\n\n{# fun Fl_Window_set_xclass as setXclass' { id `Ptr ()',`CString' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetXclass ()) WindowBase orig impl where\n runOp _ _ win c = withRef win $ \\winPtr -> copyTextToCString c >>= setXclass' winPtr\n\n{# fun Fl_Window_icon as icon' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ ( IO (Maybe (Ref Image)))) => Op (GetIcon ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> icon' winPtr >>= toMaybeRef\n\n{# fun Fl_Window_set_icon as setIcon' { id `Ptr ()', id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a RGBImage, impl ~ (Maybe( Ref a ) -> IO ())) => Op (SetIcon ()) WindowBase orig impl where\n runOp _ _ win rgbM = do\n case rgbM of\n Nothing -> withRef win $ \\winPtr -> setIcon' winPtr (castPtr nullPtr)\n Just rgb -> do\n copyIM <- copy (safeCast rgb :: Ref RGBImage) (Nothing :: Maybe Size)\n case copyIM of\n Just copyI -> withRef win $ \\winPtr -> withRef copyI $ \\iPtr -> setIcon' winPtr iPtr\n Nothing -> throwIO (userError \"Could not make a copy of icon image\")\n\n{# fun Fl_Window_shown as shown' { id `Ptr ()' } -> `Bool' toBool #}\ninstance (impl ~ ( IO (Bool))) => Op (Shown ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> shown' winPtr\n\n{# fun Fl_Window_iconize as iconize' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Iconize ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> iconize' winPtr\n\n{# fun Fl_Window_x_root as xRoot' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (X))) => Op (GetXRoot ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> xRoot' winPtr >>= return . X\n\n{# fun Fl_Window_y_root as yRoot' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Y))) => Op (GetYRoot ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> yRoot' winPtr >>= return . Y\n\n{# fun Fl_Window_current as current' { } -> `Ptr ()' id #}\ncurrentWindow :: (Parent a WindowBase) => IO (Ref a)\ncurrentWindow = current' >>= toRef\n\n{# fun Fl_Window_make_current as makeCurrent' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (MakeCurrent ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> makeCurrent' winPtr\n\n{# fun Fl_Window_set_cursor_with_bg as setCursorWithBg' { id `Ptr ()',cFromEnum `Cursor',cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_set_cursor_with_fg as setCursorWithFg' { id `Ptr ()',cFromEnum `Cursor',cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_set_cursor_with_fg_bg as setCursorWithFgBg' { id `Ptr ()',cFromEnum `Cursor',cFromColor `Color',cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_set_cursor as setCursor' { id `Ptr ()',cFromEnum `Cursor' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Cursor -> IO ())) => Op (SetCursor ()) WindowBase orig impl where\n runOp _ _ win cursor = withRef win $ \\winPtr -> setCursor' winPtr cursor\ninstance (impl ~ (Cursor -> (Maybe Color, Maybe Color) -> IO ())) => Op (SetCursorWithFgBg ()) WindowBase orig impl where\n runOp _ _ win cursor fgbg =\n case fgbg of\n ((Just fg), (Just bg)) -> withRef win $ \\winPtr -> setCursorWithFgBg' winPtr cursor fg bg\n (Nothing , (Just bg)) -> withRef win $ \\winPtr -> setCursorWithBg' winPtr cursor bg\n ((Just fg), Nothing) -> withRef win $ \\winPtr -> setCursorWithFg' winPtr cursor fg\n (Nothing, Nothing) -> withRef win $ \\winPtr -> setCursor' winPtr cursor\n\n{# fun Fl_Window_set_default_cursor_with_bg as setDefaultCursorWithBg' { id `Ptr ()',cFromEnum `CursorType',cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_set_default_cursor_with_fg as setDefaultCursorWithFg' { id `Ptr ()',cFromEnum `CursorType',cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_set_default_cursor_with_fg_bg as setDefaultCursorWithFgBg' { id `Ptr ()',cFromEnum `CursorType',cFromColor `Color',cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_set_default_cursor as setDefaultCursor' { id `Ptr ()',cFromEnum `CursorType' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (CursorType -> IO ())) => Op (SetDefaultCursor ()) WindowBase orig impl where\n runOp _ _ win cursor = withRef win $ \\winPtr -> setDefaultCursor' winPtr cursor\ninstance (impl ~ (CursorType -> (Maybe Color, Maybe Color) -> IO ())) => Op (SetDefaultCursorWithFgBg ()) WindowBase orig impl where\n runOp _ _ win cursor fgbg =\n case fgbg of\n ((Just fg), (Just bg)) -> withRef win $ \\winPtr -> setDefaultCursorWithFgBg' winPtr cursor fg bg\n (Nothing , (Just bg)) -> withRef win $ \\winPtr -> setDefaultCursorWithBg' winPtr cursor bg\n ((Just fg), Nothing) -> withRef win $ \\winPtr -> setDefaultCursorWithFg' winPtr cursor fg\n (Nothing, Nothing) -> withRef win $ \\winPtr -> setDefaultCursor' winPtr cursor\n\n{# fun Fl_Window_decorated_w as decoratedW' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetDecoratedW ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> decoratedW' winPtr\n\n{# fun Fl_Window_decorated_h as decoratedH' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetDecoratedH ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> decoratedH' winPtr\n\n{# fun Fl_Window_draw_box as windowDrawBox' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_draw_box_with_tc as windowDrawBoxWithTC' { id `Ptr ()', cFromEnum `Boxtype', cFromColor`Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_draw_box_with_txywhc as windowDrawBoxWithTXywhC' { id `Ptr ()', cFromEnum `Boxtype', `Int',`Int',`Int',`Int', cFromColor `Color' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (DrawBox ()) WindowBase orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> windowDrawBox' windowPtr\ninstance (impl ~ (Boxtype -> Color -> Maybe Rectangle -> IO ())) => Op (DrawBoxWithBoxtype ()) WindowBase orig impl where\n runOp _ _ window bx c Nothing =\n withRef window $ \\windowPtr -> windowDrawBoxWithTC' windowPtr bx c\n runOp _ _ window bx c (Just r) =\n withRef window $ \\windowPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle r\n windowDrawBoxWithTXywhC' windowPtr bx x_pos y_pos w_pos h_pos c\n{# fun Fl_Window_draw_backdrop as windowDrawBackdrop' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (DrawBackdrop ()) WindowBase orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> windowDrawBackdrop' windowPtr\n\n{# fun Fl_Window_draw_focus as windowDrawFocus' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_draw_focus_with_txywh as windowDrawFocusWithTXywh' { id `Ptr ()', cFromEnum `Boxtype', `Int', `Int', `Int', `Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Maybe (Boxtype, Rectangle) -> IO ())) => Op (DrawFocus ()) WindowBase orig impl where\n runOp _ _ window Nothing =\n withRef window $ \\ windowPtr -> windowDrawFocus' windowPtr\n runOp _ _ window (Just (bx, r)) =\n withRef window $ \\windowPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle r\n windowDrawFocusWithTXywh' windowPtr bx x_pos y_pos w_pos h_pos\n\n{# fun Fl_Window_wait_for_expose as waitForExpose' { id `Ptr ()' } -> `()' #}\ninstance (impl ~ ( IO ())) => Op (WaitForExpose ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> waitForExpose' winPtr\n\n{# fun Fl_Widget_set_type as setType' { id `Ptr ()',`Word8' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (WindowType -> IO ())) => Op (SetType ()) WindowBase orig impl where\n runOp _ _ widget t = withRef widget $ \\widgetPtr -> setType' widgetPtr (fromInteger $ toInteger $ fromEnum t)\n{# fun Fl_Widget_type as type' { id `Ptr ()' } -> `Word8' #}\ninstance (impl ~ IO (WindowType)) => Op (GetType_ ()) WindowBase orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> type' widgetPtr >>= return . toEnum . fromInteger . toInteger\n\n{# fun Fl_Window_handle_super as handleSuper' { id `Ptr ()',`Int' } -> `Int' #}\nhandleWindowBase :: Ref WindowBase -> Event -> IO (Either UnknownEvent ())\nhandleWindowBase adjuster event = withRef adjuster $ \\adjusterPtr -> handleSuper' adjusterPtr (fromIntegral (fromEnum event)) >>= return . successOrUnknownEvent\n{# fun Fl_Window_resize_super as resizeSuper' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\nresizeWindowBase :: Ref WindowBase -> Rectangle -> IO ()\nresizeWindowBase adjuster rectangle =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in withRef adjuster $ \\adjusterPtr -> resizeSuper' adjusterPtr x_pos y_pos width height\n{# fun Fl_Window_hide_super as hideSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nhideWindowBase :: Ref WindowBase -> IO ()\nhideWindowBase adjuster = withRef adjuster $ \\adjusterPtr -> hideSuper' adjusterPtr\n{# fun Fl_Window_show_super as showSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nshowWidgetWindowBase :: Ref WindowBase -> IO ()\nshowWidgetWindowBase adjuster = withRef adjuster $ \\adjusterPtr -> showSuper' adjusterPtr\n{# fun Fl_Window_flush_super as flushSuper' { id `Ptr ()' } -> `()' #}\nflushWindowBase :: Ref WindowBase -> IO ()\nflushWindowBase window = withRef window $ \\windowPtr -> flush' windowPtr\n\n{#fun Fl_DerivedWindow_handle as windowHandle' { id `Ptr ()', id `CInt' } -> `Int' #}\ninstance (impl ~ (Event -> IO (Either UnknownEvent ()))) => Op (Handle ()) WindowBase orig impl where\n runOp _ _ window event = withRef window (\\p -> windowHandle' p (fromIntegral . fromEnum $ event)) >>= return . successOrUnknownEvent\n{# fun Fl_DerivedWindow_resize as resize' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Rectangle -> IO ())) => Op (Resize ()) WindowBase orig impl where\n runOp _ _ window rectangle = withRef window $ \\windowPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle rectangle\n resize' windowPtr x_pos y_pos w_pos h_pos\n{# fun Fl_DerivedWindow_show as windowShow' {id `Ptr ()'} -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ShowWidget ()) WindowBase orig impl where\n runOp _ _ window = withRef window (\\p -> windowShow' p)\n\n{# fun Fl_DerivedWindow_hide as hide' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Hide ()) WindowBase orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> hide' windowPtr\n\n{# fun Fl_Window_flush as flush' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Flush ()) WindowBase orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> flush' windowPtr\n\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Base.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Base.Group\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Base.Window\"\n-- @\n\n-- $functions\n-- @\n-- changed :: 'Ref' 'WindowBase' -> 'IO' ('Bool')\n--\n-- clearBorder :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- copyLabel :: 'Ref' 'WindowBase' -> 'T.Text' -> 'IO' ()\n--\n-- destroy :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- drawBackdrop :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- drawBox :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- drawBoxWithBoxtype :: 'Ref' 'WindowBase' -> 'Boxtype' -> 'Color' -> 'Maybe' 'Rectangle' -> 'IO' ()\n--\n-- drawFocus :: 'Ref' 'WindowBase' -> 'Maybe' ('Boxtype', 'Rectangle') -> 'IO' ()\n--\n-- flush :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- freePosition :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- fullscreenOff :: 'Ref' 'WindowBase' -> 'Maybe' 'Rectangle' -> 'IO' ()\n--\n-- getBorder :: 'Ref' 'WindowBase' -> 'IO' ('Bool')\n--\n-- getDecoratedH :: 'Ref' 'WindowBase' -> 'IO' ('Int')\n--\n-- getDecoratedW :: 'Ref' 'WindowBase' -> 'IO' ('Int')\n--\n-- getIcon :: 'Ref' 'WindowBase' -> 'IO' ('Maybe' ('Ref' 'Image'))\n--\n-- getIconlabel :: 'Ref' 'WindowBase' -> 'IO' 'T.Text'\n--\n-- getLabel :: 'Ref' 'WindowBase' -> 'IO' 'T.Text'\n--\n-- getMenuWindow :: 'Ref' 'WindowBase' -> 'IO' ('Bool')\n--\n-- getModal :: 'Ref' 'WindowBase' -> 'IO' ('Bool')\n--\n-- getOverride :: 'Ref' 'WindowBase' -> 'IO' ('Bool')\n--\n-- getTooltipWindow :: 'Ref' 'WindowBase' -> 'IO' ('Bool')\n--\n-- getType_ :: 'Ref' 'WindowBase' -> 'IO' ('WindowType')\n--\n-- getXRoot :: 'Ref' 'WindowBase' -> 'IO' ('X')\n--\n-- getXclass :: 'Ref' 'WindowBase' -> 'IO' 'T.Text'\n--\n-- getYRoot :: 'Ref' 'WindowBase' -> 'IO' ('Y')\n--\n-- handle :: 'Ref' 'WindowBase' -> 'Event' -> 'IO' ('Either' 'UnknownEvent' ())\n--\n-- hide :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- hotSpot :: 'Ref' 'WindowBase' -> 'PositionSpec' -> 'Maybe' 'Bool' -> 'IO' ()\n--\n-- iconize :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- makeCurrent :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- makeFullscreen :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- nonModal :: 'Ref' 'WindowBase' -> 'IO' ('Bool')\n--\n-- resize :: 'Ref' 'WindowBase' -> 'Rectangle' -> 'IO' ()\n--\n-- setBorder :: 'Ref' 'WindowBase' -> 'Bool' -> 'IO' ()\n--\n-- setCallback :: 'Ref' 'WindowBase' -> ('Ref' orig -> 'IO' ()) -> 'IO' ()\n--\n-- setCursor :: 'Ref' 'WindowBase' -> 'Cursor' -> 'IO' ()\n--\n-- setCursorWithFgBg :: 'Ref' 'WindowBase' -> 'Cursor' -> ('Maybe' 'Color', 'Maybe' 'Color') -> 'IO' ()\n--\n-- setDefaultCursor :: 'Ref' 'WindowBase' -> 'CursorType' -> 'IO' ()\n--\n-- setDefaultCursorWithFgBg :: 'Ref' 'WindowBase' -> 'CursorType' -> ('Maybe' 'Color', 'Maybe' 'Color') -> 'IO' ()\n--\n-- setIcon:: ('Parent' a 'RGBImage') => 'Ref' 'WindowBase' -> 'Maybe'( 'Ref' a ) -> 'IO' ()\n--\n-- setIconlabel :: 'Ref' 'WindowBase' -> 'T.Text' -> 'IO' ()\n--\n-- setLabel :: 'Ref' 'WindowBase' -> 'T.Text' -> 'IO' ()\n--\n-- setLabelWithIconlabel :: 'Ref' 'WindowBase' -> 'T.Text' -> 'T.Text' -> 'IO' ()\n--\n-- setMenuWindow :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- setModal :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- setNonModal :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- setOverride :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- setTooltipWindow :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- setType :: 'Ref' 'WindowBase' -> 'WindowType' -> 'IO' ()\n--\n-- setXclass :: 'Ref' 'WindowBase' -> 'T.Text' -> 'IO' ()\n--\n-- showWidget :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- shown :: 'Ref' 'WindowBase' -> 'IO' ('Bool')\n--\n-- sizeRange :: 'Ref' 'WindowBase' -> 'Size' -> 'IO' ()\n--\n-- sizeRangeWithArgs :: 'Ref' 'WindowBase' -> 'Size' -> 'OptionalSizeRangeArgs' -> 'IO' ()\n--\n-- waitForExpose :: 'Ref' 'WindowBase' -> 'IO' ()\n-- @\n","old_contents":"{-# LANGUAGE CPP, UndecidableInstances, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ExistentialQuantification #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Base.Window\n (\n CustomWindowFuncs(..),\n OptionalSizeRangeArgs(..),\n PositionSpec(..),\n WindowType(..),\n defaultCustomWindowFuncs,\n fillCustomWidgetFunctionStruct,\n defaultOptionalSizeRangeArgs,\n windowCustom,\n windowNew,\n windowMaker,\n currentWindow\n , handleWindowBase\n , resizeWindowBase\n , hideWindowBase\n , showWidgetWindowBase\n , flushWindowBase\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * Functions\n --\n -- $functions\n )\nwhere\n#include \"Fl_C.h\"\n#include \"Fl_WindowC.h\"\n#include \"Fl_WidgetC.h\"\n#include \"Fl_GroupC.h\"\nimport Foreign\nimport Foreign.C\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\nimport Graphics.UI.FLTK.LowLevel.Base.Widget\n\n#c\n enum WindowType {\n SingleWindowType = FL_WINDOWC,\n DoubleWindowType = FL_DOUBLE_WINDOWC\n};\n#endc\n{#enum WindowType {} deriving (Show, Eq) #}\n\ndata PositionSpec = ByPosition Position\n | forall a. (Parent a WidgetBase) => ByWidget (Ref a)\n\ndata CustomWindowFuncs a =\n CustomWindowFuncs {\n flushCustom :: Maybe (Ref a -> IO ())\n }\n\ndata OptionalSizeRangeArgs = OptionalSizeRangeArgs {\n maxw :: Maybe Int,\n maxh :: Maybe Int,\n dw :: Maybe Int,\n dh :: Maybe Int,\n aspect :: Maybe Bool\n }\n\noptionalSizeRangeArgsToStruct :: OptionalSizeRangeArgs -> IO (Ptr ())\noptionalSizeRangeArgsToStruct args = do\n p <- mallocBytes {#sizeof fl_Window_size_range_args #}\n {#set fl_Window_size_range_args->maxw #} p $ maybe 0 fromIntegral (maxw args)\n {#set fl_Window_size_range_args->maxh #} p $ maybe 0 fromIntegral (maxh args)\n {#set fl_Window_size_range_args->dw #} p $ maybe 0 fromIntegral (dw args)\n {#set fl_Window_size_range_args->dh #} p $ maybe 0 fromIntegral (dh args)\n {#set fl_Window_size_range_args->aspect #} p $ maybe 0 fromBool (aspect args)\n return p\n\ndefaultOptionalSizeRangeArgs :: OptionalSizeRangeArgs\ndefaultOptionalSizeRangeArgs = OptionalSizeRangeArgs Nothing Nothing Nothing Nothing Nothing\n\nfillCustomWindowFunctionStruct :: forall a. (Parent a WindowBase) =>\n Ptr () ->\n CustomWindowFuncs a ->\n IO ()\nfillCustomWindowFunctionStruct structPtr (CustomWindowFuncs _flush') =\n toCallbackPrim `orNullFunPtr` _flush' >>= {#set fl_Window_Virtual_Funcs->flush#} structPtr\n\ndefaultCustomWindowFuncs :: forall a. (Parent a WindowBase) => CustomWindowFuncs a\ndefaultCustomWindowFuncs = CustomWindowFuncs Nothing\n\n{# fun Fl_Window_default_virtual_funcs as virtualFuncs' {} -> `Ptr ()' id #}\nwindowMaker :: forall a b. (Parent a WindowBase, Parent b WidgetBase) =>\n Size ->\n Maybe Position ->\n Maybe T.Text ->\n Maybe (Ref b -> IO ()) ->\n CustomWidgetFuncs b ->\n CustomWindowFuncs a ->\n (Int -> Int -> Ptr () -> IO (Ptr ())) ->\n (Int -> Int -> CString -> Ptr () -> IO (Ptr ())) ->\n (Int -> Int -> Int -> Int -> Ptr () -> IO (Ptr ())) ->\n (Int -> Int -> Int -> Int -> CString -> Ptr () -> IO (Ptr ())) ->\n IO (Ref a)\nwindowMaker (Size (Width w) (Height h))\n position\n title\n draw'\n customWidgetFuncs'\n customWindowFuncs'\n custom'\n customWithLabel'\n customXY'\n customXYWithLabel' =\n do\n p <- virtualFuncs'\n fillCustomWidgetFunctionStruct p draw' customWidgetFuncs'\n fillCustomWindowFunctionStruct p customWindowFuncs'\n ref <- case (position, title) of\n (Nothing, Nothing) -> custom' w h p >>= toRef\n (Just (Position (X x) (Y y)), Nothing) -> customXY' x y w h p >>= toRef\n (Just (Position (X x) (Y y)), (Just l')) -> copyTextToCString l' >>= \\l'' -> customXYWithLabel' x y w h l'' p >>= toRef\n (Nothing, (Just l')) -> copyTextToCString l' >>= \\l'' -> customWithLabel' w h l'' p >>= toRef\n setFlag (safeCast ref :: Ref WindowBase) WidgetFlagCopiedLabel\n setFlag (safeCast ref :: Ref WindowBase) WidgetFlagCopiedTooltip\n return ref\n\n{# fun Fl_OverriddenWindow_New as overriddenWindowNew' {`Int',`Int', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenWindow_NewXY as overriddenWindowNewXY' {`Int',`Int', `Int', `Int', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenWindow_NewXY_WithLabel as overriddenWindowNewXYWithLabel' { `Int',`Int',`Int',`Int',`CString', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenWindow_New_WithLabel as overriddenWindowNewWithLabel' { `Int',`Int', `CString', id `Ptr ()'} -> `Ptr ()' id #}\nwindowCustom :: Size -- ^ Size of this window\n -> Maybe Position -- ^ Optional position of this window\n -> Maybe T.Text -- ^ Optional label\n -> Maybe (Ref Window -> IO ()) -- ^ Optional table drawing routine\n -> CustomWidgetFuncs Window -- ^ Custom widget overrides\n -> CustomWindowFuncs Window -- ^ Custom window overrides\n -> IO (Ref Window)\nwindowCustom size position title draw' customWidgetFuncs' customWindowFuncs' =\n windowMaker\n size\n position\n title\n draw'\n customWidgetFuncs'\n customWindowFuncs'\n overriddenWindowNew'\n overriddenWindowNewWithLabel'\n overriddenWindowNewXY'\n overriddenWindowNewXYWithLabel'\n\nwindowNew :: Size -> Maybe Position -> Maybe T.Text -> IO (Ref Window)\nwindowNew size position title =\n windowMaker\n size\n position\n title\n Nothing\n (defaultCustomWidgetFuncs :: CustomWidgetFuncs Window)\n (defaultCustomWindowFuncs :: CustomWindowFuncs Window)\n overriddenWindowNew'\n overriddenWindowNewWithLabel'\n overriddenWindowNewXY'\n overriddenWindowNewXYWithLabel'\n\n{# fun Fl_Window_Destroy as windowDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Destroy ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> windowDestroy' winPtr\n\n{# fun Fl_Window_set_callback as windowSetCallback' {id `Ptr ()' , id `FunPtr CallbackWithUserDataPrim'} -> `FunPtr CallbackWithUserDataPrim' id #}\ninstance (impl ~ ((Ref orig -> IO ()) -> IO ())) => Op (SetCallback ()) WindowBase orig impl where\n runOp _ _ window callback =\n withRef window $ (\\p -> do\n callbackPtr <- toCallbackPrimWithUserData callback\n oldCb <- windowSetCallback' (castPtr p) callbackPtr\n if (oldCb == nullFunPtr)\n then return ()\n else freeHaskellFunPtr oldCb)\n\n{# fun Fl_Window_changed as changed' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ ( IO (Bool))) => Op (Changed ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> changed' winPtr\n\n{# fun Fl_Window_fullscreen as fullscreen' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (MakeFullscreen ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> fullscreen' winPtr\n\n{# fun Fl_Window_fullscreen_off as fullscreenOff' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_fullscreen_off_with_resize as fullscreenOffWithResize' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Maybe Rectangle -> IO ())) => Op (FullscreenOff ()) WindowBase orig impl where\n runOp _ _ win (Just rectangle) =\n withRef win $ \\winPtr ->\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in fullscreenOffWithResize' winPtr x_pos y_pos width height\n runOp _ _ win Nothing =\n withRef win $ \\winPtr -> fullscreenOff' winPtr\n\n{# fun Fl_Window_set_border as setBorder' { id `Ptr ()', fromBool `Bool' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Bool -> IO ())) => Op (SetBorder ()) WindowBase orig impl where\n runOp _ _ win b = withRef win $ \\winPtr -> setBorder' winPtr b\n\n{# fun Fl_Window_clear_border as clearBorder' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (ClearBorder ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> clearBorder' winPtr\n\n{# fun Fl_Window_border as border' { id `Ptr ()' } -> `Bool' toBool#}\ninstance (impl ~ ( IO (Bool))) => Op (GetBorder ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> border' winPtr\n\n{# fun Fl_Window_set_override as setOverride' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (SetOverride ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> setOverride' winPtr\n\n{# fun Fl_Window_override as override' { id `Ptr ()' } -> `Bool' toBool #}\ninstance (impl ~ ( IO (Bool))) => Op (GetOverride ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> override' winPtr\n\n{# fun Fl_Window_set_modal as setModal' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (SetModal ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> setModal' winPtr\n\n{# fun Fl_Window_modal as modal' { id `Ptr ()' } -> `Bool' toBool #}\ninstance (impl ~ ( IO (Bool))) => Op (GetModal ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> modal' winPtr\n\n{# fun Fl_Window_set_non_modal as setNonModal' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (SetNonModal ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> setNonModal' winPtr\n\n{# fun Fl_Window_non_modal as nonModal' { id `Ptr ()' } -> `Bool' toBool #}\ninstance (impl ~ ( IO (Bool))) => Op (NonModal ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> nonModal' winPtr\n\n{# fun Fl_Window_set_menu_window as setMenuWindow' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (SetMenuWindow ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> setMenuWindow' winPtr\n\n{# fun Fl_Window_menu_window as menuWindow' { id `Ptr ()' } -> `Bool' toBool #}\ninstance (impl ~ ( IO (Bool))) => Op (GetMenuWindow ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> menuWindow' winPtr\n\n{# fun Fl_Window_set_tooltip_window as setTooltipWindow' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (SetTooltipWindow ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> setTooltipWindow' winPtr\n\n{# fun Fl_Window_tooltip_window as tooltipWindow' { id `Ptr ()' } -> `Bool' toBool #}\ninstance (impl ~ ( IO (Bool))) => Op (GetTooltipWindow ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> tooltipWindow' winPtr\n\n{# fun Fl_Window_hotspot_with_x_y as hotspotWithXY' { id `Ptr ()',`Int',`Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_hotspot_with_x_y_with_offscreen as hotspotWithXYWithOffscreen' { id `Ptr ()',`Int',`Int', fromBool `Bool' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_hotspot_with_widget as hotspotWithWidget' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_hotspot_with_widget_with_offscreen as hotspotWithWidgetWithOffscreen' { id `Ptr ()',id `Ptr ()',fromBool `Bool' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (PositionSpec -> Maybe Bool -> IO ())) => Op (HotSpot ()) WindowBase orig impl where\n runOp _ _ win positionSpec offscreen =\n withRef win $ \\winPtr ->\n case (positionSpec, offscreen) of\n ((ByPosition (Position (X x) (Y y))), (Just offscreen')) ->\n hotspotWithXYWithOffscreen' winPtr x y offscreen'\n ((ByPosition (Position (X x) (Y y))), Nothing) -> hotspotWithXY' winPtr x y\n ((ByWidget templateWidget), (Just offscreen')) ->\n withRef templateWidget $ \\templatePtr ->\n hotspotWithWidgetWithOffscreen' winPtr templatePtr offscreen'\n ((ByWidget templateWidget), Nothing) ->\n withRef templateWidget $ \\templatePtr ->\n hotspotWithWidget' winPtr templatePtr\n{# fun Fl_Window_free_position as freePosition' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (FreePosition ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> freePosition' winPtr\n\n{# fun Fl_Window_size_range as sizeRange' { id `Ptr ()',`Int',`Int' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_size_range_with_args as sizeRangeWithArgs' { id `Ptr ()',`Int',`Int', id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Size -> IO ())) => Op (SizeRange ()) WindowBase orig impl where\n runOp _ _ win (Size (Width minw') (Height minh')) =\n withRef win $ \\winPtr -> sizeRange' winPtr minw' minh'\ninstance (impl ~ (Size -> OptionalSizeRangeArgs -> IO ())) => Op (SizeRangeWithArgs ()) WindowBase orig impl where\n runOp _ _ win (Size (Width minw') (Height minh')) args =\n withRef win $ \\winPtr -> do\n structPtr <- optionalSizeRangeArgsToStruct args\n sizeRangeWithArgs' winPtr minw' minh' structPtr\n\n{# fun Fl_Window_label as label' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO T.Text)) => Op (GetLabel ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> label' winPtr >>= cStringToText\n\n{# fun Fl_Window_iconlabel as iconlabel' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO T.Text)) => Op (GetIconlabel ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> iconlabel' winPtr >>= cStringToText\n\n{# fun Fl_Window_set_label as setLabel' { id `Ptr ()',`CString' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetLabel ()) WindowBase orig impl where\n runOp _ _ win l' = withRef win $ \\winPtr -> copyTextToCString l' >>= setLabel' winPtr\n\n{# fun Fl_Window_set_iconlabel as setIconlabel' { id `Ptr ()',`CString' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetIconlabel ()) WindowBase orig impl where\n runOp _ _ win l' = withRef win $ \\winPtr -> copyTextToCString l' >>= setIconlabel' winPtr\n\n{# fun Fl_Window_set_label_with_iconlabel as setLabelWithIconlabel' { id `Ptr ()',`CString',`CString' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> T.Text -> IO ())) => Op (SetLabelWithIconlabel ()) WindowBase orig impl where\n runOp _ _ win label iconlabel = withRef win $ \\winPtr -> do\n l' <- copyTextToCString label\n il' <- copyTextToCString iconlabel\n setLabelWithIconlabel' winPtr l' il'\n\n{# fun Fl_Window_copy_label as copyLabel' { id `Ptr ()',`CString' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (CopyLabel ()) WindowBase orig impl where\n runOp _ _ win a = withRef win $ \\winPtr -> withText a (copyLabel' winPtr)\n\n{# fun Fl_Window_xclass as xclass' { id `Ptr ()' } -> `CString' #}\ninstance (impl ~ ( IO T.Text)) => Op (GetXclass ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> xclass' winPtr >>= cStringToText\n\n{# fun Fl_Window_set_xclass as setXclass' { id `Ptr ()',`CString' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (T.Text -> IO ())) => Op (SetXclass ()) WindowBase orig impl where\n runOp _ _ win c = withRef win $ \\winPtr -> copyTextToCString c >>= setXclass' winPtr\n\n{# fun Fl_Window_icon as icon' { id `Ptr ()' } -> `Ptr ()' id #}\ninstance (impl ~ ( IO (Maybe (Ref Image)))) => Op (GetIcon ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> icon' winPtr >>= toMaybeRef\n\n{# fun Fl_Window_set_icon as setIcon' { id `Ptr ()', id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (Parent a RGBImage, impl ~ (Maybe( Ref a ) -> IO ())) => Op (SetIcon ()) WindowBase orig impl where\n runOp _ _ win bitmap = withRef win $ \\winPtr -> withMaybeRef bitmap $ \\bitmapPtr -> setIcon' winPtr bitmapPtr\n\n{# fun Fl_Window_shown as shown' { id `Ptr ()' } -> `Bool' toBool #}\ninstance (impl ~ ( IO (Bool))) => Op (Shown ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> shown' winPtr\n\n{# fun Fl_Window_iconize as iconize' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Iconize ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> iconize' winPtr\n\n{# fun Fl_Window_x_root as xRoot' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (X))) => Op (GetXRoot ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> xRoot' winPtr >>= return . X\n\n{# fun Fl_Window_y_root as yRoot' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Y))) => Op (GetYRoot ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> yRoot' winPtr >>= return . Y\n\n{# fun Fl_Window_current as current' { } -> `Ptr ()' id #}\ncurrentWindow :: (Parent a WindowBase) => IO (Ref a)\ncurrentWindow = current' >>= toRef\n\n{# fun Fl_Window_make_current as makeCurrent' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (MakeCurrent ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> makeCurrent' winPtr\n\n{# fun Fl_Window_set_cursor_with_bg as setCursorWithBg' { id `Ptr ()',cFromEnum `Cursor',cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_set_cursor_with_fg as setCursorWithFg' { id `Ptr ()',cFromEnum `Cursor',cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_set_cursor_with_fg_bg as setCursorWithFgBg' { id `Ptr ()',cFromEnum `Cursor',cFromColor `Color',cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_set_cursor as setCursor' { id `Ptr ()',cFromEnum `Cursor' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Cursor -> IO ())) => Op (SetCursor ()) WindowBase orig impl where\n runOp _ _ win cursor = withRef win $ \\winPtr -> setCursor' winPtr cursor\ninstance (impl ~ (Cursor -> (Maybe Color, Maybe Color) -> IO ())) => Op (SetCursorWithFgBg ()) WindowBase orig impl where\n runOp _ _ win cursor fgbg =\n case fgbg of\n ((Just fg), (Just bg)) -> withRef win $ \\winPtr -> setCursorWithFgBg' winPtr cursor fg bg\n (Nothing , (Just bg)) -> withRef win $ \\winPtr -> setCursorWithBg' winPtr cursor bg\n ((Just fg), Nothing) -> withRef win $ \\winPtr -> setCursorWithFg' winPtr cursor fg\n (Nothing, Nothing) -> withRef win $ \\winPtr -> setCursor' winPtr cursor\n\n{# fun Fl_Window_set_default_cursor_with_bg as setDefaultCursorWithBg' { id `Ptr ()',cFromEnum `CursorType',cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_set_default_cursor_with_fg as setDefaultCursorWithFg' { id `Ptr ()',cFromEnum `CursorType',cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_set_default_cursor_with_fg_bg as setDefaultCursorWithFgBg' { id `Ptr ()',cFromEnum `CursorType',cFromColor `Color',cFromColor `Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_set_default_cursor as setDefaultCursor' { id `Ptr ()',cFromEnum `CursorType' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (CursorType -> IO ())) => Op (SetDefaultCursor ()) WindowBase orig impl where\n runOp _ _ win cursor = withRef win $ \\winPtr -> setDefaultCursor' winPtr cursor\ninstance (impl ~ (CursorType -> (Maybe Color, Maybe Color) -> IO ())) => Op (SetDefaultCursorWithFgBg ()) WindowBase orig impl where\n runOp _ _ win cursor fgbg =\n case fgbg of\n ((Just fg), (Just bg)) -> withRef win $ \\winPtr -> setDefaultCursorWithFgBg' winPtr cursor fg bg\n (Nothing , (Just bg)) -> withRef win $ \\winPtr -> setDefaultCursorWithBg' winPtr cursor bg\n ((Just fg), Nothing) -> withRef win $ \\winPtr -> setDefaultCursorWithFg' winPtr cursor fg\n (Nothing, Nothing) -> withRef win $ \\winPtr -> setDefaultCursor' winPtr cursor\n\n{# fun Fl_Window_decorated_w as decoratedW' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetDecoratedW ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> decoratedW' winPtr\n\n{# fun Fl_Window_decorated_h as decoratedH' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (GetDecoratedH ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> decoratedH' winPtr\n\n{# fun Fl_Window_draw_box as windowDrawBox' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_draw_box_with_tc as windowDrawBoxWithTC' { id `Ptr ()', cFromEnum `Boxtype', cFromColor`Color' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_draw_box_with_txywhc as windowDrawBoxWithTXywhC' { id `Ptr ()', cFromEnum `Boxtype', `Int',`Int',`Int',`Int', cFromColor `Color' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (DrawBox ()) WindowBase orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> windowDrawBox' windowPtr\ninstance (impl ~ (Boxtype -> Color -> Maybe Rectangle -> IO ())) => Op (DrawBoxWithBoxtype ()) WindowBase orig impl where\n runOp _ _ window bx c Nothing =\n withRef window $ \\windowPtr -> windowDrawBoxWithTC' windowPtr bx c\n runOp _ _ window bx c (Just r) =\n withRef window $ \\windowPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle r\n windowDrawBoxWithTXywhC' windowPtr bx x_pos y_pos w_pos h_pos c\n{# fun Fl_Window_draw_backdrop as windowDrawBackdrop' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (DrawBackdrop ()) WindowBase orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> windowDrawBackdrop' windowPtr\n\n{# fun Fl_Window_draw_focus as windowDrawFocus' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\n{# fun Fl_Window_draw_focus_with_txywh as windowDrawFocusWithTXywh' { id `Ptr ()', cFromEnum `Boxtype', `Int', `Int', `Int', `Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Maybe (Boxtype, Rectangle) -> IO ())) => Op (DrawFocus ()) WindowBase orig impl where\n runOp _ _ window Nothing =\n withRef window $ \\ windowPtr -> windowDrawFocus' windowPtr\n runOp _ _ window (Just (bx, r)) =\n withRef window $ \\windowPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle r\n windowDrawFocusWithTXywh' windowPtr bx x_pos y_pos w_pos h_pos\n\n{# fun Fl_Window_wait_for_expose as waitForExpose' { id `Ptr ()' } -> `()' #}\ninstance (impl ~ ( IO ())) => Op (WaitForExpose ()) WindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> waitForExpose' winPtr\n\n{# fun Fl_Widget_set_type as setType' { id `Ptr ()',`Word8' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (WindowType -> IO ())) => Op (SetType ()) WindowBase orig impl where\n runOp _ _ widget t = withRef widget $ \\widgetPtr -> setType' widgetPtr (fromInteger $ toInteger $ fromEnum t)\n{# fun Fl_Widget_type as type' { id `Ptr ()' } -> `Word8' #}\ninstance (impl ~ IO (WindowType)) => Op (GetType_ ()) WindowBase orig impl where\n runOp _ _ widget = withRef widget $ \\widgetPtr -> type' widgetPtr >>= return . toEnum . fromInteger . toInteger\n\n{# fun Fl_Window_handle_super as handleSuper' { id `Ptr ()',`Int' } -> `Int' #}\nhandleWindowBase :: Ref WindowBase -> Event -> IO (Either UnknownEvent ())\nhandleWindowBase adjuster event = withRef adjuster $ \\adjusterPtr -> handleSuper' adjusterPtr (fromIntegral (fromEnum event)) >>= return . successOrUnknownEvent\n{# fun Fl_Window_resize_super as resizeSuper' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\nresizeWindowBase :: Ref WindowBase -> Rectangle -> IO ()\nresizeWindowBase adjuster rectangle =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in withRef adjuster $ \\adjusterPtr -> resizeSuper' adjusterPtr x_pos y_pos width height\n{# fun Fl_Window_hide_super as hideSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nhideWindowBase :: Ref WindowBase -> IO ()\nhideWindowBase adjuster = withRef adjuster $ \\adjusterPtr -> hideSuper' adjusterPtr\n{# fun Fl_Window_show_super as showSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nshowWidgetWindowBase :: Ref WindowBase -> IO ()\nshowWidgetWindowBase adjuster = withRef adjuster $ \\adjusterPtr -> showSuper' adjusterPtr\n{# fun Fl_Window_flush_super as flushSuper' { id `Ptr ()' } -> `()' #}\nflushWindowBase :: Ref WindowBase -> IO ()\nflushWindowBase window = withRef window $ \\windowPtr -> flush' windowPtr\n\n{#fun Fl_DerivedWindow_handle as windowHandle' { id `Ptr ()', id `CInt' } -> `Int' #}\ninstance (impl ~ (Event -> IO (Either UnknownEvent ()))) => Op (Handle ()) WindowBase orig impl where\n runOp _ _ window event = withRef window (\\p -> windowHandle' p (fromIntegral . fromEnum $ event)) >>= return . successOrUnknownEvent\n{# fun Fl_DerivedWindow_resize as resize' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Rectangle -> IO ())) => Op (Resize ()) WindowBase orig impl where\n runOp _ _ window rectangle = withRef window $ \\windowPtr -> do\n let (x_pos,y_pos,w_pos,h_pos) = fromRectangle rectangle\n resize' windowPtr x_pos y_pos w_pos h_pos\n{# fun Fl_DerivedWindow_show as windowShow' {id `Ptr ()'} -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (ShowWidget ()) WindowBase orig impl where\n runOp _ _ window = withRef window (\\p -> windowShow' p)\n\n{# fun Fl_DerivedWindow_hide as hide' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Hide ()) WindowBase orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> hide' windowPtr\n\n{# fun Fl_Window_flush as flush' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Flush ()) WindowBase orig impl where\n runOp _ _ window = withRef window $ \\windowPtr -> flush' windowPtr\n\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Base.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Base.Group\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Base.Window\"\n-- @\n\n-- $functions\n-- @\n-- changed :: 'Ref' 'WindowBase' -> 'IO' ('Bool')\n--\n-- clearBorder :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- copyLabel :: 'Ref' 'WindowBase' -> 'T.Text' -> 'IO' ()\n--\n-- destroy :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- drawBackdrop :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- drawBox :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- drawBoxWithBoxtype :: 'Ref' 'WindowBase' -> 'Boxtype' -> 'Color' -> 'Maybe' 'Rectangle' -> 'IO' ()\n--\n-- drawFocus :: 'Ref' 'WindowBase' -> 'Maybe' ('Boxtype', 'Rectangle') -> 'IO' ()\n--\n-- flush :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- freePosition :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- fullscreenOff :: 'Ref' 'WindowBase' -> 'Maybe' 'Rectangle' -> 'IO' ()\n--\n-- getBorder :: 'Ref' 'WindowBase' -> 'IO' ('Bool')\n--\n-- getDecoratedH :: 'Ref' 'WindowBase' -> 'IO' ('Int')\n--\n-- getDecoratedW :: 'Ref' 'WindowBase' -> 'IO' ('Int')\n--\n-- getIcon :: 'Ref' 'WindowBase' -> 'IO' ('Maybe' ('Ref' 'Image'))\n--\n-- getIconlabel :: 'Ref' 'WindowBase' -> 'IO' 'T.Text'\n--\n-- getLabel :: 'Ref' 'WindowBase' -> 'IO' 'T.Text'\n--\n-- getMenuWindow :: 'Ref' 'WindowBase' -> 'IO' ('Bool')\n--\n-- getModal :: 'Ref' 'WindowBase' -> 'IO' ('Bool')\n--\n-- getOverride :: 'Ref' 'WindowBase' -> 'IO' ('Bool')\n--\n-- getTooltipWindow :: 'Ref' 'WindowBase' -> 'IO' ('Bool')\n--\n-- getType_ :: 'Ref' 'WindowBase' -> 'IO' ('WindowType')\n--\n-- getXRoot :: 'Ref' 'WindowBase' -> 'IO' ('X')\n--\n-- getXclass :: 'Ref' 'WindowBase' -> 'IO' 'T.Text'\n--\n-- getYRoot :: 'Ref' 'WindowBase' -> 'IO' ('Y')\n--\n-- handle :: 'Ref' 'WindowBase' -> 'Event' -> 'IO' ('Either' 'UnknownEvent' ())\n--\n-- hide :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- hotSpot :: 'Ref' 'WindowBase' -> 'PositionSpec' -> 'Maybe' 'Bool' -> 'IO' ()\n--\n-- iconize :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- makeCurrent :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- makeFullscreen :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- nonModal :: 'Ref' 'WindowBase' -> 'IO' ('Bool')\n--\n-- resize :: 'Ref' 'WindowBase' -> 'Rectangle' -> 'IO' ()\n--\n-- setBorder :: 'Ref' 'WindowBase' -> 'Bool' -> 'IO' ()\n--\n-- setCallback :: 'Ref' 'WindowBase' -> ('Ref' orig -> 'IO' ()) -> 'IO' ()\n--\n-- setCursor :: 'Ref' 'WindowBase' -> 'Cursor' -> 'IO' ()\n--\n-- setCursorWithFgBg :: 'Ref' 'WindowBase' -> 'Cursor' -> ('Maybe' 'Color', 'Maybe' 'Color') -> 'IO' ()\n--\n-- setDefaultCursor :: 'Ref' 'WindowBase' -> 'CursorType' -> 'IO' ()\n--\n-- setDefaultCursorWithFgBg :: 'Ref' 'WindowBase' -> 'CursorType' -> ('Maybe' 'Color', 'Maybe' 'Color') -> 'IO' ()\n--\n-- setIcon:: ('Parent' a 'RGBImage') => 'Ref' 'WindowBase' -> 'Maybe'( 'Ref' a ) -> 'IO' ()\n--\n-- setIconlabel :: 'Ref' 'WindowBase' -> 'T.Text' -> 'IO' ()\n--\n-- setLabel :: 'Ref' 'WindowBase' -> 'T.Text' -> 'IO' ()\n--\n-- setLabelWithIconlabel :: 'Ref' 'WindowBase' -> 'T.Text' -> 'T.Text' -> 'IO' ()\n--\n-- setMenuWindow :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- setModal :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- setNonModal :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- setOverride :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- setTooltipWindow :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- setType :: 'Ref' 'WindowBase' -> 'WindowType' -> 'IO' ()\n--\n-- setXclass :: 'Ref' 'WindowBase' -> 'T.Text' -> 'IO' ()\n--\n-- showWidget :: 'Ref' 'WindowBase' -> 'IO' ()\n--\n-- shown :: 'Ref' 'WindowBase' -> 'IO' ('Bool')\n--\n-- sizeRange :: 'Ref' 'WindowBase' -> 'Size' -> 'IO' ()\n--\n-- sizeRangeWithArgs :: 'Ref' 'WindowBase' -> 'Size' -> 'OptionalSizeRangeArgs' -> 'IO' ()\n--\n-- waitForExpose :: 'Ref' 'WindowBase' -> 'IO' ()\n-- @\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"}
{"commit":"bb882257b7994f289e73100dc2f4cebdc4c678e8","subject":"copies are always writable","message":"copies are always writable\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/GDAL.chs","new_file":"src\/GDAL\/Internal\/GDAL.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE LambdaCase #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.GDAL (\n GDALRasterException (..)\n , Geotransform (..)\n , OverviewResampling (..)\n , Driver (..)\n , Dataset\n , DatasetH (..)\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , RasterBandH (..)\n , MaskType (..)\n\n , northUpGeotransform\n , gcpGeotransform\n , applyGeotransform\n , (|$|)\n , invertGeotransform\n , inv\n , composeGeotransforms\n , (|.|)\n , geoEnvelopeTransformer\n\n , nullDatasetH\n , allRegister\n , destroyDriverManager\n , create\n , createMem\n , delete\n , rename\n , copyFiles\n , flushCache\n , closeDataset\n , openReadOnly\n , openReadWrite\n , unsafeToReadOnly\n , createCopy\n , buildOverviews\n , driverCreationOptionList\n\n , bandAs\n\n , datasetDriver\n , datasetSize\n , datasetFileList\n , datasetProjection\n , datasetProjectionIO\n , setDatasetProjection\n , datasetGeotransform\n , datasetGeotransformIO\n , setDatasetGeotransform\n , datasetGCPs\n , setDatasetGCPs\n , datasetBandCount\n\n , bandDataType\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandHasOverviews\n , allBand\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , addBand\n , fillBand\n , fmapBand\n , readBand\n , createBandMask\n , readBandBlock\n , writeBand\n , writeBandBlock\n , copyBand\n , bandConduit\n , unsafeBandConduit\n , bandSink\n , bandSinkGeo\n\n , metadataDomains\n , metadata\n , metadataItem\n , setMetadataItem\n , description\n , setDescription\n\n , foldl'\n , ifoldl'\n , foldlWindow'\n , ifoldlWindow'\n , blockConduit\n , unsafeBlockConduit\n , blockSource\n , unsafeBlockSource\n , blockSink\n , allBlocks\n , zipBlocks\n , getZipBlocks\n\n , unDataset\n , unBand\n , version\n , newDatasetHandle\n , openDatasetCount\n\n , module GDAL.Internal.DataType\n) where\n\n{#context lib = \"gdal\" prefix = \"GDAL\" #}\n\nimport Control.Arrow (second)\nimport Control.Applicative (Applicative(..), (<$>), liftA2)\nimport Control.Concurrent.MVar (MVar, newMVar, takeMVar, putMVar)\nimport Control.Exception (Exception(..))\nimport Control.Monad (liftM, liftM2, when, (>=>), void, forever)\nimport Control.Monad.Trans (lift)\nimport Control.Monad.Catch (bracket)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Data.Bits ((.&.))\nimport Data.ByteString.Char8 (ByteString, packCString, useAsCString)\nimport Data.ByteString.Unsafe (unsafeUseAsCString)\nimport Data.Coerce (coerce)\nimport qualified Data.Conduit.List as CL\nimport Data.Conduit\nimport Data.Conduit.Internal (Pipe(..), ConduitM(..), injectLeftovers)\nimport Data.Maybe (fromMaybe, fromJust)\nimport Data.String (IsString)\nimport Data.Proxy\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport Data.Typeable (Typeable)\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport qualified Data.Vector.Generic.Mutable as M\nimport qualified Data.Vector.Unboxed.Mutable as UM\nimport qualified Data.Vector.Unboxed as U\nimport Data.Word (Word8)\n\nimport Foreign.C.String (withCString, CString)\nimport Foreign.C.Types\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrBytes)\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (withArrayLen)\nimport Foreign.Marshal.Utils (toBool, fromBool, with)\n\nimport GHC.Types (SPEC(..))\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.Types.Value\nimport GDAL.Internal.DataType\nimport GDAL.Internal.Common\nimport GDAL.Internal.Util\n{#import GDAL.Internal.GCP#}\n{#import GDAL.Internal.CPLError#}\n{#import GDAL.Internal.CPLString#}\n{#import GDAL.Internal.CPLProgress#}\nimport GDAL.Internal.OSR\nimport GDAL.Internal.OGRGeometry (Envelope(..), envelopeSize)\n\n\n#include \"gdal.h\"\n\nnewtype Driver = Driver ByteString\n deriving (Eq, IsString)\n\ninstance Show Driver where\n show (Driver s) = show s\n\nversion :: (Int, Int)\nversion = ({#const GDAL_VERSION_MAJOR#} , {#const GDAL_VERSION_MINOR#})\n\ndata GDALRasterException\n = InvalidRasterSize !Size\n | InvalidBlockSize !Int\n | InvalidDriverOptions\n | UnknownRasterDataType\n | NullDataset\n | NullBand\n | UnknownDriver !ByteString\n | BandDoesNotAllowNoData\n | CannotInvertGeotransform\n deriving (Typeable, Show, Eq)\n\ninstance Exception GDALRasterException where\n toException = bindingExceptionToException\n fromException = bindingExceptionFromException\n\n\n{#enum GDALAccess {} deriving (Eq, Show) #}\n\n{#enum RWFlag {} deriving (Eq, Show) #}\n\n{#pointer MajorObjectH newtype#}\n\nclass MajorObject o (t::AccessMode) where\n majorObject :: o t -> MajorObjectH\n\n\n{#pointer DatasetH newtype #}\n\n\nnullDatasetH :: DatasetH\nnullDatasetH = DatasetH nullPtr\n\nderiving instance Eq DatasetH\n\nnewtype Dataset s a (t::AccessMode) =\n Dataset (ReleaseKey, DatasetH)\n\ninstance MajorObject (Dataset s a) t where\n majorObject ds =\n let DatasetH p = unDataset ds\n in MajorObjectH (castPtr p)\n\nunDataset :: Dataset s a t -> DatasetH\nunDataset (Dataset (_,s)) = s\n\ncloseDataset :: MonadIO m => Dataset s a t -> m ()\ncloseDataset (Dataset (rk,_)) = release rk\n\ntype RODataset s a = Dataset s a ReadOnly\ntype RWDataset s a = Dataset s a ReadWrite\n\n{#pointer RasterBandH newtype #}\n\nnullBandH :: RasterBandH\nnullBandH = RasterBandH nullPtr\n\nderiving instance Eq RasterBandH\n\nnewtype Band s a (t::AccessMode) = Band (RasterBandH, DataTypeK)\n\nunBand :: Band s a t -> RasterBandH\nunBand (Band (p,_)) = p\n{-# INLINE unBand #-}\n\nbandDataType :: Band s a t -> DataTypeK\nbandDataType (Band (_,t)) = t\n{-# INLINE bandDataType #-}\n\nbandAs :: Band s a t -> DataType d -> Band s (HsType d) t\nbandAs = const . coerce\n{-# INLINE bandAs #-}\n\ninstance MajorObject (Band s a) t where\n majorObject b =\n let RasterBandH p = unBand b\n in MajorObjectH (castPtr p)\n\ntype ROBand s a = Band s a ReadOnly\ntype RWBand s a = Band s a ReadWrite\n\n\n{#pointer DriverH #}\n\n{#fun AllRegister as ^ {} -> `()' #}\n\n{#fun DestroyDriverManager as ^ {} -> `()'#}\n\ndriverByName :: Driver -> IO DriverH\ndriverByName (Driver s) = do\n d <- useAsCString s {#call unsafe GetDriverByName as ^#}\n if d == nullPtr\n then throwBindingException (UnknownDriver s)\n else return d\n\ndriverCreationOptionList :: Driver -> ByteString\ndriverCreationOptionList driver = unsafePerformIO $ do\n d <- driverByName driver\n {#call GetDriverCreationOptionList\tas ^#} d >>= packCString\n\nvalidateCreationOptions :: DriverH -> Ptr CString -> IO ()\nvalidateCreationOptions d o = do\n valid <- liftM toBool ({#call GDALValidateCreationOptions as ^ #} d o)\n when (not valid) (throwBindingException InvalidDriverOptions)\n\ncreate\n :: Driver -> String -> Size -> Int -> DataType d -> OptionList\n -> GDAL s (Dataset s (HsType d) ReadWrite)\ncreate drv path (nx :+: ny) bands dtype options =\n newDatasetHandle $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC dtype\n d <- driverByName drv\n withOptionList options $ \\opts -> do\n validateCreationOptions d opts\n {#call GDALCreate as ^#} d path' nx' ny' bands' dtype' opts\n\ndelete :: Driver -> String -> GDAL s ()\ndelete driver path =\n liftIO $\n checkCPLError \"deleteDataset\" $ do\n d <- driverByName driver\n withCString path ({#call DeleteDataset as ^#} d)\n\nrename :: Driver -> String -> String -> GDAL s ()\nrename driver newName oldName =\n liftIO $\n checkCPLError \"renameDataset\" $ do\n d <- driverByName driver\n withCString newName $\n withCString oldName . ({#call RenameDataset as ^#} d)\n\ncopyFiles :: Driver -> String -> String -> GDAL s ()\ncopyFiles driver newName oldName =\n liftIO $\n checkCPLError \"copyFiles\" $ do\n d <- driverByName driver\n withCString newName $\n withCString oldName . ({#call CopyDatasetFiles as ^#} d)\n\nopenReadOnly :: String -> DataType d -> GDAL s (RODataset s (HsType d))\nopenReadOnly p _ = openWithMode GA_ReadOnly p\n\nopenReadWrite :: String -> DataType d -> GDAL s (RWDataset s (HsType d))\nopenReadWrite p _ = openWithMode GA_Update p\n\n-- Opening datasets is not thread-safe with some drivers (eg: GeoTIFF)\n-- so we need a mutex\nopenMutex :: MVar ()\nopenMutex = unsafePerformIO (newMVar ())\n{-# NOINLINE openMutex #-}\n\nopenWithMode :: GDALAccess -> String -> GDAL s (Dataset s a t)\nopenWithMode m path =\n newDatasetHandle $\n bracket (takeMVar openMutex) (putMVar openMutex) $ const $\n withCString path $\n flip {#call GDALOpen as ^#} (fromEnumC m)\n\nunsafeToReadOnly :: RWDataset s a -> GDAL s (RODataset s a)\nunsafeToReadOnly ds = flushCache ds >> return (coerce ds)\n\ncreateCopy\n :: Driver -> String -> Dataset s a t -> Bool -> OptionList\n -> Maybe ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy driver path ds strict options progressFun =\n newDatasetHandle $\n withProgressFun \"createCopy\" progressFun $ \\pFunc -> do\n d <- driverByName driver\n withOptionList options $ \\o -> do\n validateCreationOptions d o\n withCString path $ \\p ->\n {#call GDALCreateCopy as ^#}\n d p (unDataset ds) (fromBool strict) o pFunc nullPtr\n\n\n\nnewDatasetHandle :: IO DatasetH -> GDAL s (Dataset s a t)\nnewDatasetHandle act =\n liftM Dataset $ allocate (checkGDALCall checkit act) free\n where\n checkit exc p\n | p==nullDatasetH = Just (fromMaybe\n (GDALBindingException NullDataset) exc)\n | otherwise = Nothing\n free ds = do\n refCount <- {#call unsafe DereferenceDataset as ^#} ds\n when (refCount<=0) ({#call GDALClose as ^#} ds)\n\ncreateMem\n :: Size -> Int -> DataType d -> OptionList\n -> GDAL s (Dataset s (HsType d) ReadWrite)\ncreateMem = create \"Mem\" \"\"\n\nflushCache :: RWDataset s a -> GDAL s ()\nflushCache = liftIO . {#call GDALFlushCache as ^#} . unDataset\n\ndatasetDriver :: Dataset s a t -> Driver\ndatasetDriver ds =\n unsafePerformIO $\n liftM Driver $ do\n driver <-{#call unsafe GetDatasetDriver as ^#} (unDataset ds)\n {#call unsafe GetDriverShortName as ^#} driver >>= packCString\n\ndatasetSize :: Dataset s a t -> Size\ndatasetSize ds =\n fmap fromIntegral $\n ({#call pure unsafe GetRasterXSize as ^#} (unDataset ds))\n :+: ({#call pure unsafe GetRasterYSize as ^#} (unDataset ds))\n\ndatasetFileList :: Dataset s a t -> GDAL s [Text]\ndatasetFileList =\n liftIO .\n fromCPLStringList .\n {#call unsafe GetFileList as ^#} .\n unDataset\n\ndatasetProjectionIO :: Dataset s a t -> IO (Maybe SpatialReference)\ndatasetProjectionIO =\n {#call unsafe GetProjectionRef as ^#} . unDataset\n >=> maybeSpatialReferenceFromCString\n\ndatasetProjection :: Dataset s a t -> GDAL s (Maybe SpatialReference)\ndatasetProjection = liftIO . datasetProjectionIO\n\n\nsetDatasetProjection :: SpatialReference -> RWDataset s a -> GDAL s ()\nsetDatasetProjection srs ds =\n liftIO $ checkCPLError \"SetProjection\" $\n useAsCString (srsToWkt srs)\n ({#call unsafe SetProjection as ^#} (unDataset ds))\n\nsetDatasetGCPs\n :: [GroundControlPoint] -> Maybe SpatialReference -> RWDataset s a\n -> GDAL s ()\nsetDatasetGCPs gcps mSrs ds =\n liftIO $\n checkCPLError \"setDatasetGCPs\" $\n withGCPArrayLen gcps $ \\nGcps pGcps ->\n withMaybeSRAsCString mSrs $\n {#call unsafe GDALSetGCPs as ^#}\n (unDataset ds)\n (fromIntegral nGcps)\n pGcps\n\ndatasetGCPs\n :: Dataset s a t\n -> GDAL s ([GroundControlPoint], Maybe SpatialReference)\ndatasetGCPs ds =\n liftIO $ do\n let pDs = unDataset ds\n srs <- maybeSpatialReferenceFromCString\n =<< {#call unsafe GetGCPProjection as ^#} pDs\n nGcps <- liftM fromIntegral ({#call unsafe GetGCPCount as ^#} pDs)\n gcps <- {#call unsafe GetGCPs as ^#} pDs >>= fromGCPArray nGcps\n return (gcps, srs)\n\n\ndata OverviewResampling\n = OvNearest\n | OvGauss\n | OvCubic\n | OvAverage\n | OvMode\n | OvAverageMagphase\n | OvNone\n\nbuildOverviews\n :: RWDataset s a -> OverviewResampling -> [Int] -> [Int] -> Maybe ProgressFun\n -> GDAL s ()\nbuildOverviews ds resampling overviews bands progressFun =\n liftIO $\n withResampling resampling $ \\pResampling ->\n withArrayLen (map fromIntegral overviews) $ \\nOverviews pOverviews ->\n withArrayLen (map fromIntegral bands) $ \\nBands pBands ->\n withProgressFun \"buildOverviews\" progressFun $ \\pFunc ->\n checkCPLError \"buildOverviews\" $\n {#call GDALBuildOverviews as ^#}\n (unDataset ds)\n pResampling\n (fromIntegral nOverviews)\n pOverviews\n (fromIntegral nBands)\n pBands\n pFunc\n nullPtr\n where\n withResampling OvNearest = unsafeUseAsCString \"NEAREST\\0\"\n withResampling OvGauss = unsafeUseAsCString \"GAUSS\\0\"\n withResampling OvCubic = unsafeUseAsCString \"CUBIC\\0\"\n withResampling OvAverage = unsafeUseAsCString \"AVERAGE\\0\"\n withResampling OvMode = unsafeUseAsCString \"MODE\\0\"\n withResampling OvAverageMagphase = unsafeUseAsCString \"AVERAGE_MAGPHASE\\0\"\n withResampling OvNone = unsafeUseAsCString \"NONE\\0\"\n\ndata Geotransform\n = Geotransform {\n gtXOff :: {-# UNPACK #-} !Double\n , gtXDelta :: {-# UNPACK #-} !Double\n , gtXRot :: {-# UNPACK #-} !Double\n , gtYOff :: {-# UNPACK #-} !Double\n , gtYRot :: {-# UNPACK #-} !Double\n , gtYDelta :: {-# UNPACK #-} !Double\n } deriving (Eq, Show)\n\nnorthUpGeotransform :: Size -> Envelope Double -> Geotransform\nnorthUpGeotransform size envelope =\n Geotransform {\n gtXOff = pFst (envelopeMin envelope)\n , gtXDelta = pFst (envelopeSize envelope \/ fmap fromIntegral size)\n , gtXRot = 0\n , gtYOff = pSnd (envelopeMax envelope)\n , gtYRot = 0\n , gtYDelta = negate (pSnd (envelopeSize envelope \/ fmap fromIntegral size))\n }\n\ngcpGeotransform :: [GroundControlPoint] -> ApproxOK -> Maybe Geotransform\ngcpGeotransform gcps approxOk =\n unsafePerformIO $\n alloca $ \\pGt ->\n withGCPArrayLen gcps $ \\nGcps pGcps -> do\n ret <- liftM toBool $\n {#call unsafe GCPsToGeoTransform as ^#}\n (fromIntegral nGcps)\n pGcps\n (castPtr pGt)\n (fromEnumC approxOk)\n if ret then liftM Just (peek pGt) else return Nothing\n\napplyGeotransform :: Geotransform -> Pair Double -> Pair Double\napplyGeotransform Geotransform{..} (x :+: y) =\n (gtXOff + gtXDelta*x + gtXRot * y) :+: (gtYOff + gtYRot *x + gtYDelta * y)\n{-# INLINE applyGeotransform #-}\n\ninfixr 5 |$|\n(|$|) :: Geotransform -> Pair Double -> Pair Double\n(|$|) = applyGeotransform\n\ninvertGeotransform :: Geotransform -> Maybe Geotransform\ninvertGeotransform (Geotransform g0 g1 g2 g3 g4 g5)\n | g2==0 && g4==0 && g1\/=0 && g5\/=0 -- No rotation\n = Just $! Geotransform (-g0\/g1) (1\/g1) 0 (-g3\/g5) 0 (1\/g5)\n | abs det < 1e-15 = Nothing -- not invertible\n | otherwise\n = Just $! Geotransform ((g2*g3 - g0*g5) * idet)\n (g5*idet)\n (-g2*idet)\n ((-g1*g3 + g0*g4) * idet)\n (-g4*idet)\n (g1*idet)\n where\n idet = 1\/det\n det = g1*g5 - g2*g4\n{-# INLINE invertGeotransform #-}\n\ninv :: Geotransform -> Geotransform\ninv = fromMaybe (error \"Could not invert geotransform\") . invertGeotransform\n\n-- | Creates a Geotransform equivalent to applying a and then b\ncomposeGeotransforms :: Geotransform -> Geotransform -> Geotransform\nb `composeGeotransforms` a =\n Geotransform (b1*a0 + b2*a3 + b0)\n (b1*a1 + b2*a4)\n (b1*a2 + b2*a5)\n (b4*a0 + b5*a3 + b3)\n (b4*a1 + b5*a4)\n (b4*a2 + b5*a5)\n\n where\n Geotransform a0 a1 a2 a3 a4 a5 = a\n Geotransform b0 b1 b2 b3 b4 b5 = b\n{-# INLINE composeGeotransforms #-}\n\ninfixr 9 |.|\n(|.|) :: Geotransform -> Geotransform -> Geotransform\n(|.|) = composeGeotransforms\n\ninstance Storable Geotransform where\n sizeOf _ = sizeOf (undefined :: CDouble) * 6\n alignment _ = alignment (undefined :: CDouble)\n poke pGt (Geotransform g0 g1 g2 g3 g4 g5) = do\n let p = castPtr pGt :: Ptr CDouble\n pokeElemOff p 0 (realToFrac g0)\n pokeElemOff p 1 (realToFrac g1)\n pokeElemOff p 2 (realToFrac g2)\n pokeElemOff p 3 (realToFrac g3)\n pokeElemOff p 4 (realToFrac g4)\n pokeElemOff p 5 (realToFrac g5)\n peek pGt = do\n let p = castPtr pGt :: Ptr CDouble\n Geotransform <$> liftM realToFrac (peekElemOff p 0)\n <*> liftM realToFrac (peekElemOff p 1)\n <*> liftM realToFrac (peekElemOff p 2)\n <*> liftM realToFrac (peekElemOff p 3)\n <*> liftM realToFrac (peekElemOff p 4)\n <*> liftM realToFrac (peekElemOff p 5)\n\n\ndatasetGeotransformIO :: Dataset s a t -> IO (Maybe Geotransform)\ndatasetGeotransformIO ds = alloca $ \\p -> do\n ret <- {#call unsafe GetGeoTransform as ^#} (unDataset ds) (castPtr p)\n if toEnumC ret == CE_None\n then liftM Just (peek p)\n else return Nothing\n\ndatasetGeotransform :: Dataset s a t -> GDAL s (Maybe Geotransform)\ndatasetGeotransform = liftIO . datasetGeotransformIO\n\n\nsetDatasetGeotransform :: Geotransform -> RWDataset s a -> GDAL s ()\nsetDatasetGeotransform gt ds = liftIO $\n checkCPLError \"SetGeoTransform\" $\n with gt ({#call unsafe SetGeoTransform as ^#} (unDataset ds) . castPtr)\n\n\ndatasetBandCount :: Dataset s a t -> GDAL s Int\ndatasetBandCount =\n liftM fromIntegral . liftIO . {#call unsafe GetRasterCount as ^#} . unDataset\n\ngetBand :: Int -> Dataset s a t -> GDAL s (Band s a t)\ngetBand b ds = liftIO $ do\n pB <- checkGDALCall checkit $\n {#call GetRasterBand as ^#} (unDataset ds) (fromIntegral b)\n dt <- liftM toEnumC ({#call unsafe GetRasterDataType as ^#} pB)\n return (Band (pB, dt))\n where\n checkit exc p\n | p == nullBandH = Just (fromMaybe (GDALBindingException NullBand) exc)\n | otherwise = Nothing\n\naddBand\n :: forall s a. GDALType a\n => OptionList -> RWDataset s a -> GDAL s (RWBand s a)\naddBand options ds = do\n liftIO $\n checkCPLError \"addBand\" $\n withOptionList options $\n {#call GDALAddBand as ^#} (unDataset ds) (fromEnumC dt)\n ix <- datasetBandCount ds\n getBand ix ds\n where dt = hsDataType (Proxy :: Proxy a)\n\nbandDataset :: Band s a t -> GDAL s (Dataset s a t)\nbandDataset b = newDatasetHandle $ do\n hDs <- {#call unsafe GDALGetBandDataset as ^#} (unBand b)\n void $ {#call unsafe GDALReferenceDataset as ^#} hDs\n return hDs\n\n\nbandBlockSize :: (Band s a t) -> Size\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n {#call unsafe GetBlockSize as ^#} (unBand band) xPtr yPtr\n liftM (fmap fromIntegral) (liftM2 (:+:) (peek xPtr) (peek yPtr))\n{-# NOINLINE bandBlockSize #-}\n\nbandBlockLen :: Band s a t -> Int\nbandBlockLen = (\\(x :+: y) -> x*y) . bandBlockSize\n\nbandSize :: Band s a t -> Size\nbandSize band =\n fmap fromIntegral $\n ({#call pure unsafe GetRasterBandXSize as ^#} (unBand band))\n :+: ({#call pure unsafe GetRasterBandYSize as ^#} (unBand band))\n{-# NOINLINE bandSize #-}\n\nallBand :: Band s a t -> Envelope Int\nallBand = Envelope (pure 0) . bandSize\n\nbandBlockCount :: Band s a t -> Pair Int\nbandBlockCount b = fmap ceiling $ liftA2 ((\/) :: Double -> Double -> Double)\n (fmap fromIntegral (bandSize b))\n (fmap fromIntegral (bandBlockSize b))\n\nbandHasOverviews :: Band s a t -> GDAL s Bool\nbandHasOverviews =\n liftIO . liftM toBool . {#call unsafe HasArbitraryOverviews as ^#} . unBand\n\nbandNodataValue :: GDALType a => Band s a t -> GDAL s (Maybe a)\nbandNodataValue b =\n liftIO $\n alloca $ \\p -> do\n value <- {#call unsafe GetRasterNoDataValue as ^#} (unBand b) p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just (fromCDouble value) else Nothing)\n{-# NOINLINE bandNodataValue #-}\n\n\nsetBandNodataValue :: GDALType a => a -> RWBand s a -> GDAL s ()\nsetBandNodataValue v b =\n liftIO $\n checkCPLError \"SetRasterNoDataValue\" $\n {#call unsafe SetRasterNoDataValue as ^#} (unBand b) (toCDouble v)\n\ncreateBandMask :: MaskType -> RWBand s a -> GDAL s ()\ncreateBandMask maskType band = liftIO $\n checkCPLError \"createBandMask\" $\n {#call CreateMaskBand as ^#} (unBand band) cflags\n where cflags = maskFlagsForType maskType\n\nreadBand :: forall s t a. GDALType a\n => (Band s a t)\n -> Envelope Int\n -> Size\n -> GDAL s (U.Vector (Value a))\nreadBand band win sz = liftM fromJust $ runConduit $\n yield win =$= unsafeBandConduit sz band =$= CL.head\n{-# INLINE readBand #-}\n\nbandConduit\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (U.Vector (Value a))\nbandConduit sz band =\n unsafeBandConduitM sz band =$= CL.mapM (liftIO . U.freeze)\n{-# INLINE bandConduit #-}\n\nunsafeBandConduit\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (U.Vector (Value a))\nunsafeBandConduit sz band =\n unsafeBandConduitM sz band =$= CL.mapM (liftIO . U.unsafeFreeze)\n{-# INLINE unsafeBandConduit #-}\n\n\nunsafeBandConduitM\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (UM.IOVector (Value a))\nunsafeBandConduitM (bx :+: by) band = do\n buf <- liftIO (M.new (bx*by))\n lift (bandMaskType band) >>= \\case\n MaskNoData -> do\n nd <- lift (noDataOrFail band)\n let vec = mkValueUMVector nd buf\n awaitForever $ \\win -> do\n liftIO (read_ band buf win)\n yield vec\n MaskAllValid -> do\n let vec = mkAllValidValueUMVector buf\n awaitForever $ \\win -> do\n liftIO (read_ band buf win)\n yield vec\n _ -> do\n mBuf <- liftIO $ M.replicate (bx*by) 0\n mask <- lift $ bandMask band\n let vec = mkMaskedValueUMVector mBuf buf\n awaitForever $ \\win -> do\n liftIO (read_ band buf win >> read_ mask mBuf win)\n yield vec\n where\n read_ :: forall a'. GDALType a'\n => Band s a' t -> Stm.IOVector a' -> Envelope Int -> IO ()\n read_ b vec win = do\n let sx :+: sy = envelopeSize win\n xoff :+: yoff = envelopeMin win\n Stm.unsafeWith vec $ \\ptr -> do\n checkCPLError \"RasterAdviseRead\" $\n {#call unsafe RasterAdviseRead as ^#}\n (unBand b)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n nullPtr\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand b)\n (fromEnumC GF_Read)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n 0\n 0\n{-# INLINE unsafeBandConduitM #-}\n\ngeoEnvelopeTransformer\n :: Geotransform -> Maybe (Envelope Double -> Envelope Int)\ngeoEnvelopeTransformer gt =\n case (gtXDelta gt < 0, gtYDelta gt<0, invertGeotransform gt) of\n (_,_,Nothing) -> Nothing\n (False,False,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let e0' = fmap round (applyGeotransform iGt e0)\n e1' = fmap round (applyGeotransform iGt e1)\n in Envelope e0' e1'\n (True,False,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x1 :+: y0 = fmap round (applyGeotransform iGt e0)\n x0 :+: y1 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n (False,True,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x0 :+: y1 = fmap round (applyGeotransform iGt e0)\n x1 :+: y0 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n (True,True,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x1 :+: y1 = fmap round (applyGeotransform iGt e0)\n x0 :+: y0 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n{-# INLINE geoEnvelopeTransformer #-}\n\n\nwriteBand\n :: forall s a. GDALType a\n => RWBand s a\n -> Envelope Int\n -> Size\n -> U.Vector (Value a)\n -> GDAL s ()\nwriteBand band win sz uvec =\n runConduit (yield (win, sz, uvec) =$= bandSink band)\n{-# INLINE writeBand #-}\n\n\n\nbandSink\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (Envelope Int, Size, U.Vector (Value a)) (GDAL s) ()\nbandSink band = lift (bandMaskType band) >>= \\case\n MaskNoData -> do\n nd <- lift (noDataOrFail band)\n awaitForever $ \\(win, sz, uvec) -> lift $\n write band win sz (toGVecWithNodata nd uvec)\n MaskAllValid ->\n awaitForever $ \\(win, sz, uvec) -> lift $\n maybe (throwBindingException BandDoesNotAllowNoData)\n (write band win sz)\n (toGVec uvec)\n _ -> do\n mBand <- lift (bandMask band)\n awaitForever $ \\(win, sz, uvec) -> lift $ do\n let (mask, vec) = toGVecWithMask uvec\n write band win sz vec\n write mBand win sz mask\n where\n\n write :: forall a'. GDALType a'\n => RWBand s a' -> Envelope Int -> Size -> St.Vector a' -> GDAL s ()\n write band' win sz@(bx :+: by) vec = do\n let sx :+: sy = envelopeSize win\n xoff :+: yoff = envelopeMin win\n if sizeLen sz \/= G.length vec\n then throwBindingException (InvalidRasterSize sz)\n else liftIO $\n St.unsafeWith vec $ \\ptr ->\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand band')\n (fromEnumC GF_Write)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n 0\n 0\n{-# INLINE bandSink #-}\n\nbandSinkGeo\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (Envelope Double, Size, U.Vector (Value a)) (GDAL s) ()\nbandSinkGeo band = do\n mGt <- lift (bracket (bandDataset band) closeDataset datasetGeotransform)\n case mGt >>= geoEnvelopeTransformer of\n Just trans -> CL.map (\\(e,s,v) -> (trans e,s,v)) =$= bandSink band\n Nothing -> lift (throwBindingException CannotInvertGeotransform)\n{-# INLINE bandSinkGeo #-}\n\nnoDataOrFail :: GDALType a => Band s a t -> GDAL s a\nnoDataOrFail = liftM (fromMaybe err) . bandNodataValue\n where\n err = error (\"GDAL.readMasked: band has GMF_NODATA flag but did \" ++\n \"not return a nodata value\")\n\nbandMask :: Band s a t -> GDAL s (Band s Word8 t)\nbandMask =\n liftIO . liftM (\\p -> Band (p,GByte)) . {#call GetMaskBand as ^#}\n . unBand\n\ndata MaskType\n = MaskNoData\n | MaskAllValid\n |\u00a0MaskPerBand\n |\u00a0MaskPerDataset\n\nbandMaskType :: Band s a t -> GDAL s MaskType\nbandMaskType band = do\n flags <- liftIO ({#call unsafe GetMaskFlags as ^#} (unBand band))\n let testFlag f = (fromEnumC f .&. flags) \/= 0\n return $ case () of\n () | testFlag GMF_NODATA -> MaskNoData\n () | testFlag GMF_ALL_VALID -> MaskAllValid\n () | testFlag GMF_PER_DATASET -> MaskPerDataset\n _ -> MaskPerBand\n\nmaskFlagsForType :: MaskType -> CInt\nmaskFlagsForType MaskNoData = fromEnumC GMF_NODATA\nmaskFlagsForType MaskAllValid = fromEnumC GMF_ALL_VALID\nmaskFlagsForType MaskPerBand = 0\nmaskFlagsForType MaskPerDataset = fromEnumC GMF_PER_DATASET\n\n{#enum define MaskFlag { GMF_ALL_VALID as GMF_ALL_VALID\n , GMF_PER_DATASET as GMF_PER_DATASET\n , GMF_ALPHA as GMF_ALPHA\n , GMF_NODATA as GMF_NODATA\n } deriving (Eq,Bounded,Show) #}\n\ncopyBand\n :: Band s a t -> RWBand s a -> OptionList\n -> Maybe ProgressFun -> GDAL s ()\ncopyBand src dst options progressFun =\n liftIO $\n withProgressFun \"copyBand\" progressFun $ \\pFunc ->\n withOptionList options $ \\o ->\n checkCPLError \"copyBand\" $\n {#call RasterBandCopyWholeRaster as ^#}\n (unBand src) (unBand dst) o pFunc nullPtr\n\nfillBand :: GDALType a => Value a -> RWBand s a -> GDAL s ()\nfillBand val b =\n runConduit (allBlocks b =$= CL.map (\\i -> (i,v)) =$= blockSink b)\n where v = G.replicate (bandBlockLen b) val\n\n\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s a t -> GDAL s b\nfoldl' f = ifoldl' (\\z _ v -> f z v)\n{-# INLINE foldl' #-}\n\nifoldl'\n :: forall s t a b. GDALType a\n => (b -> Pair Int -> Value a -> b) -> b -> Band s a t -> GDAL s b\nifoldl' f z band =\n runConduit (unsafeBlockSource band =$= CL.fold folder z)\n where\n !(mx :+: my) = liftA2 mod (bandSize band) (bandBlockSize band)\n !(nx :+: ny) = bandBlockCount band\n !(sx :+: sy) = bandBlockSize band\n {-# INLINE folder #-}\n folder !acc !(!(iB :+: jB), !vec) = go SPEC 0 0 acc\n where\n go !_ !i !j !acc'\n | i < stopx = go SPEC (i+1) j\n (f acc' ix (vec `G.unsafeIndex` (j*sx+i)))\n | j+1 < stopy = go SPEC 0 (j+1) acc'\n | otherwise = acc'\n where ix = iB*sx+i :+: jB*sy+j\n !stopx\n | mx \/= 0 && iB==nx-1 = mx\n | otherwise = sx\n !stopy\n | my \/= 0 && jB==ny-1 = my\n | otherwise = sy\n{-# INLINE ifoldl' #-}\n\nfoldlWindow'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s a t -> Envelope Int -> GDAL s b\nfoldlWindow' f b = ifoldlWindow' (\\z _ v -> f z v) b\n{-# INLINE foldlWindow' #-}\n\nifoldlWindow'\n :: forall s t a b. GDALType a\n => (b -> Pair Int -> Value a -> b)\n -> b -> Band s a t -> Envelope Int -> GDAL s b\nifoldlWindow' f z band (Envelope (x0 :+: y0) (x1 :+: y1)) = runConduit $\n allBlocks band =$= CL.filter inRange\n =$= decorate (unsafeBlockConduit band)\n =$= CL.fold folder z\n where\n inRange bIx = bx0 < x1 && x0 < bx1 && by0 < y1 && y0 < by1\n where\n !b0@(bx0 :+: by0) = bIx * bSize\n !(bx1 :+: by1) = b0 + bSize\n !(mx :+: my) = liftA2 mod (bandSize band) (bandBlockSize band)\n !(nx :+: ny) = bandBlockCount band\n !bSize@(sx :+: sy) = bandBlockSize band\n {-# INLINE folder #-}\n folder !acc !(!(iB :+: jB), !vec) = go SPEC 0 0 acc\n where\n go !_ !i !j !acc'\n | i < stopx = go SPEC (i+1) j acc''\n | j+1 < stopy = go SPEC 0 (j+1) acc'\n | otherwise = acc'\n where\n !ix@(ixx :+: ixy) = iB*sx+i :+: jB*sy+j\n acc''\n | x0 <= ixx && ixx < x1 && y0 <= ixy && ixy < y1\n = f acc' ix (vec `G.unsafeIndex` (j*sx+i))\n | otherwise = acc'\n !stopx\n | mx \/= 0 && iB==nx-1 = mx\n | otherwise = sx\n !stopy\n | my \/= 0 && jB==ny-1 = my\n | otherwise = sy\n{-# INLINE ifoldlWindow' #-}\n\nunsafeBlockSource\n :: GDALType a\n => Band s a t -> Source (GDAL s) (BlockIx, U.Vector (Value a))\nunsafeBlockSource band = allBlocks band =$= decorate (unsafeBlockConduit band)\n{-# INLINE unsafeBlockSource #-}\n\nblockSource\n :: GDALType a\n => Band s a t -> Source (GDAL s) (BlockIx, U.Vector (Value a))\nblockSource band = allBlocks band =$= decorate (blockConduit band)\n{-# INLINE blockSource #-}\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> BlockIx -> U.Vector (Value a) -> GDAL s ()\nwriteBandBlock band blockIx uvec =\n runConduit (yield (blockIx, uvec) =$= blockSink band)\n{-# INLINE writeBandBlock #-}\n\nfmapBand\n :: forall s a b t. (GDALType a, GDALType b)\n => (Value a -> Value b)\n -> Band s a t\n -> RWBand s b \n -> GDAL s ()\nfmapBand f src dst = runConduit $\n unsafeBlockSource src =$= CL.map (second (U.map f)) =$= blockSink dst\n{-# INLINE fmapBand #-}\n\n\nblockSink\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (BlockIx, U.Vector (Value a)) (GDAL s) ()\nblockSink band = do\n writeBlock <-\n if dtBand==dtBuf\n then return writeNative\n else do tempBuf <- liftIO (mallocForeignPtrBytes (len*szBand))\n return (writeTranslated tempBuf)\n lift (bandMaskType band) >>= \\case\n MaskNoData -> lift (noDataOrFail band) >>= sinkNodata writeBlock\n MaskAllValid -> sinkAllValid writeBlock\n _ -> lift (bandMask band) >>= sinkMask writeBlock\n\n where\n len = bandBlockLen band\n dtBand = bandDataType (band)\n szBand = sizeOfDataType dtBand\n dtBuf = hsDataType (Proxy :: Proxy a)\n szBuf = sizeOfDataType dtBuf\n\n sinkNodata writeBlock nd = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n St.unsafeWith (toGVecWithNodata nd vec) (writeBlock ix)\n\n\n sinkAllValid writeBlock = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n case toGVec vec of\n Just buf -> St.unsafeWith buf (writeBlock ix)\n Nothing -> throwBindingException BandDoesNotAllowNoData\n\n sinkMask writeBlock bMask = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n let (mask, vec') = toGVecWithMask vec\n off = bi * bs\n win = liftA2 min bs (rs - off)\n bi = fmap fromIntegral ix\n bs = fmap fromIntegral (bandBlockSize band)\n rs = fmap fromIntegral (bandSize band)\n St.unsafeWith vec' (writeBlock ix)\n St.unsafeWith mask $ \\pBuf ->\n checkCPLError \"WriteBlock\" $\n {#call RasterIO as ^#}\n (unBand bMask)\n (fromEnumC GF_Write)\n (pFst off)\n (pSnd off)\n (pFst win)\n (pSnd win)\n (castPtr pBuf)\n (pFst win)\n (pSnd win)\n (fromEnumC GByte)\n 0\n (pFst bs * fromIntegral (sizeOfDataType GByte))\n\n checkLen v\n | len \/= G.length v\n = throwBindingException (InvalidBlockSize (G.length v))\n | otherwise = return ()\n\n writeTranslated temp blockIx pBuf =\n withForeignPtr temp $ \\pTemp -> do\n {#call unsafe CopyWords as ^#}\n (castPtr pTemp)\n (fromEnumC dtBand)\n (fromIntegral szBand)\n (castPtr pBuf)\n (fromEnumC dtBuf)\n (fromIntegral szBuf)\n (fromIntegral len)\n writeNative blockIx pTemp\n\n writeNative blockIx pBuf =\n checkCPLError \"WriteBlock\" $\n {#call GDALWriteBlock as ^#}\n (unBand band)\n (pFst bi)\n (pSnd bi)\n (castPtr pBuf)\n where bi = fmap fromIntegral blockIx\n{-# INLINE blockSink #-}\n\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s a t -> BlockIx -> GDAL s (U.Vector (Value a))\nreadBandBlock band blockIx = liftM fromJust $ runConduit $\n yield blockIx =$= unsafeBlockConduit band =$= CL.head\n{-# INLINE readBandBlock #-}\n\n\nallBlocks :: Monad m => Band s a t -> Producer m BlockIx\nallBlocks band = CL.sourceList [x :+: y | y <- [0..ny-1], x <- [0..nx-1]]\n where\n !(nx :+: ny) = bandBlockCount band\n{-# INLINE allBlocks #-}\n\nblockConduit\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (U.Vector (Value a))\nblockConduit band =\n unsafeBlockConduitM band =$= CL.mapM (liftIO . U.freeze)\n{-# INLINE blockConduit #-}\n\nunsafeBlockConduit\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (U.Vector (Value a))\nunsafeBlockConduit band =\n unsafeBlockConduitM band =$= CL.mapM (liftIO . U.unsafeFreeze)\n{-# INLINE unsafeBlockConduit #-}\n\n\nunsafeBlockConduitM\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (UM.IOVector (Value a))\nunsafeBlockConduitM band = do\n buf <- liftIO (M.new len)\n maskType <- lift $ bandMaskType band\n case maskType of\n MaskNoData -> do\n noData <- lift $ noDataOrFail band\n blockReader (mkValueUMVector noData buf) buf (const (return ()))\n MaskAllValid ->\n blockReader (mkAllValidValueUMVector buf) buf (const (return ()))\n _ -> do\n mBuf <- liftIO $ M.replicate len 0\n mask <- lift $ bandMask band\n blockReader (mkMaskedValueUMVector mBuf buf) buf (readMask mask mBuf)\n where\n isNative = dtBand == dtBuf\n len = bandBlockLen band\n dtBand = bandDataType band\n dtBuf = hsDataType (Proxy :: Proxy a)\n\n {-# INLINE blockReader #-}\n blockReader vec buf extra\n | isNative = awaitForever $ \\ix -> do\n liftIO (Stm.unsafeWith buf (loadBlock ix))\n extra ix\n yield vec\n | otherwise = do\n temp <- liftIO $ mallocForeignPtrBytes (len*szBand)\n awaitForever $ \\ix -> do\n liftIO $ withForeignPtr temp $ \\pTemp -> do\n loadBlock ix pTemp\n Stm.unsafeWith buf (translateBlock pTemp)\n extra ix\n yield vec\n\n {-# INLINE loadBlock #-}\n loadBlock ix pBuf = \n checkCPLError \"ReadBlock\" $\n {#call ReadBlock as ^#}\n (unBand band)\n (fromIntegral (pFst ix))\n (fromIntegral (pSnd ix))\n (castPtr pBuf)\n\n {-# INLINE translateBlock #-}\n translateBlock pTemp pBuf = \n {#call unsafe CopyWords as ^#}\n (castPtr pTemp)\n (fromEnumC dtBand)\n (fromIntegral szBand)\n (castPtr pBuf)\n (fromEnumC dtBuf)\n (fromIntegral szBuf)\n (fromIntegral len)\n szBand = sizeOfDataType dtBand\n szBuf = sizeOfDataType dtBuf\n\n {-# INLINE readMask #-}\n readMask mask vMask ix =\n liftIO $\n Stm.unsafeWith vMask $ \\pMask ->\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand mask)\n (fromEnumC GF_Read)\n (pFst off)\n (pSnd off)\n (pFst win)\n (pSnd win)\n (castPtr pMask)\n (pFst win)\n (pSnd win)\n (fromEnumC GByte)\n 0\n (pFst bs)\n where\n bi = fmap fromIntegral ix\n off = bi * bs\n win = liftA2 min bs (rs - off)\n bs = fmap fromIntegral (bandBlockSize band)\n rs = fmap fromIntegral (bandSize band)\n{-# INLINE unsafeBlockConduitM #-}\n\nopenDatasetCount :: IO Int\nopenDatasetCount =\n alloca $ \\ppDs ->\n alloca $ \\pCount -> do\n {#call unsafe GetOpenDatasets as ^#} ppDs pCount\n liftM fromIntegral (peek pCount)\n\n-----------------------------------------------------------------------------\n-- Metadata\n-----------------------------------------------------------------------------\n\nmetadataDomains :: MajorObject o t => o t -> GDAL s [Text]\n#if SUPPORTS_METADATA_DOMAINS\nmetadataDomains o =\n liftIO $\n fromCPLStringList $\n {#call unsafe GetMetadataDomainList as ^#} (majorObject o)\n#else\nmetadataDomains = const (return [])\n#endif\n\nmetadata\n :: MajorObject o t\n => Maybe ByteString -> o t -> GDAL s [(Text,Text)]\nmetadata domain o =\n liftIO $\n withMaybeByteString domain\n ({#call unsafe GetMetadata as ^#} (majorObject o)\n >=> liftM (map breakIt) . fromBorrowedCPLStringList)\n where\n breakIt s =\n case T.break (=='=') s of\n (k,\"\") -> (k,\"\")\n (k, v) -> (k, T.tail v)\n\nmetadataItem\n :: MajorObject o t\n => Maybe ByteString -> ByteString -> o t -> GDAL s (Maybe ByteString)\nmetadataItem domain key o =\n liftIO $\n useAsCString key $ \\pKey ->\n withMaybeByteString domain $\n {#call unsafe GetMetadataItem as ^#} (majorObject o) pKey >=>\n maybePackCString\n\nsetMetadataItem\n :: (MajorObject o t, t ~ ReadWrite)\n => Maybe ByteString -> ByteString -> ByteString -> o t -> GDAL s ()\nsetMetadataItem domain key val o =\n liftIO $\n checkCPLError \"setMetadataItem\" $\n useAsCString key $ \\pKey ->\n useAsCString val $ \\pVal ->\n withMaybeByteString domain $\n {#call unsafe GDALSetMetadataItem as ^#} (majorObject o) pKey pVal\n\ndescription :: MajorObject o t => o t -> GDAL s ByteString\ndescription =\n liftIO . ({#call unsafe GetDescription as ^#} . majorObject >=> packCString)\n\nsetDescription\n :: (MajorObject o t, t ~ ReadWrite)\n => ByteString -> o t -> GDAL s ()\nsetDescription val =\n liftIO . checkGDALCall_ const .\n useAsCString val . {#call unsafe GDALSetDescription as ^#} . majorObject\n\n\n\n-----------------------------------------------------------------------------\n-- Conduit utils\n-----------------------------------------------------------------------------\n\n-- | Parallel zip of two conduits\npZipConduitApp\n :: Monad m\n => Conduit a m (b -> c)\n -> Conduit a m b\n -> Conduit a m c\npZipConduitApp (ConduitM l0) (ConduitM r0) = ConduitM $ \\rest -> let\n go (HaveOutput p c o) (HaveOutput p' c' o') =\n HaveOutput (go p p') (c>>c') (o o')\n go (NeedInput p c) (NeedInput p' c') =\n NeedInput (\\i -> go (p i) (p' i)) (\\u -> go (c u) (c' u))\n go (Done ()) (Done ()) = rest ()\n go (PipeM m) (PipeM m') = PipeM (liftM2 go m m')\n go (Leftover p i) (Leftover p' _) = Leftover (go p p') i\n go _ _ = error \"pZipConduitApp: not parallel\"\n in go (injectLeftovers $ l0 Done) (injectLeftovers $ r0 Done)\n\nnewtype PZipConduit i m o =\n PZipConduit { getPZipConduit :: Conduit i m o}\n\ninstance Monad m => Functor (PZipConduit i m) where\n fmap f = PZipConduit . mapOutput f . getPZipConduit\n\ninstance Monad m => Applicative (PZipConduit i m) where\n pure = PZipConduit . forever . yield\n PZipConduit l <*> PZipConduit r = PZipConduit (pZipConduitApp l r)\n\nzipBlocks\n :: GDALType a\n => Band s a t -> PZipConduit BlockIx (GDAL s) (U.Vector (Value a))\nzipBlocks = PZipConduit . unsafeBlockConduit\n\ngetZipBlocks\n :: PZipConduit BlockIx (GDAL s) a\n -> Conduit BlockIx (GDAL s) (BlockIx, a)\ngetZipBlocks = decorate . getPZipConduit\n\ndecorate :: Monad m => Conduit a m b -> Conduit a m (a, b)\ndecorate (ConduitM c0) = ConduitM $ \\rest -> let\n go1 HaveOutput{} = error \"unexpected NeedOutput\"\n go1 (NeedInput p c) = NeedInput (\\i -> go2 i (p i)) (go1 . c)\n go1 (Done r) = rest r\n go1 (PipeM mp) = PipeM (liftM (go1) mp)\n go1 (Leftover p i) = Leftover (go1 p) i\n\n go2 i (HaveOutput p c o) = HaveOutput (go2 i p) c (i, o)\n go2 _ (NeedInput p c) = NeedInput (\\i -> go2 i (p i)) (go1 . c)\n go2 _ (Done r) = rest r\n go2 i (PipeM mp) = PipeM (liftM (go2 i) mp)\n go2 i (Leftover p i') = Leftover (go2 i p) i'\n in go1 (c0 Done)\n{-# INLINE decorate #-}\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE LambdaCase #-}\n\n#include \"bindings.h\"\n\nmodule GDAL.Internal.GDAL (\n GDALRasterException (..)\n , Geotransform (..)\n , OverviewResampling (..)\n , Driver (..)\n , Dataset\n , DatasetH (..)\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , RasterBandH (..)\n , MaskType (..)\n\n , northUpGeotransform\n , gcpGeotransform\n , applyGeotransform\n , (|$|)\n , invertGeotransform\n , inv\n , composeGeotransforms\n , (|.|)\n , geoEnvelopeTransformer\n\n , nullDatasetH\n , allRegister\n , destroyDriverManager\n , create\n , createMem\n , delete\n , rename\n , copyFiles\n , flushCache\n , closeDataset\n , openReadOnly\n , openReadWrite\n , unsafeToReadOnly\n , createCopy\n , buildOverviews\n , driverCreationOptionList\n\n , bandAs\n\n , datasetDriver\n , datasetSize\n , datasetFileList\n , datasetProjection\n , datasetProjectionIO\n , setDatasetProjection\n , datasetGeotransform\n , datasetGeotransformIO\n , setDatasetGeotransform\n , datasetGCPs\n , setDatasetGCPs\n , datasetBandCount\n\n , bandDataType\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandHasOverviews\n , allBand\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , addBand\n , fillBand\n , fmapBand\n , readBand\n , createBandMask\n , readBandBlock\n , writeBand\n , writeBandBlock\n , copyBand\n , bandConduit\n , unsafeBandConduit\n , bandSink\n , bandSinkGeo\n\n , metadataDomains\n , metadata\n , metadataItem\n , setMetadataItem\n , description\n , setDescription\n\n , foldl'\n , ifoldl'\n , foldlWindow'\n , ifoldlWindow'\n , blockConduit\n , unsafeBlockConduit\n , blockSource\n , unsafeBlockSource\n , blockSink\n , allBlocks\n , zipBlocks\n , getZipBlocks\n\n , unDataset\n , unBand\n , version\n , newDatasetHandle\n , openDatasetCount\n\n , module GDAL.Internal.DataType\n) where\n\n{#context lib = \"gdal\" prefix = \"GDAL\" #}\n\nimport Control.Arrow (second)\nimport Control.Applicative (Applicative(..), (<$>), liftA2)\nimport Control.Concurrent.MVar (MVar, newMVar, takeMVar, putMVar)\nimport Control.Exception (Exception(..))\nimport Control.Monad (liftM, liftM2, when, (>=>), void, forever)\nimport Control.Monad.Trans (lift)\nimport Control.Monad.Catch (bracket)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Data.Bits ((.&.))\nimport Data.ByteString.Char8 (ByteString, packCString, useAsCString)\nimport Data.ByteString.Unsafe (unsafeUseAsCString)\nimport Data.Coerce (coerce)\nimport qualified Data.Conduit.List as CL\nimport Data.Conduit\nimport Data.Conduit.Internal (Pipe(..), ConduitM(..), injectLeftovers)\nimport Data.Maybe (fromMaybe, fromJust)\nimport Data.String (IsString)\nimport Data.Proxy\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport Data.Typeable (Typeable)\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport qualified Data.Vector.Generic.Mutable as M\nimport qualified Data.Vector.Unboxed.Mutable as UM\nimport qualified Data.Vector.Unboxed as U\nimport Data.Word (Word8)\n\nimport Foreign.C.String (withCString, CString)\nimport Foreign.C.Types\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrBytes)\nimport Foreign.Ptr (Ptr, FunPtr, castPtr, nullPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (withArrayLen)\nimport Foreign.Marshal.Utils (toBool, fromBool, with)\n\nimport GHC.Types (SPEC(..))\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.Types.Value\nimport GDAL.Internal.DataType\nimport GDAL.Internal.Common\nimport GDAL.Internal.Util\n{#import GDAL.Internal.GCP#}\n{#import GDAL.Internal.CPLError#}\n{#import GDAL.Internal.CPLString#}\n{#import GDAL.Internal.CPLProgress#}\nimport GDAL.Internal.OSR\nimport GDAL.Internal.OGRGeometry (Envelope(..), envelopeSize)\n\n\n#include \"gdal.h\"\n\nnewtype Driver = Driver ByteString\n deriving (Eq, IsString)\n\ninstance Show Driver where\n show (Driver s) = show s\n\nversion :: (Int, Int)\nversion = ({#const GDAL_VERSION_MAJOR#} , {#const GDAL_VERSION_MINOR#})\n\ndata GDALRasterException\n = InvalidRasterSize !Size\n | InvalidBlockSize !Int\n | InvalidDriverOptions\n | UnknownRasterDataType\n | NullDataset\n | NullBand\n | UnknownDriver !ByteString\n | BandDoesNotAllowNoData\n | CannotInvertGeotransform\n deriving (Typeable, Show, Eq)\n\ninstance Exception GDALRasterException where\n toException = bindingExceptionToException\n fromException = bindingExceptionFromException\n\n\n{#enum GDALAccess {} deriving (Eq, Show) #}\n\n{#enum RWFlag {} deriving (Eq, Show) #}\n\n{#pointer MajorObjectH newtype#}\n\nclass MajorObject o (t::AccessMode) where\n majorObject :: o t -> MajorObjectH\n\n\n{#pointer DatasetH newtype #}\n\n\nnullDatasetH :: DatasetH\nnullDatasetH = DatasetH nullPtr\n\nderiving instance Eq DatasetH\n\nnewtype Dataset s a (t::AccessMode) =\n Dataset (ReleaseKey, DatasetH)\n\ninstance MajorObject (Dataset s a) t where\n majorObject ds =\n let DatasetH p = unDataset ds\n in MajorObjectH (castPtr p)\n\nunDataset :: Dataset s a t -> DatasetH\nunDataset (Dataset (_,s)) = s\n\ncloseDataset :: MonadIO m => Dataset s a t -> m ()\ncloseDataset (Dataset (rk,_)) = release rk\n\ntype RODataset s a = Dataset s a ReadOnly\ntype RWDataset s a = Dataset s a ReadWrite\n\n{#pointer RasterBandH newtype #}\n\nnullBandH :: RasterBandH\nnullBandH = RasterBandH nullPtr\n\nderiving instance Eq RasterBandH\n\nnewtype Band s a (t::AccessMode) = Band (RasterBandH, DataTypeK)\n\nunBand :: Band s a t -> RasterBandH\nunBand (Band (p,_)) = p\n{-# INLINE unBand #-}\n\nbandDataType :: Band s a t -> DataTypeK\nbandDataType (Band (_,t)) = t\n{-# INLINE bandDataType #-}\n\nbandAs :: Band s a t -> DataType d -> Band s (HsType d) t\nbandAs = const . coerce\n{-# INLINE bandAs #-}\n\ninstance MajorObject (Band s a) t where\n majorObject b =\n let RasterBandH p = unBand b\n in MajorObjectH (castPtr p)\n\ntype ROBand s a = Band s a ReadOnly\ntype RWBand s a = Band s a ReadWrite\n\n\n{#pointer DriverH #}\n\n{#fun AllRegister as ^ {} -> `()' #}\n\n{#fun DestroyDriverManager as ^ {} -> `()'#}\n\ndriverByName :: Driver -> IO DriverH\ndriverByName (Driver s) = do\n d <- useAsCString s {#call unsafe GetDriverByName as ^#}\n if d == nullPtr\n then throwBindingException (UnknownDriver s)\n else return d\n\ndriverCreationOptionList :: Driver -> ByteString\ndriverCreationOptionList driver = unsafePerformIO $ do\n d <- driverByName driver\n {#call GetDriverCreationOptionList\tas ^#} d >>= packCString\n\nvalidateCreationOptions :: DriverH -> Ptr CString -> IO ()\nvalidateCreationOptions d o = do\n valid <- liftM toBool ({#call GDALValidateCreationOptions as ^ #} d o)\n when (not valid) (throwBindingException InvalidDriverOptions)\n\ncreate\n :: Driver -> String -> Size -> Int -> DataType d -> OptionList\n -> GDAL s (Dataset s (HsType d) ReadWrite)\ncreate drv path (nx :+: ny) bands dtype options =\n newDatasetHandle $ withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC dtype\n d <- driverByName drv\n withOptionList options $ \\opts -> do\n validateCreationOptions d opts\n {#call GDALCreate as ^#} d path' nx' ny' bands' dtype' opts\n\ndelete :: Driver -> String -> GDAL s ()\ndelete driver path =\n liftIO $\n checkCPLError \"deleteDataset\" $ do\n d <- driverByName driver\n withCString path ({#call DeleteDataset as ^#} d)\n\nrename :: Driver -> String -> String -> GDAL s ()\nrename driver newName oldName =\n liftIO $\n checkCPLError \"renameDataset\" $ do\n d <- driverByName driver\n withCString newName $\n withCString oldName . ({#call RenameDataset as ^#} d)\n\ncopyFiles :: Driver -> String -> String -> GDAL s ()\ncopyFiles driver newName oldName =\n liftIO $\n checkCPLError \"copyFiles\" $ do\n d <- driverByName driver\n withCString newName $\n withCString oldName . ({#call CopyDatasetFiles as ^#} d)\n\nopenReadOnly :: String -> DataType d -> GDAL s (RODataset s (HsType d))\nopenReadOnly p _ = openWithMode GA_ReadOnly p\n\nopenReadWrite :: String -> DataType d -> GDAL s (RWDataset s (HsType d))\nopenReadWrite p _ = openWithMode GA_Update p\n\n-- Opening datasets is not thread-safe with some drivers (eg: GeoTIFF)\n-- so we need a mutex\nopenMutex :: MVar ()\nopenMutex = unsafePerformIO (newMVar ())\n{-# NOINLINE openMutex #-}\n\nopenWithMode :: GDALAccess -> String -> GDAL s (Dataset s a t)\nopenWithMode m path =\n newDatasetHandle $\n bracket (takeMVar openMutex) (putMVar openMutex) $ const $\n withCString path $\n flip {#call GDALOpen as ^#} (fromEnumC m)\n\nunsafeToReadOnly :: RWDataset s a -> GDAL s (RODataset s a)\nunsafeToReadOnly ds = flushCache ds >> return (coerce ds)\n\ncreateCopy\n :: Driver -> String -> Dataset s a t -> Bool -> OptionList\n -> Maybe ProgressFun -> GDAL s (Dataset s a t)\ncreateCopy driver path ds strict options progressFun =\n newDatasetHandle $\n withProgressFun \"createCopy\" progressFun $ \\pFunc -> do\n d <- driverByName driver\n withOptionList options $ \\o -> do\n validateCreationOptions d o\n withCString path $ \\p ->\n {#call GDALCreateCopy as ^#}\n d p (unDataset ds) (fromBool strict) o pFunc nullPtr\n\n\n\nnewDatasetHandle :: IO DatasetH -> GDAL s (Dataset s a t)\nnewDatasetHandle act =\n liftM Dataset $ allocate (checkGDALCall checkit act) free\n where\n checkit exc p\n | p==nullDatasetH = Just (fromMaybe\n (GDALBindingException NullDataset) exc)\n | otherwise = Nothing\n free ds = do\n refCount <- {#call unsafe DereferenceDataset as ^#} ds\n when (refCount<=0) ({#call GDALClose as ^#} ds)\n\ncreateMem\n :: Size -> Int -> DataType d -> OptionList\n -> GDAL s (Dataset s (HsType d) ReadWrite)\ncreateMem = create \"Mem\" \"\"\n\nflushCache :: RWDataset s a -> GDAL s ()\nflushCache = liftIO . {#call GDALFlushCache as ^#} . unDataset\n\ndatasetDriver :: Dataset s a t -> Driver\ndatasetDriver ds =\n unsafePerformIO $\n liftM Driver $ do\n driver <-{#call unsafe GetDatasetDriver as ^#} (unDataset ds)\n {#call unsafe GetDriverShortName as ^#} driver >>= packCString\n\ndatasetSize :: Dataset s a t -> Size\ndatasetSize ds =\n fmap fromIntegral $\n ({#call pure unsafe GetRasterXSize as ^#} (unDataset ds))\n :+: ({#call pure unsafe GetRasterYSize as ^#} (unDataset ds))\n\ndatasetFileList :: Dataset s a t -> GDAL s [Text]\ndatasetFileList =\n liftIO .\n fromCPLStringList .\n {#call unsafe GetFileList as ^#} .\n unDataset\n\ndatasetProjectionIO :: Dataset s a t -> IO (Maybe SpatialReference)\ndatasetProjectionIO =\n {#call unsafe GetProjectionRef as ^#} . unDataset\n >=> maybeSpatialReferenceFromCString\n\ndatasetProjection :: Dataset s a t -> GDAL s (Maybe SpatialReference)\ndatasetProjection = liftIO . datasetProjectionIO\n\n\nsetDatasetProjection :: SpatialReference -> RWDataset s a -> GDAL s ()\nsetDatasetProjection srs ds =\n liftIO $ checkCPLError \"SetProjection\" $\n useAsCString (srsToWkt srs)\n ({#call unsafe SetProjection as ^#} (unDataset ds))\n\nsetDatasetGCPs\n :: [GroundControlPoint] -> Maybe SpatialReference -> RWDataset s a\n -> GDAL s ()\nsetDatasetGCPs gcps mSrs ds =\n liftIO $\n checkCPLError \"setDatasetGCPs\" $\n withGCPArrayLen gcps $ \\nGcps pGcps ->\n withMaybeSRAsCString mSrs $\n {#call unsafe GDALSetGCPs as ^#}\n (unDataset ds)\n (fromIntegral nGcps)\n pGcps\n\ndatasetGCPs\n :: Dataset s a t\n -> GDAL s ([GroundControlPoint], Maybe SpatialReference)\ndatasetGCPs ds =\n liftIO $ do\n let pDs = unDataset ds\n srs <- maybeSpatialReferenceFromCString\n =<< {#call unsafe GetGCPProjection as ^#} pDs\n nGcps <- liftM fromIntegral ({#call unsafe GetGCPCount as ^#} pDs)\n gcps <- {#call unsafe GetGCPs as ^#} pDs >>= fromGCPArray nGcps\n return (gcps, srs)\n\n\ndata OverviewResampling\n = OvNearest\n | OvGauss\n | OvCubic\n | OvAverage\n | OvMode\n | OvAverageMagphase\n | OvNone\n\nbuildOverviews\n :: RWDataset s a -> OverviewResampling -> [Int] -> [Int] -> Maybe ProgressFun\n -> GDAL s ()\nbuildOverviews ds resampling overviews bands progressFun =\n liftIO $\n withResampling resampling $ \\pResampling ->\n withArrayLen (map fromIntegral overviews) $ \\nOverviews pOverviews ->\n withArrayLen (map fromIntegral bands) $ \\nBands pBands ->\n withProgressFun \"buildOverviews\" progressFun $ \\pFunc ->\n checkCPLError \"buildOverviews\" $\n {#call GDALBuildOverviews as ^#}\n (unDataset ds)\n pResampling\n (fromIntegral nOverviews)\n pOverviews\n (fromIntegral nBands)\n pBands\n pFunc\n nullPtr\n where\n withResampling OvNearest = unsafeUseAsCString \"NEAREST\\0\"\n withResampling OvGauss = unsafeUseAsCString \"GAUSS\\0\"\n withResampling OvCubic = unsafeUseAsCString \"CUBIC\\0\"\n withResampling OvAverage = unsafeUseAsCString \"AVERAGE\\0\"\n withResampling OvMode = unsafeUseAsCString \"MODE\\0\"\n withResampling OvAverageMagphase = unsafeUseAsCString \"AVERAGE_MAGPHASE\\0\"\n withResampling OvNone = unsafeUseAsCString \"NONE\\0\"\n\ndata Geotransform\n = Geotransform {\n gtXOff :: {-# UNPACK #-} !Double\n , gtXDelta :: {-# UNPACK #-} !Double\n , gtXRot :: {-# UNPACK #-} !Double\n , gtYOff :: {-# UNPACK #-} !Double\n , gtYRot :: {-# UNPACK #-} !Double\n , gtYDelta :: {-# UNPACK #-} !Double\n } deriving (Eq, Show)\n\nnorthUpGeotransform :: Size -> Envelope Double -> Geotransform\nnorthUpGeotransform size envelope =\n Geotransform {\n gtXOff = pFst (envelopeMin envelope)\n , gtXDelta = pFst (envelopeSize envelope \/ fmap fromIntegral size)\n , gtXRot = 0\n , gtYOff = pSnd (envelopeMax envelope)\n , gtYRot = 0\n , gtYDelta = negate (pSnd (envelopeSize envelope \/ fmap fromIntegral size))\n }\n\ngcpGeotransform :: [GroundControlPoint] -> ApproxOK -> Maybe Geotransform\ngcpGeotransform gcps approxOk =\n unsafePerformIO $\n alloca $ \\pGt ->\n withGCPArrayLen gcps $ \\nGcps pGcps -> do\n ret <- liftM toBool $\n {#call unsafe GCPsToGeoTransform as ^#}\n (fromIntegral nGcps)\n pGcps\n (castPtr pGt)\n (fromEnumC approxOk)\n if ret then liftM Just (peek pGt) else return Nothing\n\napplyGeotransform :: Geotransform -> Pair Double -> Pair Double\napplyGeotransform Geotransform{..} (x :+: y) =\n (gtXOff + gtXDelta*x + gtXRot * y) :+: (gtYOff + gtYRot *x + gtYDelta * y)\n{-# INLINE applyGeotransform #-}\n\ninfixr 5 |$|\n(|$|) :: Geotransform -> Pair Double -> Pair Double\n(|$|) = applyGeotransform\n\ninvertGeotransform :: Geotransform -> Maybe Geotransform\ninvertGeotransform (Geotransform g0 g1 g2 g3 g4 g5)\n | g2==0 && g4==0 && g1\/=0 && g5\/=0 -- No rotation\n = Just $! Geotransform (-g0\/g1) (1\/g1) 0 (-g3\/g5) 0 (1\/g5)\n | abs det < 1e-15 = Nothing -- not invertible\n | otherwise\n = Just $! Geotransform ((g2*g3 - g0*g5) * idet)\n (g5*idet)\n (-g2*idet)\n ((-g1*g3 + g0*g4) * idet)\n (-g4*idet)\n (g1*idet)\n where\n idet = 1\/det\n det = g1*g5 - g2*g4\n{-# INLINE invertGeotransform #-}\n\ninv :: Geotransform -> Geotransform\ninv = fromMaybe (error \"Could not invert geotransform\") . invertGeotransform\n\n-- | Creates a Geotransform equivalent to applying a and then b\ncomposeGeotransforms :: Geotransform -> Geotransform -> Geotransform\nb `composeGeotransforms` a =\n Geotransform (b1*a0 + b2*a3 + b0)\n (b1*a1 + b2*a4)\n (b1*a2 + b2*a5)\n (b4*a0 + b5*a3 + b3)\n (b4*a1 + b5*a4)\n (b4*a2 + b5*a5)\n\n where\n Geotransform a0 a1 a2 a3 a4 a5 = a\n Geotransform b0 b1 b2 b3 b4 b5 = b\n{-# INLINE composeGeotransforms #-}\n\ninfixr 9 |.|\n(|.|) :: Geotransform -> Geotransform -> Geotransform\n(|.|) = composeGeotransforms\n\ninstance Storable Geotransform where\n sizeOf _ = sizeOf (undefined :: CDouble) * 6\n alignment _ = alignment (undefined :: CDouble)\n poke pGt (Geotransform g0 g1 g2 g3 g4 g5) = do\n let p = castPtr pGt :: Ptr CDouble\n pokeElemOff p 0 (realToFrac g0)\n pokeElemOff p 1 (realToFrac g1)\n pokeElemOff p 2 (realToFrac g2)\n pokeElemOff p 3 (realToFrac g3)\n pokeElemOff p 4 (realToFrac g4)\n pokeElemOff p 5 (realToFrac g5)\n peek pGt = do\n let p = castPtr pGt :: Ptr CDouble\n Geotransform <$> liftM realToFrac (peekElemOff p 0)\n <*> liftM realToFrac (peekElemOff p 1)\n <*> liftM realToFrac (peekElemOff p 2)\n <*> liftM realToFrac (peekElemOff p 3)\n <*> liftM realToFrac (peekElemOff p 4)\n <*> liftM realToFrac (peekElemOff p 5)\n\n\ndatasetGeotransformIO :: Dataset s a t -> IO (Maybe Geotransform)\ndatasetGeotransformIO ds = alloca $ \\p -> do\n ret <- {#call unsafe GetGeoTransform as ^#} (unDataset ds) (castPtr p)\n if toEnumC ret == CE_None\n then liftM Just (peek p)\n else return Nothing\n\ndatasetGeotransform :: Dataset s a t -> GDAL s (Maybe Geotransform)\ndatasetGeotransform = liftIO . datasetGeotransformIO\n\n\nsetDatasetGeotransform :: Geotransform -> RWDataset s a -> GDAL s ()\nsetDatasetGeotransform gt ds = liftIO $\n checkCPLError \"SetGeoTransform\" $\n with gt ({#call unsafe SetGeoTransform as ^#} (unDataset ds) . castPtr)\n\n\ndatasetBandCount :: Dataset s a t -> GDAL s Int\ndatasetBandCount =\n liftM fromIntegral . liftIO . {#call unsafe GetRasterCount as ^#} . unDataset\n\ngetBand :: Int -> Dataset s a t -> GDAL s (Band s a t)\ngetBand b ds = liftIO $ do\n pB <- checkGDALCall checkit $\n {#call GetRasterBand as ^#} (unDataset ds) (fromIntegral b)\n dt <- liftM toEnumC ({#call unsafe GetRasterDataType as ^#} pB)\n return (Band (pB, dt))\n where\n checkit exc p\n | p == nullBandH = Just (fromMaybe (GDALBindingException NullBand) exc)\n | otherwise = Nothing\n\naddBand\n :: forall s a. GDALType a\n => OptionList -> RWDataset s a -> GDAL s (RWBand s a)\naddBand options ds = do\n liftIO $\n checkCPLError \"addBand\" $\n withOptionList options $\n {#call GDALAddBand as ^#} (unDataset ds) (fromEnumC dt)\n ix <- datasetBandCount ds\n getBand ix ds\n where dt = hsDataType (Proxy :: Proxy a)\n\nbandDataset :: Band s a t -> GDAL s (Dataset s a t)\nbandDataset b = newDatasetHandle $ do\n hDs <- {#call unsafe GDALGetBandDataset as ^#} (unBand b)\n void $ {#call unsafe GDALReferenceDataset as ^#} hDs\n return hDs\n\n\nbandBlockSize :: (Band s a t) -> Size\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n {#call unsafe GetBlockSize as ^#} (unBand band) xPtr yPtr\n liftM (fmap fromIntegral) (liftM2 (:+:) (peek xPtr) (peek yPtr))\n{-# NOINLINE bandBlockSize #-}\n\nbandBlockLen :: Band s a t -> Int\nbandBlockLen = (\\(x :+: y) -> x*y) . bandBlockSize\n\nbandSize :: Band s a t -> Size\nbandSize band =\n fmap fromIntegral $\n ({#call pure unsafe GetRasterBandXSize as ^#} (unBand band))\n :+: ({#call pure unsafe GetRasterBandYSize as ^#} (unBand band))\n{-# NOINLINE bandSize #-}\n\nallBand :: Band s a t -> Envelope Int\nallBand = Envelope (pure 0) . bandSize\n\nbandBlockCount :: Band s a t -> Pair Int\nbandBlockCount b = fmap ceiling $ liftA2 ((\/) :: Double -> Double -> Double)\n (fmap fromIntegral (bandSize b))\n (fmap fromIntegral (bandBlockSize b))\n\nbandHasOverviews :: Band s a t -> GDAL s Bool\nbandHasOverviews =\n liftIO . liftM toBool . {#call unsafe HasArbitraryOverviews as ^#} . unBand\n\nbandNodataValue :: GDALType a => Band s a t -> GDAL s (Maybe a)\nbandNodataValue b =\n liftIO $\n alloca $ \\p -> do\n value <- {#call unsafe GetRasterNoDataValue as ^#} (unBand b) p\n hasNodata <- liftM toBool $ peek p\n return (if hasNodata then Just (fromCDouble value) else Nothing)\n{-# NOINLINE bandNodataValue #-}\n\n\nsetBandNodataValue :: GDALType a => a -> RWBand s a -> GDAL s ()\nsetBandNodataValue v b =\n liftIO $\n checkCPLError \"SetRasterNoDataValue\" $\n {#call unsafe SetRasterNoDataValue as ^#} (unBand b) (toCDouble v)\n\ncreateBandMask :: MaskType -> RWBand s a -> GDAL s ()\ncreateBandMask maskType band = liftIO $\n checkCPLError \"createBandMask\" $\n {#call CreateMaskBand as ^#} (unBand band) cflags\n where cflags = maskFlagsForType maskType\n\nreadBand :: forall s t a. GDALType a\n => (Band s a t)\n -> Envelope Int\n -> Size\n -> GDAL s (U.Vector (Value a))\nreadBand band win sz = liftM fromJust $ runConduit $\n yield win =$= unsafeBandConduit sz band =$= CL.head\n{-# INLINE readBand #-}\n\nbandConduit\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (U.Vector (Value a))\nbandConduit sz band =\n unsafeBandConduitM sz band =$= CL.mapM (liftIO . U.freeze)\n{-# INLINE bandConduit #-}\n\nunsafeBandConduit\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (U.Vector (Value a))\nunsafeBandConduit sz band =\n unsafeBandConduitM sz band =$= CL.mapM (liftIO . U.unsafeFreeze)\n{-# INLINE unsafeBandConduit #-}\n\n\nunsafeBandConduitM\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (UM.IOVector (Value a))\nunsafeBandConduitM (bx :+: by) band = do\n buf <- liftIO (M.new (bx*by))\n lift (bandMaskType band) >>= \\case\n MaskNoData -> do\n nd <- lift (noDataOrFail band)\n let vec = mkValueUMVector nd buf\n awaitForever $ \\win -> do\n liftIO (read_ band buf win)\n yield vec\n MaskAllValid -> do\n let vec = mkAllValidValueUMVector buf\n awaitForever $ \\win -> do\n liftIO (read_ band buf win)\n yield vec\n _ -> do\n mBuf <- liftIO $ M.replicate (bx*by) 0\n mask <- lift $ bandMask band\n let vec = mkMaskedValueUMVector mBuf buf\n awaitForever $ \\win -> do\n liftIO (read_ band buf win >> read_ mask mBuf win)\n yield vec\n where\n read_ :: forall a'. GDALType a'\n => Band s a' t -> Stm.IOVector a' -> Envelope Int -> IO ()\n read_ b vec win = do\n let sx :+: sy = envelopeSize win\n xoff :+: yoff = envelopeMin win\n Stm.unsafeWith vec $ \\ptr -> do\n checkCPLError \"RasterAdviseRead\" $\n {#call unsafe RasterAdviseRead as ^#}\n (unBand b)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n nullPtr\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand b)\n (fromEnumC GF_Read)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n 0\n 0\n{-# INLINE unsafeBandConduitM #-}\n\ngeoEnvelopeTransformer\n :: Geotransform -> Maybe (Envelope Double -> Envelope Int)\ngeoEnvelopeTransformer gt =\n case (gtXDelta gt < 0, gtYDelta gt<0, invertGeotransform gt) of\n (_,_,Nothing) -> Nothing\n (False,False,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let e0' = fmap round (applyGeotransform iGt e0)\n e1' = fmap round (applyGeotransform iGt e1)\n in Envelope e0' e1'\n (True,False,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x1 :+: y0 = fmap round (applyGeotransform iGt e0)\n x0 :+: y1 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n (False,True,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x0 :+: y1 = fmap round (applyGeotransform iGt e0)\n x1 :+: y0 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n (True,True,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x1 :+: y1 = fmap round (applyGeotransform iGt e0)\n x0 :+: y0 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n{-# INLINE geoEnvelopeTransformer #-}\n\n\nwriteBand\n :: forall s a. GDALType a\n => RWBand s a\n -> Envelope Int\n -> Size\n -> U.Vector (Value a)\n -> GDAL s ()\nwriteBand band win sz uvec =\n runConduit (yield (win, sz, uvec) =$= bandSink band)\n{-# INLINE writeBand #-}\n\n\n\nbandSink\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (Envelope Int, Size, U.Vector (Value a)) (GDAL s) ()\nbandSink band = lift (bandMaskType band) >>= \\case\n MaskNoData -> do\n nd <- lift (noDataOrFail band)\n awaitForever $ \\(win, sz, uvec) -> lift $\n write band win sz (toGVecWithNodata nd uvec)\n MaskAllValid ->\n awaitForever $ \\(win, sz, uvec) -> lift $\n maybe (throwBindingException BandDoesNotAllowNoData)\n (write band win sz)\n (toGVec uvec)\n _ -> do\n mBand <- lift (bandMask band)\n awaitForever $ \\(win, sz, uvec) -> lift $ do\n let (mask, vec) = toGVecWithMask uvec\n write band win sz vec\n write mBand win sz mask\n where\n\n write :: forall a'. GDALType a'\n => RWBand s a' -> Envelope Int -> Size -> St.Vector a' -> GDAL s ()\n write band' win sz@(bx :+: by) vec = do\n let sx :+: sy = envelopeSize win\n xoff :+: yoff = envelopeMin win\n if sizeLen sz \/= G.length vec\n then throwBindingException (InvalidRasterSize sz)\n else liftIO $\n St.unsafeWith vec $ \\ptr ->\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand band')\n (fromEnumC GF_Write)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n 0\n 0\n{-# INLINE bandSink #-}\n\nbandSinkGeo\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (Envelope Double, Size, U.Vector (Value a)) (GDAL s) ()\nbandSinkGeo band = do\n mGt <- lift (bracket (bandDataset band) closeDataset datasetGeotransform)\n case mGt >>= geoEnvelopeTransformer of\n Just trans -> CL.map (\\(e,s,v) -> (trans e,s,v)) =$= bandSink band\n Nothing -> lift (throwBindingException CannotInvertGeotransform)\n{-# INLINE bandSinkGeo #-}\n\nnoDataOrFail :: GDALType a => Band s a t -> GDAL s a\nnoDataOrFail = liftM (fromMaybe err) . bandNodataValue\n where\n err = error (\"GDAL.readMasked: band has GMF_NODATA flag but did \" ++\n \"not return a nodata value\")\n\nbandMask :: Band s a t -> GDAL s (Band s Word8 t)\nbandMask =\n liftIO . liftM (\\p -> Band (p,GByte)) . {#call GetMaskBand as ^#}\n . unBand\n\ndata MaskType\n = MaskNoData\n | MaskAllValid\n |\u00a0MaskPerBand\n |\u00a0MaskPerDataset\n\nbandMaskType :: Band s a t -> GDAL s MaskType\nbandMaskType band = do\n flags <- liftIO ({#call unsafe GetMaskFlags as ^#} (unBand band))\n let testFlag f = (fromEnumC f .&. flags) \/= 0\n return $ case () of\n () | testFlag GMF_NODATA -> MaskNoData\n () | testFlag GMF_ALL_VALID -> MaskAllValid\n () | testFlag GMF_PER_DATASET -> MaskPerDataset\n _ -> MaskPerBand\n\nmaskFlagsForType :: MaskType -> CInt\nmaskFlagsForType MaskNoData = fromEnumC GMF_NODATA\nmaskFlagsForType MaskAllValid = fromEnumC GMF_ALL_VALID\nmaskFlagsForType MaskPerBand = 0\nmaskFlagsForType MaskPerDataset = fromEnumC GMF_PER_DATASET\n\n{#enum define MaskFlag { GMF_ALL_VALID as GMF_ALL_VALID\n , GMF_PER_DATASET as GMF_PER_DATASET\n , GMF_ALPHA as GMF_ALPHA\n , GMF_NODATA as GMF_NODATA\n } deriving (Eq,Bounded,Show) #}\n\ncopyBand\n :: Band s a t -> RWBand s a -> OptionList\n -> Maybe ProgressFun -> GDAL s ()\ncopyBand src dst options progressFun =\n liftIO $\n withProgressFun \"copyBand\" progressFun $ \\pFunc ->\n withOptionList options $ \\o ->\n checkCPLError \"copyBand\" $\n {#call RasterBandCopyWholeRaster as ^#}\n (unBand src) (unBand dst) o pFunc nullPtr\n\nfillBand :: GDALType a => Value a -> RWBand s a -> GDAL s ()\nfillBand val b =\n runConduit (allBlocks b =$= CL.map (\\i -> (i,v)) =$= blockSink b)\n where v = G.replicate (bandBlockLen b) val\n\n\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s a t -> GDAL s b\nfoldl' f = ifoldl' (\\z _ v -> f z v)\n{-# INLINE foldl' #-}\n\nifoldl'\n :: forall s t a b. GDALType a\n => (b -> Pair Int -> Value a -> b) -> b -> Band s a t -> GDAL s b\nifoldl' f z band =\n runConduit (unsafeBlockSource band =$= CL.fold folder z)\n where\n !(mx :+: my) = liftA2 mod (bandSize band) (bandBlockSize band)\n !(nx :+: ny) = bandBlockCount band\n !(sx :+: sy) = bandBlockSize band\n {-# INLINE folder #-}\n folder !acc !(!(iB :+: jB), !vec) = go SPEC 0 0 acc\n where\n go !_ !i !j !acc'\n | i < stopx = go SPEC (i+1) j\n (f acc' ix (vec `G.unsafeIndex` (j*sx+i)))\n | j+1 < stopy = go SPEC 0 (j+1) acc'\n | otherwise = acc'\n where ix = iB*sx+i :+: jB*sy+j\n !stopx\n | mx \/= 0 && iB==nx-1 = mx\n | otherwise = sx\n !stopy\n | my \/= 0 && jB==ny-1 = my\n | otherwise = sy\n{-# INLINE ifoldl' #-}\n\nfoldlWindow'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s a t -> Envelope Int -> GDAL s b\nfoldlWindow' f b = ifoldlWindow' (\\z _ v -> f z v) b\n{-# INLINE foldlWindow' #-}\n\nifoldlWindow'\n :: forall s t a b. GDALType a\n => (b -> Pair Int -> Value a -> b)\n -> b -> Band s a t -> Envelope Int -> GDAL s b\nifoldlWindow' f z band (Envelope (x0 :+: y0) (x1 :+: y1)) = runConduit $\n allBlocks band =$= CL.filter inRange\n =$= decorate (unsafeBlockConduit band)\n =$= CL.fold folder z\n where\n inRange bIx = bx0 < x1 && x0 < bx1 && by0 < y1 && y0 < by1\n where\n !b0@(bx0 :+: by0) = bIx * bSize\n !(bx1 :+: by1) = b0 + bSize\n !(mx :+: my) = liftA2 mod (bandSize band) (bandBlockSize band)\n !(nx :+: ny) = bandBlockCount band\n !bSize@(sx :+: sy) = bandBlockSize band\n {-# INLINE folder #-}\n folder !acc !(!(iB :+: jB), !vec) = go SPEC 0 0 acc\n where\n go !_ !i !j !acc'\n | i < stopx = go SPEC (i+1) j acc''\n | j+1 < stopy = go SPEC 0 (j+1) acc'\n | otherwise = acc'\n where\n !ix@(ixx :+: ixy) = iB*sx+i :+: jB*sy+j\n acc''\n | x0 <= ixx && ixx < x1 && y0 <= ixy && ixy < y1\n = f acc' ix (vec `G.unsafeIndex` (j*sx+i))\n | otherwise = acc'\n !stopx\n | mx \/= 0 && iB==nx-1 = mx\n | otherwise = sx\n !stopy\n | my \/= 0 && jB==ny-1 = my\n | otherwise = sy\n{-# INLINE ifoldlWindow' #-}\n\nunsafeBlockSource\n :: GDALType a\n => Band s a t -> Source (GDAL s) (BlockIx, U.Vector (Value a))\nunsafeBlockSource band = allBlocks band =$= decorate (unsafeBlockConduit band)\n{-# INLINE unsafeBlockSource #-}\n\nblockSource\n :: GDALType a\n => Band s a t -> Source (GDAL s) (BlockIx, U.Vector (Value a))\nblockSource band = allBlocks band =$= decorate (blockConduit band)\n{-# INLINE blockSource #-}\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> BlockIx -> U.Vector (Value a) -> GDAL s ()\nwriteBandBlock band blockIx uvec =\n runConduit (yield (blockIx, uvec) =$= blockSink band)\n{-# INLINE writeBandBlock #-}\n\nfmapBand\n :: forall s a b t. (GDALType a, GDALType b)\n => (Value a -> Value b)\n -> Band s a t\n -> RWBand s b \n -> GDAL s ()\nfmapBand f src dst = runConduit $\n unsafeBlockSource src =$= CL.map (second (U.map f)) =$= blockSink dst\n{-# INLINE fmapBand #-}\n\n\nblockSink\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (BlockIx, U.Vector (Value a)) (GDAL s) ()\nblockSink band = do\n writeBlock <-\n if dtBand==dtBuf\n then return writeNative\n else do tempBuf <- liftIO (mallocForeignPtrBytes (len*szBand))\n return (writeTranslated tempBuf)\n lift (bandMaskType band) >>= \\case\n MaskNoData -> lift (noDataOrFail band) >>= sinkNodata writeBlock\n MaskAllValid -> sinkAllValid writeBlock\n _ -> lift (bandMask band) >>= sinkMask writeBlock\n\n where\n len = bandBlockLen band\n dtBand = bandDataType (band)\n szBand = sizeOfDataType dtBand\n dtBuf = hsDataType (Proxy :: Proxy a)\n szBuf = sizeOfDataType dtBuf\n\n sinkNodata writeBlock nd = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n St.unsafeWith (toGVecWithNodata nd vec) (writeBlock ix)\n\n\n sinkAllValid writeBlock = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n case toGVec vec of\n Just buf -> St.unsafeWith buf (writeBlock ix)\n Nothing -> throwBindingException BandDoesNotAllowNoData\n\n sinkMask writeBlock bMask = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n let (mask, vec') = toGVecWithMask vec\n off = bi * bs\n win = liftA2 min bs (rs - off)\n bi = fmap fromIntegral ix\n bs = fmap fromIntegral (bandBlockSize band)\n rs = fmap fromIntegral (bandSize band)\n St.unsafeWith vec' (writeBlock ix)\n St.unsafeWith mask $ \\pBuf ->\n checkCPLError \"WriteBlock\" $\n {#call RasterIO as ^#}\n (unBand bMask)\n (fromEnumC GF_Write)\n (pFst off)\n (pSnd off)\n (pFst win)\n (pSnd win)\n (castPtr pBuf)\n (pFst win)\n (pSnd win)\n (fromEnumC GByte)\n 0\n (pFst bs * fromIntegral (sizeOfDataType GByte))\n\n checkLen v\n | len \/= G.length v\n = throwBindingException (InvalidBlockSize (G.length v))\n | otherwise = return ()\n\n writeTranslated temp blockIx pBuf =\n withForeignPtr temp $ \\pTemp -> do\n {#call unsafe CopyWords as ^#}\n (castPtr pTemp)\n (fromEnumC dtBand)\n (fromIntegral szBand)\n (castPtr pBuf)\n (fromEnumC dtBuf)\n (fromIntegral szBuf)\n (fromIntegral len)\n writeNative blockIx pTemp\n\n writeNative blockIx pBuf =\n checkCPLError \"WriteBlock\" $\n {#call GDALWriteBlock as ^#}\n (unBand band)\n (pFst bi)\n (pSnd bi)\n (castPtr pBuf)\n where bi = fmap fromIntegral blockIx\n{-# INLINE blockSink #-}\n\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s a t -> BlockIx -> GDAL s (U.Vector (Value a))\nreadBandBlock band blockIx = liftM fromJust $ runConduit $\n yield blockIx =$= unsafeBlockConduit band =$= CL.head\n{-# INLINE readBandBlock #-}\n\n\nallBlocks :: Monad m => Band s a t -> Producer m BlockIx\nallBlocks band = CL.sourceList [x :+: y | y <- [0..ny-1], x <- [0..nx-1]]\n where\n !(nx :+: ny) = bandBlockCount band\n{-# INLINE allBlocks #-}\n\nblockConduit\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (U.Vector (Value a))\nblockConduit band =\n unsafeBlockConduitM band =$= CL.mapM (liftIO . U.freeze)\n{-# INLINE blockConduit #-}\n\nunsafeBlockConduit\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (U.Vector (Value a))\nunsafeBlockConduit band =\n unsafeBlockConduitM band =$= CL.mapM (liftIO . U.unsafeFreeze)\n{-# INLINE unsafeBlockConduit #-}\n\n\nunsafeBlockConduitM\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (UM.IOVector (Value a))\nunsafeBlockConduitM band = do\n buf <- liftIO (M.new len)\n maskType <- lift $ bandMaskType band\n case maskType of\n MaskNoData -> do\n noData <- lift $ noDataOrFail band\n blockReader (mkValueUMVector noData buf) buf (const (return ()))\n MaskAllValid ->\n blockReader (mkAllValidValueUMVector buf) buf (const (return ()))\n _ -> do\n mBuf <- liftIO $ M.replicate len 0\n mask <- lift $ bandMask band\n blockReader (mkMaskedValueUMVector mBuf buf) buf (readMask mask mBuf)\n where\n isNative = dtBand == dtBuf\n len = bandBlockLen band\n dtBand = bandDataType band\n dtBuf = hsDataType (Proxy :: Proxy a)\n\n {-# INLINE blockReader #-}\n blockReader vec buf extra\n | isNative = awaitForever $ \\ix -> do\n liftIO (Stm.unsafeWith buf (loadBlock ix))\n extra ix\n yield vec\n | otherwise = do\n temp <- liftIO $ mallocForeignPtrBytes (len*szBand)\n awaitForever $ \\ix -> do\n liftIO $ withForeignPtr temp $ \\pTemp -> do\n loadBlock ix pTemp\n Stm.unsafeWith buf (translateBlock pTemp)\n extra ix\n yield vec\n\n {-# INLINE loadBlock #-}\n loadBlock ix pBuf = \n checkCPLError \"ReadBlock\" $\n {#call ReadBlock as ^#}\n (unBand band)\n (fromIntegral (pFst ix))\n (fromIntegral (pSnd ix))\n (castPtr pBuf)\n\n {-# INLINE translateBlock #-}\n translateBlock pTemp pBuf = \n {#call unsafe CopyWords as ^#}\n (castPtr pTemp)\n (fromEnumC dtBand)\n (fromIntegral szBand)\n (castPtr pBuf)\n (fromEnumC dtBuf)\n (fromIntegral szBuf)\n (fromIntegral len)\n szBand = sizeOfDataType dtBand\n szBuf = sizeOfDataType dtBuf\n\n {-# INLINE readMask #-}\n readMask mask vMask ix =\n liftIO $\n Stm.unsafeWith vMask $ \\pMask ->\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand mask)\n (fromEnumC GF_Read)\n (pFst off)\n (pSnd off)\n (pFst win)\n (pSnd win)\n (castPtr pMask)\n (pFst win)\n (pSnd win)\n (fromEnumC GByte)\n 0\n (pFst bs)\n where\n bi = fmap fromIntegral ix\n off = bi * bs\n win = liftA2 min bs (rs - off)\n bs = fmap fromIntegral (bandBlockSize band)\n rs = fmap fromIntegral (bandSize band)\n{-# INLINE unsafeBlockConduitM #-}\n\nopenDatasetCount :: IO Int\nopenDatasetCount =\n alloca $ \\ppDs ->\n alloca $ \\pCount -> do\n {#call unsafe GetOpenDatasets as ^#} ppDs pCount\n liftM fromIntegral (peek pCount)\n\n-----------------------------------------------------------------------------\n-- Metadata\n-----------------------------------------------------------------------------\n\nmetadataDomains :: MajorObject o t => o t -> GDAL s [Text]\n#if SUPPORTS_METADATA_DOMAINS\nmetadataDomains o =\n liftIO $\n fromCPLStringList $\n {#call unsafe GetMetadataDomainList as ^#} (majorObject o)\n#else\nmetadataDomains = const (return [])\n#endif\n\nmetadata\n :: MajorObject o t\n => Maybe ByteString -> o t -> GDAL s [(Text,Text)]\nmetadata domain o =\n liftIO $\n withMaybeByteString domain\n ({#call unsafe GetMetadata as ^#} (majorObject o)\n >=> liftM (map breakIt) . fromBorrowedCPLStringList)\n where\n breakIt s =\n case T.break (=='=') s of\n (k,\"\") -> (k,\"\")\n (k, v) -> (k, T.tail v)\n\nmetadataItem\n :: MajorObject o t\n => Maybe ByteString -> ByteString -> o t -> GDAL s (Maybe ByteString)\nmetadataItem domain key o =\n liftIO $\n useAsCString key $ \\pKey ->\n withMaybeByteString domain $\n {#call unsafe GetMetadataItem as ^#} (majorObject o) pKey >=>\n maybePackCString\n\nsetMetadataItem\n :: (MajorObject o t, t ~ ReadWrite)\n => Maybe ByteString -> ByteString -> ByteString -> o t -> GDAL s ()\nsetMetadataItem domain key val o =\n liftIO $\n checkCPLError \"setMetadataItem\" $\n useAsCString key $ \\pKey ->\n useAsCString val $ \\pVal ->\n withMaybeByteString domain $\n {#call unsafe GDALSetMetadataItem as ^#} (majorObject o) pKey pVal\n\ndescription :: MajorObject o t => o t -> GDAL s ByteString\ndescription =\n liftIO . ({#call unsafe GetDescription as ^#} . majorObject >=> packCString)\n\nsetDescription\n :: (MajorObject o t, t ~ ReadWrite)\n => ByteString -> o t -> GDAL s ()\nsetDescription val =\n liftIO . checkGDALCall_ const .\n useAsCString val . {#call unsafe GDALSetDescription as ^#} . majorObject\n\n\n\n-----------------------------------------------------------------------------\n-- Conduit utils\n-----------------------------------------------------------------------------\n\n-- | Parallel zip of two conduits\npZipConduitApp\n :: Monad m\n => Conduit a m (b -> c)\n -> Conduit a m b\n -> Conduit a m c\npZipConduitApp (ConduitM l0) (ConduitM r0) = ConduitM $ \\rest -> let\n go (HaveOutput p c o) (HaveOutput p' c' o') =\n HaveOutput (go p p') (c>>c') (o o')\n go (NeedInput p c) (NeedInput p' c') =\n NeedInput (\\i -> go (p i) (p' i)) (\\u -> go (c u) (c' u))\n go (Done ()) (Done ()) = rest ()\n go (PipeM m) (PipeM m') = PipeM (liftM2 go m m')\n go (Leftover p i) (Leftover p' _) = Leftover (go p p') i\n go _ _ = error \"pZipConduitApp: not parallel\"\n in go (injectLeftovers $ l0 Done) (injectLeftovers $ r0 Done)\n\nnewtype PZipConduit i m o =\n PZipConduit { getPZipConduit :: Conduit i m o}\n\ninstance Monad m => Functor (PZipConduit i m) where\n fmap f = PZipConduit . mapOutput f . getPZipConduit\n\ninstance Monad m => Applicative (PZipConduit i m) where\n pure = PZipConduit . forever . yield\n PZipConduit l <*> PZipConduit r = PZipConduit (pZipConduitApp l r)\n\nzipBlocks\n :: GDALType a\n => Band s a t -> PZipConduit BlockIx (GDAL s) (U.Vector (Value a))\nzipBlocks = PZipConduit . unsafeBlockConduit\n\ngetZipBlocks\n :: PZipConduit BlockIx (GDAL s) a\n -> Conduit BlockIx (GDAL s) (BlockIx, a)\ngetZipBlocks = decorate . getPZipConduit\n\ndecorate :: Monad m => Conduit a m b -> Conduit a m (a, b)\ndecorate (ConduitM c0) = ConduitM $ \\rest -> let\n go1 HaveOutput{} = error \"unexpected NeedOutput\"\n go1 (NeedInput p c) = NeedInput (\\i -> go2 i (p i)) (go1 . c)\n go1 (Done r) = rest r\n go1 (PipeM mp) = PipeM (liftM (go1) mp)\n go1 (Leftover p i) = Leftover (go1 p) i\n\n go2 i (HaveOutput p c o) = HaveOutput (go2 i p) c (i, o)\n go2 _ (NeedInput p c) = NeedInput (\\i -> go2 i (p i)) (go1 . c)\n go2 _ (Done r) = rest r\n go2 i (PipeM mp) = PipeM (liftM (go2 i) mp)\n go2 i (Leftover p i') = Leftover (go2 i p) i'\n in go1 (c0 Done)\n{-# INLINE decorate #-}\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"28e525d37ac4bb8213d465445877267026bf445f","subject":"bandSink can write partial vectors","message":"bandSink can write partial vectors\n","repos":"meteogrid\/bindings-gdal,meteogrid\/bindings-gdal","old_file":"src\/GDAL\/Internal\/GDAL.chs","new_file":"src\/GDAL\/Internal\/GDAL.chs","new_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE LambdaCase #-}\n\nmodule GDAL.Internal.GDAL (\n GDALRasterException (..)\n , Geotransform (..)\n , OverviewResampling (..)\n , DriverName (..)\n , Driver (..)\n , DriverH (..)\n , Dataset\n , DatasetH (..)\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , RasterBandH (..)\n , MaskType (..)\n\n , northUpGeotransform\n , gcpGeotransform\n , applyGeotransform\n , (|$|)\n , invertGeotransform\n , inv\n , composeGeotransforms\n , (|.|)\n , geoEnvelopeTransformer\n\n , driverByName\n , driverShortName\n , driverLongName\n\n , nullDatasetH\n , allRegister\n , destroyDriverManager\n , create\n , createMem\n , delete\n , rename\n , copyFiles\n , flushCache\n , closeDataset\n , openDatasetH\n , createDatasetH\n , openReadOnly\n , openReadWrite\n , OpenFlag(..)\n , identifyDriver\n , identifyDriverEx\n , openReadOnlyEx\n , openReadWriteEx\n , unsafeToReadOnly\n , createCopy\n , buildOverviews\n , driverCreationOptionList\n\n , layerCount\n , getLayer\n , getLayerByName\n , executeSQL\n , createLayer\n , createLayerWithDef\n\n , bandAs\n\n , datasetDriver\n , datasetSize\n , datasetFileList\n , datasetProjection\n , setDatasetProjection\n , datasetProjectionWkt\n , setDatasetProjectionWkt\n , datasetGeotransform\n , setDatasetGeotransform\n , datasetGCPs\n , setDatasetGCPs\n , datasetBandCount\n\n , bandDataType\n , bandProjection\n , bandGeotransform\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandHasOverviews\n , bandBestOverviewLevel\n , allBand\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , addBand\n , fillBand\n , fmapBand\n , foldBands\n , readBand\n , createBandMask\n , bandMask\n , readBandBlock\n , writeBand\n , writeBandBlock\n , copyBand\n , bandConduit\n , unsafeBandConduit\n , bandSink\n , bandSinkGeo\n\n , metadataDomains\n , metadata\n , metadataItem\n , setMetadataItem\n , description\n , setDescription\n\n , foldl'\n , ifoldl'\n , foldlWindow'\n , ifoldlWindow'\n , blockConduit\n , unsafeBlockConduit\n , blockSource\n , unsafeBlockSource\n , blockSink\n , allBlocks\n , zipBlocks\n , getZipBlocks\n\n , unDataset\n , unBand\n , version\n , newDatasetHandle\n , unsafeBandDataset\n , openDatasetCount\n\n , module GDAL.Internal.DataType\n) where\n\n#include \"bindings.h\"\n#include \"gdal.h\"\n\n#include \"overviews.h\"\n\n\n{#context lib = \"gdal\" prefix = \"GDAL\" #}\n\nimport Control.Arrow (second)\nimport Control.Applicative (Applicative(..), (<$>), liftA2)\nimport Control.Exception (Exception(..))\nimport Control.DeepSeq (NFData(..))\nimport Control.Monad (liftM2, when, (>=>), forever)\nimport Control.Monad.Catch (MonadThrow, throwM)\nimport Control.Monad.Trans (lift)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Data.Bits ((.&.), (.|.))\nimport Data.ByteString.Char8 (ByteString, packCString, useAsCString)\nimport Data.ByteString.Unsafe (unsafeUseAsCString)\nimport Data.Coerce (coerce)\nimport qualified Data.List as L\nimport qualified Data.Conduit.List as CL\nimport Data.Conduit\nimport Data.Conduit.Internal (Pipe(..), ConduitM(..), injectLeftovers)\nimport Data.Maybe (fromMaybe, fromJust)\nimport Data.String (IsString)\nimport Data.Proxy\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport Data.Text.Encoding (decodeUtf8)\nimport Data.Typeable (Typeable)\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport qualified Data.Vector.Generic.Mutable as M\nimport qualified Data.Vector.Unboxed.Mutable as UM\nimport qualified Data.Vector.Unboxed as U\nimport Data.Word (Word8)\n\nimport Foreign.C.String (withCString, CString)\nimport Foreign.C.Types\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrBytes)\nimport Foreign.Ptr (Ptr, castPtr, nullPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (withArrayLen, advancePtr)\nimport Foreign.Marshal.Utils (toBool, fromBool, with)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.Types.Value\nimport GDAL.Internal.DataType\nimport GDAL.Internal.Common\nimport GDAL.Internal.Util\n{#import GDAL.Internal.OGRError#}\n{#import GDAL.Internal.Layer#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.OGRFeature#}\n{#import GDAL.Internal.GCP#}\n{#import GDAL.Internal.CPLError#}\n{#import GDAL.Internal.CPLString#}\n{#import GDAL.Internal.CPLProgress#}\nimport GDAL.Internal.OSR\nimport GDAL.Internal.OGRGeometry (Envelope(..), envelopeSize)\n\n\n\nnewtype DriverName = DriverName ByteString\n deriving (Eq, IsString)\n\ninstance Show DriverName where\n show (DriverName s) = show s\n\nversion :: (Int, Int)\nversion = ({#const GDAL_VERSION_MAJOR#} , {#const GDAL_VERSION_MINOR#})\n\ndata GDALRasterException\n = InvalidRasterSize !Size\n | InvalidBlockSize !Int\n | InvalidDriverOptions\n | UnknownRasterDataType\n | NullDataset\n | NullBand\n | UnknownDriver !ByteString\n | BandDoesNotAllowNoData\n | CannotInvertGeotransform\n | NotImplemented !ByteString\n deriving (Typeable, Show, Eq)\n\ninstance Exception GDALRasterException where\n toException = bindingExceptionToException\n fromException = bindingExceptionFromException\n\n\n{#enum GDALAccess {} deriving (Eq, Show) #}\n\n{#enum RWFlag {} deriving (Eq, Show) #}\n\n{#pointer MajorObjectH newtype#}\n\nclass MajorObject o (t::AccessMode) where\n majorObject :: o t -> MajorObjectH\n\n\n{#pointer DatasetH newtype #}\n\n\nnullDatasetH :: DatasetH\nnullDatasetH = DatasetH nullPtr\n\nderiving instance Eq DatasetH\nderiving instance NFData DatasetH\n\nnewtype Dataset s a (t::AccessMode) =\n Dataset (Maybe ReleaseKey, DatasetH)\n\ninstance MajorObject (Dataset s a) t where\n majorObject ds =\n let DatasetH p = unDataset ds\n in MajorObjectH (castPtr p)\n\nunDataset :: Dataset s a t -> DatasetH\nunDataset (Dataset (_,s)) = s\n\ncloseDataset :: MonadIO m => Dataset s a t -> m ()\ncloseDataset (Dataset (Just rk,_)) = release rk\ncloseDataset _ = return ()\n\ntype RODataset s a = Dataset s a ReadOnly\ntype RWDataset s a = Dataset s a ReadWrite\n\n{#pointer RasterBandH newtype #}\n\nnullBandH :: RasterBandH\nnullBandH = RasterBandH nullPtr\n\nderiving instance Eq RasterBandH\n\nnewtype Band s a (t::AccessMode) = Band (RasterBandH, DataTypeK)\n\nunBand :: Band s a t -> RasterBandH\nunBand (Band (p,_)) = p\n\nbandDataType :: Band s a t -> DataTypeK\nbandDataType (Band (_,t)) = t\n{-# INLINE bandDataType #-}\n\nbandAs :: Band s a t -> DataType d -> Band s (HsType d) t\nbandAs = const . coerce\n{-# INLINE bandAs #-}\n\ninstance MajorObject (Band s a) t where\n majorObject b =\n let RasterBandH p = unBand b\n in MajorObjectH (castPtr p)\n\ntype ROBand s a = Band s a ReadOnly\ntype RWBand s a = Band s a ReadWrite\n\n\n{#pointer DriverH newtype #}\n\nnullDriverH :: DriverH\nnullDriverH = DriverH nullPtr\n\nderiving instance Eq DriverH\n\nnewtype Driver (t::AccessMode) = Driver { unDriver :: DriverH }\n\ninstance MajorObject Driver t where\n majorObject d =\n let DriverH p = unDriver d\n in MajorObjectH (castPtr p)\n\n{#fun AllRegister as ^ {} -> `()' #}\n\n{#fun DestroyDriverManager as ^ {} -> `()'#}\n\ndriverByName :: MonadIO m => DriverName -> m (Driver t)\ndriverByName (DriverName s) = liftIO $ do\n d <- useAsCString s {#call unsafe GetDriverByName as ^#}\n let DriverH p = d in if p == nullPtr\n then throwBindingException (UnknownDriver s)\n else return (Driver d)\n\ndriverHByName :: MonadIO m => DriverName -> m DriverH\ndriverHByName s = (\\(Driver h) -> h) <$> driverByName s\n\ndriverLongName :: Driver d -> Text\ndriverLongName (Driver d) = unsafePerformIO $\n {#call unsafe GetDriverLongName as ^#} d >>= fmap decodeUtf8 . packCString\n\ndriverShortName :: Driver d -> Text\ndriverShortName (Driver d) = unsafePerformIO $\n {#call unsafe GetDriverShortName as ^#} d >>= fmap decodeUtf8 . packCString\n\ndriverCreationOptionList :: Driver d -> ByteString\ndriverCreationOptionList (Driver d) = unsafePerformIO $\n {#call GetDriverCreationOptionList as ^#} d >>= packCString\n\nvalidateCreationOptions :: DriverH -> Ptr CString -> IO ()\nvalidateCreationOptions d o = do\n valid <- fmap toBool ({#call GDALValidateCreationOptions as ^ #} d o)\n when (not valid) (throwBindingException InvalidDriverOptions)\n\ncreate\n :: DriverName -> String -> Size -> Int -> DataType d -> OptionList\n -> GDAL s (Dataset s (HsType d) ReadWrite)\ncreate drv path size bands dtype optList = do\n d <- driverByName drv\n newDatasetHandle $ createDatasetH d path size bands dtype optList\n\ncreateDatasetH\n :: MonadIO m\n => Driver t -> String -> Size -> Int -> DataType d -> OptionList\n -> m DatasetH\ncreateDatasetH drv path (nx :+: ny) bands dtype opts = liftIO $\n withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC dtype\n d = unDriver drv\n withOptionList opts $ \\o -> do\n validateCreationOptions d o\n {#call GDALCreate as ^#} d path' nx' ny' bands' dtype' o\n\ndelete :: DriverName -> String -> GDAL s ()\ndelete driver path =\n liftIO $\n checkCPLError \"deleteDataset\" $ do\n d <- driverHByName driver\n withCString path ({#call DeleteDataset as ^#} d)\n\nrename :: DriverName -> String -> String -> GDAL s ()\nrename driver newName oldName =\n liftIO $\n checkCPLError \"renameDataset\" $ do\n d <- driverHByName driver\n withCString newName $\n withCString oldName . ({#call RenameDataset as ^#} d)\n\ncopyFiles :: DriverName -> String -> String -> GDAL s ()\ncopyFiles driver newName oldName =\n liftIO $\n checkCPLError \"copyFiles\" $ do\n d <- driverHByName driver\n withCString newName $\n withCString oldName . ({#call CopyDatasetFiles as ^#} d)\n\nopenReadOnly :: String -> DataType d -> GDAL s (RODataset s (HsType d))\nopenReadOnly p _ = openWithMode GA_ReadOnly p\n\nopenReadWrite :: String -> DataType d -> GDAL s (RWDataset s (HsType d))\nopenReadWrite p _ = openWithMode GA_Update p\n\nopenWithMode :: GDALAccess -> String -> GDAL s (Dataset s a t)\nopenWithMode m = newDatasetHandle . openDatasetH m\n\nopenDatasetH :: MonadIO m => GDALAccess -> String -> m DatasetH\nopenDatasetH m path =\n liftIO $\n withCString path $\n flip {#call GDALOpen as ^#} (fromEnumC m)\n\nidentifyDriver\n :: String -> GDAL s (Maybe (Driver t))\nidentifyDriver path = do\n d <- liftIO $ withCString path $\n flip {#call GDALIdentifyDriver as ^#} nullPtr\n return $ if d == nullDriverH then Nothing else Just (Driver d)\n\nopenReadOnlyEx :: [OpenFlag] -> OptionList -> String -> DataType d -> GDAL s (RODataset s (HsType d))\nopenReadWriteEx :: [OpenFlag] -> OptionList -> String -> DataType d -> GDAL s (RWDataset s (HsType d))\nidentifyDriverEx :: [OpenFlag] -> String -> GDAL s (Maybe (Driver t))\n\n#if SUPPORTS_OPENEX\n{#enum define OpenFlag {\n GDAL_OF_READONLY as OFReadonly\n , GDAL_OF_UPDATE as OFUpdate\n , GDAL_OF_ALL as OFAll\n , GDAL_OF_RASTER as OFRaster\n , GDAL_OF_VECTOR as OFVector\n , GDAL_OF_GNM as OFGnm\n , GDAL_OF_SHARED as OFShared\n , GDAL_OF_VERBOSE_ERROR as OFVerboseError\n , GDAL_OF_INTERNAL as OFInternal\n , GDAL_OF_DEFAULT_BLOCK_ACCESS as OFDefaultBlockAccess\n , GDAL_OF_ARRAY_BLOCK_ACCESS as OFArrayBlockAccess\n , GDAL_OF_HASHSET_BLOCK_ACCESS as OFHashsetBlockAccess\n } deriving (Eq, Bounded, Show) #}\n\nopenDatasetHEx :: MonadIO m => [OpenFlag] -> OptionList -> String -> m DatasetH\nopenDatasetHEx flgs opts path =\n liftIO $\n withOptionList opts $ \\ os -> \n withCString path $ \\ p ->\n {#call GDALOpenEx as ^#} p cflgs nullPtr os nullPtr\n where cflgs = foldr (.|.) 0 $ map (fromIntegral.fromEnum) flgs\n\nopenReadOnlyEx flgs opts p _ =\n newDatasetHandle (openDatasetHEx (OFReadonly:flgs) opts p)\n\nopenReadWriteEx flgs opts p _ =\n newDatasetHandle (openDatasetHEx (OFUpdate:flgs) opts p)\n\nidentifyDriverEx flgs path = do\n d <- liftIO $ withCString path $ \\ p ->\n {#call GDALIdentifyDriverEx as ^#} p cflgs nullPtr nullPtr\n return $ if d == nullDriverH then Nothing else Just (Driver d)\n where cflgs = foldr (.|.) 0 $ map (fromIntegral.fromEnum) flgs\n\n#else\ndata OpenFlag\nopenReadOnlyEx _ _ = openReadOnly\nopenReadWriteEx _ _ = openReadWrite\nidentifyDriverEx _ = identifyDriver\n#endif\n\nunsafeToReadOnly :: RWDataset s a -> GDAL s (RODataset s a)\nunsafeToReadOnly ds = flushCache ds >> return (coerce ds)\n\ncreateCopy\n :: DriverName -> String -> Dataset s a t -> Bool -> OptionList\n -> Maybe ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy driver path ds strict opts progress =\n newDatasetHandle $\n withProgressFun \"createCopy\" progress $ \\pFunc -> do\n d <- driverHByName driver\n withOptionList opts $ \\o -> do\n validateCreationOptions d o\n withCString path $ \\p ->\n {#call GDALCreateCopy as ^#}\n d p (unDataset ds) (fromBool strict) o pFunc nullPtr\n\nnewDatasetHandle :: IO DatasetH -> GDAL s (Dataset s a t)\nnewDatasetHandle act = do\n (rk,ds) <- allocate (checkGDALCall checkit act) free\n return (Dataset (Just rk, ds))\n where\n checkit exc p\n | p==nullDatasetH = Just (fromMaybe\n (GDALBindingException NullDataset) exc)\n | otherwise = Nothing\n free = {#call GDALClose as ^#}\n\ncreateMem\n :: Size -> Int -> DataType d -> OptionList\n -> GDAL s (Dataset s (HsType d) ReadWrite)\ncreateMem = create \"Mem\" \"\"\n\nflushCache :: RWDataset s a -> GDAL s ()\nflushCache = liftIO . {#call GDALFlushCache as ^#} . unDataset\n\ndatasetDriver :: Dataset s a t -> Driver t'\ndatasetDriver ds =\n unsafePerformIO $\n Driver <$> {#call unsafe GetDatasetDriver as ^#} (unDataset ds)\n\ndatasetSize :: Dataset s a t -> Size\ndatasetSize ds =\n fmap fromIntegral $\n ({#call pure unsafe GetRasterXSize as ^#} (unDataset ds))\n :+: ({#call pure unsafe GetRasterYSize as ^#} (unDataset ds))\n\ndatasetFileList :: Dataset s a t -> GDAL s [Text]\ndatasetFileList =\n liftIO .\n fromCPLStringList .\n {#call unsafe GetFileList as ^#} .\n unDataset\n\ndatasetProjection\n :: (MonadThrow m, MonadIO m)\n => Dataset s a t -> m (Maybe SpatialReference)\ndatasetProjection ds = do\n mWkt <- datasetProjectionWkt ds\n case mWkt of\n Just wkt -> either throwM (return . Just) (srsFromWkt wkt)\n Nothing -> return Nothing\n\ndatasetProjectionWkt :: MonadIO m => Dataset s a t -> m (Maybe ByteString)\ndatasetProjectionWkt ds = liftIO $ do\n p <- {#call GetProjectionRef as ^#} (unDataset ds)\n if p == nullPtr then return Nothing else do\n c <- peek p\n if c == 0 then return Nothing else Just <$> packCString p\n\nsetDatasetProjection :: SpatialReference -> RWDataset s a -> GDAL s ()\nsetDatasetProjection srs = setDatasetProjectionWkt (srsToWkt srs)\n\nsetDatasetProjectionWkt :: ByteString -> RWDataset s a -> GDAL s ()\nsetDatasetProjectionWkt srs ds =\n liftIO $ checkCPLError \"SetProjection\" $\n useAsCString srs ({#call SetProjection as ^#} (unDataset ds))\n\nsetDatasetGCPs\n :: [GroundControlPoint] -> Maybe SpatialReference -> RWDataset s a\n -> GDAL s ()\nsetDatasetGCPs gcps mSrs ds =\n liftIO $\n checkCPLError \"setDatasetGCPs\" $\n withGCPArrayLen gcps $ \\nGcps pGcps ->\n withMaybeSRAsCString mSrs $\n {#call unsafe GDALSetGCPs as ^#}\n (unDataset ds)\n (fromIntegral nGcps)\n pGcps\n\ndatasetGCPs\n :: Dataset s a t\n -> GDAL s ([GroundControlPoint], Maybe SpatialReference)\ndatasetGCPs ds =\n liftIO $ do\n let pDs = unDataset ds\n srs <- maybeSpatialReferenceFromCString\n =<< {#call unsafe GetGCPProjection as ^#} pDs\n nGcps <- fmap fromIntegral ({#call unsafe GetGCPCount as ^#} pDs)\n gcps <- {#call unsafe GetGCPs as ^#} pDs >>= fromGCPArray nGcps\n return (gcps, srs)\n\n\ndata OverviewResampling\n = OvNearest\n | OvGauss\n | OvCubic\n | OvAverage\n | OvMode\n | OvAverageMagphase\n | OvNone\n\nbuildOverviews\n :: RWDataset s a -> OverviewResampling -> [Int] -> [Int] -> Maybe ProgressFun\n -> GDAL s ()\nbuildOverviews ds resampling overviews bands progress =\n liftIO $\n withResampling resampling $ \\pResampling ->\n withArrayLen (map fromIntegral overviews) $ \\nOverviews pOverviews ->\n withArrayLen (map fromIntegral bands) $ \\nBands pBands ->\n withProgressFun \"buildOverviews\" progress $ \\pFunc ->\n checkCPLError \"buildOverviews\" $\n {#call GDALBuildOverviews as ^#}\n (unDataset ds)\n pResampling\n (fromIntegral nOverviews)\n pOverviews\n (fromIntegral nBands)\n pBands\n pFunc\n nullPtr\n where\n withResampling OvNearest = unsafeUseAsCString \"NEAREST\\0\"\n withResampling OvGauss = unsafeUseAsCString \"GAUSS\\0\"\n withResampling OvCubic = unsafeUseAsCString \"CUBIC\\0\"\n withResampling OvAverage = unsafeUseAsCString \"AVERAGE\\0\"\n withResampling OvMode = unsafeUseAsCString \"MODE\\0\"\n withResampling OvAverageMagphase = unsafeUseAsCString \"AVERAGE_MAGPHASE\\0\"\n withResampling OvNone = unsafeUseAsCString \"NONE\\0\"\n\ndata Geotransform\n = Geotransform {\n gtXOff :: {-# UNPACK #-} !Double\n , gtXDelta :: {-# UNPACK #-} !Double\n , gtXRot :: {-# UNPACK #-} !Double\n , gtYOff :: {-# UNPACK #-} !Double\n , gtYRot :: {-# UNPACK #-} !Double\n , gtYDelta :: {-# UNPACK #-} !Double\n } deriving (Eq, Show)\n\ninstance NFData Geotransform where\n rnf Geotransform{} = ()\n\nnorthUpGeotransform :: Size -> Envelope Double -> Geotransform\nnorthUpGeotransform size envelope =\n Geotransform {\n gtXOff = pFst (envelopeMin envelope)\n , gtXDelta = pFst (envelopeSize envelope \/ fmap fromIntegral size)\n , gtXRot = 0\n , gtYOff = pSnd (envelopeMax envelope)\n , gtYRot = 0\n , gtYDelta = negate (pSnd (envelopeSize envelope \/ fmap fromIntegral size))\n }\n\ngcpGeotransform :: [GroundControlPoint] -> ApproxOK -> Maybe Geotransform\ngcpGeotransform gcps approxOk =\n unsafePerformIO $\n alloca $ \\pGt ->\n withGCPArrayLen gcps $ \\nGcps pGcps -> do\n ret <- fmap toBool $\n {#call unsafe GCPsToGeoTransform as ^#}\n (fromIntegral nGcps)\n pGcps\n (castPtr pGt)\n (fromEnumC approxOk)\n if ret then fmap Just (peek pGt) else return Nothing\n\napplyGeotransform :: Geotransform -> Pair Double -> Pair Double\napplyGeotransform Geotransform{..} (x :+: y) =\n (gtXOff + gtXDelta*x + gtXRot * y) :+: (gtYOff + gtYRot *x + gtYDelta * y)\n\ninfixr 5 |$|\n(|$|) :: Geotransform -> Pair Double -> Pair Double\n(|$|) = applyGeotransform\n\ninvertGeotransform :: Geotransform -> Maybe Geotransform\ninvertGeotransform (Geotransform g0 g1 g2 g3 g4 g5)\n | g2==0 && g4==0 && g1\/=0 && g5\/=0 -- No rotation\n = Just $! Geotransform (-g0\/g1) (1\/g1) 0 (-g3\/g5) 0 (1\/g5)\n | abs det < 1e-15 = Nothing -- not invertible\n | otherwise\n = Just $! Geotransform ((g2*g3 - g0*g5) * idet)\n (g5*idet)\n (-g2*idet)\n ((-g1*g3 + g0*g4) * idet)\n (-g4*idet)\n (g1*idet)\n where\n idet = 1\/det\n det = g1*g5 - g2*g4\n\ninv :: Geotransform -> Geotransform\ninv = fromMaybe (error \"Could not invert geotransform\") . invertGeotransform\n\n-- | Creates a Geotransform equivalent to applying a and then b\ncomposeGeotransforms :: Geotransform -> Geotransform -> Geotransform\nb `composeGeotransforms` a =\n Geotransform (b1*a0 + b2*a3 + b0)\n (b1*a1 + b2*a4)\n (b1*a2 + b2*a5)\n (b4*a0 + b5*a3 + b3)\n (b4*a1 + b5*a4)\n (b4*a2 + b5*a5)\n\n where\n Geotransform a0 a1 a2 a3 a4 a5 = a\n Geotransform b0 b1 b2 b3 b4 b5 = b\n\ninfixr 9 |.|\n(|.|) :: Geotransform -> Geotransform -> Geotransform\n(|.|) = composeGeotransforms\n\ninstance Storable Geotransform where\n sizeOf _ = sizeOf (undefined :: CDouble) * 6\n alignment _ = alignment (undefined :: CDouble)\n poke pGt (Geotransform g0 g1 g2 g3 g4 g5) = do\n let p = castPtr pGt :: Ptr CDouble\n pokeElemOff p 0 (realToFrac g0)\n pokeElemOff p 1 (realToFrac g1)\n pokeElemOff p 2 (realToFrac g2)\n pokeElemOff p 3 (realToFrac g3)\n pokeElemOff p 4 (realToFrac g4)\n pokeElemOff p 5 (realToFrac g5)\n peek pGt = do\n let p = castPtr pGt :: Ptr CDouble\n Geotransform <$> fmap realToFrac (peekElemOff p 0)\n <*> fmap realToFrac (peekElemOff p 1)\n <*> fmap realToFrac (peekElemOff p 2)\n <*> fmap realToFrac (peekElemOff p 3)\n <*> fmap realToFrac (peekElemOff p 4)\n <*> fmap realToFrac (peekElemOff p 5)\n\n\ndatasetGeotransform:: MonadIO m => Dataset s a t -> m (Maybe Geotransform)\ndatasetGeotransform ds = liftIO $ alloca $ \\p -> do\n ret <- {#call unsafe GetGeoTransform as ^#} (unDataset ds) (castPtr p)\n if toEnumC ret == CE_None\n then fmap Just (peek p)\n else return Nothing\n\nsetDatasetGeotransform :: MonadIO m => Geotransform -> RWDataset s a -> m ()\nsetDatasetGeotransform gt ds = liftIO $\n checkCPLError \"SetGeoTransform\" $\n with gt ({#call unsafe SetGeoTransform as ^#} (unDataset ds) . castPtr)\n\n\ndatasetBandCount :: MonadIO m => Dataset s a t -> m Int\ndatasetBandCount =\n fmap fromIntegral . liftIO . {#call unsafe GetRasterCount as ^#} . unDataset\n\ngetBand :: Int -> Dataset s a t -> GDAL s (Band s a t)\ngetBand b ds = liftIO $ do\n pB <- checkGDALCall checkit $\n {#call GetRasterBand as ^#} (unDataset ds) (fromIntegral b)\n dt <- fmap toEnumC ({#call unsafe GetRasterDataType as ^#} pB)\n return (Band (pB, dt))\n where\n checkit exc p\n | p == nullBandH = Just (fromMaybe (GDALBindingException NullBand) exc)\n | otherwise = Nothing\n\naddBand\n :: forall s a. GDALType a\n => OptionList -> RWDataset s a -> GDAL s (RWBand s a)\naddBand opts ds = do\n liftIO $\n checkCPLError \"addBand\" $\n withOptionList opts $\n {#call GDALAddBand as ^#} (unDataset ds) (fromEnumC dt)\n ix <- datasetBandCount ds\n getBand ix ds\n where dt = hsDataType (Proxy :: Proxy a)\n\n\nbandBlockSize :: (Band s a t) -> Size\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n {#call unsafe GetBlockSize as ^#} (unBand band) xPtr yPtr\n fmap (fmap fromIntegral) (liftM2 (:+:) (peek xPtr) (peek yPtr))\n\nbandBlockLen :: Band s a t -> Int\nbandBlockLen = (\\(x :+: y) -> x*y) . bandBlockSize\n\nbandSize :: Band s a t -> Size\nbandSize band =\n fmap fromIntegral $\n ({#call pure unsafe GetRasterBandXSize as ^#} (unBand band))\n :+: ({#call pure unsafe GetRasterBandYSize as ^#} (unBand band))\n\nbandBestOverviewLevel\n :: MonadIO m\n => Band s a t -> Envelope Int -> Size -> m (Maybe Int)\nbandBestOverviewLevel band (Envelope (x0 :+: y0) (x1 :+: y1)) (nx :+: ny) =\n liftIO $\n toMaybeBandNo <$> {#call unsafe hs_gdal_band_get_best_overview_level#}\n (unBand band)\n (fromIntegral x0)\n (fromIntegral y0)\n (fromIntegral (x1-x0))\n (fromIntegral (y1-y0))\n (fromIntegral nx)\n (fromIntegral ny)\n where\n toMaybeBandNo n | n>=0 = Just (fromIntegral n)\n toMaybeBandNo _ = Nothing\n\n\nallBand :: Band s a t -> Envelope Int\nallBand = Envelope (pure 0) . bandSize\n\nbandBlockCount :: Band s a t -> Pair Int\nbandBlockCount b = fmap ceiling $ liftA2 ((\/) :: Double -> Double -> Double)\n (fmap fromIntegral (bandSize b))\n (fmap fromIntegral (bandBlockSize b))\n\nbandHasOverviews :: Band s a t -> GDAL s Bool\nbandHasOverviews =\n liftIO . fmap toBool . {#call unsafe HasArbitraryOverviews as ^#} . unBand\n\nbandNodataValue :: GDALType a => Band s a t -> GDAL s (Maybe a)\nbandNodataValue b =\n liftIO $\n alloca $ \\p -> do\n value <- {#call unsafe GetRasterNoDataValue as ^#} (unBand b) p\n hasNodata <- fmap toBool $ peek p\n return (if hasNodata then Just (fromCDouble value) else Nothing)\n\n\nsetBandNodataValue :: GDALType a => a -> RWBand s a -> GDAL s ()\nsetBandNodataValue v b =\n liftIO $\n checkCPLError \"SetRasterNoDataValue\" $\n {#call unsafe SetRasterNoDataValue as ^#} (unBand b) (toCDouble v)\n\ncreateBandMask :: MaskType -> RWBand s a -> GDAL s ()\ncreateBandMask maskType band = liftIO $\n checkCPLError \"createBandMask\" $\n {#call CreateMaskBand as ^#} (unBand band) cflags\n where cflags = maskFlagsForType maskType\n\nreadBand :: forall s t a. GDALType a\n => (Band s a t)\n -> Envelope Int\n -> Size\n -> GDAL s (U.Vector (Value a))\nreadBand band win sz = fmap fromJust $ runConduit $\n yield win =$= unsafeBandConduit sz band =$= CL.head\n\nbandConduit\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (U.Vector (Value a))\nbandConduit sz band =\n unsafeBandConduitM sz band =$= CL.mapM (liftIO . U.freeze)\n\nunsafeBandConduit\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (U.Vector (Value a))\nunsafeBandConduit sz band =\n unsafeBandConduitM sz band =$= CL.mapM (liftIO . U.unsafeFreeze)\n\n\nunsafeBandConduitM\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (UM.IOVector (Value a))\nunsafeBandConduitM size@(bx :+: by) band = do\n buf <- liftIO (M.new (bx*by))\n lift (bandMaskType band) >>= \\case\n MaskNoData -> do\n nd <- lift (noDataOrFail band)\n let vec = mkValueUMVector nd buf\n awaitForever $ \\win -> do\n liftIO (M.set buf nd >> read_ band buf win)\n yield vec\n _ -> do\n mBuf <- liftIO $ M.replicate (bx*by) 0\n mask <- lift $ bandMask band\n let vec = mkMaskedValueUMVector mBuf buf\n awaitForever $ \\win -> do\n liftIO (read_ band buf win >> read_ mask mBuf win)\n yield vec\n where\n read_ :: forall a'. GDALType a'\n => Band s a' t -> Stm.IOVector a' -> Envelope Int -> IO ()\n read_ b vec win = do\n let -- Requested minEnv\n x0 :+: y0 = envelopeMin win\n -- Effective minEnv\n x0' :+: y0' = max 0 <$> envelopeMin win\n -- Effective maxEnv\n x1' :+: y1' = min <$> bandSize b <*> envelopeMax win\n -- Effective origin\n e0 = x0' - x0 :+: y0' - y0\n -- Projected origin\n x :+: y = truncate <$> factor * fmap fromIntegral e0\n -- Effective buffer size\n sx :+: sy = (x1' - x0' :+: y1' - y0')\n -- Projected window\n bx' :+: by' = truncate\n <$> factor * fmap fromIntegral (sx :+: sy)\n\n --buffer size \/ envelope size ratio\n factor :: Pair Double\n factor = (fromIntegral <$> size)\n \/ (fromIntegral <$> envelopeSize win)\n\n off = y * bx + x\n\n Stm.unsafeWith vec $ \\ptr -> do\n checkCPLError \"RasterAdviseRead\" $\n {#call unsafe RasterAdviseRead as ^#}\n (unBand b)\n (fromIntegral x0')\n (fromIntegral y0')\n (fromIntegral sx)\n (fromIntegral sy)\n bx'\n by'\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n nullPtr\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand b)\n (fromEnumC GF_Read)\n (fromIntegral x0')\n (fromIntegral y0')\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr (ptr `advancePtr` off))\n bx'\n by'\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n 0\n (fromIntegral bx * fromIntegral (sizeOf (undefined :: a')))\n\ngeoEnvelopeTransformer\n :: Geotransform -> Maybe (Envelope Double -> Envelope Int)\ngeoEnvelopeTransformer gt =\n case (gtXDelta gt < 0, gtYDelta gt<0, invertGeotransform gt) of\n (_,_,Nothing) -> Nothing\n (False,False,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let e0' = fmap round (applyGeotransform iGt e0)\n e1' = fmap round (applyGeotransform iGt e1)\n in Envelope e0' e1'\n (True,False,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x1 :+: y0 = fmap round (applyGeotransform iGt e0)\n x0 :+: y1 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n (False,True,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x0 :+: y1 = fmap round (applyGeotransform iGt e0)\n x1 :+: y0 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n (True,True,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x1 :+: y1 = fmap round (applyGeotransform iGt e0)\n x0 :+: y0 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n\n\nwriteBand\n :: forall s a. GDALType a\n => RWBand s a\n -> Envelope Int\n -> Size\n -> U.Vector (Value a)\n -> GDAL s ()\nwriteBand band win sz uvec =\n runConduit (yield (win, Envelope 0 sz, sz, uvec) =$= bandSink band)\n\n\n\nbandSink\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (Envelope Int, Envelope Int, Size, U.Vector (Value a)) (GDAL s) ()\nbandSink band = lift (bandMaskType band) >>= \\case\n MaskNoData -> do\n nd <- lift (noDataOrFail band)\n awaitForever $ \\(win, bWin, sz, uvec) -> lift $\n write band win bWin sz (toGVecWithNodata nd uvec)\n MaskAllValid ->\n awaitForever $ \\(win, bWin, sz, uvec) -> lift $\n maybe (throwBindingException BandDoesNotAllowNoData)\n (write band win bWin sz)\n (toGVec uvec)\n _ -> do\n mBand <- lift (bandMask band)\n awaitForever $ \\(win, bWin, sz, uvec) -> lift $ do\n let (mask, vec) = toGVecWithMask uvec\n write band win bWin sz vec\n write mBand win bWin sz mask\n where\n\n write :: forall a'. GDALType a'\n => RWBand s a'\n -> Envelope Int -> Envelope Int\n -> Size\n -> St.Vector a'\n -> GDAL s ()\n write band' win bWin sz vec = do\n let sx :+: sy = envelopeSize win\n xoff :+: yoff = envelopeMin win\n bx :+: by = envelopeSize bWin\n vi :+: vj = envelopeMin bWin\n off = vj * pFst sz + vi\n if sizeLen sz \/= G.length vec\n || vi < 0\n || vj < 0\n || (bx*by) > G.length vec\n then throwBindingException (InvalidRasterSize sz)\n else liftIO $\n St.unsafeWith vec $ \\ptr ->\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand band')\n (fromEnumC GF_Write)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr (ptr `advancePtr` off))\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n 0\n (fromIntegral (pFst sz * sizeOf (undefined :: a')))\n\nunsafeBandDataset :: Band s a t -> Dataset s a t\nunsafeBandDataset band = Dataset (Nothing, dsH) where\n dsH = {#call pure unsafe GDALGetBandDataset as ^#} (unBand band)\n\nbandGeotransform :: MonadIO m => Band s a t -> m (Maybe Geotransform)\nbandGeotransform = datasetGeotransform . unsafeBandDataset\n\nbandProjection :: (MonadThrow m, MonadIO m) => Band s a t -> m (Maybe SpatialReference)\nbandProjection = datasetProjection . unsafeBandDataset\n\n\nbandSinkGeo\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (Envelope Double, Envelope Int, Size, U.Vector (Value a)) (GDAL s) ()\nbandSinkGeo band = do\n mGt <- bandGeotransform band\n case mGt >>= geoEnvelopeTransformer of\n Just trans -> CL.map (\\(e,be,s,v) -> (trans e,be,s,v)) =$= bandSink band\n Nothing -> lift (throwBindingException CannotInvertGeotransform)\n\nnoDataOrFail :: GDALType a => Band s a t -> GDAL s a\nnoDataOrFail = fmap (fromMaybe err) . bandNodataValue\n where\n err = error (\"GDAL.readMasked: band has GMF_NODATA flag but did \" ++\n \"not return a nodata value\")\n\nbandMask :: Band s a t -> GDAL s (Band s Word8 t)\nbandMask =\n liftIO . fmap (\\p -> Band (p,GByte)) . {#call GetMaskBand as ^#}\n . unBand\n\ndata MaskType\n = MaskNoData\n | MaskAllValid\n |\u00a0MaskPerBand\n |\u00a0MaskPerDataset\n\nbandMaskType :: Band s a t -> GDAL s MaskType\nbandMaskType band = do\n flags <- liftIO ({#call unsafe GetMaskFlags as ^#} (unBand band))\n let testFlag f = (fromEnumC f .&. flags) \/= 0\n return $ case () of\n () | testFlag GMF_NODATA -> MaskNoData\n () | testFlag GMF_ALL_VALID -> MaskAllValid\n () | testFlag GMF_PER_DATASET -> MaskPerDataset\n _ -> MaskPerBand\n\nmaskFlagsForType :: MaskType -> CInt\nmaskFlagsForType MaskNoData = fromEnumC GMF_NODATA\nmaskFlagsForType MaskAllValid = fromEnumC GMF_ALL_VALID\nmaskFlagsForType MaskPerBand = 0\nmaskFlagsForType MaskPerDataset = fromEnumC GMF_PER_DATASET\n\n{#enum define MaskFlag { GMF_ALL_VALID as GMF_ALL_VALID\n , GMF_PER_DATASET as GMF_PER_DATASET\n , GMF_ALPHA as GMF_ALPHA\n , GMF_NODATA as GMF_NODATA\n } deriving (Eq,Bounded,Show) #}\n\ncopyBand\n :: Band s a t -> RWBand s a -> OptionList\n -> Maybe ProgressFun -> GDAL s ()\ncopyBand src dst opts progress =\n liftIO $\n withProgressFun \"copyBand\" progress $ \\pFunc ->\n withOptionList opts $ \\o ->\n checkCPLError \"copyBand\" $\n {#call RasterBandCopyWholeRaster as ^#}\n (unBand src) (unBand dst) o pFunc nullPtr\n\nfillBand :: GDALType a => Value a -> RWBand s a -> GDAL s ()\nfillBand val b =\n runConduit (allBlocks b =$= CL.map (\\i -> (i,v)) =$= blockSink b)\n where v = G.replicate (bandBlockLen b) val\n\n\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s a t -> GDAL s b\nfoldl' f = ifoldl' (\\z _ v -> f z v)\n{-# INLINE foldl' #-}\n\nifoldl'\n :: forall s t a b. GDALType a\n => (b -> Pair Int -> Value a -> b) -> b -> Band s a t -> GDAL s b\nifoldl' f z band =\n runConduit (unsafeBlockSource band =$= CL.fold folder z)\n where\n !(mx :+: my) = liftA2 mod (bandSize band) (bandBlockSize band)\n !(nx :+: ny) = bandBlockCount band\n !(sx :+: sy) = bandBlockSize band\n folder !acc !(!(iB :+: jB), !vec) = go 0 0 acc\n where\n go !i !j !acc'\n | i < stopx = go (i+1) j\n (f acc' ix (vec `G.unsafeIndex` (j*sx+i)))\n | j+1 < stopy = go 0 (j+1) acc'\n | otherwise = acc'\n where ix = iB*sx+i :+: jB*sy+j\n !stopx\n | mx \/= 0 && iB==nx-1 = mx\n | otherwise = sx\n !stopy\n | my \/= 0 && jB==ny-1 = my\n | otherwise = sy\n{-# INLINEABLE ifoldl' #-}\n\nfoldlWindow'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s a t -> Envelope Int -> GDAL s b\nfoldlWindow' f b = ifoldlWindow' (\\z _ v -> f z v) b\n{-# INLINE foldlWindow' #-}\n\nifoldlWindow'\n :: forall s t a b. GDALType a\n => (b -> Pair Int -> Value a -> b)\n -> b -> Band s a t -> Envelope Int -> GDAL s b\nifoldlWindow' f z band (Envelope (x0 :+: y0) (x1 :+: y1)) = runConduit $\n allBlocks band =$= CL.filter inRange\n =$= decorate (unsafeBlockConduit band)\n =$= CL.fold folder z\n where\n inRange bIx = bx0 < x1 && x0 < bx1 && by0 < y1 && y0 < by1\n where\n !b0@(bx0 :+: by0) = bIx * bSize\n !(bx1 :+: by1) = b0 + bSize\n !(mx :+: my) = liftA2 mod (bandSize band) (bandBlockSize band)\n !(nx :+: ny) = bandBlockCount band\n !bSize@(sx :+: sy) = bandBlockSize band\n folder !acc !(!(iB :+: jB), !vec) = go 0 0 acc\n where\n go !i !j !acc'\n | i < stopx = go (i+1) j acc''\n | j+1 < stopy = go 0 (j+1) acc'\n | otherwise = acc'\n where\n !ix@(ixx :+: ixy) = iB*sx+i :+: jB*sy+j\n acc''\n | x0 <= ixx && ixx < x1 && y0 <= ixy && ixy < y1\n = f acc' ix (vec `G.unsafeIndex` (j*sx+i))\n | otherwise = acc'\n !stopx\n | mx \/= 0 && iB==nx-1 = mx\n | otherwise = sx\n !stopy\n | my \/= 0 && jB==ny-1 = my\n | otherwise = sy\n{-# INLINEABLE ifoldlWindow' #-}\n\nunsafeBlockSource\n :: GDALType a\n => Band s a t -> Source (GDAL s) (BlockIx, U.Vector (Value a))\nunsafeBlockSource band = allBlocks band =$= decorate (unsafeBlockConduit band)\n\nblockSource\n :: GDALType a\n => Band s a t -> Source (GDAL s) (BlockIx, U.Vector (Value a))\nblockSource band = allBlocks band =$= decorate (blockConduit band)\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> BlockIx -> U.Vector (Value a) -> GDAL s ()\nwriteBandBlock band blockIx uvec =\n runConduit (yield (blockIx, uvec) =$= blockSink band)\n\nfmapBand\n :: forall s a b t. (GDALType a, GDALType b)\n => (Value a -> Value b)\n -> Band s a t\n -> RWBand s b \n -> GDAL s ()\nfmapBand f src dst\n | bandSize src \/= bandSize dst\n = throwBindingException (InvalidRasterSize (bandSize src))\n | bandBlockSize src \/= bandBlockSize dst\n = throwBindingException notImplementedErr\n | otherwise = runConduit\n (unsafeBlockSource src =$= CL.map (second (U.map f)) =$= blockSink dst)\n where\n notImplementedErr = NotImplemented\n \"fmapBand: Not implemented for bands of different block size\"\n\nfoldBands\n :: forall s a b t. (GDALType a, GDALType b)\n => (Value b -> Value a -> Value b)\n -> RWBand s b\n -> [Band s a t]\n -> GDAL s ()\nfoldBands fun zb bs =\n runConduit (unsafeBlockSource zb =$= awaitForever foldThem =$= blockSink zb)\n where\n foldThem (bix, acc) = do\n r <- fmap (L.foldl' (G.zipWith fun) acc)\n (lift (mapM (flip readBandBlock bix) bs))\n yield (bix, r)\n\n\n\nblockSink\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (BlockIx, U.Vector (Value a)) (GDAL s) ()\nblockSink band = do\n writeBlock <-\n if dtBand==dtBuf\n then return writeNative\n else do tempBuf <- liftIO (mallocForeignPtrBytes (len*szBand))\n return (writeTranslated tempBuf)\n lift (bandMaskType band) >>= \\case\n MaskNoData -> lift (noDataOrFail band) >>= sinkNodata writeBlock\n MaskAllValid -> sinkAllValid writeBlock\n _ -> lift (bandMask band) >>= sinkMask writeBlock\n\n where\n len = bandBlockLen band\n dtBand = bandDataType (band)\n szBand = sizeOfDataType dtBand\n dtBuf = hsDataType (Proxy :: Proxy a)\n szBuf = sizeOfDataType dtBuf\n\n sinkNodata writeBlock nd = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n St.unsafeWith (toGVecWithNodata nd vec) (writeBlock ix)\n\n\n sinkAllValid writeBlock = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n case toGVec vec of\n Just buf -> St.unsafeWith buf (writeBlock ix)\n Nothing -> throwBindingException BandDoesNotAllowNoData\n\n sinkMask writeBlock bMask = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n let (mask, vec') = toGVecWithMask vec\n off = bi * bs\n win = liftA2 min bs (rs - off)\n bi = fmap fromIntegral ix\n bs = fmap fromIntegral (bandBlockSize band)\n rs = fmap fromIntegral (bandSize band)\n St.unsafeWith vec' (writeBlock ix)\n St.unsafeWith mask $ \\pBuf ->\n checkCPLError \"WriteBlock\" $\n {#call RasterIO as ^#}\n (unBand bMask)\n (fromEnumC GF_Write)\n (pFst off)\n (pSnd off)\n (pFst win)\n (pSnd win)\n (castPtr pBuf)\n (pFst win)\n (pSnd win)\n (fromEnumC GByte)\n 0\n (pFst bs * fromIntegral (sizeOfDataType GByte))\n\n checkLen v\n | len \/= G.length v\n = throwBindingException (InvalidBlockSize (G.length v))\n | otherwise = return ()\n\n writeTranslated temp blockIx pBuf =\n withForeignPtr temp $ \\pTemp -> do\n {#call unsafe CopyWords as ^#}\n (castPtr pTemp)\n (fromEnumC dtBand)\n (fromIntegral szBand)\n (castPtr pBuf)\n (fromEnumC dtBuf)\n (fromIntegral szBuf)\n (fromIntegral len)\n writeNative blockIx pTemp\n\n writeNative blockIx pBuf =\n checkCPLError \"WriteBlock\" $\n {#call GDALWriteBlock as ^#}\n (unBand band)\n (pFst bi)\n (pSnd bi)\n (castPtr pBuf)\n where bi = fmap fromIntegral blockIx\n\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s a t -> BlockIx -> GDAL s (U.Vector (Value a))\nreadBandBlock band blockIx = fmap fromJust $ runConduit $\n yield blockIx =$= unsafeBlockConduit band =$= CL.head\n\n\nallBlocks :: Monad m => Band s a t -> Producer m BlockIx\nallBlocks band = CL.sourceList [x :+: y | y <- [0..ny-1], x <- [0..nx-1]]\n where\n !(nx :+: ny) = bandBlockCount band\n\nblockConduit\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (U.Vector (Value a))\nblockConduit band =\n unsafeBlockConduitM band =$= CL.mapM (liftIO . U.freeze)\n\nunsafeBlockConduit\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (U.Vector (Value a))\nunsafeBlockConduit band =\n unsafeBlockConduitM band =$= CL.mapM (liftIO . U.unsafeFreeze)\n\n\nunsafeBlockConduitM\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (UM.IOVector (Value a))\nunsafeBlockConduitM band = do\n buf <- liftIO (M.new len)\n maskType <- lift $ bandMaskType band\n case maskType of\n MaskNoData -> do\n noData <- lift $ noDataOrFail band\n blockReader (mkValueUMVector noData buf) buf (const (return ()))\n MaskAllValid ->\n blockReader (mkAllValidValueUMVector buf) buf (const (return ()))\n _ -> do\n mBuf <- liftIO $ M.replicate len 0\n mask <- lift $ bandMask band\n blockReader (mkMaskedValueUMVector mBuf buf) buf (readMask mask mBuf)\n where\n isNative = dtBand == dtBuf\n len = bandBlockLen band\n dtBand = bandDataType band\n dtBuf = hsDataType (Proxy :: Proxy a)\n\n blockReader vec buf extra\n | isNative = awaitForever $ \\ix -> do\n liftIO (Stm.unsafeWith buf (loadBlock ix))\n extra ix\n yield vec\n | otherwise = do\n temp <- liftIO $ mallocForeignPtrBytes (len*szBand)\n awaitForever $ \\ix -> do\n liftIO $ withForeignPtr temp $ \\pTemp -> do\n loadBlock ix pTemp\n Stm.unsafeWith buf (translateBlock pTemp)\n extra ix\n yield vec\n\n loadBlock ix pBuf = \n checkCPLError \"ReadBlock\" $\n {#call ReadBlock as ^#}\n (unBand band)\n (fromIntegral (pFst ix))\n (fromIntegral (pSnd ix))\n (castPtr pBuf)\n\n translateBlock pTemp pBuf = \n {#call unsafe CopyWords as ^#}\n (castPtr pTemp)\n (fromEnumC dtBand)\n (fromIntegral szBand)\n (castPtr pBuf)\n (fromEnumC dtBuf)\n (fromIntegral szBuf)\n (fromIntegral len)\n szBand = sizeOfDataType dtBand\n szBuf = sizeOfDataType dtBuf\n\n readMask mask vMask ix =\n liftIO $\n Stm.unsafeWith vMask $ \\pMask ->\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand mask)\n (fromEnumC GF_Read)\n (pFst off)\n (pSnd off)\n (pFst win)\n (pSnd win)\n (castPtr pMask)\n (pFst win)\n (pSnd win)\n (fromEnumC GByte)\n 0\n (pFst bs)\n where\n bi = fmap fromIntegral ix\n off = bi * bs\n win = liftA2 min bs (rs - off)\n bs = fmap fromIntegral (bandBlockSize band)\n rs = fmap fromIntegral (bandSize band)\n\nopenDatasetCount :: IO Int\nopenDatasetCount =\n alloca $ \\ppDs ->\n alloca $ \\pCount -> do\n {#call unsafe GetOpenDatasets as ^#} ppDs pCount\n fmap fromIntegral (peek pCount)\n\n-----------------------------------------------------------------------------\n-- Metadata\n-----------------------------------------------------------------------------\n\nmetadataDomains\n :: (MonadIO m, MajorObject o t)\n => o t -> m [Text]\n#if SUPPORTS_METADATA_DOMAINS\nmetadataDomains o =\n liftIO $\n fromCPLStringList $\n {#call unsafe GetMetadataDomainList as ^#} (majorObject o)\n#else\nmetadataDomains = const (return [])\n#endif\n\nmetadata\n :: (MonadIO m, MajorObject o t)\n => Maybe ByteString -> o t -> m [(Text,Text)]\nmetadata domain o =\n liftIO $\n withMaybeByteString domain\n ({#call unsafe GetMetadata as ^#} (majorObject o)\n >=> fmap (map breakIt) . fromBorrowedCPLStringList)\n where\n breakIt s =\n case T.break (=='=') s of\n (k,\"\") -> (k,\"\")\n (k, v) -> (k, T.tail v)\n\nmetadataItem\n :: (MonadIO m, MajorObject o t)\n => Maybe ByteString -> ByteString -> o t -> m (Maybe ByteString)\nmetadataItem domain key o =\n liftIO $\n useAsCString key $ \\pKey ->\n withMaybeByteString domain $\n {#call unsafe GetMetadataItem as ^#} (majorObject o) pKey >=>\n maybePackCString\n\nsetMetadataItem\n :: (MonadIO m, MajorObject o t, t ~ ReadWrite)\n => Maybe ByteString -> ByteString -> ByteString -> o t -> m ()\nsetMetadataItem domain key val o =\n liftIO $\n checkCPLError \"setMetadataItem\" $\n useAsCString key $ \\pKey ->\n useAsCString val $ \\pVal ->\n withMaybeByteString domain $\n {#call unsafe GDALSetMetadataItem as ^#} (majorObject o) pKey pVal\n\ndescription :: (MonadIO m, MajorObject o t) => o t -> m ByteString\ndescription =\n liftIO . ({#call unsafe GetDescription as ^#} . majorObject >=> packCString)\n\nsetDescription\n :: (MonadIO m, MajorObject o t, t ~ ReadWrite)\n => ByteString -> o t -> m ()\nsetDescription val =\n liftIO . checkGDALCall_ const .\n useAsCString val . {#call unsafe GDALSetDescription as ^#} . majorObject\n\n-----------------------------------------------------------------------------\n-- GDAL2 OGR-GDAL consolidated API (WIP)\n-----------------------------------------------------------------------------\n\n\nlayerCount :: Dataset s a t -> GDAL s Int\n\ngetLayer :: Int -> Dataset s a t -> GDAL s (Layer s l t a)\n\ngetLayerByName :: Text -> Dataset s a t -> GDAL s (Layer s l t a)\n\nexecuteSQL\n :: OGRFeature a\n => SQLDialect -> Text -> Maybe Geometry -> RODataset s any\n -> GDAL s (ROLayer s l a)\n\ncreateLayer\n :: forall s l a any. OGRFeatureDef a\n => RWDataset s any -> ApproxOK -> OptionList -> GDAL s (RWLayer s l a)\n\ncreateLayerWithDef\n :: forall s l a any\n . RWDataset s any -> FeatureDef -> ApproxOK -> OptionList\n -> GDAL s (RWLayer s l a)\n\n#if GDAL_VERSION_MAJOR >= 2\nlayerCount = fmap fromIntegral\n . liftIO . {#call GDALDatasetGetLayerCount as ^#} . unDataset\n\ngetLayer ix ds =\n fmap Layer $\n flip allocate (const (return ())) $\n checkGDALCall checkIt $\n {#call GDALDatasetGetLayer as ^#} (unDataset ds) (fromIntegral ix)\n where\n checkIt e p' |\u00a0p'==nullLayerH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALBindingException (InvalidLayerIndex ix)\n\ngetLayerByName name ds =\n fmap Layer $\n flip allocate (const (return ())) $\n checkGDALCall checkIt $\n useAsEncodedCString name $\n {#call GDALDatasetGetLayerByName as ^#} (unDataset ds)\n where\n checkIt e p' |\u00a0p'==nullLayerH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALBindingException (InvalidLayerName name)\n\nexecuteSQL dialect query mSpatialFilter ds =\n fmap Layer $ allocate execute freeIfNotNull\n where\n execute =\n checkGDALCall checkit $\n withMaybeGeometry mSpatialFilter $ \\pF ->\n useAsEncodedCString query $ \\pQ ->\n withSQLDialect dialect $ {#call GDALDatasetExecuteSQL as ^#} pDs pQ pF\n\n freeIfNotNull pL\n | pL \/= nullLayerH = {#call unsafe GDALDatasetReleaseResultSet as ^#} pDs pL\n | otherwise = return ()\n\n pDs = unDataset ds\n checkit (Just (GDALException{gdalErrNum=AppDefined, gdalErrMsg=msg})) _ =\n Just (GDALBindingException (SQLQueryError msg))\n checkit Nothing p | p==nullLayerH =\n Just (GDALBindingException NullLayer)\n checkit e p | p==nullLayerH = e\n checkit _ _ = Nothing\n\ncreateLayer ds = createLayerWithDef ds (featureDef (Proxy :: Proxy a))\n\ncreateLayerWithDef ds FeatureDef{..} approxOk opts =\n fmap Layer $\n flip allocate (const (return ())) $\n useAsEncodedCString fdName $ \\pName ->\n withMaybeSpatialReference (gfdSrs fdGeom) $ \\pSrs ->\n withOptionList opts $ \\pOpts -> do\n pL <- checkGDALCall checkIt $\n {#call GDALDatasetCreateLayer as ^#} pDs pName pSrs gType pOpts\n G.forM_ fdFields $ \\(n,f) -> withFieldDefnH n f $ \\pFld ->\n checkOGRError \"CreateField\" $\n {#call unsafe OGR_L_CreateField as ^#} pL pFld iApproxOk\n when (not (G.null fdGeoms)) $\n if supportsMultiGeomFields pL\n then\n#if SUPPORTS_MULTI_GEOM_FIELDS\n G.forM_ fdGeoms $ \\(n,f) -> withGeomFieldDefnH n f $ \\pGFld ->\n {#call unsafe OGR_L_CreateGeomField as ^#} pL pGFld iApproxOk\n#else\n error \"should never reach here\"\n#endif\n else throwBindingException MultipleGeomFieldsNotSupported\n return pL\n where\n supportsMultiGeomFields pL =\n layerHasCapability pL CreateGeomField &&\n dataSourceHasCapability pDs CreateGeomFieldAfterCreateLayer\n iApproxOk = fromEnumC approxOk\n pDs = unDataset ds\n gType = fromEnumC (gfdType fdGeom)\n checkIt e p' |\u00a0p'==nullLayerH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALBindingException NullLayer\n\n dataSourceHasCapability :: DatasetH -> DataSourceCapability -> Bool\n dataSourceHasCapability d c = unsafePerformIO $ do\n withCString (\"ODsC\" ++ show c)\n (fmap toBool . {#call unsafe GDALDatasetTestCapability as ^#} d)\n\n\n#else\nrequiresGDAL2 :: String -> a\nrequiresGDAL2 funName = error $\n show funName \n ++ \" on a Dataset requires GDAL version >= 2. Use the API from OGR instead\"\nlayerCount = requiresGDAL2 \"layerCount\"\ngetLayer = requiresGDAL2 \"getLayer\"\ngetLayerByName = requiresGDAL2 \"getLayerByName\"\nexecuteSQL = requiresGDAL2 \"executeSQL\"\ncreateLayer = requiresGDAL2 \"createLayer\"\ncreateLayerWithDef = requiresGDAL2 \"createLayerWithDef\"\n#endif\n\n-----------------------------------------------------------------------------\n-- Conduit utils\n-----------------------------------------------------------------------------\n\n-- | Parallel zip of two conduits\npZipConduitApp\n :: Monad m\n => Conduit a m (b -> c)\n -> Conduit a m b\n -> Conduit a m c\npZipConduitApp (ConduitM l0) (ConduitM r0) = ConduitM $ \\rest -> let\n go (HaveOutput p c o) (HaveOutput p' c' o') =\n HaveOutput (go p p') (c>>c') (o o')\n go (NeedInput p c) (NeedInput p' c') =\n NeedInput (\\i -> go (p i) (p' i)) (\\u -> go (c u) (c' u))\n go (Done ()) (Done ()) = rest ()\n go (PipeM m) (PipeM m') = PipeM (liftM2 go m m')\n go (Leftover p i) (Leftover p' _) = Leftover (go p p') i\n go _ _ = error \"pZipConduitApp: not parallel\"\n in go (injectLeftovers $ l0 Done) (injectLeftovers $ r0 Done)\n\nnewtype PZipConduit i m o =\n PZipConduit { getPZipConduit :: Conduit i m o}\n\ninstance Monad m => Functor (PZipConduit i m) where\n fmap f = PZipConduit . mapOutput f . getPZipConduit\n\ninstance Monad m => Applicative (PZipConduit i m) where\n pure = PZipConduit . forever . yield\n PZipConduit l <*> PZipConduit r = PZipConduit (pZipConduitApp l r)\n\nzipBlocks\n :: GDALType a\n => Band s a t -> PZipConduit BlockIx (GDAL s) (U.Vector (Value a))\nzipBlocks = PZipConduit . unsafeBlockConduit\n\ngetZipBlocks\n :: PZipConduit BlockIx (GDAL s) a\n -> Conduit BlockIx (GDAL s) (BlockIx, a)\ngetZipBlocks = decorate . getPZipConduit\n\ndecorate :: Monad m => Conduit a m b -> Conduit a m (a, b)\ndecorate (ConduitM c0) = ConduitM $ \\rest -> let\n go1 HaveOutput{} = error \"unexpected NeedOutput\"\n go1 (NeedInput p c) = NeedInput (\\i -> go2 i (p i)) (go1 . c)\n go1 (Done r) = rest r\n go1 (PipeM mp) = PipeM (fmap (go1) mp)\n go1 (Leftover p i) = Leftover (go1 p) i\n\n go2 i (HaveOutput p c o) = HaveOutput (go2 i p) c (i, o)\n go2 _ (NeedInput p c) = NeedInput (\\i -> go2 i (p i)) (go1 . c)\n go2 _ (Done r) = rest r\n go2 i (PipeM mp) = PipeM (fmap (go2 i) mp)\n go2 i (Leftover p i') = Leftover (go2 i p) i'\n in go1 (c0 Done)\n","old_contents":"{-# LANGUAGE CPP #-}\n{-# LANGUAGE RecordWildCards #-}\n{-# LANGUAGE MultiParamTypeClasses #-}\n{-# LANGUAGE TypeFamilies #-}\n{-# LANGUAGE ForeignFunctionInterface #-}\n{-# LANGUAGE OverloadedStrings #-}\n{-# LANGUAGE FlexibleInstances #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE BangPatterns #-}\n{-# LANGUAGE ScopedTypeVariables #-}\n{-# LANGUAGE RankNTypes #-}\n{-# LANGUAGE DataKinds #-}\n{-# LANGUAGE KindSignatures #-}\n{-# LANGUAGE StandaloneDeriving #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DeriveDataTypeable #-}\n{-# LANGUAGE LambdaCase #-}\n\nmodule GDAL.Internal.GDAL (\n GDALRasterException (..)\n , Geotransform (..)\n , OverviewResampling (..)\n , DriverName (..)\n , Driver (..)\n , DriverH (..)\n , Dataset\n , DatasetH (..)\n , RWDataset\n , RODataset\n , RWBand\n , ROBand\n , Band\n , RasterBandH (..)\n , MaskType (..)\n\n , northUpGeotransform\n , gcpGeotransform\n , applyGeotransform\n , (|$|)\n , invertGeotransform\n , inv\n , composeGeotransforms\n , (|.|)\n , geoEnvelopeTransformer\n\n , driverByName\n , driverShortName\n , driverLongName\n\n , nullDatasetH\n , allRegister\n , destroyDriverManager\n , create\n , createMem\n , delete\n , rename\n , copyFiles\n , flushCache\n , closeDataset\n , openDatasetH\n , createDatasetH\n , openReadOnly\n , openReadWrite\n , OpenFlag(..)\n , identifyDriver\n , identifyDriverEx\n , openReadOnlyEx\n , openReadWriteEx\n , unsafeToReadOnly\n , createCopy\n , buildOverviews\n , driverCreationOptionList\n\n , layerCount\n , getLayer\n , getLayerByName\n , executeSQL\n , createLayer\n , createLayerWithDef\n\n , bandAs\n\n , datasetDriver\n , datasetSize\n , datasetFileList\n , datasetProjection\n , setDatasetProjection\n , datasetProjectionWkt\n , setDatasetProjectionWkt\n , datasetGeotransform\n , setDatasetGeotransform\n , datasetGCPs\n , setDatasetGCPs\n , datasetBandCount\n\n , bandDataType\n , bandProjection\n , bandGeotransform\n , bandBlockSize\n , bandBlockCount\n , bandBlockLen\n , bandSize\n , bandHasOverviews\n , bandBestOverviewLevel\n , allBand\n , bandNodataValue\n , setBandNodataValue\n , getBand\n , addBand\n , fillBand\n , fmapBand\n , foldBands\n , readBand\n , createBandMask\n , bandMask\n , readBandBlock\n , writeBand\n , writeBandBlock\n , copyBand\n , bandConduit\n , unsafeBandConduit\n , bandSink\n , bandSinkGeo\n\n , metadataDomains\n , metadata\n , metadataItem\n , setMetadataItem\n , description\n , setDescription\n\n , foldl'\n , ifoldl'\n , foldlWindow'\n , ifoldlWindow'\n , blockConduit\n , unsafeBlockConduit\n , blockSource\n , unsafeBlockSource\n , blockSink\n , allBlocks\n , zipBlocks\n , getZipBlocks\n\n , unDataset\n , unBand\n , version\n , newDatasetHandle\n , unsafeBandDataset\n , openDatasetCount\n\n , module GDAL.Internal.DataType\n) where\n\n#include \"bindings.h\"\n#include \"gdal.h\"\n\n#include \"overviews.h\"\n\n\n{#context lib = \"gdal\" prefix = \"GDAL\" #}\n\nimport Control.Arrow (second)\nimport Control.Applicative (Applicative(..), (<$>), liftA2)\nimport Control.Exception (Exception(..))\nimport Control.DeepSeq (NFData(..))\nimport Control.Monad (liftM2, when, (>=>), forever)\nimport Control.Monad.Catch (MonadThrow, throwM)\nimport Control.Monad.Trans (lift)\nimport Control.Monad.IO.Class (MonadIO(liftIO))\n\nimport Data.Bits ((.&.), (.|.))\nimport Data.ByteString.Char8 (ByteString, packCString, useAsCString)\nimport Data.ByteString.Unsafe (unsafeUseAsCString)\nimport Data.Coerce (coerce)\nimport qualified Data.List as L\nimport qualified Data.Conduit.List as CL\nimport Data.Conduit\nimport Data.Conduit.Internal (Pipe(..), ConduitM(..), injectLeftovers)\nimport Data.Maybe (fromMaybe, fromJust)\nimport Data.String (IsString)\nimport Data.Proxy\nimport Data.Text (Text)\nimport qualified Data.Text as T\nimport Data.Text.Encoding (decodeUtf8)\nimport Data.Typeable (Typeable)\nimport qualified Data.Vector.Generic as G\nimport qualified Data.Vector.Storable as St\nimport qualified Data.Vector.Storable.Mutable as Stm\nimport qualified Data.Vector.Generic.Mutable as M\nimport qualified Data.Vector.Unboxed.Mutable as UM\nimport qualified Data.Vector.Unboxed as U\nimport Data.Word (Word8)\n\nimport Foreign.C.String (withCString, CString)\nimport Foreign.C.Types\nimport Foreign.ForeignPtr (withForeignPtr, mallocForeignPtrBytes)\nimport Foreign.Ptr (Ptr, castPtr, nullPtr)\nimport Foreign.Storable (Storable(..))\nimport Foreign.Marshal.Alloc (alloca)\nimport Foreign.Marshal.Array (withArrayLen, advancePtr)\nimport Foreign.Marshal.Utils (toBool, fromBool, with)\n\nimport System.IO.Unsafe (unsafePerformIO)\n\nimport GDAL.Internal.Types\nimport GDAL.Internal.Types.Value\nimport GDAL.Internal.DataType\nimport GDAL.Internal.Common\nimport GDAL.Internal.Util\n{#import GDAL.Internal.OGRError#}\n{#import GDAL.Internal.Layer#}\n{#import GDAL.Internal.OGRGeometry#}\n{#import GDAL.Internal.OGRFeature#}\n{#import GDAL.Internal.GCP#}\n{#import GDAL.Internal.CPLError#}\n{#import GDAL.Internal.CPLString#}\n{#import GDAL.Internal.CPLProgress#}\nimport GDAL.Internal.OSR\nimport GDAL.Internal.OGRGeometry (Envelope(..), envelopeSize)\n\n\n\nnewtype DriverName = DriverName ByteString\n deriving (Eq, IsString)\n\ninstance Show DriverName where\n show (DriverName s) = show s\n\nversion :: (Int, Int)\nversion = ({#const GDAL_VERSION_MAJOR#} , {#const GDAL_VERSION_MINOR#})\n\ndata GDALRasterException\n = InvalidRasterSize !Size\n | InvalidBlockSize !Int\n | InvalidDriverOptions\n | UnknownRasterDataType\n | NullDataset\n | NullBand\n | UnknownDriver !ByteString\n | BandDoesNotAllowNoData\n | CannotInvertGeotransform\n | NotImplemented !ByteString\n deriving (Typeable, Show, Eq)\n\ninstance Exception GDALRasterException where\n toException = bindingExceptionToException\n fromException = bindingExceptionFromException\n\n\n{#enum GDALAccess {} deriving (Eq, Show) #}\n\n{#enum RWFlag {} deriving (Eq, Show) #}\n\n{#pointer MajorObjectH newtype#}\n\nclass MajorObject o (t::AccessMode) where\n majorObject :: o t -> MajorObjectH\n\n\n{#pointer DatasetH newtype #}\n\n\nnullDatasetH :: DatasetH\nnullDatasetH = DatasetH nullPtr\n\nderiving instance Eq DatasetH\nderiving instance NFData DatasetH\n\nnewtype Dataset s a (t::AccessMode) =\n Dataset (Maybe ReleaseKey, DatasetH)\n\ninstance MajorObject (Dataset s a) t where\n majorObject ds =\n let DatasetH p = unDataset ds\n in MajorObjectH (castPtr p)\n\nunDataset :: Dataset s a t -> DatasetH\nunDataset (Dataset (_,s)) = s\n\ncloseDataset :: MonadIO m => Dataset s a t -> m ()\ncloseDataset (Dataset (Just rk,_)) = release rk\ncloseDataset _ = return ()\n\ntype RODataset s a = Dataset s a ReadOnly\ntype RWDataset s a = Dataset s a ReadWrite\n\n{#pointer RasterBandH newtype #}\n\nnullBandH :: RasterBandH\nnullBandH = RasterBandH nullPtr\n\nderiving instance Eq RasterBandH\n\nnewtype Band s a (t::AccessMode) = Band (RasterBandH, DataTypeK)\n\nunBand :: Band s a t -> RasterBandH\nunBand (Band (p,_)) = p\n\nbandDataType :: Band s a t -> DataTypeK\nbandDataType (Band (_,t)) = t\n{-# INLINE bandDataType #-}\n\nbandAs :: Band s a t -> DataType d -> Band s (HsType d) t\nbandAs = const . coerce\n{-# INLINE bandAs #-}\n\ninstance MajorObject (Band s a) t where\n majorObject b =\n let RasterBandH p = unBand b\n in MajorObjectH (castPtr p)\n\ntype ROBand s a = Band s a ReadOnly\ntype RWBand s a = Band s a ReadWrite\n\n\n{#pointer DriverH newtype #}\n\nnullDriverH :: DriverH\nnullDriverH = DriverH nullPtr\n\nderiving instance Eq DriverH\n\nnewtype Driver (t::AccessMode) = Driver { unDriver :: DriverH }\n\ninstance MajorObject Driver t where\n majorObject d =\n let DriverH p = unDriver d\n in MajorObjectH (castPtr p)\n\n{#fun AllRegister as ^ {} -> `()' #}\n\n{#fun DestroyDriverManager as ^ {} -> `()'#}\n\ndriverByName :: MonadIO m => DriverName -> m (Driver t)\ndriverByName (DriverName s) = liftIO $ do\n d <- useAsCString s {#call unsafe GetDriverByName as ^#}\n let DriverH p = d in if p == nullPtr\n then throwBindingException (UnknownDriver s)\n else return (Driver d)\n\ndriverHByName :: MonadIO m => DriverName -> m DriverH\ndriverHByName s = (\\(Driver h) -> h) <$> driverByName s\n\ndriverLongName :: Driver d -> Text\ndriverLongName (Driver d) = unsafePerformIO $\n {#call unsafe GetDriverLongName as ^#} d >>= fmap decodeUtf8 . packCString\n\ndriverShortName :: Driver d -> Text\ndriverShortName (Driver d) = unsafePerformIO $\n {#call unsafe GetDriverShortName as ^#} d >>= fmap decodeUtf8 . packCString\n\ndriverCreationOptionList :: Driver d -> ByteString\ndriverCreationOptionList (Driver d) = unsafePerformIO $\n {#call GetDriverCreationOptionList as ^#} d >>= packCString\n\nvalidateCreationOptions :: DriverH -> Ptr CString -> IO ()\nvalidateCreationOptions d o = do\n valid <- fmap toBool ({#call GDALValidateCreationOptions as ^ #} d o)\n when (not valid) (throwBindingException InvalidDriverOptions)\n\ncreate\n :: DriverName -> String -> Size -> Int -> DataType d -> OptionList\n -> GDAL s (Dataset s (HsType d) ReadWrite)\ncreate drv path size bands dtype optList = do\n d <- driverByName drv\n newDatasetHandle $ createDatasetH d path size bands dtype optList\n\ncreateDatasetH\n :: MonadIO m\n => Driver t -> String -> Size -> Int -> DataType d -> OptionList\n -> m DatasetH\ncreateDatasetH drv path (nx :+: ny) bands dtype opts = liftIO $\n withCString path $ \\path' -> do\n let nx' = fromIntegral nx\n ny' = fromIntegral ny\n bands' = fromIntegral bands\n dtype' = fromEnumC dtype\n d = unDriver drv\n withOptionList opts $ \\o -> do\n validateCreationOptions d o\n {#call GDALCreate as ^#} d path' nx' ny' bands' dtype' o\n\ndelete :: DriverName -> String -> GDAL s ()\ndelete driver path =\n liftIO $\n checkCPLError \"deleteDataset\" $ do\n d <- driverHByName driver\n withCString path ({#call DeleteDataset as ^#} d)\n\nrename :: DriverName -> String -> String -> GDAL s ()\nrename driver newName oldName =\n liftIO $\n checkCPLError \"renameDataset\" $ do\n d <- driverHByName driver\n withCString newName $\n withCString oldName . ({#call RenameDataset as ^#} d)\n\ncopyFiles :: DriverName -> String -> String -> GDAL s ()\ncopyFiles driver newName oldName =\n liftIO $\n checkCPLError \"copyFiles\" $ do\n d <- driverHByName driver\n withCString newName $\n withCString oldName . ({#call CopyDatasetFiles as ^#} d)\n\nopenReadOnly :: String -> DataType d -> GDAL s (RODataset s (HsType d))\nopenReadOnly p _ = openWithMode GA_ReadOnly p\n\nopenReadWrite :: String -> DataType d -> GDAL s (RWDataset s (HsType d))\nopenReadWrite p _ = openWithMode GA_Update p\n\nopenWithMode :: GDALAccess -> String -> GDAL s (Dataset s a t)\nopenWithMode m = newDatasetHandle . openDatasetH m\n\nopenDatasetH :: MonadIO m => GDALAccess -> String -> m DatasetH\nopenDatasetH m path =\n liftIO $\n withCString path $\n flip {#call GDALOpen as ^#} (fromEnumC m)\n\nidentifyDriver\n :: String -> GDAL s (Maybe (Driver t))\nidentifyDriver path = do\n d <- liftIO $ withCString path $\n flip {#call GDALIdentifyDriver as ^#} nullPtr\n return $ if d == nullDriverH then Nothing else Just (Driver d)\n\nopenReadOnlyEx :: [OpenFlag] -> OptionList -> String -> DataType d -> GDAL s (RODataset s (HsType d))\nopenReadWriteEx :: [OpenFlag] -> OptionList -> String -> DataType d -> GDAL s (RWDataset s (HsType d))\nidentifyDriverEx :: [OpenFlag] -> String -> GDAL s (Maybe (Driver t))\n\n#if SUPPORTS_OPENEX\n{#enum define OpenFlag {\n GDAL_OF_READONLY as OFReadonly\n , GDAL_OF_UPDATE as OFUpdate\n , GDAL_OF_ALL as OFAll\n , GDAL_OF_RASTER as OFRaster\n , GDAL_OF_VECTOR as OFVector\n , GDAL_OF_GNM as OFGnm\n , GDAL_OF_SHARED as OFShared\n , GDAL_OF_VERBOSE_ERROR as OFVerboseError\n , GDAL_OF_INTERNAL as OFInternal\n , GDAL_OF_DEFAULT_BLOCK_ACCESS as OFDefaultBlockAccess\n , GDAL_OF_ARRAY_BLOCK_ACCESS as OFArrayBlockAccess\n , GDAL_OF_HASHSET_BLOCK_ACCESS as OFHashsetBlockAccess\n } deriving (Eq, Bounded, Show) #}\n\nopenDatasetHEx :: MonadIO m => [OpenFlag] -> OptionList -> String -> m DatasetH\nopenDatasetHEx flgs opts path =\n liftIO $\n withOptionList opts $ \\ os -> \n withCString path $ \\ p ->\n {#call GDALOpenEx as ^#} p cflgs nullPtr os nullPtr\n where cflgs = foldr (.|.) 0 $ map (fromIntegral.fromEnum) flgs\n\nopenReadOnlyEx flgs opts p _ =\n newDatasetHandle (openDatasetHEx (OFReadonly:flgs) opts p)\n\nopenReadWriteEx flgs opts p _ =\n newDatasetHandle (openDatasetHEx (OFUpdate:flgs) opts p)\n\nidentifyDriverEx flgs path = do\n d <- liftIO $ withCString path $ \\ p ->\n {#call GDALIdentifyDriverEx as ^#} p cflgs nullPtr nullPtr\n return $ if d == nullDriverH then Nothing else Just (Driver d)\n where cflgs = foldr (.|.) 0 $ map (fromIntegral.fromEnum) flgs\n\n#else\ndata OpenFlag\nopenReadOnlyEx _ _ = openReadOnly\nopenReadWriteEx _ _ = openReadWrite\nidentifyDriverEx _ = identifyDriver\n#endif\n\nunsafeToReadOnly :: RWDataset s a -> GDAL s (RODataset s a)\nunsafeToReadOnly ds = flushCache ds >> return (coerce ds)\n\ncreateCopy\n :: DriverName -> String -> Dataset s a t -> Bool -> OptionList\n -> Maybe ProgressFun -> GDAL s (RWDataset s a)\ncreateCopy driver path ds strict opts progress =\n newDatasetHandle $\n withProgressFun \"createCopy\" progress $ \\pFunc -> do\n d <- driverHByName driver\n withOptionList opts $ \\o -> do\n validateCreationOptions d o\n withCString path $ \\p ->\n {#call GDALCreateCopy as ^#}\n d p (unDataset ds) (fromBool strict) o pFunc nullPtr\n\nnewDatasetHandle :: IO DatasetH -> GDAL s (Dataset s a t)\nnewDatasetHandle act = do\n (rk,ds) <- allocate (checkGDALCall checkit act) free\n return (Dataset (Just rk, ds))\n where\n checkit exc p\n | p==nullDatasetH = Just (fromMaybe\n (GDALBindingException NullDataset) exc)\n | otherwise = Nothing\n free = {#call GDALClose as ^#}\n\ncreateMem\n :: Size -> Int -> DataType d -> OptionList\n -> GDAL s (Dataset s (HsType d) ReadWrite)\ncreateMem = create \"Mem\" \"\"\n\nflushCache :: RWDataset s a -> GDAL s ()\nflushCache = liftIO . {#call GDALFlushCache as ^#} . unDataset\n\ndatasetDriver :: Dataset s a t -> Driver t'\ndatasetDriver ds =\n unsafePerformIO $\n Driver <$> {#call unsafe GetDatasetDriver as ^#} (unDataset ds)\n\ndatasetSize :: Dataset s a t -> Size\ndatasetSize ds =\n fmap fromIntegral $\n ({#call pure unsafe GetRasterXSize as ^#} (unDataset ds))\n :+: ({#call pure unsafe GetRasterYSize as ^#} (unDataset ds))\n\ndatasetFileList :: Dataset s a t -> GDAL s [Text]\ndatasetFileList =\n liftIO .\n fromCPLStringList .\n {#call unsafe GetFileList as ^#} .\n unDataset\n\ndatasetProjection\n :: (MonadThrow m, MonadIO m)\n => Dataset s a t -> m (Maybe SpatialReference)\ndatasetProjection ds = do\n mWkt <- datasetProjectionWkt ds\n case mWkt of\n Just wkt -> either throwM (return . Just) (srsFromWkt wkt)\n Nothing -> return Nothing\n\ndatasetProjectionWkt :: MonadIO m => Dataset s a t -> m (Maybe ByteString)\ndatasetProjectionWkt ds = liftIO $ do\n p <- {#call GetProjectionRef as ^#} (unDataset ds)\n if p == nullPtr then return Nothing else do\n c <- peek p\n if c == 0 then return Nothing else Just <$> packCString p\n\nsetDatasetProjection :: SpatialReference -> RWDataset s a -> GDAL s ()\nsetDatasetProjection srs = setDatasetProjectionWkt (srsToWkt srs)\n\nsetDatasetProjectionWkt :: ByteString -> RWDataset s a -> GDAL s ()\nsetDatasetProjectionWkt srs ds =\n liftIO $ checkCPLError \"SetProjection\" $\n useAsCString srs ({#call SetProjection as ^#} (unDataset ds))\n\nsetDatasetGCPs\n :: [GroundControlPoint] -> Maybe SpatialReference -> RWDataset s a\n -> GDAL s ()\nsetDatasetGCPs gcps mSrs ds =\n liftIO $\n checkCPLError \"setDatasetGCPs\" $\n withGCPArrayLen gcps $ \\nGcps pGcps ->\n withMaybeSRAsCString mSrs $\n {#call unsafe GDALSetGCPs as ^#}\n (unDataset ds)\n (fromIntegral nGcps)\n pGcps\n\ndatasetGCPs\n :: Dataset s a t\n -> GDAL s ([GroundControlPoint], Maybe SpatialReference)\ndatasetGCPs ds =\n liftIO $ do\n let pDs = unDataset ds\n srs <- maybeSpatialReferenceFromCString\n =<< {#call unsafe GetGCPProjection as ^#} pDs\n nGcps <- fmap fromIntegral ({#call unsafe GetGCPCount as ^#} pDs)\n gcps <- {#call unsafe GetGCPs as ^#} pDs >>= fromGCPArray nGcps\n return (gcps, srs)\n\n\ndata OverviewResampling\n = OvNearest\n | OvGauss\n | OvCubic\n | OvAverage\n | OvMode\n | OvAverageMagphase\n | OvNone\n\nbuildOverviews\n :: RWDataset s a -> OverviewResampling -> [Int] -> [Int] -> Maybe ProgressFun\n -> GDAL s ()\nbuildOverviews ds resampling overviews bands progress =\n liftIO $\n withResampling resampling $ \\pResampling ->\n withArrayLen (map fromIntegral overviews) $ \\nOverviews pOverviews ->\n withArrayLen (map fromIntegral bands) $ \\nBands pBands ->\n withProgressFun \"buildOverviews\" progress $ \\pFunc ->\n checkCPLError \"buildOverviews\" $\n {#call GDALBuildOverviews as ^#}\n (unDataset ds)\n pResampling\n (fromIntegral nOverviews)\n pOverviews\n (fromIntegral nBands)\n pBands\n pFunc\n nullPtr\n where\n withResampling OvNearest = unsafeUseAsCString \"NEAREST\\0\"\n withResampling OvGauss = unsafeUseAsCString \"GAUSS\\0\"\n withResampling OvCubic = unsafeUseAsCString \"CUBIC\\0\"\n withResampling OvAverage = unsafeUseAsCString \"AVERAGE\\0\"\n withResampling OvMode = unsafeUseAsCString \"MODE\\0\"\n withResampling OvAverageMagphase = unsafeUseAsCString \"AVERAGE_MAGPHASE\\0\"\n withResampling OvNone = unsafeUseAsCString \"NONE\\0\"\n\ndata Geotransform\n = Geotransform {\n gtXOff :: {-# UNPACK #-} !Double\n , gtXDelta :: {-# UNPACK #-} !Double\n , gtXRot :: {-# UNPACK #-} !Double\n , gtYOff :: {-# UNPACK #-} !Double\n , gtYRot :: {-# UNPACK #-} !Double\n , gtYDelta :: {-# UNPACK #-} !Double\n } deriving (Eq, Show)\n\ninstance NFData Geotransform where\n rnf Geotransform{} = ()\n\nnorthUpGeotransform :: Size -> Envelope Double -> Geotransform\nnorthUpGeotransform size envelope =\n Geotransform {\n gtXOff = pFst (envelopeMin envelope)\n , gtXDelta = pFst (envelopeSize envelope \/ fmap fromIntegral size)\n , gtXRot = 0\n , gtYOff = pSnd (envelopeMax envelope)\n , gtYRot = 0\n , gtYDelta = negate (pSnd (envelopeSize envelope \/ fmap fromIntegral size))\n }\n\ngcpGeotransform :: [GroundControlPoint] -> ApproxOK -> Maybe Geotransform\ngcpGeotransform gcps approxOk =\n unsafePerformIO $\n alloca $ \\pGt ->\n withGCPArrayLen gcps $ \\nGcps pGcps -> do\n ret <- fmap toBool $\n {#call unsafe GCPsToGeoTransform as ^#}\n (fromIntegral nGcps)\n pGcps\n (castPtr pGt)\n (fromEnumC approxOk)\n if ret then fmap Just (peek pGt) else return Nothing\n\napplyGeotransform :: Geotransform -> Pair Double -> Pair Double\napplyGeotransform Geotransform{..} (x :+: y) =\n (gtXOff + gtXDelta*x + gtXRot * y) :+: (gtYOff + gtYRot *x + gtYDelta * y)\n\ninfixr 5 |$|\n(|$|) :: Geotransform -> Pair Double -> Pair Double\n(|$|) = applyGeotransform\n\ninvertGeotransform :: Geotransform -> Maybe Geotransform\ninvertGeotransform (Geotransform g0 g1 g2 g3 g4 g5)\n | g2==0 && g4==0 && g1\/=0 && g5\/=0 -- No rotation\n = Just $! Geotransform (-g0\/g1) (1\/g1) 0 (-g3\/g5) 0 (1\/g5)\n | abs det < 1e-15 = Nothing -- not invertible\n | otherwise\n = Just $! Geotransform ((g2*g3 - g0*g5) * idet)\n (g5*idet)\n (-g2*idet)\n ((-g1*g3 + g0*g4) * idet)\n (-g4*idet)\n (g1*idet)\n where\n idet = 1\/det\n det = g1*g5 - g2*g4\n\ninv :: Geotransform -> Geotransform\ninv = fromMaybe (error \"Could not invert geotransform\") . invertGeotransform\n\n-- | Creates a Geotransform equivalent to applying a and then b\ncomposeGeotransforms :: Geotransform -> Geotransform -> Geotransform\nb `composeGeotransforms` a =\n Geotransform (b1*a0 + b2*a3 + b0)\n (b1*a1 + b2*a4)\n (b1*a2 + b2*a5)\n (b4*a0 + b5*a3 + b3)\n (b4*a1 + b5*a4)\n (b4*a2 + b5*a5)\n\n where\n Geotransform a0 a1 a2 a3 a4 a5 = a\n Geotransform b0 b1 b2 b3 b4 b5 = b\n\ninfixr 9 |.|\n(|.|) :: Geotransform -> Geotransform -> Geotransform\n(|.|) = composeGeotransforms\n\ninstance Storable Geotransform where\n sizeOf _ = sizeOf (undefined :: CDouble) * 6\n alignment _ = alignment (undefined :: CDouble)\n poke pGt (Geotransform g0 g1 g2 g3 g4 g5) = do\n let p = castPtr pGt :: Ptr CDouble\n pokeElemOff p 0 (realToFrac g0)\n pokeElemOff p 1 (realToFrac g1)\n pokeElemOff p 2 (realToFrac g2)\n pokeElemOff p 3 (realToFrac g3)\n pokeElemOff p 4 (realToFrac g4)\n pokeElemOff p 5 (realToFrac g5)\n peek pGt = do\n let p = castPtr pGt :: Ptr CDouble\n Geotransform <$> fmap realToFrac (peekElemOff p 0)\n <*> fmap realToFrac (peekElemOff p 1)\n <*> fmap realToFrac (peekElemOff p 2)\n <*> fmap realToFrac (peekElemOff p 3)\n <*> fmap realToFrac (peekElemOff p 4)\n <*> fmap realToFrac (peekElemOff p 5)\n\n\ndatasetGeotransform:: MonadIO m => Dataset s a t -> m (Maybe Geotransform)\ndatasetGeotransform ds = liftIO $ alloca $ \\p -> do\n ret <- {#call unsafe GetGeoTransform as ^#} (unDataset ds) (castPtr p)\n if toEnumC ret == CE_None\n then fmap Just (peek p)\n else return Nothing\n\nsetDatasetGeotransform :: MonadIO m => Geotransform -> RWDataset s a -> m ()\nsetDatasetGeotransform gt ds = liftIO $\n checkCPLError \"SetGeoTransform\" $\n with gt ({#call unsafe SetGeoTransform as ^#} (unDataset ds) . castPtr)\n\n\ndatasetBandCount :: MonadIO m => Dataset s a t -> m Int\ndatasetBandCount =\n fmap fromIntegral . liftIO . {#call unsafe GetRasterCount as ^#} . unDataset\n\ngetBand :: Int -> Dataset s a t -> GDAL s (Band s a t)\ngetBand b ds = liftIO $ do\n pB <- checkGDALCall checkit $\n {#call GetRasterBand as ^#} (unDataset ds) (fromIntegral b)\n dt <- fmap toEnumC ({#call unsafe GetRasterDataType as ^#} pB)\n return (Band (pB, dt))\n where\n checkit exc p\n | p == nullBandH = Just (fromMaybe (GDALBindingException NullBand) exc)\n | otherwise = Nothing\n\naddBand\n :: forall s a. GDALType a\n => OptionList -> RWDataset s a -> GDAL s (RWBand s a)\naddBand opts ds = do\n liftIO $\n checkCPLError \"addBand\" $\n withOptionList opts $\n {#call GDALAddBand as ^#} (unDataset ds) (fromEnumC dt)\n ix <- datasetBandCount ds\n getBand ix ds\n where dt = hsDataType (Proxy :: Proxy a)\n\n\nbandBlockSize :: (Band s a t) -> Size\nbandBlockSize band = unsafePerformIO $ alloca $ \\xPtr -> alloca $ \\yPtr -> do\n {#call unsafe GetBlockSize as ^#} (unBand band) xPtr yPtr\n fmap (fmap fromIntegral) (liftM2 (:+:) (peek xPtr) (peek yPtr))\n\nbandBlockLen :: Band s a t -> Int\nbandBlockLen = (\\(x :+: y) -> x*y) . bandBlockSize\n\nbandSize :: Band s a t -> Size\nbandSize band =\n fmap fromIntegral $\n ({#call pure unsafe GetRasterBandXSize as ^#} (unBand band))\n :+: ({#call pure unsafe GetRasterBandYSize as ^#} (unBand band))\n\nbandBestOverviewLevel\n :: MonadIO m\n => Band s a t -> Envelope Int -> Size -> m (Maybe Int)\nbandBestOverviewLevel band (Envelope (x0 :+: y0) (x1 :+: y1)) (nx :+: ny) =\n liftIO $\n toMaybeBandNo <$> {#call unsafe hs_gdal_band_get_best_overview_level#}\n (unBand band)\n (fromIntegral x0)\n (fromIntegral y0)\n (fromIntegral (x1-x0))\n (fromIntegral (y1-y0))\n (fromIntegral nx)\n (fromIntegral ny)\n where\n toMaybeBandNo n | n>=0 = Just (fromIntegral n)\n toMaybeBandNo _ = Nothing\n\n\nallBand :: Band s a t -> Envelope Int\nallBand = Envelope (pure 0) . bandSize\n\nbandBlockCount :: Band s a t -> Pair Int\nbandBlockCount b = fmap ceiling $ liftA2 ((\/) :: Double -> Double -> Double)\n (fmap fromIntegral (bandSize b))\n (fmap fromIntegral (bandBlockSize b))\n\nbandHasOverviews :: Band s a t -> GDAL s Bool\nbandHasOverviews =\n liftIO . fmap toBool . {#call unsafe HasArbitraryOverviews as ^#} . unBand\n\nbandNodataValue :: GDALType a => Band s a t -> GDAL s (Maybe a)\nbandNodataValue b =\n liftIO $\n alloca $ \\p -> do\n value <- {#call unsafe GetRasterNoDataValue as ^#} (unBand b) p\n hasNodata <- fmap toBool $ peek p\n return (if hasNodata then Just (fromCDouble value) else Nothing)\n\n\nsetBandNodataValue :: GDALType a => a -> RWBand s a -> GDAL s ()\nsetBandNodataValue v b =\n liftIO $\n checkCPLError \"SetRasterNoDataValue\" $\n {#call unsafe SetRasterNoDataValue as ^#} (unBand b) (toCDouble v)\n\ncreateBandMask :: MaskType -> RWBand s a -> GDAL s ()\ncreateBandMask maskType band = liftIO $\n checkCPLError \"createBandMask\" $\n {#call CreateMaskBand as ^#} (unBand band) cflags\n where cflags = maskFlagsForType maskType\n\nreadBand :: forall s t a. GDALType a\n => (Band s a t)\n -> Envelope Int\n -> Size\n -> GDAL s (U.Vector (Value a))\nreadBand band win sz = fmap fromJust $ runConduit $\n yield win =$= unsafeBandConduit sz band =$= CL.head\n\nbandConduit\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (U.Vector (Value a))\nbandConduit sz band =\n unsafeBandConduitM sz band =$= CL.mapM (liftIO . U.freeze)\n\nunsafeBandConduit\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (U.Vector (Value a))\nunsafeBandConduit sz band =\n unsafeBandConduitM sz band =$= CL.mapM (liftIO . U.unsafeFreeze)\n\n\nunsafeBandConduitM\n :: forall s a t. GDALType a\n => Size\n -> Band s a t\n -> Conduit (Envelope Int) (GDAL s) (UM.IOVector (Value a))\nunsafeBandConduitM size@(bx :+: by) band = do\n buf <- liftIO (M.new (bx*by))\n lift (bandMaskType band) >>= \\case\n MaskNoData -> do\n nd <- lift (noDataOrFail band)\n let vec = mkValueUMVector nd buf\n awaitForever $ \\win -> do\n liftIO (M.set buf nd >> read_ band buf win)\n yield vec\n _ -> do\n mBuf <- liftIO $ M.replicate (bx*by) 0\n mask <- lift $ bandMask band\n let vec = mkMaskedValueUMVector mBuf buf\n awaitForever $ \\win -> do\n liftIO (read_ band buf win >> read_ mask mBuf win)\n yield vec\n where\n read_ :: forall a'. GDALType a'\n => Band s a' t -> Stm.IOVector a' -> Envelope Int -> IO ()\n read_ b vec win = do\n let -- Requested minEnv\n x0 :+: y0 = envelopeMin win\n -- Effective minEnv\n x0' :+: y0' = max 0 <$> envelopeMin win\n -- Effective maxEnv\n x1' :+: y1' = min <$> bandSize b <*> envelopeMax win\n -- Effective origin\n e0 = x0' - x0 :+: y0' - y0\n -- Projected origin\n x :+: y = truncate <$> factor * fmap fromIntegral e0\n -- Effective buffer size\n sx :+: sy = (x1' - x0' :+: y1' - y0')\n -- Projected window\n bx' :+: by' = truncate\n <$> factor * fmap fromIntegral (sx :+: sy)\n\n --buffer size \/ envelope size ratio\n factor :: Pair Double\n factor = (fromIntegral <$> size)\n \/ (fromIntegral <$> envelopeSize win)\n\n off = y * bx + x\n\n Stm.unsafeWith vec $ \\ptr -> do\n checkCPLError \"RasterAdviseRead\" $\n {#call unsafe RasterAdviseRead as ^#}\n (unBand b)\n (fromIntegral x0')\n (fromIntegral y0')\n (fromIntegral sx)\n (fromIntegral sy)\n bx'\n by'\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n nullPtr\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand b)\n (fromEnumC GF_Read)\n (fromIntegral x0')\n (fromIntegral y0')\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr (ptr `advancePtr` off))\n bx'\n by'\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n 0\n (fromIntegral bx * fromIntegral (sizeOf (undefined :: a')))\n\ngeoEnvelopeTransformer\n :: Geotransform -> Maybe (Envelope Double -> Envelope Int)\ngeoEnvelopeTransformer gt =\n case (gtXDelta gt < 0, gtYDelta gt<0, invertGeotransform gt) of\n (_,_,Nothing) -> Nothing\n (False,False,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let e0' = fmap round (applyGeotransform iGt e0)\n e1' = fmap round (applyGeotransform iGt e1)\n in Envelope e0' e1'\n (True,False,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x1 :+: y0 = fmap round (applyGeotransform iGt e0)\n x0 :+: y1 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n (False,True,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x0 :+: y1 = fmap round (applyGeotransform iGt e0)\n x1 :+: y0 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n (True,True,Just iGt) -> Just $ \\(Envelope e0 e1) ->\n let x1 :+: y1 = fmap round (applyGeotransform iGt e0)\n x0 :+: y0 = fmap round (applyGeotransform iGt e1)\n in Envelope (x0 :+: y0) (x1 :+: y1)\n\n\nwriteBand\n :: forall s a. GDALType a\n => RWBand s a\n -> Envelope Int\n -> Size\n -> U.Vector (Value a)\n -> GDAL s ()\nwriteBand band win sz uvec =\n runConduit (yield (win, sz, uvec) =$= bandSink band)\n\n\n\nbandSink\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (Envelope Int, Size, U.Vector (Value a)) (GDAL s) ()\nbandSink band = lift (bandMaskType band) >>= \\case\n MaskNoData -> do\n nd <- lift (noDataOrFail band)\n awaitForever $ \\(win, sz, uvec) -> lift $\n write band win sz (toGVecWithNodata nd uvec)\n MaskAllValid ->\n awaitForever $ \\(win, sz, uvec) -> lift $\n maybe (throwBindingException BandDoesNotAllowNoData)\n (write band win sz)\n (toGVec uvec)\n _ -> do\n mBand <- lift (bandMask band)\n awaitForever $ \\(win, sz, uvec) -> lift $ do\n let (mask, vec) = toGVecWithMask uvec\n write band win sz vec\n write mBand win sz mask\n where\n\n write :: forall a'. GDALType a'\n => RWBand s a' -> Envelope Int -> Size -> St.Vector a' -> GDAL s ()\n write band' win sz@(bx :+: by) vec = do\n let sx :+: sy = envelopeSize win\n xoff :+: yoff = envelopeMin win\n if sizeLen sz \/= G.length vec\n then throwBindingException (InvalidRasterSize sz)\n else liftIO $\n St.unsafeWith vec $ \\ptr ->\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand band')\n (fromEnumC GF_Write)\n (fromIntegral xoff)\n (fromIntegral yoff)\n (fromIntegral sx)\n (fromIntegral sy)\n (castPtr ptr)\n (fromIntegral bx)\n (fromIntegral by)\n (fromEnumC (hsDataType (Proxy :: Proxy a')))\n 0\n 0\n\nunsafeBandDataset :: Band s a t -> Dataset s a t\nunsafeBandDataset band = Dataset (Nothing, dsH) where\n dsH = {#call pure unsafe GDALGetBandDataset as ^#} (unBand band)\n\nbandGeotransform :: MonadIO m => Band s a t -> m (Maybe Geotransform)\nbandGeotransform = datasetGeotransform . unsafeBandDataset\n\nbandProjection :: (MonadThrow m, MonadIO m) => Band s a t -> m (Maybe SpatialReference)\nbandProjection = datasetProjection . unsafeBandDataset\n\n\nbandSinkGeo\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (Envelope Double, Size, U.Vector (Value a)) (GDAL s) ()\nbandSinkGeo band = do\n mGt <- bandGeotransform band\n case mGt >>= geoEnvelopeTransformer of\n Just trans -> CL.map (\\(e,s,v) -> (trans e,s,v)) =$= bandSink band\n Nothing -> lift (throwBindingException CannotInvertGeotransform)\n\nnoDataOrFail :: GDALType a => Band s a t -> GDAL s a\nnoDataOrFail = fmap (fromMaybe err) . bandNodataValue\n where\n err = error (\"GDAL.readMasked: band has GMF_NODATA flag but did \" ++\n \"not return a nodata value\")\n\nbandMask :: Band s a t -> GDAL s (Band s Word8 t)\nbandMask =\n liftIO . fmap (\\p -> Band (p,GByte)) . {#call GetMaskBand as ^#}\n . unBand\n\ndata MaskType\n = MaskNoData\n | MaskAllValid\n |\u00a0MaskPerBand\n |\u00a0MaskPerDataset\n\nbandMaskType :: Band s a t -> GDAL s MaskType\nbandMaskType band = do\n flags <- liftIO ({#call unsafe GetMaskFlags as ^#} (unBand band))\n let testFlag f = (fromEnumC f .&. flags) \/= 0\n return $ case () of\n () | testFlag GMF_NODATA -> MaskNoData\n () | testFlag GMF_ALL_VALID -> MaskAllValid\n () | testFlag GMF_PER_DATASET -> MaskPerDataset\n _ -> MaskPerBand\n\nmaskFlagsForType :: MaskType -> CInt\nmaskFlagsForType MaskNoData = fromEnumC GMF_NODATA\nmaskFlagsForType MaskAllValid = fromEnumC GMF_ALL_VALID\nmaskFlagsForType MaskPerBand = 0\nmaskFlagsForType MaskPerDataset = fromEnumC GMF_PER_DATASET\n\n{#enum define MaskFlag { GMF_ALL_VALID as GMF_ALL_VALID\n , GMF_PER_DATASET as GMF_PER_DATASET\n , GMF_ALPHA as GMF_ALPHA\n , GMF_NODATA as GMF_NODATA\n } deriving (Eq,Bounded,Show) #}\n\ncopyBand\n :: Band s a t -> RWBand s a -> OptionList\n -> Maybe ProgressFun -> GDAL s ()\ncopyBand src dst opts progress =\n liftIO $\n withProgressFun \"copyBand\" progress $ \\pFunc ->\n withOptionList opts $ \\o ->\n checkCPLError \"copyBand\" $\n {#call RasterBandCopyWholeRaster as ^#}\n (unBand src) (unBand dst) o pFunc nullPtr\n\nfillBand :: GDALType a => Value a -> RWBand s a -> GDAL s ()\nfillBand val b =\n runConduit (allBlocks b =$= CL.map (\\i -> (i,v)) =$= blockSink b)\n where v = G.replicate (bandBlockLen b) val\n\n\nfoldl'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s a t -> GDAL s b\nfoldl' f = ifoldl' (\\z _ v -> f z v)\n{-# INLINE foldl' #-}\n\nifoldl'\n :: forall s t a b. GDALType a\n => (b -> Pair Int -> Value a -> b) -> b -> Band s a t -> GDAL s b\nifoldl' f z band =\n runConduit (unsafeBlockSource band =$= CL.fold folder z)\n where\n !(mx :+: my) = liftA2 mod (bandSize band) (bandBlockSize band)\n !(nx :+: ny) = bandBlockCount band\n !(sx :+: sy) = bandBlockSize band\n folder !acc !(!(iB :+: jB), !vec) = go 0 0 acc\n where\n go !i !j !acc'\n | i < stopx = go (i+1) j\n (f acc' ix (vec `G.unsafeIndex` (j*sx+i)))\n | j+1 < stopy = go 0 (j+1) acc'\n | otherwise = acc'\n where ix = iB*sx+i :+: jB*sy+j\n !stopx\n | mx \/= 0 && iB==nx-1 = mx\n | otherwise = sx\n !stopy\n | my \/= 0 && jB==ny-1 = my\n | otherwise = sy\n{-# INLINEABLE ifoldl' #-}\n\nfoldlWindow'\n :: forall s t a b. GDALType a\n => (b -> Value a -> b) -> b -> Band s a t -> Envelope Int -> GDAL s b\nfoldlWindow' f b = ifoldlWindow' (\\z _ v -> f z v) b\n{-# INLINE foldlWindow' #-}\n\nifoldlWindow'\n :: forall s t a b. GDALType a\n => (b -> Pair Int -> Value a -> b)\n -> b -> Band s a t -> Envelope Int -> GDAL s b\nifoldlWindow' f z band (Envelope (x0 :+: y0) (x1 :+: y1)) = runConduit $\n allBlocks band =$= CL.filter inRange\n =$= decorate (unsafeBlockConduit band)\n =$= CL.fold folder z\n where\n inRange bIx = bx0 < x1 && x0 < bx1 && by0 < y1 && y0 < by1\n where\n !b0@(bx0 :+: by0) = bIx * bSize\n !(bx1 :+: by1) = b0 + bSize\n !(mx :+: my) = liftA2 mod (bandSize band) (bandBlockSize band)\n !(nx :+: ny) = bandBlockCount band\n !bSize@(sx :+: sy) = bandBlockSize band\n folder !acc !(!(iB :+: jB), !vec) = go 0 0 acc\n where\n go !i !j !acc'\n | i < stopx = go (i+1) j acc''\n | j+1 < stopy = go 0 (j+1) acc'\n | otherwise = acc'\n where\n !ix@(ixx :+: ixy) = iB*sx+i :+: jB*sy+j\n acc''\n | x0 <= ixx && ixx < x1 && y0 <= ixy && ixy < y1\n = f acc' ix (vec `G.unsafeIndex` (j*sx+i))\n | otherwise = acc'\n !stopx\n | mx \/= 0 && iB==nx-1 = mx\n | otherwise = sx\n !stopy\n | my \/= 0 && jB==ny-1 = my\n | otherwise = sy\n{-# INLINEABLE ifoldlWindow' #-}\n\nunsafeBlockSource\n :: GDALType a\n => Band s a t -> Source (GDAL s) (BlockIx, U.Vector (Value a))\nunsafeBlockSource band = allBlocks band =$= decorate (unsafeBlockConduit band)\n\nblockSource\n :: GDALType a\n => Band s a t -> Source (GDAL s) (BlockIx, U.Vector (Value a))\nblockSource band = allBlocks band =$= decorate (blockConduit band)\n\nwriteBandBlock\n :: forall s a. GDALType a\n => RWBand s a -> BlockIx -> U.Vector (Value a) -> GDAL s ()\nwriteBandBlock band blockIx uvec =\n runConduit (yield (blockIx, uvec) =$= blockSink band)\n\nfmapBand\n :: forall s a b t. (GDALType a, GDALType b)\n => (Value a -> Value b)\n -> Band s a t\n -> RWBand s b \n -> GDAL s ()\nfmapBand f src dst\n | bandSize src \/= bandSize dst\n = throwBindingException (InvalidRasterSize (bandSize src))\n | bandBlockSize src \/= bandBlockSize dst\n = throwBindingException notImplementedErr\n | otherwise = runConduit\n (unsafeBlockSource src =$= CL.map (second (U.map f)) =$= blockSink dst)\n where\n notImplementedErr = NotImplemented\n \"fmapBand: Not implemented for bands of different block size\"\n\nfoldBands\n :: forall s a b t. (GDALType a, GDALType b)\n => (Value b -> Value a -> Value b)\n -> RWBand s b\n -> [Band s a t]\n -> GDAL s ()\nfoldBands fun zb bs =\n runConduit (unsafeBlockSource zb =$= awaitForever foldThem =$= blockSink zb)\n where\n foldThem (bix, acc) = do\n r <- fmap (L.foldl' (G.zipWith fun) acc)\n (lift (mapM (flip readBandBlock bix) bs))\n yield (bix, r)\n\n\n\nblockSink\n :: forall s a. GDALType a\n => RWBand s a\n -> Sink (BlockIx, U.Vector (Value a)) (GDAL s) ()\nblockSink band = do\n writeBlock <-\n if dtBand==dtBuf\n then return writeNative\n else do tempBuf <- liftIO (mallocForeignPtrBytes (len*szBand))\n return (writeTranslated tempBuf)\n lift (bandMaskType band) >>= \\case\n MaskNoData -> lift (noDataOrFail band) >>= sinkNodata writeBlock\n MaskAllValid -> sinkAllValid writeBlock\n _ -> lift (bandMask band) >>= sinkMask writeBlock\n\n where\n len = bandBlockLen band\n dtBand = bandDataType (band)\n szBand = sizeOfDataType dtBand\n dtBuf = hsDataType (Proxy :: Proxy a)\n szBuf = sizeOfDataType dtBuf\n\n sinkNodata writeBlock nd = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n St.unsafeWith (toGVecWithNodata nd vec) (writeBlock ix)\n\n\n sinkAllValid writeBlock = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n case toGVec vec of\n Just buf -> St.unsafeWith buf (writeBlock ix)\n Nothing -> throwBindingException BandDoesNotAllowNoData\n\n sinkMask writeBlock bMask = awaitForever $ \\(ix, vec) -> liftIO $ do\n checkLen vec\n let (mask, vec') = toGVecWithMask vec\n off = bi * bs\n win = liftA2 min bs (rs - off)\n bi = fmap fromIntegral ix\n bs = fmap fromIntegral (bandBlockSize band)\n rs = fmap fromIntegral (bandSize band)\n St.unsafeWith vec' (writeBlock ix)\n St.unsafeWith mask $ \\pBuf ->\n checkCPLError \"WriteBlock\" $\n {#call RasterIO as ^#}\n (unBand bMask)\n (fromEnumC GF_Write)\n (pFst off)\n (pSnd off)\n (pFst win)\n (pSnd win)\n (castPtr pBuf)\n (pFst win)\n (pSnd win)\n (fromEnumC GByte)\n 0\n (pFst bs * fromIntegral (sizeOfDataType GByte))\n\n checkLen v\n | len \/= G.length v\n = throwBindingException (InvalidBlockSize (G.length v))\n | otherwise = return ()\n\n writeTranslated temp blockIx pBuf =\n withForeignPtr temp $ \\pTemp -> do\n {#call unsafe CopyWords as ^#}\n (castPtr pTemp)\n (fromEnumC dtBand)\n (fromIntegral szBand)\n (castPtr pBuf)\n (fromEnumC dtBuf)\n (fromIntegral szBuf)\n (fromIntegral len)\n writeNative blockIx pTemp\n\n writeNative blockIx pBuf =\n checkCPLError \"WriteBlock\" $\n {#call GDALWriteBlock as ^#}\n (unBand band)\n (pFst bi)\n (pSnd bi)\n (castPtr pBuf)\n where bi = fmap fromIntegral blockIx\n\n\nreadBandBlock\n :: forall s t a. GDALType a\n => Band s a t -> BlockIx -> GDAL s (U.Vector (Value a))\nreadBandBlock band blockIx = fmap fromJust $ runConduit $\n yield blockIx =$= unsafeBlockConduit band =$= CL.head\n\n\nallBlocks :: Monad m => Band s a t -> Producer m BlockIx\nallBlocks band = CL.sourceList [x :+: y | y <- [0..ny-1], x <- [0..nx-1]]\n where\n !(nx :+: ny) = bandBlockCount band\n\nblockConduit\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (U.Vector (Value a))\nblockConduit band =\n unsafeBlockConduitM band =$= CL.mapM (liftIO . U.freeze)\n\nunsafeBlockConduit\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (U.Vector (Value a))\nunsafeBlockConduit band =\n unsafeBlockConduitM band =$= CL.mapM (liftIO . U.unsafeFreeze)\n\n\nunsafeBlockConduitM\n :: forall s a t. GDALType a\n => Band s a t\n -> Conduit BlockIx (GDAL s) (UM.IOVector (Value a))\nunsafeBlockConduitM band = do\n buf <- liftIO (M.new len)\n maskType <- lift $ bandMaskType band\n case maskType of\n MaskNoData -> do\n noData <- lift $ noDataOrFail band\n blockReader (mkValueUMVector noData buf) buf (const (return ()))\n MaskAllValid ->\n blockReader (mkAllValidValueUMVector buf) buf (const (return ()))\n _ -> do\n mBuf <- liftIO $ M.replicate len 0\n mask <- lift $ bandMask band\n blockReader (mkMaskedValueUMVector mBuf buf) buf (readMask mask mBuf)\n where\n isNative = dtBand == dtBuf\n len = bandBlockLen band\n dtBand = bandDataType band\n dtBuf = hsDataType (Proxy :: Proxy a)\n\n blockReader vec buf extra\n | isNative = awaitForever $ \\ix -> do\n liftIO (Stm.unsafeWith buf (loadBlock ix))\n extra ix\n yield vec\n | otherwise = do\n temp <- liftIO $ mallocForeignPtrBytes (len*szBand)\n awaitForever $ \\ix -> do\n liftIO $ withForeignPtr temp $ \\pTemp -> do\n loadBlock ix pTemp\n Stm.unsafeWith buf (translateBlock pTemp)\n extra ix\n yield vec\n\n loadBlock ix pBuf = \n checkCPLError \"ReadBlock\" $\n {#call ReadBlock as ^#}\n (unBand band)\n (fromIntegral (pFst ix))\n (fromIntegral (pSnd ix))\n (castPtr pBuf)\n\n translateBlock pTemp pBuf = \n {#call unsafe CopyWords as ^#}\n (castPtr pTemp)\n (fromEnumC dtBand)\n (fromIntegral szBand)\n (castPtr pBuf)\n (fromEnumC dtBuf)\n (fromIntegral szBuf)\n (fromIntegral len)\n szBand = sizeOfDataType dtBand\n szBuf = sizeOfDataType dtBuf\n\n readMask mask vMask ix =\n liftIO $\n Stm.unsafeWith vMask $ \\pMask ->\n checkCPLError \"RasterIO\" $\n {#call RasterIO as ^#}\n (unBand mask)\n (fromEnumC GF_Read)\n (pFst off)\n (pSnd off)\n (pFst win)\n (pSnd win)\n (castPtr pMask)\n (pFst win)\n (pSnd win)\n (fromEnumC GByte)\n 0\n (pFst bs)\n where\n bi = fmap fromIntegral ix\n off = bi * bs\n win = liftA2 min bs (rs - off)\n bs = fmap fromIntegral (bandBlockSize band)\n rs = fmap fromIntegral (bandSize band)\n\nopenDatasetCount :: IO Int\nopenDatasetCount =\n alloca $ \\ppDs ->\n alloca $ \\pCount -> do\n {#call unsafe GetOpenDatasets as ^#} ppDs pCount\n fmap fromIntegral (peek pCount)\n\n-----------------------------------------------------------------------------\n-- Metadata\n-----------------------------------------------------------------------------\n\nmetadataDomains\n :: (MonadIO m, MajorObject o t)\n => o t -> m [Text]\n#if SUPPORTS_METADATA_DOMAINS\nmetadataDomains o =\n liftIO $\n fromCPLStringList $\n {#call unsafe GetMetadataDomainList as ^#} (majorObject o)\n#else\nmetadataDomains = const (return [])\n#endif\n\nmetadata\n :: (MonadIO m, MajorObject o t)\n => Maybe ByteString -> o t -> m [(Text,Text)]\nmetadata domain o =\n liftIO $\n withMaybeByteString domain\n ({#call unsafe GetMetadata as ^#} (majorObject o)\n >=> fmap (map breakIt) . fromBorrowedCPLStringList)\n where\n breakIt s =\n case T.break (=='=') s of\n (k,\"\") -> (k,\"\")\n (k, v) -> (k, T.tail v)\n\nmetadataItem\n :: (MonadIO m, MajorObject o t)\n => Maybe ByteString -> ByteString -> o t -> m (Maybe ByteString)\nmetadataItem domain key o =\n liftIO $\n useAsCString key $ \\pKey ->\n withMaybeByteString domain $\n {#call unsafe GetMetadataItem as ^#} (majorObject o) pKey >=>\n maybePackCString\n\nsetMetadataItem\n :: (MonadIO m, MajorObject o t, t ~ ReadWrite)\n => Maybe ByteString -> ByteString -> ByteString -> o t -> m ()\nsetMetadataItem domain key val o =\n liftIO $\n checkCPLError \"setMetadataItem\" $\n useAsCString key $ \\pKey ->\n useAsCString val $ \\pVal ->\n withMaybeByteString domain $\n {#call unsafe GDALSetMetadataItem as ^#} (majorObject o) pKey pVal\n\ndescription :: (MonadIO m, MajorObject o t) => o t -> m ByteString\ndescription =\n liftIO . ({#call unsafe GetDescription as ^#} . majorObject >=> packCString)\n\nsetDescription\n :: (MonadIO m, MajorObject o t, t ~ ReadWrite)\n => ByteString -> o t -> m ()\nsetDescription val =\n liftIO . checkGDALCall_ const .\n useAsCString val . {#call unsafe GDALSetDescription as ^#} . majorObject\n\n-----------------------------------------------------------------------------\n-- GDAL2 OGR-GDAL consolidated API (WIP)\n-----------------------------------------------------------------------------\n\n\nlayerCount :: Dataset s a t -> GDAL s Int\n\ngetLayer :: Int -> Dataset s a t -> GDAL s (Layer s l t a)\n\ngetLayerByName :: Text -> Dataset s a t -> GDAL s (Layer s l t a)\n\nexecuteSQL\n :: OGRFeature a\n => SQLDialect -> Text -> Maybe Geometry -> RODataset s any\n -> GDAL s (ROLayer s l a)\n\ncreateLayer\n :: forall s l a any. OGRFeatureDef a\n => RWDataset s any -> ApproxOK -> OptionList -> GDAL s (RWLayer s l a)\n\ncreateLayerWithDef\n :: forall s l a any\n . RWDataset s any -> FeatureDef -> ApproxOK -> OptionList\n -> GDAL s (RWLayer s l a)\n\n#if GDAL_VERSION_MAJOR >= 2\nlayerCount = fmap fromIntegral\n . liftIO . {#call GDALDatasetGetLayerCount as ^#} . unDataset\n\ngetLayer ix ds =\n fmap Layer $\n flip allocate (const (return ())) $\n checkGDALCall checkIt $\n {#call GDALDatasetGetLayer as ^#} (unDataset ds) (fromIntegral ix)\n where\n checkIt e p' |\u00a0p'==nullLayerH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALBindingException (InvalidLayerIndex ix)\n\ngetLayerByName name ds =\n fmap Layer $\n flip allocate (const (return ())) $\n checkGDALCall checkIt $\n useAsEncodedCString name $\n {#call GDALDatasetGetLayerByName as ^#} (unDataset ds)\n where\n checkIt e p' |\u00a0p'==nullLayerH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALBindingException (InvalidLayerName name)\n\nexecuteSQL dialect query mSpatialFilter ds =\n fmap Layer $ allocate execute freeIfNotNull\n where\n execute =\n checkGDALCall checkit $\n withMaybeGeometry mSpatialFilter $ \\pF ->\n useAsEncodedCString query $ \\pQ ->\n withSQLDialect dialect $ {#call GDALDatasetExecuteSQL as ^#} pDs pQ pF\n\n freeIfNotNull pL\n | pL \/= nullLayerH = {#call unsafe GDALDatasetReleaseResultSet as ^#} pDs pL\n | otherwise = return ()\n\n pDs = unDataset ds\n checkit (Just (GDALException{gdalErrNum=AppDefined, gdalErrMsg=msg})) _ =\n Just (GDALBindingException (SQLQueryError msg))\n checkit Nothing p | p==nullLayerH =\n Just (GDALBindingException NullLayer)\n checkit e p | p==nullLayerH = e\n checkit _ _ = Nothing\n\ncreateLayer ds = createLayerWithDef ds (featureDef (Proxy :: Proxy a))\n\ncreateLayerWithDef ds FeatureDef{..} approxOk opts =\n fmap Layer $\n flip allocate (const (return ())) $\n useAsEncodedCString fdName $ \\pName ->\n withMaybeSpatialReference (gfdSrs fdGeom) $ \\pSrs ->\n withOptionList opts $ \\pOpts -> do\n pL <- checkGDALCall checkIt $\n {#call GDALDatasetCreateLayer as ^#} pDs pName pSrs gType pOpts\n G.forM_ fdFields $ \\(n,f) -> withFieldDefnH n f $ \\pFld ->\n checkOGRError \"CreateField\" $\n {#call unsafe OGR_L_CreateField as ^#} pL pFld iApproxOk\n when (not (G.null fdGeoms)) $\n if supportsMultiGeomFields pL\n then\n#if SUPPORTS_MULTI_GEOM_FIELDS\n G.forM_ fdGeoms $ \\(n,f) -> withGeomFieldDefnH n f $ \\pGFld ->\n {#call unsafe OGR_L_CreateGeomField as ^#} pL pGFld iApproxOk\n#else\n error \"should never reach here\"\n#endif\n else throwBindingException MultipleGeomFieldsNotSupported\n return pL\n where\n supportsMultiGeomFields pL =\n layerHasCapability pL CreateGeomField &&\n dataSourceHasCapability pDs CreateGeomFieldAfterCreateLayer\n iApproxOk = fromEnumC approxOk\n pDs = unDataset ds\n gType = fromEnumC (gfdType fdGeom)\n checkIt e p' |\u00a0p'==nullLayerH = Just (fromMaybe dflt e)\n checkIt e _ = e\n dflt = GDALBindingException NullLayer\n\n dataSourceHasCapability :: DatasetH -> DataSourceCapability -> Bool\n dataSourceHasCapability d c = unsafePerformIO $ do\n withCString (\"ODsC\" ++ show c)\n (fmap toBool . {#call unsafe GDALDatasetTestCapability as ^#} d)\n\n\n#else\nrequiresGDAL2 :: String -> a\nrequiresGDAL2 funName = error $\n show funName \n ++ \" on a Dataset requires GDAL version >= 2. Use the API from OGR instead\"\nlayerCount = requiresGDAL2 \"layerCount\"\ngetLayer = requiresGDAL2 \"getLayer\"\ngetLayerByName = requiresGDAL2 \"getLayerByName\"\nexecuteSQL = requiresGDAL2 \"executeSQL\"\ncreateLayer = requiresGDAL2 \"createLayer\"\ncreateLayerWithDef = requiresGDAL2 \"createLayerWithDef\"\n#endif\n\n-----------------------------------------------------------------------------\n-- Conduit utils\n-----------------------------------------------------------------------------\n\n-- | Parallel zip of two conduits\npZipConduitApp\n :: Monad m\n => Conduit a m (b -> c)\n -> Conduit a m b\n -> Conduit a m c\npZipConduitApp (ConduitM l0) (ConduitM r0) = ConduitM $ \\rest -> let\n go (HaveOutput p c o) (HaveOutput p' c' o') =\n HaveOutput (go p p') (c>>c') (o o')\n go (NeedInput p c) (NeedInput p' c') =\n NeedInput (\\i -> go (p i) (p' i)) (\\u -> go (c u) (c' u))\n go (Done ()) (Done ()) = rest ()\n go (PipeM m) (PipeM m') = PipeM (liftM2 go m m')\n go (Leftover p i) (Leftover p' _) = Leftover (go p p') i\n go _ _ = error \"pZipConduitApp: not parallel\"\n in go (injectLeftovers $ l0 Done) (injectLeftovers $ r0 Done)\n\nnewtype PZipConduit i m o =\n PZipConduit { getPZipConduit :: Conduit i m o}\n\ninstance Monad m => Functor (PZipConduit i m) where\n fmap f = PZipConduit . mapOutput f . getPZipConduit\n\ninstance Monad m => Applicative (PZipConduit i m) where\n pure = PZipConduit . forever . yield\n PZipConduit l <*> PZipConduit r = PZipConduit (pZipConduitApp l r)\n\nzipBlocks\n :: GDALType a\n => Band s a t -> PZipConduit BlockIx (GDAL s) (U.Vector (Value a))\nzipBlocks = PZipConduit . unsafeBlockConduit\n\ngetZipBlocks\n :: PZipConduit BlockIx (GDAL s) a\n -> Conduit BlockIx (GDAL s) (BlockIx, a)\ngetZipBlocks = decorate . getPZipConduit\n\ndecorate :: Monad m => Conduit a m b -> Conduit a m (a, b)\ndecorate (ConduitM c0) = ConduitM $ \\rest -> let\n go1 HaveOutput{} = error \"unexpected NeedOutput\"\n go1 (NeedInput p c) = NeedInput (\\i -> go2 i (p i)) (go1 . c)\n go1 (Done r) = rest r\n go1 (PipeM mp) = PipeM (fmap (go1) mp)\n go1 (Leftover p i) = Leftover (go1 p) i\n\n go2 i (HaveOutput p c o) = HaveOutput (go2 i p) c (i, o)\n go2 _ (NeedInput p c) = NeedInput (\\i -> go2 i (p i)) (go1 . c)\n go2 _ (Done r) = rest r\n go2 i (PipeM mp) = PipeM (fmap (go2 i) mp)\n go2 i (Leftover p i') = Leftover (go2 i p) i'\n in go1 (c0 Done)\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"f5b1c8aa1e3c39f6ff0fbe614e383ec43961cccc","subject":"Get rid of some type defaulting warnings","message":"Get rid of some type defaulting warnings\n","repos":"HIPERFIT\/hopencl,HIPERFIT\/hopencl","old_file":"Foreign\/OpenCL\/Bindings\/Kernel.chs","new_file":"Foreign\/OpenCL\/Bindings\/Kernel.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface, GADTs #-}\n-- |\n-- Module : Foreign.OpenCL.Bindings.Kernel\n-- Copyright : (c) 2011, Martin Dybdal\n-- License : BSD3\n-- \n-- Maintainer : Martin Dybdal \n-- Stability : experimental\n-- Portability : non-portable (GHC extensions)\n--\n-- \n-- OpenCL kernel creation, invocation and scheduling.\n\nmodule Foreign.OpenCL.Bindings.Kernel (\n createKernel,\n\n kernelContext, kernelFunctionName, kernelNumArgs,\n kernelWorkGroupSize, kernelCompileWorkGroupSize, kernelLocalMemSize,\n kernelPreferredWorkGroupSizeMultiple, kernelPrivateMemSize,\n\n enqueueNDRangeKernel, enqueueTask,\n\n KernelArg(..), setKernelArg, setKernelArgs\n ) where\n\n#include \n\nimport Control.Monad\n\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\n{# import Foreign.OpenCL.Bindings.Internal.Types #}\nimport Foreign.OpenCL.Bindings.Internal.Finalizers\nimport Foreign.OpenCL.Bindings.Internal.Error\nimport Foreign.OpenCL.Bindings.Internal.Util\n\n-- | Create a program from a string containing the source code\n--\ncreateKernel :: Program -- ^The program that contains the kernel code\n -> String -- ^The name of the kernel (as written in the program source)\n -> IO Kernel -- ^The newly created kernel\ncreateKernel prog name =\n withForeignPtr prog $ \\prog_ptr ->\n withCString name $ \\cstr ->\n alloca $ \\ep -> do\n kernel <- {# call unsafe clCreateKernel #} prog_ptr cstr ep\n checkClError_ \"clCreateKernel\" =<< peek ep\n attachFinalizer kernel\n\n-- | Enqueues a command to execute a given kernel on a device. See section 5.8 in the OpenCL 1.1 specification\nenqueueNDRangeKernel :: CommandQueue \n -> Kernel\n -> [ClSize] -- ^ Global work offsets\n -> [ClSize] -- ^ Global work sizes\n -> [ClSize] -- ^ Local work sizes\n -> [Event] \n -> IO Event\nenqueueNDRangeKernel cq k globalWorkOffsets globalWorkSizes localWorkSizes waitEvs =\n withForeignPtr cq $ \\queue ->\n withForeignPtr k $ \\kernel ->\n withArrayNull globalWorkOffsets $ \\globalWorkOffsetPtr ->\n withArrayNull globalWorkSizes $ \\globalWorkSizePtr ->\n withArrayNull localWorkSizes $ \\localWorkSizePtr ->\n withForeignPtrs waitEvs $ \\event_ptrs ->\n withArrayNullLen event_ptrs $ \\n event_array ->\n alloca $ \\eventPtr ->\n do checkClError_ \"clEnqueueNDRangeKernel\" =<< \n {# call unsafe clEnqueueNDRangeKernel #} \n queue kernel workDim\n globalWorkOffsetPtr\n globalWorkSizePtr\n localWorkSizePtr\n (fromIntegral n)\n event_array\n eventPtr\n attachFinalizer =<< peek eventPtr\n where workDim = fromIntegral . maximum $ map length [globalWorkOffsets, globalWorkSizes, localWorkSizes]\n\ndata KernelArg where\n MObjArg :: MemObject a -> KernelArg\n LocalArrayArg :: Storable a => a -> Int -> KernelArg\n VArg :: Storable a => a -> KernelArg\n StructArg :: Storable a => [a] -> KernelArg\n\n-- | Invoking @setKernelArg krn n arg@ sets argument @n@ of the kernel @krn@\nsetKernelArg :: Kernel -> Int -> KernelArg -> IO ()\nsetKernelArg kernel n param =\n withForeignPtr kernel $ \\k ->\n withPtr param $ \\param_ptr -> do\n err <- {# call unsafe clSetKernelArg #} k (fromIntegral n) (size param) param_ptr\n case toEnum $ fromIntegral err of\n InvalidArgSize -> error $ \"ClInvalidArgSize occurred in call to: clSetKernelArg. Argument #\"\n ++ show n ++ \" was set to size \" ++ show (size param)\n InvalidArgIndex -> error $ \"ClInvalidArgIndex occurred in call to: clSetKernelArg, when setting argument #\"\n ++ show n\n _ -> checkClError_ \"clSetKernelArg\" err\n where size :: KernelArg -> CULong\n size (MObjArg mobj) = fromIntegral $ sizeOf (memobjPtr mobj)\n size (VArg v) = fromIntegral $ sizeOf v\n size (StructArg xs) = fromIntegral . sum $ map sizeOf xs\n size (LocalArrayArg x m) = fromIntegral $ m * sizeOf x \n\n withPtr :: KernelArg -> (Ptr () -> IO c) -> IO c\n withPtr (MObjArg mobj) f = with (memobjPtr mobj) $ f . castPtr\n withPtr (VArg v) f = with v $ f . castPtr\n withPtr (LocalArrayArg _ _) f = f nullPtr\n withPtr a@(StructArg xs) f = do\n allocaBytes (fromIntegral $ size a) $ \\ptr -> do\n pokeElems ptr xs\n f (castPtr ptr)\n\n pokeElems :: Storable a => Ptr a -> [a] -> IO ()\n pokeElems ptr (x:xs) = poke ptr x >> pokeElems (plusPtr ptr (sizeOf x)) xs\n pokeElems _ [] = return ()\n\n-- | Sets all arguments of a kernel to the parameters in the list\nsetKernelArgs :: Kernel -> [KernelArg] -> IO ()\nsetKernelArgs kernel args = zipWithM_ (setKernelArg kernel) [0..] args\n\n-- | Enqueue a command to execute a kernel using a single work-item.\nenqueueTask :: CommandQueue -> Kernel -> [Event] -> IO Event\nenqueueTask cq k waitEvs =\n withForeignPtr cq $ \\queue ->\n withForeignPtr k $ \\kernel ->\n withForeignPtrs waitEvs $ \\event_ptrs ->\n withArrayNullLen event_ptrs $ \\n event_array ->\n alloca $ \\eventPtr ->\n do checkClError_ \"clEnqueueTask\" =<<\n {# call unsafe clEnqueueTask #}\n queue kernel\n (fromIntegral n)\n event_array\n eventPtr\n attachFinalizer =<< peek eventPtr\n\n-- | The 'Context' associated with a 'Kernel'\nkernelContext :: Kernel -> IO Context\nkernelContext kernel = \n getKernelInfo kernel KernelContext >>= attachRetainFinalizer\n\n-- | The function name (in the OpenCL C source code) of a 'Kernel'\nkernelFunctionName :: Kernel -> IO String\nkernelFunctionName kernel = getKernelInfo kernel KernelFunctionName\n\n-- | The number of arguments that needs to be set before invoking a 'Kernel'\nkernelNumArgs :: Kernel -> IO Int\nkernelNumArgs kernel = fromIntegral `fmap` (getKernelInfo kernel KernelNumArgs :: IO ClUInt)\n\n-- | The maximum work-group size that can be used to execute a kernel\n-- on a specific device given by device. The OpenCL implementation\n-- uses the resource requirements of the kernel (register usage etc.)\n-- to determine what this work group size should be.\nkernelWorkGroupSize :: Kernel -> DeviceID -> IO CSize\nkernelWorkGroupSize kernel device =\n getKernelWorkGroupInfo kernel device KernelWorkGroupSize\n\n-- | Returns the work-group size specified by the\n-- @__attribute__((reqd_work_group_size(X, Y, Z)))@ qualifier.\n-- Refer to section 6.8.2 of the OpenCL 1.1 specification\n-- If undefined, this function returns (0,0,0)\nkernelCompileWorkGroupSize :: Kernel -> DeviceID -> IO CSize\nkernelCompileWorkGroupSize kernel device =\n getKernelWorkGroupInfo kernel device KernelCompileWorkGroupSize\n\n-- | Returns the amount of local memory in bytes being used by a\n-- kernel. This includes local memory that may be needed by an\n-- implementation to execute the kernel, variables declared inside the\n-- kernel with the __local address qualifier and local memory to be\n-- allocated for arguments to the kernel declared as pointers with the\n-- __local address qualifier and whose size is specified with\n-- 'setKernelArg'.\n--\n-- If the local memory size, for any pointer argument to the kernel\n-- declared with the __local address qualifier, is not specified, its\n-- size is assumed to be 0.\nkernelLocalMemSize :: Kernel -> DeviceID -> IO Word64\nkernelLocalMemSize kernel device =\n getKernelWorkGroupInfo kernel device KernelLocalMemSize\n\n-- | Returns the preferred multiple of work-group size for\n-- launch. This is a performance hint. Specifying a work-group size\n-- that is not a multiple of the value returned by this query as the\n-- value of the local work size argument to 'enqueueNDRangeKernel'\n-- will not fail to enqueue the kernel for execution unless the\n-- work-group size specified is larger than the device maximum.\nkernelPreferredWorkGroupSizeMultiple :: Kernel -> DeviceID -> IO CSize\nkernelPreferredWorkGroupSizeMultiple kernel device =\n getKernelWorkGroupInfo kernel device KernelPreferredWorkGroupSizeMultiple\n\n-- | Returns the minimum amount of private memory, in bytes, used by\n-- each work-item in the kernel. This value may include any private\n-- memory needed by an implementation to execute the kernel, including\n-- that used by the language built-ins and variable declared inside\n-- the kernel with the __private qualifier.\nkernelPrivateMemSize :: Kernel -> DeviceID -> IO Word64\nkernelPrivateMemSize kernel device =\n getKernelWorkGroupInfo kernel device KernelPrivateMemSize\n\n-- C interfacing functions\ngetKernelInfo kernel info =\n withForeignPtr kernel $ \\kernel_ptr ->\n getInfo (clGetKernelInfo_ kernel_ptr) info\n where\n clGetKernelInfo_ =\n checkClError5 \"clGetKernelInfo\"\n {#call unsafe clGetKernelInfo #}\n\ngetKernelWorkGroupInfo kernel device info =\n withForeignPtr kernel $ \\kernel_ptr ->\n getInfo (clGetKernelWorkGroupInfo_ kernel_ptr device) info\n where\n clGetKernelWorkGroupInfo_ =\n checkClError6 \"clGetKernelWorkGroupInfo\" \n {#call unsafe clGetKernelWorkGroupInfo #}\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface, GADTs #-}\n-- |\n-- Module : Foreign.OpenCL.Bindings.Kernel\n-- Copyright : (c) 2011, Martin Dybdal\n-- License : BSD3\n-- \n-- Maintainer : Martin Dybdal \n-- Stability : experimental\n-- Portability : non-portable (GHC extensions)\n--\n-- \n-- OpenCL kernel creation, invocation and scheduling.\n\nmodule Foreign.OpenCL.Bindings.Kernel (\n createKernel,\n\n kernelContext, kernelFunctionName, kernelNumArgs,\n kernelWorkGroupSize, kernelCompileWorkGroupSize, kernelLocalMemSize,\n kernelPreferredWorkGroupSizeMultiple, kernelPrivateMemSize,\n\n enqueueNDRangeKernel, enqueueTask,\n\n KernelArg(..), setKernelArg, setKernelArgs\n ) where\n\n#include \n\nimport Control.Monad\n\nimport Foreign\nimport Foreign.C.String\nimport Foreign.C.Types\n\n{# import Foreign.OpenCL.Bindings.Internal.Types #}\nimport Foreign.OpenCL.Bindings.Internal.Finalizers\nimport Foreign.OpenCL.Bindings.Internal.Error\nimport Foreign.OpenCL.Bindings.Internal.Util\n\n-- | Create a program from a string containing the source code\n--\ncreateKernel :: Program -- ^The program that contains the kernel code\n -> String -- ^The name of the kernel (as written in the program source)\n -> IO Kernel -- ^The newly created kernel\ncreateKernel prog name =\n withForeignPtr prog $ \\prog_ptr ->\n withCString name $ \\cstr ->\n alloca $ \\ep -> do\n kernel <- {# call unsafe clCreateKernel #} prog_ptr cstr ep\n checkClError_ \"clCreateKernel\" =<< peek ep\n attachFinalizer kernel\n\n-- | Enqueues a command to execute a given kernel on a device. See section 5.8 in the OpenCL 1.1 specification\nenqueueNDRangeKernel :: CommandQueue \n -> Kernel\n -> [ClSize] -- ^ Global work offsets\n -> [ClSize] -- ^ Global work sizes\n -> [ClSize] -- ^ Local work sizes\n -> [Event] \n -> IO Event\nenqueueNDRangeKernel cq k globalWorkOffsets globalWorkSizes localWorkSizes waitEvs =\n withForeignPtr cq $ \\queue ->\n withForeignPtr k $ \\kernel ->\n withArrayNull globalWorkOffsets $ \\globalWorkOffsetPtr ->\n withArrayNull globalWorkSizes $ \\globalWorkSizePtr ->\n withArrayNull localWorkSizes $ \\localWorkSizePtr ->\n withForeignPtrs waitEvs $ \\event_ptrs ->\n withArrayNullLen event_ptrs $ \\n event_array ->\n alloca $ \\eventPtr ->\n do checkClError_ \"clEnqueueNDRangeKernel\" =<< \n {# call unsafe clEnqueueNDRangeKernel #} \n queue kernel workDim\n globalWorkOffsetPtr\n globalWorkSizePtr\n localWorkSizePtr\n (fromIntegral n)\n event_array\n eventPtr\n attachFinalizer =<< peek eventPtr\n where workDim = fromIntegral . maximum $ map length [globalWorkOffsets, globalWorkSizes, localWorkSizes]\n\ndata KernelArg where\n MObjArg :: MemObject a -> KernelArg\n LocalArrayArg :: Storable a => a -> Int -> KernelArg\n VArg :: Storable a => a -> KernelArg\n StructArg :: Storable a => [a] -> KernelArg\n\n-- | Invoking @setKernelArg krn n arg@ sets argument @n@ of the kernel @krn@\nsetKernelArg :: Kernel -> Int -> KernelArg -> IO ()\nsetKernelArg kernel n param =\n withForeignPtr kernel $ \\k ->\n withPtr param $ \\param_ptr -> do\n err <- {# call unsafe clSetKernelArg #} k (fromIntegral n) (size param) param_ptr\n case toEnum $ fromIntegral err of\n InvalidArgSize -> error $ \"ClInvalidArgSize occurred in call to: clSetKernelArg. Argument #\"\n ++ show n ++ \" was set to size \" ++ show (size param)\n InvalidArgIndex -> error $ \"ClInvalidArgIndex occurred in call to: clSetKernelArg, when setting argument #\"\n ++ show n\n _ -> checkClError_ \"clSetKernelArg\" err\n where size (MObjArg mobj) = fromIntegral $ sizeOf (memobjPtr mobj)\n size (VArg v) = fromIntegral $ sizeOf v\n size (StructArg xs) = fromIntegral . sum $ map sizeOf xs\n size (LocalArrayArg x m) = fromIntegral $ m * sizeOf x \n\n withPtr :: KernelArg -> (Ptr () -> IO c) -> IO c\n withPtr (MObjArg mobj) f = with (memobjPtr mobj) $ f . castPtr\n withPtr (VArg v) f = with v $ f . castPtr\n withPtr (LocalArrayArg _ _) f = f nullPtr\n withPtr a@(StructArg xs) f = do\n allocaBytes (fromIntegral $ size a) $ \\ptr -> do\n pokeElems ptr xs\n f (castPtr ptr)\n\n pokeElems :: Storable a => Ptr a -> [a] -> IO ()\n pokeElems ptr (x:xs) = poke ptr x >> pokeElems (plusPtr ptr (sizeOf x)) xs\n pokeElems _ [] = return ()\n\n-- | Sets all arguments of a kernel to the parameters in the list\nsetKernelArgs :: Kernel -> [KernelArg] -> IO ()\nsetKernelArgs kernel args = zipWithM_ (setKernelArg kernel) [0..] args\n\n-- | Enqueue a command to execute a kernel using a single work-item.\nenqueueTask :: CommandQueue -> Kernel -> [Event] -> IO Event\nenqueueTask cq k waitEvs =\n withForeignPtr cq $ \\queue ->\n withForeignPtr k $ \\kernel ->\n withForeignPtrs waitEvs $ \\event_ptrs ->\n withArrayNullLen event_ptrs $ \\n event_array ->\n alloca $ \\eventPtr ->\n do checkClError_ \"clEnqueueTask\" =<<\n {# call unsafe clEnqueueTask #}\n queue kernel\n (fromIntegral n)\n event_array\n eventPtr\n attachFinalizer =<< peek eventPtr\n\n-- | The 'Context' associated with a 'Kernel'\nkernelContext :: Kernel -> IO Context\nkernelContext kernel = \n getKernelInfo kernel KernelContext >>= attachRetainFinalizer\n\n-- | The function name (in the OpenCL C source code) of a 'Kernel'\nkernelFunctionName :: Kernel -> IO String\nkernelFunctionName kernel = getKernelInfo kernel KernelFunctionName\n\n-- | The number of arguments that needs to be set before invoking a 'Kernel'\nkernelNumArgs :: Kernel -> IO Int\nkernelNumArgs kernel = fromIntegral `fmap` (getKernelInfo kernel KernelNumArgs :: IO ClUInt)\n\n-- | The maximum work-group size that can be used to execute a kernel\n-- on a specific device given by device. The OpenCL implementation\n-- uses the resource requirements of the kernel (register usage etc.)\n-- to determine what this work group size should be.\nkernelWorkGroupSize :: Kernel -> DeviceID -> IO CSize\nkernelWorkGroupSize kernel device =\n getKernelWorkGroupInfo kernel device KernelWorkGroupSize\n\n-- | Returns the work-group size specified by the\n-- @__attribute__((reqd_work_group_size(X, Y, Z)))@ qualifier.\n-- Refer to section 6.8.2 of the OpenCL 1.1 specification\n-- If undefined, this function returns (0,0,0)\nkernelCompileWorkGroupSize :: Kernel -> DeviceID -> IO CSize\nkernelCompileWorkGroupSize kernel device =\n getKernelWorkGroupInfo kernel device KernelCompileWorkGroupSize\n\n-- | Returns the amount of local memory in bytes being used by a\n-- kernel. This includes local memory that may be needed by an\n-- implementation to execute the kernel, variables declared inside the\n-- kernel with the __local address qualifier and local memory to be\n-- allocated for arguments to the kernel declared as pointers with the\n-- __local address qualifier and whose size is specified with\n-- 'setKernelArg'.\n--\n-- If the local memory size, for any pointer argument to the kernel\n-- declared with the __local address qualifier, is not specified, its\n-- size is assumed to be 0.\nkernelLocalMemSize :: Kernel -> DeviceID -> IO Word64\nkernelLocalMemSize kernel device =\n getKernelWorkGroupInfo kernel device KernelLocalMemSize\n\n-- | Returns the preferred multiple of work-group size for\n-- launch. This is a performance hint. Specifying a work-group size\n-- that is not a multiple of the value returned by this query as the\n-- value of the local work size argument to 'enqueueNDRangeKernel'\n-- will not fail to enqueue the kernel for execution unless the\n-- work-group size specified is larger than the device maximum.\nkernelPreferredWorkGroupSizeMultiple :: Kernel -> DeviceID -> IO CSize\nkernelPreferredWorkGroupSizeMultiple kernel device =\n getKernelWorkGroupInfo kernel device KernelPreferredWorkGroupSizeMultiple\n\n-- | Returns the minimum amount of private memory, in bytes, used by\n-- each work-item in the kernel. This value may include any private\n-- memory needed by an implementation to execute the kernel, including\n-- that used by the language built-ins and variable declared inside\n-- the kernel with the __private qualifier.\nkernelPrivateMemSize :: Kernel -> DeviceID -> IO Word64\nkernelPrivateMemSize kernel device =\n getKernelWorkGroupInfo kernel device KernelPrivateMemSize\n\n-- C interfacing functions\ngetKernelInfo kernel info =\n withForeignPtr kernel $ \\kernel_ptr ->\n getInfo (clGetKernelInfo_ kernel_ptr) info\n where\n clGetKernelInfo_ =\n checkClError5 \"clGetKernelInfo\"\n {#call unsafe clGetKernelInfo #}\n\ngetKernelWorkGroupInfo kernel device info =\n withForeignPtr kernel $ \\kernel_ptr ->\n getInfo (clGetKernelWorkGroupInfo_ kernel_ptr device) info\n where\n clGetKernelWorkGroupInfo_ =\n checkClError6 \"clGetKernelWorkGroupInfo\" \n {#call unsafe clGetKernelWorkGroupInfo #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"a0ceac0c5b6fe33d33dc4eff4c7a72745c3d6f60","subject":"gstreamer: more docs for M.S.G.Core.Bus","message":"gstreamer: more docs for M.S.G.Core.Bus\n","repos":"gtk2hs\/vte,gtk2hs\/vte,gtk2hs\/webkit,gtk2hs\/gstreamer,gtk2hs\/webkit,gtk2hs\/webkit","old_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Bus.chs","new_file":"gstreamer\/Media\/Streaming\/GStreamer\/Core\/Bus.chs","new_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gstreamer -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GStreamer, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GStreamer documentation.\n-- \n-- |\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\n-- \n-- An asynchronous message bus subsystem.\nmodule Media.Streaming.GStreamer.Core.Bus (\n-- * Detail\n -- | The 'Bus' is resposible for delivering 'Message's in a\n -- first-in, first-out order, from the streaming threads to the\n -- application.\n -- \n -- Since the application typically only wants to deal with\n -- delivery of these messages from one thread, the 'Bus' will\n -- marshal the messages between different threads. This is\n -- important since the actual streaming of media is done in\n -- a thread separate from the application.\n --\n -- The 'Bus' provides support for 'System.Glib.MainLoop.Source'\n -- based notifications. This makes it possible to handle the\n -- delivery in the GLib 'System.Glib.MainLoop.Source'.\n --\n -- A message is posted on the bus with the 'busPost' method. With\n -- the 'busPeek' and 'busPop' methods one can look at or retrieve\n -- a previously posted message.\n --\n -- The bus can be polled with the 'busPoll' method. This methods\n -- blocks up to the specified timeout value until one of the\n -- specified messages types is posted on the bus. The application\n -- can then pop the messages from the bus to handle\n -- them. Alternatively the application can register an\n -- asynchronous bus function using 'busAddWatch'. This function\n -- will install a 'System.Glib.MainLoop.Source' in the default\n -- GLib main loop and will deliver messages a short while after\n -- they have been posted. Note that the main loop should be\n -- running for the asynchronous callbacks.\n --\n -- It is also possible to get messages from the bus without any\n -- thread marshalling with the 'busSetSyncHandler' method. This\n -- makes it possible to react to a message in the same thread that\n -- posted the message on the bus. This should only be used if the\n -- application is able to deal with messages from different\n -- threads.\n -- \n -- Every 'Pipeline' has one bus.\n --\n -- Note that a 'Pipeline' will set its bus into flushing state\n -- when changing from 'StateReady' to 'StateNull'.\n\n-- * Types\n Bus,\n BusClass,\n -- | The result of a 'BusSyncHandler'.\n BusSyncReply,\n -- | A handler that will be invoked synchronously when a new message\n -- is injected into the bus. This function is mostly used internally.\n -- Only one sync handler may be attached to a given bus.\n BusSyncHandler,\n castToBus,\n toBus,\n-- * Bus Operations\n busGetFlags,\n busSetFlags,\n busUnsetFlags,\n busNew,\n busPost,\n busHavePending,\n busPeek,\n busPop,\n busTimedPop,\n busSetFlushing,\n busSetSyncHandler,\n busUseSyncSignalHandler,\n busCreateWatch,\n busAddWatch,\n busDisableSyncMessageEmission,\n busEnableSyncMessageEmission,\n busAddSignalWatch,\n busRemoveSignalWatch,\n busPoll,\n \n-- * Bus Signals\n busMessage,\n busSyncMessage,\n \n ) where\n\nimport Control.Monad ( liftM\n , when )\n{#import Media.Streaming.GStreamer.Core.Object#}\n{#import Media.Streaming.GStreamer.Core.Types#}\n{#import Media.Streaming.GStreamer.Core.Signals#}\n{#import System.Glib.MainLoop#}\nimport System.Glib.Flags\nimport System.Glib.FFI\n{#import System.Glib.GObject#}\n{#import System.Glib.MainLoop#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\n-- | Get the flags set on this bus.\nbusGetFlags :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> IO [BusFlags] -- ^ the flags set on @bus@\nbusGetFlags = mkObjectGetFlags\n\n-- | Set flags on this bus.\nbusSetFlags :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> [BusFlags] -- ^ the flags to set on @bus@\n -> IO ()\nbusSetFlags = mkObjectSetFlags\n\n-- | Unset flags on this bus.\nbusUnsetFlags :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> [BusFlags] -- ^ the flags to unset on @bus@\n -> IO ()\nbusUnsetFlags = mkObjectUnsetFlags\n\n-- | Create a new bus.\nbusNew :: IO Bus -- ^ the newly created 'Bus' object\nbusNew =\n {# call bus_new #} >>= takeObject\n\n-- | Post a message to the bus.\nbusPost :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> Message -- ^ @message@ - the message to post\n -> IO Bool -- ^ 'True' if the message was posted, or\n -- 'False' if the bus is flushing\nbusPost bus message =\n do {# call gst_mini_object_ref #} (toMiniObject message)\n liftM toBool $ {# call bus_post #} (toBus bus) message\n\n-- | Check if there are pending messages on the bus.\nbusHavePending :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> IO Bool -- ^ 'True' if there are messages\n -- on the bus to be handled, otherwise 'False'\nbusHavePending bus =\n liftM toBool $ {# call bus_have_pending #} $ toBus bus\n\n-- | Get the message at the front of the queue. Any message returned\n-- will remain on the queue.\nbusPeek :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> IO (Maybe Message) -- ^ the first 'Message' on the bus, or\n -- 'Nothing' if the bus is empty\nbusPeek bus =\n {# call bus_peek #} (toBus bus) >>= maybePeek takeMiniObject\n\n-- | Get the message at the front of the queue. It will be removed\n-- from the queue.\nbusPop :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> IO (Maybe Message) -- ^ the first 'Message' on the bus, or\n -- 'Nothing' if the bus is empty\nbusPop bus =\n {# call bus_pop #} (toBus bus) >>= maybePeek takeMiniObject\n\n-- | Get a message from the bus, waiting up to the specified timeout.\n-- If the time given is 'Nothing', the function will wait forever.\n-- If the time given is @0@, the function will behave like 'busPop'.\nbusTimedPop :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> Maybe ClockTime -- ^ @timeoutM@ - the time to wait for,\n -- or 'Nothing' to wait forever\n -> IO (Maybe Message) -- ^ the first message recieved, or\n -- 'Nothing' if the timeout has expired\nbusTimedPop bus timeoutM =\n let timeout = case timeoutM of\n Just timeout' -> timeout'\n Nothing -> clockTimeNone\n in {# call bus_timed_pop #} (toBus bus) (fromIntegral timeout) >>=\n maybePeek takeMiniObject\n\n-- | If @flushing@ is 'True', the bus will flush out any queued\n-- messages, as well as any future messages, until the function is\n-- called with @flushing@ set to 'False'.\nbusSetFlushing :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> Bool -- ^ @flushing@ - the new flushing state\n -> IO ()\nbusSetFlushing bus flushing =\n {# call bus_set_flushing #} (toBus bus) $ fromBool flushing\n\ntype CBusSyncHandler = Ptr Bus\n -> Ptr Message\n -> {# type gpointer #}\n -> IO {# type GstBusSyncReply #}\nmarshalBusSyncHandler :: BusSyncHandler\n -> IO {# type GstBusSyncHandler #}\nmarshalBusSyncHandler busSyncHandler =\n makeBusSyncHandler cBusSyncHandler\n where cBusSyncHandler :: CBusSyncHandler\n cBusSyncHandler busPtr messagePtr _ =\n do bus <- peekObject busPtr\n message <- peekMiniObject messagePtr\n reply <- busSyncHandler bus message\n when (reply == BusDrop) $\n {# call gst_mini_object_unref #} (toMiniObject message)\n return $ fromIntegral $ fromEnum reply\nforeign import ccall \"wrapper\"\n makeBusSyncHandler :: CBusSyncHandler\n -> IO {# type GstBusSyncHandler #}\n\n-- the following mess is necessary to clean up the FunPtr after\n-- busSetSyncHandler. gstreamer doesn't give us a nice way to do this\n-- (such as a DestroyNotify pointer in the argument list)\nweakNotifyQuark, funPtrQuark :: Quark\nweakNotifyQuark = unsafePerformIO $ quarkFromString \"Gtk2HS::SyncHandlerWeakNotify\"\nfunPtrQuark = unsafePerformIO $ quarkFromString \"Gtk2HS::SyncHandlerFunPtr\"\n\ngetWeakNotify :: BusClass busT\n => busT\n -> IO (Maybe GWeakNotify)\ngetWeakNotify = objectGetAttributeUnsafe weakNotifyQuark\n\nsetWeakNotify :: BusClass busT\n => busT\n -> Maybe GWeakNotify\n -> IO ()\nsetWeakNotify = objectSetAttribute weakNotifyQuark\n\ngetFunPtr :: BusClass busT\n => busT\n -> IO (Maybe {# type GstBusSyncHandler #})\ngetFunPtr = objectGetAttributeUnsafe funPtrQuark\n\nsetFunPtr :: BusClass busT\n => busT\n -> Maybe {# type GstBusSyncHandler #}\n -> IO ()\nsetFunPtr = objectSetAttribute funPtrQuark\n\nunsetSyncHandler :: BusClass busT\n => busT\n -> IO ()\nunsetSyncHandler bus = do\n {# call bus_set_sync_handler #} (toBus bus) nullFunPtr nullPtr\n oldWeakNotifyM <- getWeakNotify bus\n case oldWeakNotifyM of\n Just oldWeakNotify -> objectWeakunref bus oldWeakNotify\n Nothing -> return ()\n setWeakNotify bus Nothing\n oldFunPtrM <- getFunPtr bus\n case oldFunPtrM of\n Just oldFunPtr -> freeHaskellFunPtr oldFunPtr\n Nothing -> return ()\n setFunPtr bus Nothing\n\n-- | Set the synchronous message handler on the bus. The function will\n-- be called every time a new message is posted to the bus. Note\n-- that the function will be called from the thread context of the\n-- poster.\n-- \n-- Calling this function will replace any previously set sync\n-- handler. If 'Nothing' is passed to this function, it will unset\n-- the handler.\nbusSetSyncHandler :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> Maybe BusSyncHandler -- ^ @busSyncHandlerM@ - the new 'BusSyncHandler'\n -> IO ()\nbusSetSyncHandler bus busSyncHandlerM = do\n objectWithLock bus $ do\n unsetSyncHandler bus\n case busSyncHandlerM of\n Just busSyncHandler ->\n do funPtr <- marshalBusSyncHandler busSyncHandler\n setFunPtr bus $ Just funPtr\n weakNotify <- objectWeakref bus $ freeHaskellFunPtr funPtr\n setWeakNotify bus $ Just weakNotify\n {# call bus_set_sync_handler #} (toBus bus) funPtr nullPtr\n Nothing ->\n return ()\n\n-- | Use a synchronous message handler that converts all messages to signals.\nbusUseSyncSignalHandler :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> IO ()\nbusUseSyncSignalHandler bus = do\n objectWithLock bus $ do\n unsetSyncHandler bus\n {# call bus_set_sync_handler #} (toBus bus) cBusSyncSignalHandlerPtr nullPtr\nforeign import ccall unsafe \"&gst_bus_sync_signal_handler\"\n cBusSyncSignalHandlerPtr :: {# type GstBusSyncHandler #}\n\n-- | Create a watch for the bus. The 'Source' will dispatch a signal\n-- whenever a message is on the bus. After the signal is dispatched,\n-- the message is popped off the bus.\nbusCreateWatch :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> IO Source -- ^ the new event 'Source'\nbusCreateWatch bus =\n liftM Source $ {# call bus_create_watch #} (toBus bus) >>=\n flip newForeignPtr sourceFinalizer\nforeign import ccall unsafe \"&g_source_unref\"\n sourceFinalizer :: FunPtr (Ptr Source -> IO ())\n\ntype CBusFunc = Ptr Bus\n -> Ptr Message\n -> {# type gpointer #}\n -> IO {# type gboolean #}\nmarshalBusFunc :: BusFunc\n -> IO {# type GstBusFunc #}\nmarshalBusFunc busFunc =\n makeBusFunc cBusFunc\n where cBusFunc :: CBusFunc\n cBusFunc busPtr messagePtr userData =\n do bus <- peekObject busPtr\n message <- peekMiniObject messagePtr\n liftM fromBool $ busFunc bus message\nforeign import ccall \"wrapper\"\n makeBusFunc :: CBusFunc\n -> IO {# type GstBusFunc #}\n\n-- | Adds a bus watch to the default main context with the given\n-- priority. This function is used to receive asynchronous messages\n-- in the main loop.\n-- \n-- The watch can be removed by calling 'System.Glib.MainLoop.sourceRemove'.\nbusAddWatch :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> Priority -- ^ @priority@ - the priority of the watch\n -> BusFunc -- ^ @func@ - the action to perform when a message is recieved\n -> IO HandlerId -- ^ the event source ID\nbusAddWatch bus priority func =\n do busFuncPtr <- marshalBusFunc func\n destroyNotify <- mkFunPtrDestroyNotify busFuncPtr\n liftM fromIntegral $\n {# call bus_add_watch_full #}\n (toBus bus)\n (fromIntegral priority)\n busFuncPtr\n nullPtr\n destroyNotify\n\n-- | Instructs GStreamer to stop emitting the 'busSyncMessage' signal\n-- for this bus. See 'busEnableSyncMessageEmission' for more\n-- information.\n-- \n-- In the event that multiple pieces of code have called\n-- 'busEnableSyncMessageEmission', the sync-message\n-- emissions will only be stopped after all calls to\n-- 'busEnableSyncMessageEmission' were \"cancelled\" by\n-- calling this function.\nbusDisableSyncMessageEmission :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> IO ()\nbusDisableSyncMessageEmission =\n {# call bus_disable_sync_message_emission #} . toBus\n\n-- | Instructs GStreamer to emit the 'busSyncMessage' signal after\n-- running the bus's sync handler. This function is here so that\n-- programmers can ensure that they can synchronously receive\n-- messages without having to affect what the bin's sync handler is.\n-- \n-- This function may be called multiple times. To clean up, the\n-- caller is responsible for calling 'busDisableSyncMessageEmission'\n-- as many times as this function is called.\n-- \n-- While this function looks similar to 'busAddSignalWatch', it is\n-- not exactly the same -- this function enables synchronous\n-- emission of signals when messages arrive; 'busAddSignalWatch'\n-- adds an idle callback to pop messages off the bus\n-- asynchronously. The 'busSyncMessage' signal comes from the thread\n-- of whatever object posted the message; the 'busMessage' signal is\n-- marshalled to the main thread via the main loop.\nbusEnableSyncMessageEmission :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> IO ()\nbusEnableSyncMessageEmission =\n {# call bus_enable_sync_message_emission #} . toBus\n\n-- | Adds a bus signal watch to the default main context with the\n-- given priority. After calling this method, the bus will emit the\n-- 'busMessage' signal for each message posted on the bus.\n-- \n-- This function may be called multiple times. To clean up, the\n-- caller is responsible for calling 'busRemoveSignalWatch' as many\n-- times.\nbusAddSignalWatch :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> Priority -- ^ @priority@ - the priority of the watch\n -> IO ()\nbusAddSignalWatch bus priority =\n {# call bus_add_signal_watch_full #} (toBus bus) $ fromIntegral priority\n\n-- | Remove the signal watch that was added with 'busAddSignalWatch'.\nbusRemoveSignalWatch :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> IO ()\nbusRemoveSignalWatch =\n {# call bus_remove_signal_watch #} . toBus\n\n-- | Poll the bus for a message. Will block while waiting for messages\n-- to come. You can specify the maximum amount of time to wait with\n-- the @timeout@ parameter. If @timeout@ is negative, the function\n-- will wait indefinitely.\n-- \n-- Messages not in @events@ will be popped off the bus and ignored.\n-- \n-- Because 'busPoll' is implemented using the 'busMessage' signal\n-- enabled by 'busAddSignalWatch', calling 'busPoll' will cause the\n-- 'busMessage' signal to be emitted for every message that the\n-- function sees. Thus, a 'busMessage' signal handler will see every\n-- message that 'busPoll' sees -- neither will steal messages from\n-- the other.\n-- \n-- This function will run a main loop in the default main context\n-- while polling.\nbusPoll :: BusClass busT\n => busT -- ^ @bus@ - a 'Bus'\n -> [MessageType] -- ^ @events@ - the set of messages to poll for\n -> ClockTimeDiff -- ^ @timeout@ - the time to wait, or -1 to wait indefinitely\n -> IO Message\nbusPoll bus events timeout =\n {# call bus_poll #} (toBus bus)\n (fromIntegral $ fromFlags events)\n (fromIntegral timeout) >>=\n takeMiniObject\n\n-- | A message has been posted on the bus. This signal is emitted from\n-- a 'Source' added to the 'MainLoop', and only when it is running.\nbusMessage :: BusClass busT\n => Signal busT (Message -> IO ())\nbusMessage =\n Signal $ connect_BOXED__NONE \"message\" peekMiniObject\n\n-- | A message has been posted on the bus. This signal is emitted from\n-- the thread that posted the message so one has to be careful with\n-- locking.\n-- \n-- This signal will not be emitted by default, you must first call\n-- 'busUseSyncSignalHandler' if you want this signal to be emitted\n-- when a message is posted on the bus.\nbusSyncMessage :: BusClass busT\n => Signal busT (Message -> IO ())\nbusSyncMessage =\n Signal $ connect_BOXED__NONE \"sync-message\" peekMiniObject\n","old_contents":"-- GIMP Toolkit (GTK) Binding for Haskell: binding to gstreamer -*-haskell-*-\n--\n-- Author : Peter Gavin\n-- Created: 1-Apr-2007\n--\n-- Copyright (c) 2007 Peter Gavin\n--\n-- This library is free software: you can redistribute it and\/or\n-- modify it under the terms of the GNU Lesser General Public License\n-- as published by the Free Software Foundation, either version 3 of\n-- the License, or (at your option) any later version.\n-- \n-- This library is distributed in the hope that it will be useful,\n-- but WITHOUT ANY WARRANTY; without even the implied warranty of\n-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n-- Lesser General Public License for more details.\n-- \n-- You should have received a copy of the GNU Lesser General Public\n-- License along with this program. If not, see\n-- .\n-- \n-- GStreamer, the C library which this Haskell library depends on, is\n-- available under LGPL Version 2. The documentation included with\n-- this library is based on the original GStreamer documentation.\n-- \n-- |\n-- Maintainer : gtk2hs-devel@lists.sourceforge.net\n-- Stability : alpha\n-- Portability : portable (depends on GHC)\n-- \n-- An asynchronous message bus subsystem.\nmodule Media.Streaming.GStreamer.Core.Bus (\n-- * Detail\n -- | The 'Bus' is resposible for delivering 'Message's in a\n -- first-in, first-out order, from the streaming threads to the\n -- application.\n -- \n -- Since the application typically only wants to deal with\n -- delivery of these messages from one thread, the 'Bus' will\n -- marshal the messages between different threads. This is\n -- important since the actual streaming of media is done in\n -- a thread separate from the application.\n --\n -- The 'Bus' provides support for 'System.Glib.MainLoop.Source'\n -- based notifications. This makes it possible to handle the\n -- delivery in the GLib 'System.Glib.MainLoop.Source'.\n --\n -- A message is posted on the bus with the 'busPost' method. With\n -- the 'busPeek' and 'busPop' methods one can look at or retrieve\n -- a previously posted message.\n --\n -- The bus can be polled with the 'busPoll' method. This methods\n -- blocks up to the specified timeout value until one of the\n -- specified messages types is posted on the bus. The application\n -- can then pop the messages from the bus to handle\n -- them. Alternatively the application can register an\n -- asynchronous bus function using 'busAddWatch'. This function\n -- will install a 'System.Glib.MainLoop.Source' in the default\n -- GLib main loop and will deliver messages a short while after\n -- they have been posted. Note that the main loop should be\n -- running for the asynchronous callbacks.\n --\n -- It is also possible to get messages from the bus without any\n -- thread marshalling with the 'busSetSyncHandler' method. This\n -- makes it possible to react to a message in the same thread that\n -- posted the message on the bus. This should only be used if the\n -- application is able to deal with messages from different\n -- threads.\n -- \n -- Every 'Pipeline' has one bus.\n --\n -- Note that a 'Pipeline' will set its bus into flushing state\n -- when changing from 'StateReady' to 'StateNull'.\n\n-- * Types\n Bus,\n -- | The result of a 'BusSyncHandler'.\n BusSyncReply,\n -- | A handler that will be invoked synchronously when a new message\n -- is injected into the bus. This function is mostly used internally.\n -- Only one sync handler may be attached to a given bus.\n BusSyncHandler,\n BusClass,\n castToBus,\n toBus,\n-- * Bus Operations\n busGetFlags,\n busSetFlags,\n busUnsetFlags,\n busNew,\n busPost,\n busHavePending,\n busPeek,\n busPop,\n busTimedPop,\n busSetFlushing,\n busSetSyncHandler,\n busUseSyncSignalHandler,\n busCreateWatch,\n busAddWatch,\n busDisableSyncMessageEmission,\n busEnableSyncMessageEmission,\n busAddSignalWatch,\n busRemoveSignalWatch,\n busPoll,\n \n-- * Bus Signals\n busMessage,\n busSyncMessage,\n \n ) where\n\nimport Control.Monad ( liftM\n , when )\n{#import Media.Streaming.GStreamer.Core.Object#}\n{#import Media.Streaming.GStreamer.Core.Types#}\n{#import Media.Streaming.GStreamer.Core.Signals#}\n{#import System.Glib.MainLoop#}\nimport System.Glib.Flags\nimport System.Glib.FFI\n{#import System.Glib.GObject#}\n{#import System.Glib.MainLoop#}\n\n{# context lib = \"gstreamer\" prefix = \"gst\" #}\n\n-- | Get the flags set on this bus.\nbusGetFlags :: BusClass busT\n => busT\n -> IO [BusFlags]\nbusGetFlags = mkObjectGetFlags\n\n-- | Set flags on this bus.\nbusSetFlags :: BusClass busT\n => busT\n -> [BusFlags]\n -> IO ()\nbusSetFlags = mkObjectSetFlags\n\n-- | Unset flags on this bus.\nbusUnsetFlags :: BusClass busT\n => busT\n -> [BusFlags]\n -> IO ()\nbusUnsetFlags = mkObjectUnsetFlags\n\n-- | Create a new bus.\nbusNew :: IO Bus\nbusNew =\n {# call bus_new #} >>= takeObject\n\n-- | Post a message to the bus.\nbusPost :: BusClass busT\n => busT\n -> Message\n -> IO Bool\nbusPost bus message =\n do {# call gst_mini_object_ref #} (toMiniObject message)\n liftM toBool $ {# call bus_post #} (toBus bus) message\n\n-- | Check if there are pending messages on the bus.\nbusHavePending :: BusClass busT\n => busT\n -> IO Bool\nbusHavePending bus =\n liftM toBool $ {# call bus_have_pending #} $ toBus bus\n\n-- | Get the message at the front of the queue. It will remain on the\n-- queue.\nbusPeek :: BusClass busT\n => busT\n -> IO (Maybe Message)\nbusPeek bus =\n {# call bus_peek #} (toBus bus) >>= maybePeek takeMiniObject\n\n-- | Get the message at the front of the queue. It will be removed\n-- from the queue.\nbusPop :: BusClass busT\n => busT\n -> IO (Maybe Message)\nbusPop bus =\n {# call bus_pop #} (toBus bus) >>= maybePeek takeMiniObject\n\n-- | Get a message from the bus, waiting up to the specified timeout.\n-- If the time given is 'Nothing', the function will wait forever.\n-- If the time given is @0@, the function will behave like 'busPop'.\nbusTimedPop :: BusClass busT\n => busT\n -> Maybe ClockTime\n -> IO (Maybe Message)\nbusTimedPop bus timeoutM =\n let timeout = case timeoutM of\n Just timeout' -> timeout'\n Nothing -> clockTimeNone\n in {# call bus_timed_pop #} (toBus bus) (fromIntegral timeout) >>=\n maybePeek takeMiniObject\n\n-- | If @flushing@ is 'True', the bus will flush out any queued\n-- messages, as well as any future messages, until the function is\n-- called with @flushing@ set to 'False'.\nbusSetFlushing :: BusClass busT\n => busT\n -> Bool\n -> IO ()\nbusSetFlushing bus flushing =\n {# call bus_set_flushing #} (toBus bus) $ fromBool flushing\n\n-- these will leak memory, maybe one day we can set a destroy notifier...\n\ntype CBusSyncHandler = Ptr Bus\n -> Ptr Message\n -> {# type gpointer #}\n -> IO {# type GstBusSyncReply #}\nmarshalBusSyncHandler :: BusSyncHandler\n -> IO {# type GstBusSyncHandler #}\nmarshalBusSyncHandler busSyncHandler =\n makeBusSyncHandler cBusSyncHandler\n where cBusSyncHandler :: CBusSyncHandler\n cBusSyncHandler busPtr messagePtr _ =\n do bus <- peekObject busPtr\n message <- peekMiniObject messagePtr\n reply <- busSyncHandler bus message\n when (reply == BusDrop) $\n {# call gst_mini_object_unref #} (toMiniObject message)\n return $ fromIntegral $ fromEnum reply\nforeign import ccall \"wrapper\"\n makeBusSyncHandler :: CBusSyncHandler\n -> IO {# type GstBusSyncHandler #}\n\n-- the following mess is necessary to clean up safely after busSetSyncHandler.\n-- gstreamer doesn't give us a nice way to do this (such as a DestroyNotify)\nweakNotifyQuark, funPtrQuark :: Quark\nweakNotifyQuark = unsafePerformIO $ quarkFromString \"Gtk2HS::SyncHandlerWeakNotify\"\nfunPtrQuark = unsafePerformIO $ quarkFromString \"Gtk2HS::SyncHandlerFunPtr\"\n\ngetWeakNotify :: BusClass busT\n => busT\n -> IO (Maybe GWeakNotify)\ngetWeakNotify = objectGetAttributeUnsafe weakNotifyQuark\n\nsetWeakNotify :: BusClass busT\n => busT\n -> Maybe GWeakNotify\n -> IO ()\nsetWeakNotify = objectSetAttribute weakNotifyQuark\n\ngetFunPtr :: BusClass busT\n => busT\n -> IO (Maybe {# type GstBusSyncHandler #})\ngetFunPtr = objectGetAttributeUnsafe funPtrQuark\n\nsetFunPtr :: BusClass busT\n => busT\n -> Maybe {# type GstBusSyncHandler #}\n -> IO ()\nsetFunPtr = objectSetAttribute funPtrQuark\n\nunsetSyncHandler :: BusClass busT\n => busT\n -> IO ()\nunsetSyncHandler bus = do\n {# call bus_set_sync_handler #} (toBus bus) nullFunPtr nullPtr\n oldWeakNotifyM <- getWeakNotify bus\n case oldWeakNotifyM of\n Just oldWeakNotify -> objectWeakunref bus oldWeakNotify\n Nothing -> return ()\n setWeakNotify bus Nothing\n oldFunPtrM <- getFunPtr bus\n case oldFunPtrM of\n Just oldFunPtr -> freeHaskellFunPtr oldFunPtr\n Nothing -> return ()\n setFunPtr bus Nothing\n\n-- | Set the synchronous message handler on the bus. The function will\n-- be called every time a new message is posted to the bus. Note\n-- that the function will be called from the thread context of the\n-- poster.\n-- \n-- Calling this function will replace any previously set sync\n-- handler. If 'Nothing' is passed to this function, it will unset\n-- the handler.\nbusSetSyncHandler :: BusClass busT\n => busT\n -> Maybe BusSyncHandler\n -> IO ()\nbusSetSyncHandler bus busSyncHandlerM = do\n objectWithLock bus $ do\n unsetSyncHandler bus\n case busSyncHandlerM of\n Just busSyncHandler ->\n do funPtr <- marshalBusSyncHandler busSyncHandler\n setFunPtr bus $ Just funPtr\n weakNotify <- objectWeakref bus $ freeHaskellFunPtr funPtr\n setWeakNotify bus $ Just weakNotify\n {# call bus_set_sync_handler #} (toBus bus) funPtr nullPtr\n Nothing ->\n return ()\n\n-- | Use a synchronous message handler that converts all messages to signals.\nbusUseSyncSignalHandler :: BusClass busT\n => busT\n -> IO ()\nbusUseSyncSignalHandler bus = do\n objectWithLock bus $ do\n unsetSyncHandler bus\n {# call bus_set_sync_handler #} (toBus bus) cBusSyncSignalHandlerPtr nullPtr\nforeign import ccall unsafe \"&gst_bus_sync_signal_handler\"\n cBusSyncSignalHandlerPtr :: {# type GstBusSyncHandler #}\n\n-- | Create a watch for the bus. The 'Source' will dispatch a signal\n-- whenever a message is on the bus. After the signal is dispatched,\n-- the message is popped off the bus.\nbusCreateWatch :: BusClass busT\n => busT\n -> IO Source\nbusCreateWatch bus =\n liftM Source $ {# call bus_create_watch #} (toBus bus) >>=\n flip newForeignPtr sourceFinalizer\nforeign import ccall unsafe \"&g_source_unref\"\n sourceFinalizer :: FunPtr (Ptr Source -> IO ())\n\ntype CBusFunc = Ptr Bus\n -> Ptr Message\n -> {# type gpointer #}\n -> IO {# type gboolean #}\nmarshalBusFunc :: BusFunc\n -> IO {# type GstBusFunc #}\nmarshalBusFunc busFunc =\n makeBusFunc cBusFunc\n where cBusFunc :: CBusFunc\n cBusFunc busPtr messagePtr userData =\n do bus <- peekObject busPtr\n message <- peekMiniObject messagePtr\n liftM fromBool $ busFunc bus message\nforeign import ccall \"wrapper\"\n makeBusFunc :: CBusFunc\n -> IO {# type GstBusFunc #}\n\n-- | Adds a bus watch to the default main context with the given\n-- priority. This function is used to receive asynchronous messages\n-- in the main loop.\n-- \n-- The watch can be removed by calling 'System.Glib.MainLoop.sourceRemove'.\nbusAddWatch :: BusClass busT\n => busT\n -> Priority\n -> BusFunc\n -> IO HandlerId\nbusAddWatch bus priority func =\n do busFuncPtr <- marshalBusFunc func\n destroyNotify <- mkFunPtrDestroyNotify busFuncPtr\n liftM fromIntegral $\n {# call bus_add_watch_full #}\n (toBus bus)\n (fromIntegral priority)\n busFuncPtr\n nullPtr\n destroyNotify\n\n-- | Instructs GStreamer to stop emitting the 'busSyncMessage' signal\n-- for this bus. See 'busEnableSyncMessageEmission' for more\n-- information.\n-- \n-- In the event that multiple pieces of code have called\n-- 'busEnableSyncMessageEmission', the sync-message\n-- emissions will only be stopped after all calls to\n-- 'busEnableSyncMessageEmission' were \"cancelled\" by\n-- calling this function.\nbusDisableSyncMessageEmission :: BusClass busT\n => busT\n -> IO ()\nbusDisableSyncMessageEmission =\n {# call bus_disable_sync_message_emission #} . toBus\n\n-- | Instructs GStreamer to emit the 'busSyncMessage' signal after\n-- running the bus's sync handler. This function is here so that\n-- programmers can ensure that they can synchronously receive\n-- messages without having to affect what the bin's sync handler is.\n-- \n-- This function may be called multiple times. To clean up, the\n-- caller is responsible for calling 'busDisableSyncMessageEmission'\n-- as many times as this function is called.\n-- \n-- While this function looks similar to 'busAddSignalWatch', it is\n-- not exactly the same -- this function enables synchronous\n-- emission of signals when messages arrive; 'busAddSignalWatch'\n-- adds an idle callback to pop messages off the bus\n-- asynchronously. The 'busSyncMessage' signal comes from the thread\n-- of whatever object posted the message; the 'busMessage' signal is\n-- marshalled to the main thread via the main loop.\nbusEnableSyncMessageEmission :: BusClass busT\n => busT\n -> IO ()\nbusEnableSyncMessageEmission =\n {# call bus_enable_sync_message_emission #} . toBus\n\n-- | Adds a bus signal watch to the default main context with the\n-- given priority. After calling this method, the bus will emit the\n-- 'busMessage' signal for each message posted on the bus.\n-- \n-- This function may be called multiple times. To clean up, the\n-- caller is responsible for calling 'busRemoveSignalWatch' as many\n-- times.\nbusAddSignalWatch :: BusClass busT\n => busT\n -> Priority\n -> IO ()\nbusAddSignalWatch bus priority =\n {# call bus_add_signal_watch_full #} (toBus bus) $ fromIntegral priority\n\n-- | Remove the signal watch that was added with 'busAddSignalWatch'.\nbusRemoveSignalWatch :: BusClass busT\n => busT\n -> IO ()\nbusRemoveSignalWatch =\n {# call bus_remove_signal_watch #} . toBus\n\n-- | Poll the bus for a message. Will block while waiting for messages\n-- to come. You can specify the maximum amount of time to wait with\n-- the @timeout@ parameter. If @timeout@ is negative, the function\n-- will wait indefinitely.\n-- \n-- Messages not in @events@ will be popped off the bus and ignored.\n-- \n-- Because 'busPoll' is implemented using the 'busMessage' signal\n-- enabled by 'busAddSignalWatch', calling 'busPoll' will cause the\n-- 'busMessage' signal to be emitted for every message that the\n-- function sees. Thus, a 'busMessage' signal handler will see every\n-- message that 'busPoll' sees -- neither will steal messages from\n-- the other.\n-- \n-- This function will run a main loop in the default main context\n-- while polling.\nbusPoll :: Bus\n -> [MessageType]\n -> ClockTimeDiff\n -> IO Message\nbusPoll bus events timeout =\n {# call bus_poll #} bus\n (fromIntegral $ fromFlags events)\n (fromIntegral timeout) >>=\n takeMiniObject\n\n-- | A message has been posted on the bus. This signal is emitted from\n-- a 'Source' added to the 'MainLoop', and only when it is running.\nbusMessage :: BusClass bus\n => Signal bus (Message -> IO ())\nbusMessage =\n Signal $ connect_BOXED__NONE \"message\" peekMiniObject\n\n-- | A message has been posted on the bus. This signal is emitted from\n-- the thread that posted the message so one has to be careful with\n-- locking.\n-- \n-- This signal will not be emitted by default, you must first call\n-- 'busUseSyncSignalHandler' if you want this signal to be emitted\n-- when a message is posted on the bus.\nbusSyncMessage :: BusClass bus\n => Signal bus (Message -> IO ())\nbusSyncMessage =\n Signal $ connect_BOXED__NONE \"sync-message\" peekMiniObject\n","returncode":0,"stderr":"","license":"lgpl-2.1","lang":"C2hs Haskell"}
{"commit":"918e3a8d5a35a20ba05773dcea3b034f9c7e4d89","subject":"Derive Read instance for StatusCode (#27)","message":"Derive Read instance for StatusCode (#27)\n\n","repos":"awakenetworks\/gRPC-haskell,awakenetworks\/gRPC-haskell,awakenetworks\/gRPC-haskell","old_file":"src\/Network\/GRPC\/Unsafe\/Op.chs","new_file":"src\/Network\/GRPC\/Unsafe\/Op.chs","new_contents":"{-# LANGUAGE StandaloneDeriving #-}\n\nmodule Network.GRPC.Unsafe.Op where\n\n{#import Network.GRPC.Unsafe.Slice#}\n\nimport Control.Exception\nimport Foreign.C.Types\nimport Foreign.Ptr\n{#import Network.GRPC.Unsafe.ByteBuffer#}\n{#import Network.GRPC.Unsafe.Metadata#}\n\n#include \n#include \n#include \n#include \n\n{#context prefix = \"grpc\" #}\n\n{#enum grpc_op_type as OpType {underscoreToCase} deriving (Eq, Show)#}\n{#enum grpc_status_code as StatusCode {underscoreToCase} deriving (Eq, Read, Show)#}\n\n-- NOTE: We don't alloc the space for the enum in Haskell because enum size is\n-- implementation-dependent. See:\n-- http:\/\/stackoverflow.com\/questions\/1113855\/is-the-sizeofenum-sizeofint-always\n-- | Allocates space for a 'StatusCode' and returns a pointer to it. Used to\n-- receive a status code from the server with 'opRecvStatusClient'.\n{#fun unsafe create_status_code_ptr as ^ {} -> `Ptr StatusCode' castPtr#}\n\n{#fun unsafe deref_status_code_ptr as ^ {castPtr `Ptr StatusCode'} -> `StatusCode'#}\n\n{#fun unsafe destroy_status_code_ptr as ^ {castPtr `Ptr StatusCode'} -> `()' #}\n\n-- | Represents an array of ops to be passed to 'grpcCallStartBatch'.\n-- Create an array with 'opArrayCreate', then create individual ops in the array\n-- using the op* functions. For these functions, the first two arguments are\n-- always the OpArray to mutate and the index in the array at which to create\n-- the new op. After processing the batch and getting out any results, call\n-- 'opArrayDestroy'.\n{#pointer *grpc_op as OpArray newtype #}\n\nderiving instance Show OpArray\n\n-- | Creates an empty 'OpArray' with space for the given number of ops.\n{#fun unsafe op_array_create as ^ {`Int'} -> `OpArray'#}\n\n-- | Destroys an 'OpArray' of the given size.\n{#fun unsafe op_array_destroy as ^ {`OpArray', `Int'} -> `()'#}\n\n-- | brackets creating and destroying an 'OpArray' with the given size.\nwithOpArray :: Int -> (OpArray -> IO a) -> IO a\nwithOpArray n f = bracket (opArrayCreate n) (flip opArrayDestroy n) f\n\n-- | Creates an op of type GRPC_OP_SEND_INITIAL_METADATA at the specified\n-- index of the given 'OpArray', containing the given\n-- metadata. The metadata is copied and can be destroyed after calling this\n-- function.\n{#fun unsafe op_send_initial_metadata as ^\n {`OpArray', `Int', `MetadataKeyValPtr', `Int'} -> `()'#}\n\n-- | Creates an op of type GRPC_OP_SEND_INITIAL_METADATA at the specified\n-- index of the given 'OpArray'. The op will contain no metadata.\n{#fun unsafe op_send_initial_metadata_empty as ^ {`OpArray', `Int'} -> `()'#}\n\n-- | Creates an op of type GRPC_OP_SEND_MESSAGE at the specified index of\n-- the given 'OpArray'. The given 'ByteBuffer' is\n-- copied and can be destroyed after calling this function.\n{#fun unsafe op_send_message as ^ {`OpArray', `Int', `ByteBuffer'} -> `()'#}\n\n-- | Creates an 'Op' of type GRPC_OP_SEND_CLOSE_FROM_CLIENT at the specified\n-- index of the given 'OpArray'.\n{#fun unsafe op_send_close_client as ^ {`OpArray', `Int'} -> `()'#}\n\n-- | Creates an op of type GRPC_OP_RECV_INITIAL_METADATA at the specified\n-- index of the given 'OpArray', and ties the given\n-- 'MetadataArray' pointer to that op so that the received metadata can be\n-- accessed. It is the user's responsibility to destroy the 'MetadataArray'.\n{#fun unsafe op_recv_initial_metadata as ^\n {`OpArray', `Int',id `Ptr MetadataArray'} -> `()'#}\n\n-- | Creates an op of type GRPC_OP_RECV_MESSAGE at the specified index of the\n-- given 'OpArray', and ties the given\n-- 'ByteBuffer' pointer to that op so that the received message can be\n-- accessed. It is the user's responsibility to destroy the 'ByteBuffer'.\n{#fun unsafe op_recv_message as ^ {`OpArray', `Int',id `Ptr ByteBuffer'} -> `()'#}\n\n-- | Creates an op of type GRPC_OP_RECV_STATUS_ON_CLIENT at the specified\n-- index of the given 'OpArray', and ties all the\n-- input pointers to that op so that the results of the receive can be\n-- accessed. It is the user's responsibility to free all the input args after\n-- this call.\n{#fun unsafe op_recv_status_client as ^\n {`OpArray', `Int',id `Ptr MetadataArray', castPtr `Ptr StatusCode',\n `Slice'}\n -> `()'#}\n\n-- | Creates an op of type GRPC_OP_RECV_CLOSE_ON_SERVER at the specified index\n-- of the given 'OpArray', and ties the input\n-- pointer to that op so that the result of the receive can be accessed. It is\n-- the user's responsibility to free the pointer.\n{#fun unsafe op_recv_close_server as ^ {`OpArray', `Int', id `Ptr CInt'} -> `()'#}\n\n-- | Creates an op of type GRPC_OP_SEND_STATUS_FROM_SERVER at the specified\n-- index of the given 'OpArray'. The given\n-- Metadata and string are copied when creating the op, and can be safely\n-- destroyed immediately after calling this function.\n{#fun unsafe op_send_status_server as ^\n {`OpArray', `Int', `Int', `MetadataKeyValPtr', `StatusCode', `Slice'}\n -> `()'#}\n","old_contents":"{-# LANGUAGE StandaloneDeriving #-}\n\nmodule Network.GRPC.Unsafe.Op where\n\n{#import Network.GRPC.Unsafe.Slice#}\n\nimport Control.Exception\nimport Foreign.C.Types\nimport Foreign.Ptr\n{#import Network.GRPC.Unsafe.ByteBuffer#}\n{#import Network.GRPC.Unsafe.Metadata#}\n\n#include \n#include \n#include \n#include \n\n{#context prefix = \"grpc\" #}\n\n{#enum grpc_op_type as OpType {underscoreToCase} deriving (Eq, Show)#}\n{#enum grpc_status_code as StatusCode {underscoreToCase} deriving (Eq, Show)#}\n\n-- NOTE: We don't alloc the space for the enum in Haskell because enum size is\n-- implementation-dependent. See:\n-- http:\/\/stackoverflow.com\/questions\/1113855\/is-the-sizeofenum-sizeofint-always\n-- | Allocates space for a 'StatusCode' and returns a pointer to it. Used to\n-- receive a status code from the server with 'opRecvStatusClient'.\n{#fun unsafe create_status_code_ptr as ^ {} -> `Ptr StatusCode' castPtr#}\n\n{#fun unsafe deref_status_code_ptr as ^ {castPtr `Ptr StatusCode'} -> `StatusCode'#}\n\n{#fun unsafe destroy_status_code_ptr as ^ {castPtr `Ptr StatusCode'} -> `()' #}\n\n-- | Represents an array of ops to be passed to 'grpcCallStartBatch'.\n-- Create an array with 'opArrayCreate', then create individual ops in the array\n-- using the op* functions. For these functions, the first two arguments are\n-- always the OpArray to mutate and the index in the array at which to create\n-- the new op. After processing the batch and getting out any results, call\n-- 'opArrayDestroy'.\n{#pointer *grpc_op as OpArray newtype #}\n\nderiving instance Show OpArray\n\n-- | Creates an empty 'OpArray' with space for the given number of ops.\n{#fun unsafe op_array_create as ^ {`Int'} -> `OpArray'#}\n\n-- | Destroys an 'OpArray' of the given size.\n{#fun unsafe op_array_destroy as ^ {`OpArray', `Int'} -> `()'#}\n\n-- | brackets creating and destroying an 'OpArray' with the given size.\nwithOpArray :: Int -> (OpArray -> IO a) -> IO a\nwithOpArray n f = bracket (opArrayCreate n) (flip opArrayDestroy n) f\n\n-- | Creates an op of type GRPC_OP_SEND_INITIAL_METADATA at the specified\n-- index of the given 'OpArray', containing the given\n-- metadata. The metadata is copied and can be destroyed after calling this\n-- function.\n{#fun unsafe op_send_initial_metadata as ^\n {`OpArray', `Int', `MetadataKeyValPtr', `Int'} -> `()'#}\n\n-- | Creates an op of type GRPC_OP_SEND_INITIAL_METADATA at the specified\n-- index of the given 'OpArray'. The op will contain no metadata.\n{#fun unsafe op_send_initial_metadata_empty as ^ {`OpArray', `Int'} -> `()'#}\n\n-- | Creates an op of type GRPC_OP_SEND_MESSAGE at the specified index of\n-- the given 'OpArray'. The given 'ByteBuffer' is\n-- copied and can be destroyed after calling this function.\n{#fun unsafe op_send_message as ^ {`OpArray', `Int', `ByteBuffer'} -> `()'#}\n\n-- | Creates an 'Op' of type GRPC_OP_SEND_CLOSE_FROM_CLIENT at the specified\n-- index of the given 'OpArray'.\n{#fun unsafe op_send_close_client as ^ {`OpArray', `Int'} -> `()'#}\n\n-- | Creates an op of type GRPC_OP_RECV_INITIAL_METADATA at the specified\n-- index of the given 'OpArray', and ties the given\n-- 'MetadataArray' pointer to that op so that the received metadata can be\n-- accessed. It is the user's responsibility to destroy the 'MetadataArray'.\n{#fun unsafe op_recv_initial_metadata as ^\n {`OpArray', `Int',id `Ptr MetadataArray'} -> `()'#}\n\n-- | Creates an op of type GRPC_OP_RECV_MESSAGE at the specified index of the\n-- given 'OpArray', and ties the given\n-- 'ByteBuffer' pointer to that op so that the received message can be\n-- accessed. It is the user's responsibility to destroy the 'ByteBuffer'.\n{#fun unsafe op_recv_message as ^ {`OpArray', `Int',id `Ptr ByteBuffer'} -> `()'#}\n\n-- | Creates an op of type GRPC_OP_RECV_STATUS_ON_CLIENT at the specified\n-- index of the given 'OpArray', and ties all the\n-- input pointers to that op so that the results of the receive can be\n-- accessed. It is the user's responsibility to free all the input args after\n-- this call.\n{#fun unsafe op_recv_status_client as ^\n {`OpArray', `Int',id `Ptr MetadataArray', castPtr `Ptr StatusCode',\n `Slice'}\n -> `()'#}\n\n-- | Creates an op of type GRPC_OP_RECV_CLOSE_ON_SERVER at the specified index\n-- of the given 'OpArray', and ties the input\n-- pointer to that op so that the result of the receive can be accessed. It is\n-- the user's responsibility to free the pointer.\n{#fun unsafe op_recv_close_server as ^ {`OpArray', `Int', id `Ptr CInt'} -> `()'#}\n\n-- | Creates an op of type GRPC_OP_SEND_STATUS_FROM_SERVER at the specified\n-- index of the given 'OpArray'. The given\n-- Metadata and string are copied when creating the op, and can be safely\n-- destroyed immediately after calling this function.\n{#fun unsafe op_send_status_server as ^\n {`OpArray', `Int', `Int', `MetadataKeyValPtr', `StatusCode', `Slice'}\n -> `()'#}\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"C2hs Haskell"}
{"commit":"bb6f15ec3f91225d46ed28dbf00929d8cfc42846","subject":"Follow recent changes in upstream C library","message":"Follow recent changes in upstream C library\n","repos":"grpc\/grpc-haskell","old_file":"src\/Network\/Grpc\/Core\/Call.chs","new_file":"src\/Network\/Grpc\/Core\/Call.chs","new_contents":"-- Copyright (c) 2016, Google Inc.\n-- All rights reserved.\n--\n-- Redistribution and use in source and binary forms, with or without\n-- modification, are permitted provided that the following conditions are met:\n-- * Redistributions of source code must retain the above copyright\n-- notice, this list of conditions and the following disclaimer.\n-- * Redistributions in binary form must reproduce the above copyright\n-- notice, this list of conditions and the following disclaimer in the\n-- documentation and\/or other materials provided with the distribution.\n-- * Neither the name of Google Inc. nor the\n-- names of its contributors may be used to endorse or promote products\n-- derived from this software without specific prior written permission.\n--\n-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n-- DISCLAIMED. IN NO EVENT SHALL Google Inc. BE LIABLE FOR ANY\n-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n--\n--------------------------------------------------------------------------------\n{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, ExistentialQuantification, RecordWildCards #-}\nmodule Network.Grpc.Core.Call where\n\n\nimport Control.Concurrent\nimport Control.Exception\nimport Control.Monad\n\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Lazy as L\nimport Data.Monoid ((<>), Last(..))\nimport Data.IORef\n\nimport Foreign.C.Types as C\nimport qualified Foreign.Marshal.Alloc as C\nimport qualified Foreign.Marshal.Utils as C\nimport qualified Foreign.Ptr as C\nimport Foreign.Ptr (Ptr)\nimport qualified Foreign.Storable as C\n\n-- transformers\nimport Control.Monad.IO.Class\nimport Control.Monad.Trans.Except\n\nimport qualified Network.Grpc.CompletionQueue as CQ\nimport Network.Grpc.Lib.PropagationBits\n{#import Network.Grpc.Lib.ByteBuffer#}\n{#import Network.Grpc.Lib.Metadata#}\n{#import Network.Grpc.Lib.TimeSpec#}\n{#import Network.Grpc.Lib.Core#}\n\n\n#include \n#include \"hs_grpc.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\ndata Deadline\n = AbsoluteDeadline TimeSpec\n | RelativeDeadline Int -- milliseconds\n\ndata ClientContext = ClientContext\n { ccChannel :: Channel\n , ccCQ :: CompletionQueue\n , ccWorker :: CQ.Worker\n }\n\ndata CallOptions = CallOptions\n { coDeadline :: Maybe Deadline\n , coParentContext :: Maybe () -- todo\n , coPropagationMask :: Maybe PropagationMask\n , coMetadata :: [Metadata]\n }\n\ninstance Monoid CallOptions where\n mempty = CallOptions Nothing Nothing Nothing []\n mappend (CallOptions a b c d) (CallOptions a' b' c' d') =\n CallOptions\n (getLast (Last a <> Last a'))\n (getLast (Last b <> Last b'))\n (getLast (Last c <> Last c'))\n (d <> d')\n\nwithAbsoluteDeadline :: TimeSpec -> CallOptions\nwithAbsoluteDeadline deadline =\n mempty { coDeadline = Just (AbsoluteDeadline deadline) }\n\nwithRelativeDeadlineSeconds :: Int -> CallOptions\nwithRelativeDeadlineSeconds seconds =\n mempty { coDeadline = Just (RelativeDeadline (seconds*1000)) }\n\nwithRelativeDeadlineMillis :: Int -> CallOptions\nwithRelativeDeadlineMillis ms =\n mempty { coDeadline = Just (RelativeDeadline ms) }\n\nwithParentContext :: () -> CallOptions\nwithParentContext ctx =\n mempty { coParentContext = Just ctx }\n\nwithParentContextPropagating :: () -> PropagationMask -> CallOptions\nwithParentContextPropagating ctx prop =\n mempty { coParentContext = Just ctx\n , coPropagationMask = Just prop }\n\nwithMetadata :: [Metadata] -> CallOptions\nwithMetadata md =\n mempty { coMetadata = md }\n\nresolveDeadline :: CallOptions -> IO TimeSpec\nresolveDeadline co =\n case coDeadline co of\n Nothing -> return gprInfFuture\n Just (AbsoluteDeadline deadline) -> return deadline\n Just (RelativeDeadline ms) ->\n millisFromNow (fromIntegral ms)\n\nnewClientContext :: Channel -> IO ClientContext\nnewClientContext chan = do\n cq <- completionQueueCreate reservedPtr\n cqt <- CQ.startCompletionQueueThread cq\n return (ClientContext chan cq cqt)\n\ndestroyClientContext :: ClientContext -> IO ()\ndestroyClientContext (ClientContext _ cq w) = do\n completionQueueShutdown cq\n CQ.waitWorkerTermination w\n\ntype MethodName = B.ByteString\ntype Arg = B.ByteString\n\n-- | Run the IO function once, cache it in the MVar.\nonceMVar :: MVar (Maybe a) -> IO a -> IO a\nonceMVar mvar io = modifyMVar mvar $ \\x ->\n case x of\n Just x' -> return (x, x')\n Nothing -> do\n x' <- io\n return (Just x', x')\n\nreservedPtr :: Ptr ()\nreservedPtr = C.nullPtr\n\ndata UnaryResult a = UnaryResult [Metadata] [Metadata] a deriving Show\n\ncallUnary :: ClientContext -> CallOptions -> MethodName -> Arg -> IO (RpcReply (UnaryResult L.ByteString))\ncallUnary ctx@(ClientContext chan cq _) co method arg = do\n deadline <- resolveDeadline co\n bracket (grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline) grpcCallDestroy $ \\call0 -> newMVar call0 >>= \\mcall -> do\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n recvStatusOp <- opRecvStatusOnClient crw\n recvMessageOp <- opRecvMessage\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX recvInitialMetadataOp\n , OpX recvMessageOp\n , OpX sendMessageOp\n , OpX recvStatusOp\n ]\n case res of\n RpcOk _ -> do\n (RpcStatus trailMD status statusDetails) <- opRead recvStatusOp\n case status of\n StatusOk -> do\n initMD <- opRead recvInitialMetadataOp\n answ <- opRead recvMessageOp\n let answ' = maybe L.empty id answ\n return (RpcOk (UnaryResult initMD trailMD answ'))\n _ -> return (RpcError (StatusError status statusDetails))\n RpcError err -> return (RpcError err)\n\ncallDownstream :: ClientContext -> CallOptions -> MethodName -> Arg -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallDownstream ctx@(ClientContext chan cq _) co method arg = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX sendMessageOp\n ]\n case res of\n RpcOk _ -> do\n res' <- callBatchStatusOnClient crw\n case res' of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n RpcError err -> return (RpcError err)\n\ncallUpstream :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallUpstream ctx@(ClientContext chan cq _) co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> do\n res' <- callBatchStatusOnClient crw\n case res' of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n RpcError err -> return (RpcError err)\n\ncallBidi :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallBidi ctx@(ClientContext chan cq _) co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n\n crw <- newClientReaderWriter ctx mcall\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> do\n res' <- callBatchStatusOnClient crw\n case res' of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n RpcError err -> return (RpcError err)\n\ndata Client req resp = Client\n { clientCrw :: ClientReaderWriter\n , clientEncoder :: Encoder req\n , clientDecoder :: Decoder resp\n }\n\ntype Decoder a = L.ByteString -> IO (RpcReply a)\ntype Encoder a = a -> IO (RpcReply B.ByteString)\n\ndefaultDecoder :: L.ByteString -> IO (RpcReply L.ByteString)\ndefaultDecoder bs = return (RpcOk bs)\n\ndefaultEncoder :: B.ByteString -> IO (RpcReply B.ByteString)\ndefaultEncoder bs = return (RpcOk bs)\n\ndata ClientReaderWriter = ClientReaderWriter {\n context :: ClientContext,\n callMVar_ :: MVar Call,\n initialMDRef :: !(IORef (Maybe [Metadata])),\n trailingMDRef :: !(IORef (Maybe [Metadata])),\n statusFromServer :: !(MVar RpcStatus),\n statusFromServerTag :: !(MVar CQ.EventDesc)\n}\n\nnewClientReaderWriter :: ClientContext -> MVar Call -> IO ClientReaderWriter\nnewClientReaderWriter ctx mcall = do\n initMD <- newIORef Nothing\n trailMD <- newIORef Nothing\n status <- newEmptyMVar\n statusEvent <- newEmptyMVar\n return (ClientReaderWriter ctx mcall initMD trailMD status statusEvent)\n\ndata OpX = forall t. OpX (OpT t)\n\ndata OpArray = OpArray { opArrPtr :: !GrpcOpPtr\n , opArrLen :: !CULong\n , opArrFinishAndFree :: !(IO ())\n }\n\ntoArray :: [OpX] -> IO OpArray\ntoArray ops = do\n aptr <- C.mallocBytes (length ops * {#sizeof grpc_op#})\n let ptrs = iterate (`C.plusPtr` {#sizeof grpc_op#}) aptr\n ops' = concatMap (\\(OpX op) -> opAdd op) ops\n free = C.free aptr >> sequence_ (map (\\(OpX op) -> opFinish op) ops)\n write op p = do\n {#set grpc_op->flags#} p 0\n {#set grpc_op->reserved#} p C.nullPtr\n op p\n zipWithM_ write ops' ptrs\n return $! OpArray aptr (fromIntegral $ length ops) free\n\ncallBatch :: ClientReaderWriter -> [OpX] -> IO (RpcReply ())\ncallBatch crw ops = do\n let ctx = context crw\n arr <- toArray ops\n let onBatchComplete = opArrFinishAndFree arr\n CQ.withEvent (ccWorker ctx) onBatchComplete $ \\eDesc -> do\n callStatus <- withMVar (callMVar_ crw) $ \\call ->\n grpcCallStartBatch call (opArrPtr arr) (opArrLen arr) (CQ.eventTag eDesc) reservedPtr\n case callStatus of\n CallOk -> do\n e <- CQ.interruptibleWaitEvent eDesc\n case e of\n QueueOpComplete OpSuccess _ -> return (RpcOk ())\n QueueOpComplete OpError _ -> return (RpcError (Error \"callBatch: op error\"))\n QueueTimeOut -> return (RpcError DeadlineExceeded)\n QueueShutdown -> return (RpcError (Error \"queue shutdown\"))\n _ -> do\n return (RpcError (CallErrorStatus callStatus))\n\ncallBatchStatusOnClient :: ClientReaderWriter -> IO (RpcReply ())\ncallBatchStatusOnClient crw@ClientReaderWriter{..} = do\n tag <- tryReadMVar statusFromServerTag\n case tag of\n Just _ -> return (RpcOk ()) -- already did this before\n Nothing -> do\n statusOp <- opRecvStatusOnClient crw\n arr <- toArray [ OpX statusOp ]\n let onBatchComplete = opArrFinishAndFree arr\n eDesc <- CQ.allocateEvent (ccWorker context) onBatchComplete\n putMVar statusFromServerTag eDesc\n callStatus <- withMVar callMVar_ $ \\call ->\n grpcCallStartBatch call (opArrPtr arr) (opArrLen arr) (CQ.eventTag eDesc) reservedPtr\n case callStatus of\n CallOk -> return (RpcOk ())\n _ -> return (RpcError (CallErrorStatus callStatus))\n\ndata OpT out = Op\n { opAdd :: [Ptr GrpcOp -> IO ()]\n , opValue :: IORef out\n , opFinish :: IO ()\n }\n\nopRead :: OpT a -> IO a\nopRead op = readIORef (opValue op)\n\nopRecvInitialMetadata :: ClientReaderWriter -> IO (OpT [Metadata])\nopRecvInitialMetadata crw = do\n arr <- mallocMetadataArray\n value <- newIORef (error \"opRecvInitialMetadata never finished\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvInitialMetadata))\n {#set grpc_op->data.recv_initial_metadata.recv_initial_metadata#} p arr\n ]\n finish = do\n mds <- readMetadataArray arr\n writeIORef (initialMDRef crw) (Just mds)\n writeIORef value mds\n freeMetadataArray arr\n return (Op add value finish)\n\nopSendMessage :: B.ByteString -> IO (OpT ())\nopSendMessage bs = do\n bb <- fromByteString bs\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendMessage))\n {#set grpc_op->data.send_message.send_message#} p bb\n ]\n finish =\n byteBufferDestroy bb\n return (Op add value finish)\n\nopRecvMessage :: IO (OpT (Maybe L.ByteString))\nopRecvMessage = do\n bbptr <- C.malloc :: IO (Ptr (Ptr CByteBuffer))\n value <- newIORef Nothing\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvMessage))\n {#set grpc_op->data.recv_message.recv_message#} p bbptr\n ]\n finish = do\n bb <- C.peek bbptr\n C.free bbptr\n writeIORef value =<< if bb \/= C.nullPtr\n then do\n lbs <- toLazyByteString bb\n byteBufferDestroy bb\n return (Just lbs)\n else return Nothing\n return (Op add value finish)\n\nopSendInitialMetadata :: [Metadata] -> IO (OpT ())\nopSendInitialMetadata elems = do\n (mdArrPtr, free) <- mallocMetadata elems\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendInitialMetadata))\n {#set grpc_op->data.send_initial_metadata.count#} p (fromIntegral (length elems))\n {#set grpc_op->data.send_initial_metadata.metadata#} p (C.castPtr mdArrPtr)\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.is_set#} p 0\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.level#} p 0\n ]\n finish = do\n free\n return (Op add value finish)\n\ndata RpcStatus = RpcStatus [Metadata] StatusCode B.ByteString\n deriving Show\n\nopRecvStatusOnClient :: ClientReaderWriter -> IO (OpT RpcStatus)\nopRecvStatusOnClient (ClientReaderWriter{..}) = do\n trailingMetadataArrPtr <- mallocMetadataArray\n statusCodePtr <- C.malloc :: IO (Ptr StatusCodeT)\n ptrPtrStatusStr <- C.new C.nullPtr :: IO (Ptr (Ptr CChar))\n capacityPtr <- C.new 0 :: IO (Ptr SizeT)\n value <- newIORef (error \"opRecvStatusOnClient never ran\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvStatusOnClient))\n {#set grpc_op->data.recv_status_on_client.trailing_metadata#} p trailingMetadataArrPtr\n {#set grpc_op->data.recv_status_on_client.status#} p statusCodePtr\n {#set grpc_op->data.recv_status_on_client.status_details#} p ptrPtrStatusStr\n {#set grpc_op->data.recv_status_on_client.status_details_capacity#} p capacityPtr\n ]\n finish = do\n trailingMd <- readMetadataArray trailingMetadataArrPtr\n statusCode <- fmap toStatusCode (C.peek statusCodePtr)\n statusDetails <- B.packCString =<< C.peek ptrPtrStatusStr\n let status = RpcStatus trailingMd statusCode statusDetails\n writeIORef value status\n putMVar statusFromServer status\n free\n free = do\n freeMetadataArray trailingMetadataArrPtr\n C.free statusCodePtr\n C.free ptrPtrStatusStr\n C.free capacityPtr\n return (Op add value finish)\n\nopSendCloseFromClient :: IO (OpT ())\nopSendCloseFromClient = do\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendCloseFromClient))\n ]\n finish =\n return ()\n return (Op add value finish)\n\nclientWaitForInitialMetadata :: ClientReaderWriter -> IO (RpcReply [Metadata])\nclientWaitForInitialMetadata crw@(ClientReaderWriter { .. }) = do\n initMD <- readIORef initialMDRef\n case initMD of\n Just md -> return (RpcOk md)\n Nothing -> do\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n res <- callBatch crw [ OpX recvInitialMetadataOp ]\n case res of\n RpcOk _ -> do\n md <- opRead recvInitialMetadataOp\n writeIORef initialMDRef (Just md)\n return (RpcOk md)\n RpcError err ->\n return (RpcError err)\n\nclientReadInitialMetadata :: ClientReaderWriter -> IO (RpcReply (Maybe [Metadata]))\nclientReadInitialMetadata (ClientReaderWriter {..}) = do\n md <- readIORef initialMDRef\n return (RpcOk md)\n\nclientRead :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nclientRead crw = do\n _ <- clientWaitForInitialMetadata crw\n recvMessage crw\n\nrecvMessage :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nrecvMessage crw = do\n recvMessageOp <- opRecvMessage\n res <- callBatch crw [ OpX recvMessageOp ]\n case res of\n RpcOk _ -> do\n bs <- opRead recvMessageOp\n return (RpcOk bs)\n RpcError err -> do\n putStrLn \"recvMessage: callBatch failed\"\n return (RpcError err)\n\nclientWaitForStatus :: ClientReaderWriter -> IO (RpcReply RpcStatus)\nclientWaitForStatus ClientReaderWriter{..} = do\n status <- readMVar statusFromServer\n return (RpcOk status)\n\nclientWrite :: ClientReaderWriter -> B.ByteString -> IO (RpcReply ())\nclientWrite crw@(ClientReaderWriter{..}) arg = do\n sendMessageOp <- opSendMessage arg\n callBatch crw [ OpX sendMessageOp ]\n\nclientSendHalfClose :: ClientReaderWriter -> IO (RpcReply ())\nclientSendHalfClose crw@(ClientReaderWriter{..}) = do\n sendCloseOp <- opSendCloseFromClient\n callBatch crw [ OpX sendCloseOp ]\n\nclientCloseCall :: ClientReaderWriter -> IO ()\nclientCloseCall ClientReaderWriter{..} = do\n tag <- tryTakeMVar statusFromServerTag\n case tag of\n Nothing -> return ()\n Just eDesc ->\n CQ.releaseEvent (ccWorker context) eDesc\n modifyMVar_ callMVar_ $ \\call -> do\n grpcCallDestroy call\n return (error \"grpcCallDestroy called on this Call\")\n\nclientCancelCall :: ClientReaderWriter -> IO (RpcReply ())\nclientCancelCall ClientReaderWriter{..} = do\n err <- withMVar callMVar_ $ \\call -> do\n grpcCallCancel call reservedPtr\n case err of\n CallOk -> return (RpcOk ())\n _ -> return (RpcError (CallErrorStatus err))\n\nclientCancelCallWithStatus :: ClientReaderWriter -> StatusCode -> B.ByteString -> IO (RpcReply ())\nclientCancelCallWithStatus ClientReaderWriter{..} status details = do\n err <- withMVar callMVar_ $ \\call -> do\n grpcCallCancelWithStatus call status details reservedPtr\n case err of\n CallOk -> return (RpcOk ())\n _ -> return (RpcError (CallErrorStatus err))\n\ntype Rpc a = ExceptT RpcError IO a\n\njoinReply :: RpcReply a -> Rpc a\njoinReply (RpcOk a) = return a\njoinReply (RpcError err) = throwE err\n\nrunRpc :: Rpc a -> IO (RpcReply a)\nrunRpc m = do\n e <- runExceptT m\n case e of\n Left err -> return (RpcError err)\n Right a -> return (RpcOk a)\n\nclientRWOp :: Client req resp -> (ClientReaderWriter -> IO a) -> Rpc a\nclientRWOp client act =\n liftIO (act (clientCrw client))\n\njoinClientRWOp :: Client req resp -> (ClientReaderWriter -> IO (RpcReply a)) -> Rpc a\njoinClientRWOp client act = do\n x <- clientRWOp client act\n joinReply x\n\nbranchOnStatus :: Client req resp\n -> Rpc a\n -> Rpc a\n -> (StatusCode -> B.ByteString -> Rpc a)\n -> Rpc a\nbranchOnStatus client onProcessing onSuccess onFail = do\n status <- clientRWOp client (tryReadMVar . statusFromServer)\n case status of\n Nothing -> onProcessing\n Just (RpcStatus _ code msg)\n | code == StatusOk -> onSuccess\n | otherwise -> onFail code msg\n\nthrowIfErrorStatus :: Client req resp -> Rpc ()\nthrowIfErrorStatus client =\n branchOnStatus\n client\n (return ())\n (return ())\n (\\code msg -> throwE (StatusError code msg))\n\ninitialMetadata :: Client req resp -> Rpc [Metadata]\ninitialMetadata client = do\n status <- clientRWOp client (readIORef . initialMDRef)\n case status of\n Just md -> return md\n Nothing ->\n branchOnStatus\n client\n (joinClientRWOp client clientWaitForInitialMetadata)\n (joinClientRWOp client clientWaitForInitialMetadata)\n (\\code msg -> throwE (StatusError code msg))\n\nwaitForStatus :: Client req resp -> Rpc RpcStatus\nwaitForStatus client = do\n status <- clientRWOp client (tryReadMVar . statusFromServer)\n case status of\n Nothing -> joinClientRWOp client clientWaitForStatus\n Just status' -> return status'\n\nreceiveMessage :: Client req resp -> Rpc (Maybe resp)\nreceiveMessage client = do\n let\n onProcessing = do\n msg <- joinClientRWOp client clientRead\n case msg of\n Nothing -> return Nothing\n Just x -> do\n let decoder = clientDecoder client\n liftM Just (joinReply =<< liftIO (decoder x))\n onSuccess = return Nothing\n onFail code msg = throwE (StatusError code msg)\n branchOnStatus client onProcessing onSuccess onFail\n\nreceiveAllMessages :: Client req resp -> Rpc [resp]\nreceiveAllMessages client = do\n let\n decoder = clientDecoder client\n go acc = do\n value <- joinClientRWOp client clientRead\n case value of\n Just x -> do\n y <- joinReply =<< (liftIO (decoder x))\n go (y:acc)\n Nothing -> return (reverse acc)\n go []\n\nsendMessage :: Client req resp -> req -> Rpc ()\nsendMessage client req = do\n throwIfErrorStatus client\n let encoder = clientEncoder client\n bs <- joinReply =<< liftIO (encoder req)\n joinClientRWOp client (\\crw -> clientWrite crw bs)\n\nsendHalfClose :: Client req resp -> Rpc ()\nsendHalfClose client = do\n throwIfErrorStatus client\n joinClientRWOp client clientSendHalfClose\n\ncloseCall :: Client req resp -> Rpc ()\ncloseCall client = do\n _ <- waitForStatus client\n clientRWOp client clientCloseCall\n throwIfErrorStatus client\n\n-- | Called by clients to cancel an RPC on the server.\n-- Can be called multiple times, from any thread.\ncancelCall :: Client req resp -> Rpc ()\ncancelCall client =\n branchOnStatus\n client\n (joinClientRWOp client clientCancelCall)\n (return ())\n (\\code msg -> throwE (StatusError code msg))\n\n-- | Called by clients to cancel an RPC on the server.\n-- Can be called multiple times, from any thread.\n-- If a status has not been received for the call, set it to the status code\n-- and description passed in.\n-- Importantly, this function does not send status nor description to the\n-- remote endpoint.\ncancelCallWithStatus :: Client req resp -> StatusCode -> B.ByteString -> Rpc ()\ncancelCallWithStatus client status details =\n branchOnStatus\n client\n (joinClientRWOp client (\\crw -> clientCancelCallWithStatus crw status details))\n (return ())\n (\\code msg -> throwE (StatusError code msg))\n\ndata RpcReply a\n = RpcOk a\n | RpcError RpcError\n deriving Show\n\ndata RpcError\n = DeadlineExceeded\n | Cancelled\n | Error String\n | CallErrorStatus CallError\n | StatusError StatusCode B.ByteString\n deriving Show\n","old_contents":"-- Copyright (c) 2016, Google Inc.\n-- All rights reserved.\n--\n-- Redistribution and use in source and binary forms, with or without\n-- modification, are permitted provided that the following conditions are met:\n-- * Redistributions of source code must retain the above copyright\n-- notice, this list of conditions and the following disclaimer.\n-- * Redistributions in binary form must reproduce the above copyright\n-- notice, this list of conditions and the following disclaimer in the\n-- documentation and\/or other materials provided with the distribution.\n-- * Neither the name of Google Inc. nor the\n-- names of its contributors may be used to endorse or promote products\n-- derived from this software without specific prior written permission.\n--\n-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n-- DISCLAIMED. IN NO EVENT SHALL Google Inc. BE LIABLE FOR ANY\n-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n--\n--------------------------------------------------------------------------------\n{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, ExistentialQuantification, RecordWildCards #-}\nmodule Network.Grpc.Core.Call where\n\n\nimport Control.Concurrent\nimport Control.Exception\nimport Control.Monad\n\nimport qualified Data.ByteString as B\nimport qualified Data.ByteString.Lazy as L\nimport Data.Monoid ((<>), Last(..))\nimport Data.IORef\n\nimport Foreign.C.Types as C\nimport qualified Foreign.Marshal.Alloc as C\nimport qualified Foreign.Marshal.Utils as C\nimport qualified Foreign.Ptr as C\nimport Foreign.Ptr (Ptr)\nimport qualified Foreign.Storable as C\n\n-- transformers\nimport Control.Monad.IO.Class\nimport Control.Monad.Trans.Except\n\nimport qualified Network.Grpc.CompletionQueue as CQ\nimport Network.Grpc.Lib.PropagationBits\n{#import Network.Grpc.Lib.ByteBuffer#}\n{#import Network.Grpc.Lib.Metadata#}\n{#import Network.Grpc.Lib.TimeSpec#}\n{#import Network.Grpc.Lib.Core#}\n\n\n#include \n#include \"hs_grpc.h\"\n\n{#context lib = \"grpc\" prefix = \"grpc\" #}\n\ndata Deadline\n = AbsoluteDeadline TimeSpec\n | RelativeDeadline Int -- milliseconds\n\ndata ClientContext = ClientContext\n { ccChannel :: Channel\n , ccCQ :: CompletionQueue\n , ccWorker :: CQ.Worker\n }\n\ndata CallOptions = CallOptions\n { coDeadline :: Maybe Deadline\n , coParentContext :: Maybe () -- todo\n , coPropagationMask :: Maybe PropagationMask\n , coMetadata :: [Metadata]\n }\n\ninstance Monoid CallOptions where\n mempty = CallOptions Nothing Nothing Nothing []\n mappend (CallOptions a b c d) (CallOptions a' b' c' d') =\n CallOptions\n (getLast (Last a <> Last a'))\n (getLast (Last b <> Last b'))\n (getLast (Last c <> Last c'))\n (d <> d')\n\nwithAbsoluteDeadline :: TimeSpec -> CallOptions\nwithAbsoluteDeadline deadline =\n mempty { coDeadline = Just (AbsoluteDeadline deadline) }\n\nwithRelativeDeadlineSeconds :: Int -> CallOptions\nwithRelativeDeadlineSeconds seconds =\n mempty { coDeadline = Just (RelativeDeadline (seconds*1000)) }\n\nwithRelativeDeadlineMillis :: Int -> CallOptions\nwithRelativeDeadlineMillis ms =\n mempty { coDeadline = Just (RelativeDeadline ms) }\n\nwithParentContext :: () -> CallOptions\nwithParentContext ctx =\n mempty { coParentContext = Just ctx }\n\nwithParentContextPropagating :: () -> PropagationMask -> CallOptions\nwithParentContextPropagating ctx prop =\n mempty { coParentContext = Just ctx\n , coPropagationMask = Just prop }\n\nwithMetadata :: [Metadata] -> CallOptions\nwithMetadata md =\n mempty { coMetadata = md }\n\nresolveDeadline :: CallOptions -> IO TimeSpec\nresolveDeadline co =\n case coDeadline co of\n Nothing -> return gprInfFuture\n Just (AbsoluteDeadline deadline) -> return deadline\n Just (RelativeDeadline ms) ->\n millisFromNow (fromIntegral ms)\n\nnewClientContext :: Channel -> IO ClientContext\nnewClientContext chan = do\n cq <- completionQueueCreate reservedPtr\n cqt <- CQ.startCompletionQueueThread cq\n return (ClientContext chan cq cqt)\n\ndestroyClientContext :: ClientContext -> IO ()\ndestroyClientContext (ClientContext _ cq w) = do\n completionQueueShutdown cq\n CQ.waitWorkerTermination w\n\ntype MethodName = B.ByteString\ntype Arg = B.ByteString\n\n-- | Run the IO function once, cache it in the MVar.\nonceMVar :: MVar (Maybe a) -> IO a -> IO a\nonceMVar mvar io = modifyMVar mvar $ \\x ->\n case x of\n Just x' -> return (x, x')\n Nothing -> do\n x' <- io\n return (Just x', x')\n\nreservedPtr :: Ptr ()\nreservedPtr = C.nullPtr\n\ndata UnaryResult a = UnaryResult [Metadata] [Metadata] a deriving Show\n\ncallUnary :: ClientContext -> CallOptions -> MethodName -> Arg -> IO (RpcReply (UnaryResult L.ByteString))\ncallUnary ctx@(ClientContext chan cq _) co method arg = do\n deadline <- resolveDeadline co\n bracket (grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline) grpcCallDestroy $ \\call0 -> newMVar call0 >>= \\mcall -> do\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n recvStatusOp <- opRecvStatusOnClient crw\n recvMessageOp <- opRecvMessage\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX recvInitialMetadataOp\n , OpX recvMessageOp\n , OpX sendMessageOp\n , OpX recvStatusOp\n ]\n case res of\n RpcOk _ -> do\n (RpcStatus trailMD status statusDetails) <- opRead recvStatusOp\n case status of\n StatusOk -> do\n initMD <- opRead recvInitialMetadataOp\n answ <- opRead recvMessageOp\n let answ' = maybe L.empty id answ\n return (RpcOk (UnaryResult initMD trailMD answ'))\n _ -> return (RpcError (StatusError status statusDetails))\n RpcError err -> return (RpcError err)\n\ncallDownstream :: ClientContext -> CallOptions -> MethodName -> Arg -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallDownstream ctx@(ClientContext chan cq _) co method arg = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n sendCloseOp <- opSendCloseFromClient\n sendMessageOp <- opSendMessage arg\n\n res <- callBatch crw [\n OpX sendInitOp\n , OpX sendCloseOp\n , OpX sendMessageOp\n ]\n case res of\n RpcOk _ -> do\n res' <- callBatchStatusOnClient crw\n case res' of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n RpcError err -> return (RpcError err)\n\ncallUpstream :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallUpstream ctx@(ClientContext chan cq _) co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n crw <- newClientReaderWriter ctx mcall\n\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> do\n res' <- callBatchStatusOnClient crw\n case res' of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n RpcError err -> return (RpcError err)\n\ncallBidi :: ClientContext -> CallOptions -> MethodName -> IO (RpcReply (Client B.ByteString L.ByteString))\ncallBidi ctx@(ClientContext chan cq _) co method = do\n deadline <- resolveDeadline co\n mcall <- grpcChannelCreateCall (cChannel chan) C.nullPtr propagateDefaults cq method (cHost chan) deadline >>= newMVar\n\n crw <- newClientReaderWriter ctx mcall\n sendInitOp <- opSendInitialMetadata (coMetadata co)\n\n res <- callBatch crw [ OpX sendInitOp ]\n case res of\n RpcOk _ -> do\n res' <- callBatchStatusOnClient crw\n case res' of\n RpcOk _ -> return (RpcOk (Client crw defaultEncoder defaultDecoder))\n RpcError err -> return (RpcError err)\n RpcError err -> return (RpcError err)\n\ndata Client req resp = Client\n { clientCrw :: ClientReaderWriter\n , clientEncoder :: Encoder req\n , clientDecoder :: Decoder resp\n }\n\ntype Decoder a = L.ByteString -> IO (RpcReply a)\ntype Encoder a = a -> IO (RpcReply B.ByteString)\n\ndefaultDecoder :: L.ByteString -> IO (RpcReply L.ByteString)\ndefaultDecoder bs = return (RpcOk bs)\n\ndefaultEncoder :: B.ByteString -> IO (RpcReply B.ByteString)\ndefaultEncoder bs = return (RpcOk bs)\n\ndata ClientReaderWriter = ClientReaderWriter {\n context :: ClientContext,\n callMVar_ :: MVar Call,\n initialMDRef :: !(IORef (Maybe [Metadata])),\n trailingMDRef :: !(IORef (Maybe [Metadata])),\n statusFromServer :: !(MVar RpcStatus),\n statusFromServerTag :: !(MVar CQ.EventDesc)\n}\n\nnewClientReaderWriter :: ClientContext -> MVar Call -> IO ClientReaderWriter\nnewClientReaderWriter ctx mcall = do\n initMD <- newIORef Nothing\n trailMD <- newIORef Nothing\n status <- newEmptyMVar\n statusEvent <- newEmptyMVar\n return (ClientReaderWriter ctx mcall initMD trailMD status statusEvent)\n\ndata OpX = forall t. OpX (OpT t)\n\ndata OpArray = OpArray { opArrPtr :: !GrpcOpPtr\n , opArrLen :: !CULong\n , opArrFinishAndFree :: !(IO ())\n }\n\ntoArray :: [OpX] -> IO OpArray\ntoArray ops = do\n aptr <- C.mallocBytes (length ops * {#sizeof grpc_op#})\n let ptrs = iterate (`C.plusPtr` {#sizeof grpc_op#}) aptr\n ops' = concatMap (\\(OpX op) -> opAdd op) ops\n free = C.free aptr >> sequence_ (map (\\(OpX op) -> opFinish op) ops)\n write op p = do\n {#set grpc_op->flags#} p 0\n {#set grpc_op->reserved#} p C.nullPtr\n op p\n zipWithM_ write ops' ptrs\n return $! OpArray aptr (fromIntegral $ length ops) free\n\ncallBatch :: ClientReaderWriter -> [OpX] -> IO (RpcReply ())\ncallBatch crw ops = do\n let ctx = context crw\n arr <- toArray ops\n let onBatchComplete = opArrFinishAndFree arr\n CQ.withEvent (ccWorker ctx) onBatchComplete $ \\eDesc -> do\n callStatus <- withMVar (callMVar_ crw) $ \\call ->\n grpcCallStartBatch call (opArrPtr arr) (opArrLen arr) (CQ.eventTag eDesc) reservedPtr\n case callStatus of\n CallOk -> do\n e <- CQ.interruptibleWaitEvent eDesc\n case e of\n QueueOpComplete OpSuccess _ -> return (RpcOk ())\n QueueOpComplete OpError _ -> return (RpcError (Error \"callBatch: op error\"))\n QueueTimeOut -> return (RpcError DeadlineExceeded)\n QueueShutdown -> return (RpcError (Error \"queue shutdown\"))\n _ -> do\n return (RpcError (CallErrorStatus callStatus))\n\ncallBatchStatusOnClient :: ClientReaderWriter -> IO (RpcReply ())\ncallBatchStatusOnClient crw@ClientReaderWriter{..} = do\n tag <- tryReadMVar statusFromServerTag\n case tag of\n Just _ -> return (RpcOk ()) -- already did this before\n Nothing -> do\n statusOp <- opRecvStatusOnClient crw\n arr <- toArray [ OpX statusOp ]\n let onBatchComplete = opArrFinishAndFree arr\n eDesc <- CQ.allocateEvent (ccWorker context) onBatchComplete\n putMVar statusFromServerTag eDesc\n callStatus <- withMVar callMVar_ $ \\call ->\n grpcCallStartBatch call (opArrPtr arr) (opArrLen arr) (CQ.eventTag eDesc) reservedPtr\n case callStatus of\n CallOk -> return (RpcOk ())\n _ -> return (RpcError (CallErrorStatus callStatus))\n\ndata OpT out = Op\n { opAdd :: [Ptr GrpcOp -> IO ()]\n , opValue :: IORef out\n , opFinish :: IO ()\n }\n\nopRead :: OpT a -> IO a\nopRead op = readIORef (opValue op)\n\nopRecvInitialMetadata :: ClientReaderWriter -> IO (OpT [Metadata])\nopRecvInitialMetadata crw = do\n arr <- mallocMetadataArray\n value <- newIORef (error \"opRecvInitialMetadata never finished\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvInitialMetadata))\n {#set grpc_op->data.recv_initial_metadata#} p arr\n ]\n finish = do\n mds <- readMetadataArray arr\n writeIORef (initialMDRef crw) (Just mds)\n writeIORef value mds\n freeMetadataArray arr\n return (Op add value finish)\n\nopSendMessage :: B.ByteString -> IO (OpT ())\nopSendMessage bs = do\n bb <- fromByteString bs\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendMessage))\n {#set grpc_op->data.send_message#} p bb\n ]\n finish =\n byteBufferDestroy bb\n return (Op add value finish)\n\nopRecvMessage :: IO (OpT (Maybe L.ByteString))\nopRecvMessage = do\n bbptr <- C.malloc :: IO (Ptr (Ptr CByteBuffer))\n value <- newIORef Nothing\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvMessage))\n {#set grpc_op->data.recv_message#} p bbptr\n ]\n finish = do\n bb <- C.peek bbptr\n C.free bbptr\n writeIORef value =<< if bb \/= C.nullPtr\n then do\n lbs <- toLazyByteString bb\n byteBufferDestroy bb\n return (Just lbs)\n else return Nothing\n return (Op add value finish)\n\nopSendInitialMetadata :: [Metadata] -> IO (OpT ())\nopSendInitialMetadata elems = do\n (mdArrPtr, free) <- mallocMetadata elems\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendInitialMetadata))\n {#set grpc_op->data.send_initial_metadata.count#} p (fromIntegral (length elems))\n {#set grpc_op->data.send_initial_metadata.metadata#} p (C.castPtr mdArrPtr)\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.is_set#} p 0\n {#set grpc_op->data.send_initial_metadata.maybe_compression_level.level#} p 0\n ]\n finish = do\n free\n return (Op add value finish)\n\ndata RpcStatus = RpcStatus [Metadata] StatusCode B.ByteString\n deriving Show\n\nopRecvStatusOnClient :: ClientReaderWriter -> IO (OpT RpcStatus)\nopRecvStatusOnClient (ClientReaderWriter{..}) = do\n trailingMetadataArrPtr <- mallocMetadataArray\n statusCodePtr <- C.malloc :: IO (Ptr StatusCodeT)\n ptrPtrStatusStr <- C.new C.nullPtr :: IO (Ptr (Ptr CChar))\n capacityPtr <- C.new 0 :: IO (Ptr SizeT)\n value <- newIORef (error \"opRecvStatusOnClient never ran\")\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpRecvStatusOnClient))\n {#set grpc_op->data.recv_status_on_client.trailing_metadata#} p trailingMetadataArrPtr\n {#set grpc_op->data.recv_status_on_client.status#} p statusCodePtr\n {#set grpc_op->data.recv_status_on_client.status_details#} p ptrPtrStatusStr\n {#set grpc_op->data.recv_status_on_client.status_details_capacity#} p capacityPtr\n ]\n finish = do\n trailingMd <- readMetadataArray trailingMetadataArrPtr\n statusCode <- fmap toStatusCode (C.peek statusCodePtr)\n statusDetails <- B.packCString =<< C.peek ptrPtrStatusStr\n let status = RpcStatus trailingMd statusCode statusDetails\n writeIORef value status\n putMVar statusFromServer status\n free\n free = do\n freeMetadataArray trailingMetadataArrPtr\n C.free statusCodePtr\n C.free ptrPtrStatusStr\n C.free capacityPtr\n return (Op add value finish)\n\nopSendCloseFromClient :: IO (OpT ())\nopSendCloseFromClient = do\n value <- newIORef ()\n let\n add =\n [ \\p -> do\n {#set grpc_op->op#} p (fromIntegral (fromEnum OpSendCloseFromClient))\n ]\n finish =\n return ()\n return (Op add value finish)\n\nclientWaitForInitialMetadata :: ClientReaderWriter -> IO (RpcReply [Metadata])\nclientWaitForInitialMetadata crw@(ClientReaderWriter { .. }) = do\n initMD <- readIORef initialMDRef\n case initMD of\n Just md -> return (RpcOk md)\n Nothing -> do\n recvInitialMetadataOp <- opRecvInitialMetadata crw\n res <- callBatch crw [ OpX recvInitialMetadataOp ]\n case res of\n RpcOk _ -> do\n md <- opRead recvInitialMetadataOp\n writeIORef initialMDRef (Just md)\n return (RpcOk md)\n RpcError err ->\n return (RpcError err)\n\nclientReadInitialMetadata :: ClientReaderWriter -> IO (RpcReply (Maybe [Metadata]))\nclientReadInitialMetadata (ClientReaderWriter {..}) = do\n md <- readIORef initialMDRef\n return (RpcOk md)\n\nclientRead :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nclientRead crw = do\n _ <- clientWaitForInitialMetadata crw\n recvMessage crw\n\nrecvMessage :: ClientReaderWriter -> IO (RpcReply (Maybe L.ByteString))\nrecvMessage crw = do\n recvMessageOp <- opRecvMessage\n res <- callBatch crw [ OpX recvMessageOp ]\n case res of\n RpcOk _ -> do\n bs <- opRead recvMessageOp\n return (RpcOk bs)\n RpcError err -> do\n putStrLn \"recvMessage: callBatch failed\"\n return (RpcError err)\n\nclientWaitForStatus :: ClientReaderWriter -> IO (RpcReply RpcStatus)\nclientWaitForStatus ClientReaderWriter{..} = do\n status <- readMVar statusFromServer\n return (RpcOk status)\n\nclientWrite :: ClientReaderWriter -> B.ByteString -> IO (RpcReply ())\nclientWrite crw@(ClientReaderWriter{..}) arg = do\n sendMessageOp <- opSendMessage arg\n callBatch crw [ OpX sendMessageOp ]\n\nclientSendHalfClose :: ClientReaderWriter -> IO (RpcReply ())\nclientSendHalfClose crw@(ClientReaderWriter{..}) = do\n sendCloseOp <- opSendCloseFromClient\n callBatch crw [ OpX sendCloseOp ]\n\nclientCloseCall :: ClientReaderWriter -> IO ()\nclientCloseCall ClientReaderWriter{..} = do\n tag <- tryTakeMVar statusFromServerTag\n case tag of\n Nothing -> return ()\n Just eDesc ->\n CQ.releaseEvent (ccWorker context) eDesc\n modifyMVar_ callMVar_ $ \\call -> do\n grpcCallDestroy call\n return (error \"grpcCallDestroy called on this Call\")\n\nclientCancelCall :: ClientReaderWriter -> IO (RpcReply ())\nclientCancelCall ClientReaderWriter{..} = do\n err <- withMVar callMVar_ $ \\call -> do\n grpcCallCancel call reservedPtr\n case err of\n CallOk -> return (RpcOk ())\n _ -> return (RpcError (CallErrorStatus err))\n\nclientCancelCallWithStatus :: ClientReaderWriter -> StatusCode -> B.ByteString -> IO (RpcReply ())\nclientCancelCallWithStatus ClientReaderWriter{..} status details = do\n err <- withMVar callMVar_ $ \\call -> do\n grpcCallCancelWithStatus call status details reservedPtr\n case err of\n CallOk -> return (RpcOk ())\n _ -> return (RpcError (CallErrorStatus err))\n\ntype Rpc a = ExceptT RpcError IO a\n\njoinReply :: RpcReply a -> Rpc a\njoinReply (RpcOk a) = return a\njoinReply (RpcError err) = throwE err\n\nrunRpc :: Rpc a -> IO (RpcReply a)\nrunRpc m = do\n e <- runExceptT m\n case e of\n Left err -> return (RpcError err)\n Right a -> return (RpcOk a)\n\nclientRWOp :: Client req resp -> (ClientReaderWriter -> IO a) -> Rpc a\nclientRWOp client act =\n liftIO (act (clientCrw client))\n\njoinClientRWOp :: Client req resp -> (ClientReaderWriter -> IO (RpcReply a)) -> Rpc a\njoinClientRWOp client act = do\n x <- clientRWOp client act\n joinReply x\n\nbranchOnStatus :: Client req resp\n -> Rpc a\n -> Rpc a\n -> (StatusCode -> B.ByteString -> Rpc a)\n -> Rpc a\nbranchOnStatus client onProcessing onSuccess onFail = do\n status <- clientRWOp client (tryReadMVar . statusFromServer)\n case status of\n Nothing -> onProcessing\n Just (RpcStatus _ code msg)\n | code == StatusOk -> onSuccess\n | otherwise -> onFail code msg\n\nthrowIfErrorStatus :: Client req resp -> Rpc ()\nthrowIfErrorStatus client =\n branchOnStatus\n client\n (return ())\n (return ())\n (\\code msg -> throwE (StatusError code msg))\n\ninitialMetadata :: Client req resp -> Rpc [Metadata]\ninitialMetadata client = do\n status <- clientRWOp client (readIORef . initialMDRef)\n case status of\n Just md -> return md\n Nothing ->\n branchOnStatus\n client\n (joinClientRWOp client clientWaitForInitialMetadata)\n (joinClientRWOp client clientWaitForInitialMetadata)\n (\\code msg -> throwE (StatusError code msg))\n\nwaitForStatus :: Client req resp -> Rpc RpcStatus\nwaitForStatus client = do\n status <- clientRWOp client (tryReadMVar . statusFromServer)\n case status of\n Nothing -> joinClientRWOp client clientWaitForStatus\n Just status' -> return status'\n\nreceiveMessage :: Client req resp -> Rpc (Maybe resp)\nreceiveMessage client = do\n let\n onProcessing = do\n msg <- joinClientRWOp client clientRead\n case msg of\n Nothing -> return Nothing\n Just x -> do\n let decoder = clientDecoder client\n liftM Just (joinReply =<< liftIO (decoder x))\n onSuccess = return Nothing\n onFail code msg = throwE (StatusError code msg)\n branchOnStatus client onProcessing onSuccess onFail\n\nreceiveAllMessages :: Client req resp -> Rpc [resp]\nreceiveAllMessages client = do\n let\n decoder = clientDecoder client\n go acc = do\n value <- joinClientRWOp client clientRead\n case value of\n Just x -> do\n y <- joinReply =<< (liftIO (decoder x))\n go (y:acc)\n Nothing -> return (reverse acc)\n go []\n\nsendMessage :: Client req resp -> req -> Rpc ()\nsendMessage client req = do\n throwIfErrorStatus client\n let encoder = clientEncoder client\n bs <- joinReply =<< liftIO (encoder req)\n joinClientRWOp client (\\crw -> clientWrite crw bs)\n\nsendHalfClose :: Client req resp -> Rpc ()\nsendHalfClose client = do\n throwIfErrorStatus client\n joinClientRWOp client clientSendHalfClose\n\ncloseCall :: Client req resp -> Rpc ()\ncloseCall client = do\n _ <- waitForStatus client\n clientRWOp client clientCloseCall\n throwIfErrorStatus client\n\n-- | Called by clients to cancel an RPC on the server.\n-- Can be called multiple times, from any thread.\ncancelCall :: Client req resp -> Rpc ()\ncancelCall client =\n branchOnStatus\n client\n (joinClientRWOp client clientCancelCall)\n (return ())\n (\\code msg -> throwE (StatusError code msg))\n\n-- | Called by clients to cancel an RPC on the server.\n-- Can be called multiple times, from any thread.\n-- If a status has not been received for the call, set it to the status code\n-- and description passed in.\n-- Importantly, this function does not send status nor description to the\n-- remote endpoint.\ncancelCallWithStatus :: Client req resp -> StatusCode -> B.ByteString -> Rpc ()\ncancelCallWithStatus client status details =\n branchOnStatus\n client\n (joinClientRWOp client (\\crw -> clientCancelCallWithStatus crw status details))\n (return ())\n (\\code msg -> throwE (StatusError code msg))\n\ndata RpcReply a\n = RpcOk a\n | RpcError RpcError\n deriving Show\n\ndata RpcError\n = DeadlineExceeded\n | Cancelled\n | Error String\n | CallErrorStatus CallError\n | StatusError StatusCode B.ByteString\n deriving Show\n","returncode":0,"stderr":"","license":"apache-2.0","lang":"C2hs Haskell"}
{"commit":"117d44d2c265162417f0e895bb2d42ec1f875e48","subject":"explicitly use C types when determining sizeOf function parameters","message":"explicitly use C types when determining sizeOf function parameters\n\nIgnore-this: 5929708505eb782810268bb4c53c12cf\n\ndarcs-hash:20100217012520-dcabc-555aaaa23a760533925b465769b4d2227c5f2da5.gz\n","repos":"mwu-tow\/cuda,phaazon\/cuda,phaazon\/cuda,phaazon\/cuda","old_file":"Foreign\/CUDA\/Driver\/Exec.chs","new_file":"Foreign\/CUDA\/Driver\/Exec.chs","new_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Exec\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Kernel execution control for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Exec\n (\n Fun(Fun), -- need to export the data constructor for use by Module )=\n FunParam(..), FunAttribute(..),\n requires, setBlockShape, setSharedSize, setParams, launch\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Stream (Stream(..))\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad (zipWithM_)\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A @__global__@ device function\n--\nnewtype Fun = Fun { useFun :: {# type CUfunction #}}\n\n\n-- |\n-- Function attributes\n--\n{# enum CUfunction_attribute as FunAttribute\n { underscoreToCase\n , MAX_THREADS_PER_BLOCK as MaxKernelThreadsPerBlock }\n with prefix=\"CU_FUNC_ATTRIBUTE\" deriving (Eq, Show) #}\n\n\n-- |\n-- Kernel function parameters\n--\ndata Storable a => FunParam a\n = IArg Int\n | FArg Float\n | VArg a\n-- | TArg Texture\n\n--------------------------------------------------------------------------------\n-- Execution Control\n--------------------------------------------------------------------------------\n\n-- |\n-- Returns the value of the selected attribute requirement for the given kernel\n--\nrequires :: Fun -> FunAttribute -> IO Int\nrequires fn att = resultIfOk =<< cuFuncGetAttribute att fn\n\n{# fun unsafe cuFuncGetAttribute\n { alloca- `Int' peekIntConv*\n , cFromEnum `FunAttribute'\n , useFun `Fun' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the (x,y,z) dimensions of the thread blocks that are created when the\n-- given kernel function is lanched\n--\nsetBlockShape :: Fun -> (Int,Int,Int) -> IO ()\nsetBlockShape fn (x,y,z) = nothingIfOk =<< cuFuncSetBlockShape fn x y z\n\n{# fun unsafe cuFuncSetBlockShape\n { useFun `Fun'\n , `Int'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set the number of bytes of dynamic shared memory to be available to each\n-- thread block when the function is launched\n--\nsetSharedSize :: Fun -> Integer -> IO ()\nsetSharedSize fn bytes = nothingIfOk =<< cuFuncSetSharedSize fn bytes\n\n{# fun unsafe cuFuncSetSharedSize\n { useFun `Fun'\n , cIntConv `Integer' } -> `Status' cToEnum #}\n\n\n-- |\n-- Invoke the kernel on a size (w,h) grid of blocks. Each block contains the\n-- number of threads specified by a previous call to `setBlockShape'. The launch\n-- may also be associated with a specific `Stream'.\n--\nlaunch :: Fun -> (Int,Int) -> Maybe Stream -> IO ()\nlaunch fn (w,h) mst =\n nothingIfOk =<< case mst of\n Nothing -> cuLaunchGridAsync fn w h (Stream nullPtr)\n Just st -> cuLaunchGridAsync fn w h st\n\n{# fun unsafe cuLaunchGridAsync\n { useFun `Fun'\n , `Int'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Kernel function parameters\n--------------------------------------------------------------------------------\n\n-- |\n-- Set the parameters that will specified next time the kernel is invoked\n--\nsetParams :: Storable a => Fun -> [FunParam a] -> IO ()\nsetParams fn prs = do\n zipWithM_ (set fn) offsets prs\n nothingIfOk =<< cuParamSetSize fn (last offsets)\n where\n offsets = scanl (\\a b -> a + size b) 0 prs\n\n size (IArg _) = sizeOf (undefined::CUInt)\n size (FArg _) = sizeOf (undefined::CFloat)\n size (VArg v) = sizeOf v\n\n set f o (IArg v) = nothingIfOk =<< cuParamSeti f o v\n set f o (FArg v) = nothingIfOk =<< cuParamSetf f o v\n set f o (VArg v) = with v $ \\p -> (nothingIfOk =<< cuParamSetv f o p (sizeOf v))\n\n\n{# fun unsafe cuParamSetSize\n { useFun `Fun'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSeti\n { useFun `Fun'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSetf\n { useFun `Fun'\n , `Int'\n , `Float' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSetv\n `Storable a' =>\n { useFun `Fun'\n , `Int'\n , castPtr `Ptr a'\n , `Int' } -> `Status' cToEnum #}\n\n","old_contents":"{-# LANGUAGE ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Exec\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- Kernel execution control for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Exec\n (\n Fun(Fun), -- need to export the data constructor for use by Module )=\n FunParam(..), FunAttribute(..),\n requires, setBlockShape, setSharedSize, setParams, launch\n )\n where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Stream (Stream(..))\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Control.Monad (zipWithM_)\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A @__global__@ device function\n--\nnewtype Fun = Fun { useFun :: {# type CUfunction #}}\n\n\n-- |\n-- Function attributes\n--\n{# enum CUfunction_attribute as FunAttribute\n { underscoreToCase\n , MAX_THREADS_PER_BLOCK as MaxKernelThreadsPerBlock }\n with prefix=\"CU_FUNC_ATTRIBUTE\" deriving (Eq, Show) #}\n\n\n-- |\n-- Kernel function parameters\n--\ndata Storable a => FunParam a\n = IArg Int\n | FArg Float\n | VArg a\n-- | TArg Texture\n\n--------------------------------------------------------------------------------\n-- Execution Control\n--------------------------------------------------------------------------------\n\n-- |\n-- Returns the value of the selected attribute requirement for the given kernel\n--\nrequires :: Fun -> FunAttribute -> IO Int\nrequires fn att = resultIfOk =<< cuFuncGetAttribute att fn\n\n{# fun unsafe cuFuncGetAttribute\n { alloca- `Int' peekIntConv*\n , cFromEnum `FunAttribute'\n , useFun `Fun' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the (x,y,z) dimensions of the thread blocks that are created when the\n-- given kernel function is lanched\n--\nsetBlockShape :: Fun -> (Int,Int,Int) -> IO ()\nsetBlockShape fn (x,y,z) = nothingIfOk =<< cuFuncSetBlockShape fn x y z\n\n{# fun unsafe cuFuncSetBlockShape\n { useFun `Fun'\n , `Int'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set the number of bytes of dynamic shared memory to be available to each\n-- thread block when the function is launched\n--\nsetSharedSize :: Fun -> Integer -> IO ()\nsetSharedSize fn bytes = nothingIfOk =<< cuFuncSetSharedSize fn bytes\n\n{# fun unsafe cuFuncSetSharedSize\n { useFun `Fun'\n , cIntConv `Integer' } -> `Status' cToEnum #}\n\n\n-- |\n-- Invoke the kernel on a size (w,h) grid of blocks. Each block contains the\n-- number of threads specified by a previous call to `setBlockShape'. The launch\n-- may also be associated with a specific `Stream'.\n--\nlaunch :: Fun -> (Int,Int) -> Maybe Stream -> IO ()\nlaunch fn (w,h) mst =\n nothingIfOk =<< case mst of\n Nothing -> cuLaunchGridAsync fn w h (Stream nullPtr)\n Just st -> cuLaunchGridAsync fn w h st\n\n{# fun unsafe cuLaunchGridAsync\n { useFun `Fun'\n , `Int'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n--------------------------------------------------------------------------------\n-- Kernel function parameters\n--------------------------------------------------------------------------------\n\n-- |\n-- Set the parameters that will specified next time the kernel is invoked\n--\nsetParams :: Storable a => Fun -> [FunParam a] -> IO ()\nsetParams fn prs = do\n zipWithM_ (set fn) offsets prs\n nothingIfOk =<< cuParamSetSize fn (last offsets)\n where\n offsets = scanl (\\a b -> a + size b) 0 prs\n\n size (IArg v) = sizeOf v\n size (FArg v) = sizeOf v\n size (VArg v) = sizeOf v\n\n set f o (IArg v) = nothingIfOk =<< cuParamSeti f o v\n set f o (FArg v) = nothingIfOk =<< cuParamSetf f o v\n set f o (VArg v) = with v $ \\p -> (nothingIfOk =<< cuParamSetv f o p (sizeOf v))\n\n\n{# fun unsafe cuParamSetSize\n { useFun `Fun'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSeti\n { useFun `Fun'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSetf\n { useFun `Fun'\n , `Int'\n , `Float' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSetv\n `Storable a' =>\n { useFun `Fun'\n , `Int'\n , castPtr `Ptr a'\n , `Int' } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"d7af7480573b95648c995633b9dc9c776a18bd16","subject":"allow sizeOf to evaluate its argument in launchKernel","message":"allow sizeOf to evaluate its argument in launchKernel\n","repos":"phaazon\/cuda,phaazon\/cuda,phaazon\/cuda,mwu-tow\/cuda","old_file":"Foreign\/CUDA\/Driver\/Exec.chs","new_file":"Foreign\/CUDA\/Driver\/Exec.chs","new_contents":"{-# LANGUAGE GADTs, CPP, ForeignFunctionInterface, EmptyDataDecls #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Exec\n-- Copyright : (c) [2009..2011] Trevor L. McDonell\n-- License : BSD\n--\n-- Kernel execution control for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Exec (\n\n -- * Kernel Execution\n Fun(Fun), FunParam(..), FunAttribute(..), CacheConfig(..),\n requires, setBlockShape, setSharedSize, setParams, setCacheConfigFun,\n launch, launchKernel, launchKernel'\n\n) where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Stream (Stream(..))\nimport Foreign.CUDA.Driver.Texture (Texture(..))\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Data.Maybe\nimport Control.Monad (zipWithM_)\n\n\n#if CUDA_VERSION >= 3020\n{-# DEPRECATED TArg \"as of CUDA version 3.2\" #-}\n#endif\n#if CUDA_VERSION >= 4000\n{-# DEPRECATED setBlockShape, setSharedSize, setParams, launch\n \"use launchKernel instead\" #-}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A @__global__@ device function\n--\nnewtype Fun = Fun { useFun :: {# type CUfunction #}}\n\n\n-- |\n-- Function attributes\n--\n{# enum CUfunction_attribute as FunAttribute\n { underscoreToCase\n , MAX_THREADS_PER_BLOCK as MaxKernelThreadsPerBlock }\n with prefix=\"CU_FUNC_ATTRIBUTE\" deriving (Eq, Show) #}\n\n-- |\n-- Cache configuration preference\n--\n#if CUDA_VERSION < 3000\ndata CacheConfig\n#else\n{# enum CUfunc_cache_enum as CacheConfig\n { underscoreToCase }\n with prefix=\"CU_FUNC_CACHE_PREFER\" deriving (Eq, Show) #}\n#endif\n\n-- |\n-- Kernel function parameters\n--\ndata FunParam where\n IArg :: !Int -> FunParam\n FArg :: !Float -> FunParam\n TArg :: !Texture -> FunParam\n VArg :: Storable a => !a -> FunParam\n\ninstance Storable FunParam where\n sizeOf (IArg _) = sizeOf (undefined :: CUInt)\n sizeOf (FArg _) = sizeOf (undefined :: CFloat)\n sizeOf (VArg v) = sizeOf v\n sizeOf (TArg _) = 0\n\n alignment (IArg _) = alignment (undefined :: CUInt)\n alignment (FArg _) = alignment (undefined :: CFloat)\n alignment (VArg v) = alignment v\n alignment (TArg _) = 0\n\n poke p (IArg i) = poke (castPtr p) i\n poke p (FArg f) = poke (castPtr p) f\n poke p (VArg v) = poke (castPtr p) v\n poke _ (TArg _) = return ()\n\n\n--------------------------------------------------------------------------------\n-- Execution Control\n--------------------------------------------------------------------------------\n\n-- |\n-- Returns the value of the selected attribute requirement for the given kernel\n--\nrequires :: Fun -> FunAttribute -> IO Int\nrequires fn att = resultIfOk =<< cuFuncGetAttribute att fn\n\n{# fun unsafe cuFuncGetAttribute\n { alloca- `Int' peekIntConv*\n , cFromEnum `FunAttribute'\n , useFun `Fun' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the @(x,y,z)@ dimensions of the thread blocks that are created when\n-- the given kernel function is launched.\n--\nsetBlockShape :: Fun -> (Int,Int,Int) -> IO ()\nsetBlockShape fn (x,y,z) = nothingIfOk =<< cuFuncSetBlockShape fn x y z\n\n{# fun unsafe cuFuncSetBlockShape\n { useFun `Fun'\n , `Int'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set the number of bytes of dynamic shared memory to be available to each\n-- thread block when the function is launched\n--\nsetSharedSize :: Fun -> Integer -> IO ()\nsetSharedSize fn bytes = nothingIfOk =<< cuFuncSetSharedSize fn bytes\n\n{# fun unsafe cuFuncSetSharedSize\n { useFun `Fun'\n , cIntConv `Integer' } -> `Status' cToEnum #}\n\n\n-- |\n-- On devices where the L1 cache and shared memory use the same hardware\n-- resources, this sets the preferred cache configuration for the given device\n-- function. This is only a preference; the driver is free to choose a different\n-- configuration as required to execute the function.\n--\n-- Switching between configuration modes may insert a device-side\n-- synchronisation point for streamed kernel launches.\n--\nsetCacheConfigFun :: Fun -> CacheConfig -> IO ()\n#if CUDA_VERSION < 3000\nsetCacheConfigFun _ _ = requireSDK 3.0 \"setCacheConfigFun\"\n#else\nsetCacheConfigFun fn pref = nothingIfOk =<< cuFuncSetCacheConfig fn pref\n\n{# fun unsafe cuFuncSetCacheConfig\n { useFun `Fun'\n , cFromEnum `CacheConfig' } -> `Status' cToEnum #}\n#endif\n\n-- |\n-- Invoke the kernel on a size @(w,h)@ grid of blocks. Each block contains the\n-- number of threads specified by a previous call to 'setBlockShape'. The launch\n-- may also be associated with a specific 'Stream'.\n--\nlaunch :: Fun -> (Int,Int) -> Maybe Stream -> IO ()\nlaunch fn (w,h) mst =\n nothingIfOk =<< case mst of\n Nothing -> cuLaunchGridAsync fn w h (Stream nullPtr)\n Just st -> cuLaunchGridAsync fn w h st\n\n{# fun unsafe cuLaunchGridAsync\n { useFun `Fun'\n , `Int'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Invoke a kernel on a @(gx * gy * gz)@ grid of blocks, where each block\n-- contains @(tx * ty * tz)@ threads and has access to a given number of bytes\n-- of shared memory. The launch may also be associated with a specific 'Stream'.\n--\n-- In 'launchKernel', the number of kernel parameters and their offsets and\n-- sizes do not need to be specified, as this information is retrieved directly\n-- from the kernel's image. This requires the kernel to have been compiled with\n-- toolchain version 3.2 or later.\n--\n-- The alternative 'launchKernel'' will pass the arguments in directly,\n-- requiring the application to know the size and alignment\/padding of each\n-- kernel parameter.\n--\nlaunchKernel, launchKernel'\n :: Fun -- ^ function to execute\n -> (Int,Int,Int) -- ^ block grid dimension\n -> (Int,Int,Int) -- ^ thread block shape\n -> Int -- ^ shared memory (bytes)\n -> Maybe Stream -- ^ (optional) stream to execute in\n -> [FunParam] -- ^ list of function parameters\n -> IO ()\n#if CUDA_VERSION >= 4000\nlaunchKernel fn (gx,gy,gz) (tx,ty,tz) sm mst args\n = (=<<) nothingIfOk\n $ withMany withFP args\n $ \\pa -> withArray pa\n $ \\pp -> cuLaunchKernel fn gx gy gz tx ty tz sm st pp nullPtr\n where\n st = fromMaybe (Stream nullPtr) mst\n\n withFP :: FunParam -> (Ptr FunParam -> IO b) -> IO b\n withFP p f = case p of\n IArg v -> with' v (f . castPtr)\n FArg v -> with' v (f . castPtr)\n VArg v -> with' v (f . castPtr)\n TArg _ -> error \"launchKernel: TArg is deprecated\"\n\n -- can't use the standard 'with' because 'alloca' will pass an undefined\n -- dummy argument when determining 'sizeOf' and 'alignment', but sometimes\n -- instances in Accelerate need to evaluate this argument.\n --\n with' :: Storable a => a -> (Ptr a -> IO b) -> IO b\n with' val f =\n allocaBytes (sizeOf val) $ \\ptr -> do\n poke ptr val\n f ptr\n\n\nlaunchKernel' fn (gx,gy,gz) (tx,ty,tz) sm mst args\n = (=<<) nothingIfOk\n $ with bytes\n $ \\pb -> withArray' args\n $ \\pa -> withArray0 nullPtr [buffer, castPtr pa, size, castPtr pb]\n $ \\pp -> cuLaunchKernel fn gx gy gz tx ty tz sm st nullPtr pp\n where\n buffer = wordPtrToPtr 0x01 -- CU_LAUNCH_PARAM_BUFFER_POINTER\n size = wordPtrToPtr 0x02 -- CU_LAUNCH_PARAM_BUFFER_SIZE\n bytes = foldl (\\a x -> a + sizeOf x) 0 args\n st = fromMaybe (Stream nullPtr) mst\n\n -- can't use the standard 'withArray' because 'mallocArray' will pass\n -- 'undefined' to 'sizeOf' when determining how many bytes to allocate, but\n -- our Storable instance for FunParam needs to dispatch on each constructor,\n -- hence evaluating the undefined.\n --\n withArray' vals f =\n allocaBytes bytes $ \\ptr -> do\n pokeArray ptr vals\n f ptr\n\n\n{# fun unsafe cuLaunchKernel\n { useFun `Fun'\n , `Int', `Int', `Int'\n , `Int', `Int', `Int'\n , `Int'\n , useStream `Stream'\n , castPtr `Ptr (Ptr FunParam)'\n , castPtr `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n#else\nlaunchKernel fn (gx,gy,_) (tx,ty,tz) sm mst args = do\n setParams fn args\n setSharedSize fn (toInteger sm)\n setBlockShape fn (tx,ty,tz)\n launch fn (gx,gy) mst\n\nlaunchKernel' = launchKernel\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Kernel function parameters\n--------------------------------------------------------------------------------\n\n-- |\n-- Set the parameters that will specified next time the kernel is invoked\n--\nsetParams :: Fun -> [FunParam] -> IO ()\nsetParams fn prs = do\n zipWithM_ (set fn) offsets prs\n nothingIfOk =<< cuParamSetSize fn (last offsets)\n where\n offsets = scanl (\\a b -> a + size b) 0 prs\n\n size (IArg _) = sizeOf (undefined :: CUInt)\n size (FArg _) = sizeOf (undefined :: CFloat)\n size (TArg _) = 0\n size (VArg v) = sizeOf v\n\n set f o (IArg v) = nothingIfOk =<< cuParamSeti f o v\n set f o (FArg v) = nothingIfOk =<< cuParamSetf f o v\n set f _ (TArg v) = nothingIfOk =<< cuParamSetTexRef f (-1) v\n set f o (VArg v) = with v $ \\p -> (nothingIfOk =<< cuParamSetv f o p (sizeOf v))\n\n\n{# fun unsafe cuParamSetSize\n { useFun `Fun'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSeti\n { useFun `Fun'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSetf\n { useFun `Fun'\n , `Int'\n , `Float' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSetv\n `Storable a' =>\n { useFun `Fun'\n , `Int'\n , castPtr `Ptr a'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSetTexRef\n { useFun `Fun'\n , `Int' -- must be CU_PARAM_TR_DEFAULT (-1)\n , useTexture `Texture' } -> `Status' cToEnum #}\n\n","old_contents":"{-# LANGUAGE GADTs, CPP, ForeignFunctionInterface, EmptyDataDecls #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Foreign.CUDA.Driver.Exec\n-- Copyright : (c) [2009..2011] Trevor L. McDonell\n-- License : BSD\n--\n-- Kernel execution control for low-level driver interface\n--\n--------------------------------------------------------------------------------\n\nmodule Foreign.CUDA.Driver.Exec (\n\n -- * Kernel Execution\n Fun(Fun), FunParam(..), FunAttribute(..), CacheConfig(..),\n requires, setBlockShape, setSharedSize, setParams, setCacheConfigFun,\n launch, launchKernel, launchKernel'\n\n) where\n\n#include \n{# context lib=\"cuda\" #}\n\n-- Friends\nimport Foreign.CUDA.Internal.C2HS\nimport Foreign.CUDA.Driver.Error\nimport Foreign.CUDA.Driver.Stream (Stream(..))\nimport Foreign.CUDA.Driver.Texture (Texture(..))\n\n-- System\nimport Foreign\nimport Foreign.C\nimport Data.Maybe\nimport Control.Monad (zipWithM_)\n\n\n#if CUDA_VERSION >= 3020\n{-# DEPRECATED TArg \"as of CUDA version 3.2\" #-}\n#endif\n#if CUDA_VERSION >= 4000\n{-# DEPRECATED setBlockShape, setSharedSize, setParams, launch\n \"use launchKernel instead\" #-}\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Data Types\n--------------------------------------------------------------------------------\n\n-- |\n-- A @__global__@ device function\n--\nnewtype Fun = Fun { useFun :: {# type CUfunction #}}\n\n\n-- |\n-- Function attributes\n--\n{# enum CUfunction_attribute as FunAttribute\n { underscoreToCase\n , MAX_THREADS_PER_BLOCK as MaxKernelThreadsPerBlock }\n with prefix=\"CU_FUNC_ATTRIBUTE\" deriving (Eq, Show) #}\n\n-- |\n-- Cache configuration preference\n--\n#if CUDA_VERSION < 3000\ndata CacheConfig\n#else\n{# enum CUfunc_cache_enum as CacheConfig\n { underscoreToCase }\n with prefix=\"CU_FUNC_CACHE_PREFER\" deriving (Eq, Show) #}\n#endif\n\n-- |\n-- Kernel function parameters\n--\ndata FunParam where\n IArg :: !Int -> FunParam\n FArg :: !Float -> FunParam\n TArg :: !Texture -> FunParam\n VArg :: Storable a => !a -> FunParam\n\ninstance Storable FunParam where\n sizeOf (IArg _) = sizeOf (undefined :: CUInt)\n sizeOf (FArg _) = sizeOf (undefined :: CFloat)\n sizeOf (VArg v) = sizeOf v\n sizeOf (TArg _) = 0\n\n alignment (IArg _) = alignment (undefined :: CUInt)\n alignment (FArg _) = alignment (undefined :: CFloat)\n alignment (VArg v) = alignment v\n alignment (TArg _) = 0\n\n poke p (IArg i) = poke (castPtr p) i\n poke p (FArg f) = poke (castPtr p) f\n poke p (VArg v) = poke (castPtr p) v\n poke _ (TArg _) = return ()\n\n\n--------------------------------------------------------------------------------\n-- Execution Control\n--------------------------------------------------------------------------------\n\n-- |\n-- Returns the value of the selected attribute requirement for the given kernel\n--\nrequires :: Fun -> FunAttribute -> IO Int\nrequires fn att = resultIfOk =<< cuFuncGetAttribute att fn\n\n{# fun unsafe cuFuncGetAttribute\n { alloca- `Int' peekIntConv*\n , cFromEnum `FunAttribute'\n , useFun `Fun' } -> `Status' cToEnum #}\n\n\n-- |\n-- Specify the @(x,y,z)@ dimensions of the thread blocks that are created when\n-- the given kernel function is launched.\n--\nsetBlockShape :: Fun -> (Int,Int,Int) -> IO ()\nsetBlockShape fn (x,y,z) = nothingIfOk =<< cuFuncSetBlockShape fn x y z\n\n{# fun unsafe cuFuncSetBlockShape\n { useFun `Fun'\n , `Int'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n\n\n-- |\n-- Set the number of bytes of dynamic shared memory to be available to each\n-- thread block when the function is launched\n--\nsetSharedSize :: Fun -> Integer -> IO ()\nsetSharedSize fn bytes = nothingIfOk =<< cuFuncSetSharedSize fn bytes\n\n{# fun unsafe cuFuncSetSharedSize\n { useFun `Fun'\n , cIntConv `Integer' } -> `Status' cToEnum #}\n\n\n-- |\n-- On devices where the L1 cache and shared memory use the same hardware\n-- resources, this sets the preferred cache configuration for the given device\n-- function. This is only a preference; the driver is free to choose a different\n-- configuration as required to execute the function.\n--\n-- Switching between configuration modes may insert a device-side\n-- synchronisation point for streamed kernel launches.\n--\nsetCacheConfigFun :: Fun -> CacheConfig -> IO ()\n#if CUDA_VERSION < 3000\nsetCacheConfigFun _ _ = requireSDK 3.0 \"setCacheConfigFun\"\n#else\nsetCacheConfigFun fn pref = nothingIfOk =<< cuFuncSetCacheConfig fn pref\n\n{# fun unsafe cuFuncSetCacheConfig\n { useFun `Fun'\n , cFromEnum `CacheConfig' } -> `Status' cToEnum #}\n#endif\n\n-- |\n-- Invoke the kernel on a size @(w,h)@ grid of blocks. Each block contains the\n-- number of threads specified by a previous call to 'setBlockShape'. The launch\n-- may also be associated with a specific 'Stream'.\n--\nlaunch :: Fun -> (Int,Int) -> Maybe Stream -> IO ()\nlaunch fn (w,h) mst =\n nothingIfOk =<< case mst of\n Nothing -> cuLaunchGridAsync fn w h (Stream nullPtr)\n Just st -> cuLaunchGridAsync fn w h st\n\n{# fun unsafe cuLaunchGridAsync\n { useFun `Fun'\n , `Int'\n , `Int'\n , useStream `Stream' } -> `Status' cToEnum #}\n\n\n-- |\n-- Invoke a kernel on a @(gx * gy * gz)@ grid of blocks, where each block\n-- contains @(tx * ty * tz)@ threads and has access to a given number of bytes\n-- of shared memory. The launch may also be associated with a specific 'Stream'.\n--\n-- In 'launchKernel', the number of kernel parameters and their offsets and\n-- sizes do not need to be specified, as this information is retrieved directly\n-- from the kernel's image. This requires the kernel to have been compiled with\n-- toolchain version 3.2 or later.\n--\n-- The alternative 'launchKernel'' will pass the arguments in directly,\n-- requiring the application to know the size and alignment\/padding of each\n-- kernel parameter.\n--\nlaunchKernel, launchKernel'\n :: Fun -- ^ function to execute\n -> (Int,Int,Int) -- ^ block grid dimension\n -> (Int,Int,Int) -- ^ thread block shape\n -> Int -- ^ shared memory (bytes)\n -> Maybe Stream -- ^ (optional) stream to execute in\n -> [FunParam] -- ^ list of function parameters\n -> IO ()\n#if CUDA_VERSION >= 4000\nlaunchKernel fn (gx,gy,gz) (tx,ty,tz) sm mst args\n = (=<<) nothingIfOk\n $ withMany withFP args\n $ \\pa -> withArray pa\n $ \\pp -> cuLaunchKernel fn gx gy gz tx ty tz sm st pp nullPtr\n where\n st = fromMaybe (Stream nullPtr) mst\n\n withFP :: FunParam -> (Ptr FunParam -> IO b) -> IO b\n withFP p f = case p of\n IArg v -> with v (f . castPtr)\n FArg v -> with v (f . castPtr)\n VArg v -> with v (f . castPtr)\n TArg _ -> error \"launchKernel: TArg is deprecated\"\n\n\nlaunchKernel' fn (gx,gy,gz) (tx,ty,tz) sm mst args\n = (=<<) nothingIfOk\n $ with bytes\n $ \\pb -> withArray' args\n $ \\pa -> withArray0 nullPtr [buffer, castPtr pa, size, castPtr pb]\n $ \\pp -> cuLaunchKernel fn gx gy gz tx ty tz sm st nullPtr pp\n where\n buffer = wordPtrToPtr 0x01 -- CU_LAUNCH_PARAM_BUFFER_POINTER\n size = wordPtrToPtr 0x02 -- CU_LAUNCH_PARAM_BUFFER_SIZE\n bytes = foldl (\\a x -> a + sizeOf x) 0 args\n st = fromMaybe (Stream nullPtr) mst\n\n -- can't use the standard 'withArray' because 'mallocArray' will pass\n -- 'undefined' to 'sizeOf' when determining how many bytes to allocate, but\n -- our Storable instance for FunParam needs to dispatch on each constructor,\n -- hence evaluating the undefined.\n --\n withArray' vals f =\n allocaBytes bytes $ \\ptr -> do\n pokeArray ptr vals\n f ptr\n\n\n{# fun unsafe cuLaunchKernel\n { useFun `Fun'\n , `Int', `Int', `Int'\n , `Int', `Int', `Int'\n , `Int'\n , useStream `Stream'\n , castPtr `Ptr (Ptr FunParam)'\n , castPtr `Ptr (Ptr ())' } -> `Status' cToEnum #}\n\n#else\nlaunchKernel fn (gx,gy,_) (tx,ty,tz) sm mst args = do\n setParams fn args\n setSharedSize fn (toInteger sm)\n setBlockShape fn (tx,ty,tz)\n launch fn (gx,gy) mst\n\nlaunchKernel' = launchKernel\n#endif\n\n\n--------------------------------------------------------------------------------\n-- Kernel function parameters\n--------------------------------------------------------------------------------\n\n-- |\n-- Set the parameters that will specified next time the kernel is invoked\n--\nsetParams :: Fun -> [FunParam] -> IO ()\nsetParams fn prs = do\n zipWithM_ (set fn) offsets prs\n nothingIfOk =<< cuParamSetSize fn (last offsets)\n where\n offsets = scanl (\\a b -> a + size b) 0 prs\n\n size (IArg _) = sizeOf (undefined :: CUInt)\n size (FArg _) = sizeOf (undefined :: CFloat)\n size (TArg _) = 0\n size (VArg v) = sizeOf v\n\n set f o (IArg v) = nothingIfOk =<< cuParamSeti f o v\n set f o (FArg v) = nothingIfOk =<< cuParamSetf f o v\n set f _ (TArg v) = nothingIfOk =<< cuParamSetTexRef f (-1) v\n set f o (VArg v) = with v $ \\p -> (nothingIfOk =<< cuParamSetv f o p (sizeOf v))\n\n\n{# fun unsafe cuParamSetSize\n { useFun `Fun'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSeti\n { useFun `Fun'\n , `Int'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSetf\n { useFun `Fun'\n , `Int'\n , `Float' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSetv\n `Storable a' =>\n { useFun `Fun'\n , `Int'\n , castPtr `Ptr a'\n , `Int' } -> `Status' cToEnum #}\n\n{# fun unsafe cuParamSetTexRef\n { useFun `Fun'\n , `Int' -- must be CU_PARAM_TR_DEFAULT (-1)\n , useTexture `Texture' } -> `Status' cToEnum #}\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"f5c1c5dbda6585b62ce73937e2517dd6354e6d09","subject":"Extract OpenGL modes in GlWindow.","message":"Extract OpenGL modes in GlWindow.\n","repos":"deech\/fltkhs,deech\/fltkhs,deech\/fltkhs","old_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Base\/GlWindow.chs","new_file":"src\/Graphics\/UI\/FLTK\/LowLevel\/Base\/GlWindow.chs","new_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Base.GlWindow\n (\n glWindowNew,\n glWindowCustom,\n glWindowCanDo\n , drawGlWindowBase\n , handleGlWindowBase\n , resizeGlWindowBase\n , hideGlWindowBase\n , showWidgetGlWindowBase\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * GlWindow functions\n --\n -- $functions\n )\nwhere\n#include \"Fl_C.h\"\n#include \"Fl_Double_WindowC.h\"\n#include \"Fl_Gl_WindowC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Foreign\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Window\nimport Graphics.UI.FLTK.LowLevel.Base.Widget\nimport Graphics.UI.FLTK.LowLevel.Base.Window\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\n\n{# fun Fl_OverriddenGl_Window_New as overriddenWindowNew' {`Int',`Int', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenGl_Window_NewXY as overriddenWindowNewXY' {`Int',`Int', `Int', `Int', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenGl_Window_NewXY_WithLabel as overriddenWindowNewXYWithLabel' { `Int',`Int',`Int',`Int',`CString', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenGl_Window_New_WithLabel as overriddenWindowNewWithLabel' { `Int',`Int', `CString', id `Ptr ()'} -> `Ptr ()' id #}\nglWindowCustom :: Size -- ^ The size of this window\n -> Maybe Position -- ^ The position of this window\n -> Maybe T.Text -- ^ The window label\n -> Maybe (Ref GlWindow -> IO ()) -- ^ Optional custom drawing function\n -> CustomWidgetFuncs GlWindow -- ^ other custom widget functions\n -> CustomWindowFuncs GlWindow -- ^ Other custom window functions\n -> IO (Ref GlWindow)\nglWindowCustom size position title draw' customWidgetFuncs' customWindowFuncs' =\n windowMaker\n size\n position\n title\n draw'\n customWidgetFuncs'\n customWindowFuncs'\n overriddenWindowNew'\n overriddenWindowNewWithLabel'\n overriddenWindowNewXY'\n overriddenWindowNewXYWithLabel'\nglWindowNew :: Size -> Maybe Position -> Maybe T.Text -> IO (Ref GlWindow)\nglWindowNew size position title =\n windowMaker\n size\n position\n title\n Nothing\n (defaultCustomWidgetFuncs :: CustomWidgetFuncs GlWindow)\n (defaultCustomWindowFuncs :: CustomWindowFuncs GlWindow)\n overriddenWindowNew'\n overriddenWindowNewWithLabel'\n overriddenWindowNewXY'\n overriddenWindowNewXYWithLabel'\n\n{# fun Fl_Gl_Window_can_do_with_m as canDoWithM' { `Int'} -> `Bool' cToBool #}\nglWindowCanDo :: Mode -> IO Bool\nglWindowCanDo m = canDoWithM' (fromEnum m)\n\n{# fun Fl_Gl_Window_draw_super as drawSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ndrawGlWindowBase :: Ref GlWindowBase -> IO ()\ndrawGlWindowBase glWindow = withRef glWindow $ \\glWindowPtr -> drawSuper' glWindowPtr\n{# fun Fl_Gl_Window_handle_super as handleSuper' { id `Ptr ()',`Int' } -> `Int' #}\nhandleGlWindowBase :: Ref GlWindowBase -> Event -> IO (Either UnknownEvent ())\nhandleGlWindowBase glWindow event = withRef glWindow $ \\glWindowPtr -> handleSuper' glWindowPtr (fromIntegral (fromEnum event)) >>= return . successOrUnknownEvent\n{# fun Fl_Gl_Window_resize_super as resizeSuper' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\nresizeGlWindowBase :: Ref GlWindowBase -> Rectangle -> IO ()\nresizeGlWindowBase glWindow rectangle =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in withRef glWindow $ \\glWindowPtr -> resizeSuper' glWindowPtr x_pos y_pos width height\n{# fun Fl_Gl_Window_hide_super as hideSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nhideGlWindowBase :: Ref GlWindowBase -> IO ()\nhideGlWindowBase glWindow = withRef glWindow $ \\glWindowPtr -> hideSuper' glWindowPtr\n{# fun Fl_Gl_Window_show_super as showSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nshowWidgetGlWindowBase :: Ref GlWindowBase -> IO ()\nshowWidgetGlWindowBase glWindow = withRef glWindow $ \\glWindowPtr -> showSuper' glWindowPtr\n\n\n{# fun Fl_DerivedGl_Window_flush as flush' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Flush ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> flush' winPtr\n{# fun Fl_DerivedGl_Window_hide as hide' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Hide ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> hide' winPtr\n{# fun Fl_DerivedGl_Window_show as show' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (ShowWidget ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> show' winPtr\n{# fun Fl_DerivedGl_Window_handle as handle' { id `Ptr ()', cFromEnum `Event' } -> `Int' #}\ninstance (impl ~ (Event -> IO(Either UnknownEvent ()))) => Op (Handle ()) GlWindowBase orig impl where\n runOp _ _ self event = withRef self $ \\selfPtr -> handle' selfPtr event >>= return . successOrUnknownEvent\n{# fun Fl_DerivedGl_Window_Destroy as windowDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Destroy ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> windowDestroy' winPtr\n{# fun Fl_DerivedGl_Window_resize as resize' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Rectangle -> IO ())) => Op (Resize ()) GlWindowBase orig impl where\n runOp _ _ win rectangle' =\n let (x_pos', y_pos', width', height') = fromRectangle rectangle' in\n withRef win $ \\winPtr -> resize' winPtr x_pos' y_pos' width' height'\n\n{# fun Fl_Gl_Window_valid as valid' { id `Ptr ()' } -> `Bool' #}\ninstance (impl ~ ( IO (Bool))) => Op (GetValid ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> valid' winPtr\n{# fun Fl_Gl_Window_set_valid as setValid' { id `Ptr ()', `Bool' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Bool -> IO ())) => Op (SetValid ()) GlWindowBase orig impl where\n runOp _ _ win v = withRef win $ \\winPtr -> setValid' winPtr v\n{# fun Fl_Gl_Window_invalidate as invalidate' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Invalidate ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> invalidate' winPtr\n{# fun Fl_Gl_Window_context_valid as contextValid' { id `Ptr ()' } -> `Bool' toBool #}\ninstance (impl ~ ( IO (Bool))) => Op (GetContextValid ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> contextValid' winPtr\n{# fun Fl_Gl_Window_set_context_valid as setContextValid' { id `Ptr ()', fromBool `Bool' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Bool -> IO ())) => Op (SetContextValid ()) GlWindowBase orig impl where\n runOp _ _ win v = withRef win $ \\winPtr -> setContextValid' winPtr v\n{# fun Fl_Gl_Window_can_do as canDo' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ ( IO (Bool))) => Op (CanDo ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> canDo' winPtr\n{# fun Fl_Gl_Window_mode as mode' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Modes))) => Op (GetMode ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> mode' winPtr >>= return . intToModes\n{# fun Fl_Gl_Window_set_mode as setMode' { id `Ptr ()',`Int' } -> `Int' #}\ninstance (impl ~ (Modes -> IO ())) => Op (SetMode ()) GlWindowBase orig impl where\n runOp _ _ win a = withRef win $ \\winPtr -> setMode' winPtr (modesToInt a) >> return ()\n{# fun Fl_Gl_Window_context as context' { id `Ptr ()' } -> `Ptr ()' #}\ninstance (impl ~ ( IO (Ref FlGlContext))) => Op (GetContext ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> context' winPtr >>= toRef\n{# fun Fl_Gl_Window_set_context as setContext' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Ref FlGlContext -> IO ())) => Op (SetContext ()) GlWindowBase orig impl where\n runOp _ _ win context = withRef win $ \\winPtr -> withRef context $ \\contextPtr -> setContext' winPtr contextPtr\n{# fun Fl_Gl_Window_set_context_with_destroy_flag as setContextWithDestroyFlag' { id `Ptr ()',id `Ptr ()', fromBool `Bool'} -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Ref FlGlContext -> Bool -> IO ())) => Op (SetContextWithDestroyFlag ()) GlWindowBase orig impl where\n runOp _ _ win context destroyFlag= withRef win $ \\winPtr -> withRef context $ \\contextPtr -> setContextWithDestroyFlag' winPtr contextPtr destroyFlag\n{# fun Fl_Gl_Window_swap_buffers as swapBuffers' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (SwapBuffers ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> swapBuffers' winPtr\n{# fun Fl_Gl_Window_ortho as ortho' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Ortho ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> ortho' winPtr\n{# fun Fl_Gl_Window_can_do_overlay as canDoOverlay' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ ( IO (Bool))) => Op (CanDoOverlay ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> canDoOverlay' winPtr\n{# fun Fl_Gl_Window_redraw_overlay as redrawOverlay' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (RedrawOverlay ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> redrawOverlay' winPtr\n{# fun Fl_Gl_Window_hide_overlay as hideOverlay' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (HideOverlay ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> hideOverlay' winPtr\n{# fun Fl_Gl_Window_make_overlay_current as makeOverlayCurrent' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (MakeOverlayCurrent ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> makeOverlayCurrent' winPtr\n{# fun Fl_Gl_Window_pixels_per_unit as pixelsPerUnit' { id `Ptr ()'} -> `Float' #}\ninstance (impl ~ ( IO (Float))) => Op (PixelsPerUnit ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> pixelsPerUnit' winPtr\n{# fun Fl_Gl_Window_pixel_h as pixelH' { id `Ptr ()'} -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (PixelH ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> pixelH' winPtr\n{# fun Fl_Gl_Window_pixel_w as pixelW' { id `Ptr ()'} -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (PixelW ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> pixelW' winPtr\n\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Base.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Base.Group\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Base.Window\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Base.GlWindow\"\n-- @\n\n-- $functions\n-- @\n-- canDo :: 'Ref' 'GlWindowBase' -> 'IO' ('Bool')\n--\n-- canDoOverlay :: 'Ref' 'GlWindowBase' -> 'IO' ('Bool')\n--\n-- destroy :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- flush :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- getContext :: 'Ref' 'GlWindowBase' -> 'IO' ('Ref' 'FlGlContext')\n--\n-- getContextValid :: 'Ref' 'GlWindowBase' -> 'IO' ('Bool')\n--\n-- getMode :: 'Ref' 'GlWindowBase' -> 'IO' ('Mode')\n--\n-- getValid :: 'Ref' 'GlWindowBase' -> 'IO' ('Bool')\n--\n-- handle :: 'Ref' 'GlWindowBase' -> 'Event' -> 'IO(Either' 'UnknownEvent' ())\n--\n-- hide :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- hideOverlay :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- invalidate :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- makeOverlayCurrent :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- ortho :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- pixelH :: 'Ref' 'GlWindowBase' -> 'IO' ('Int')\n--\n-- pixelW :: 'Ref' 'GlWindowBase' -> 'IO' ('Int')\n--\n-- pixelsPerUnit :: 'Ref' 'GlWindowBase' -> 'IO' ('Float')\n--\n-- redrawOverlay :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- resize :: 'Ref' 'GlWindowBase' -> 'Rectangle' -> 'IO' ()\n--\n-- setContext :: 'Ref' 'GlWindowBase' -> 'Ref' 'FlGlContext' -> 'IO' ()\n--\n-- setContextValid :: 'Ref' 'GlWindowBase' -> 'Bool' -> 'IO' ()\n--\n-- setContextWithDestroyFlag :: 'Ref' 'GlWindowBase' -> 'Ref' 'FlGlContext' -> 'Bool' -> 'IO' ()\n--\n-- setMode :: 'Ref' 'GlWindowBase' -> 'Modes' -> 'IO' ()\n--\n-- setValid :: 'Ref' 'GlWindowBase' -> 'Bool' -> 'IO' ()\n--\n-- showWidget :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- swapBuffers :: 'Ref' 'GlWindowBase' -> 'IO' ()\n-- @\n","old_contents":"{-# LANGUAGE CPP, ExistentialQuantification, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts, ScopedTypeVariables #-}\n{-# OPTIONS_GHC -fno-warn-orphans #-}\nmodule Graphics.UI.FLTK.LowLevel.Base.GlWindow\n (\n glWindowNew,\n glWindowCustom,\n glWindowCanDo\n , drawGlWindowBase\n , handleGlWindowBase\n , resizeGlWindowBase\n , hideGlWindowBase\n , showWidgetGlWindowBase\n -- * Hierarchy\n --\n -- $hierarchy\n\n -- * GlWindow functions\n --\n -- $functions\n )\nwhere\n#include \"Fl_C.h\"\n#include \"Fl_Double_WindowC.h\"\n#include \"Fl_Gl_WindowC.h\"\nimport C2HS hiding (cFromEnum, cFromBool, cToBool,cToEnum)\nimport Foreign\nimport Graphics.UI.FLTK.LowLevel.Fl_Types\nimport Graphics.UI.FLTK.LowLevel.Fl_Enumerations\nimport Graphics.UI.FLTK.LowLevel.Utils\nimport Graphics.UI.FLTK.LowLevel.Window\nimport Graphics.UI.FLTK.LowLevel.Base.Widget\nimport Graphics.UI.FLTK.LowLevel.Base.Window\nimport Graphics.UI.FLTK.LowLevel.Hierarchy\nimport Graphics.UI.FLTK.LowLevel.Dispatch\nimport qualified Data.Text as T\n\n{# fun Fl_OverriddenGl_Window_New as overriddenWindowNew' {`Int',`Int', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenGl_Window_NewXY as overriddenWindowNewXY' {`Int',`Int', `Int', `Int', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenGl_Window_NewXY_WithLabel as overriddenWindowNewXYWithLabel' { `Int',`Int',`Int',`Int',`CString', id `Ptr ()'} -> `Ptr ()' id #}\n{# fun Fl_OverriddenGl_Window_New_WithLabel as overriddenWindowNewWithLabel' { `Int',`Int', `CString', id `Ptr ()'} -> `Ptr ()' id #}\nglWindowCustom :: Size -- ^ The size of this window\n -> Maybe Position -- ^ The position of this window\n -> Maybe T.Text -- ^ The window label\n -> Maybe (Ref GlWindow -> IO ()) -- ^ Optional custom drawing function\n -> CustomWidgetFuncs GlWindow -- ^ other custom widget functions\n -> CustomWindowFuncs GlWindow -- ^ Other custom window functions\n -> IO (Ref GlWindow)\nglWindowCustom size position title draw' customWidgetFuncs' customWindowFuncs' =\n windowMaker\n size\n position\n title\n draw'\n customWidgetFuncs'\n customWindowFuncs'\n overriddenWindowNew'\n overriddenWindowNewWithLabel'\n overriddenWindowNewXY'\n overriddenWindowNewXYWithLabel'\nglWindowNew :: Size -> Maybe Position -> Maybe T.Text -> IO (Ref GlWindow)\nglWindowNew size position title =\n windowMaker\n size\n position\n title\n Nothing\n (defaultCustomWidgetFuncs :: CustomWidgetFuncs GlWindow)\n (defaultCustomWindowFuncs :: CustomWindowFuncs GlWindow)\n overriddenWindowNew'\n overriddenWindowNewWithLabel'\n overriddenWindowNewXY'\n overriddenWindowNewXYWithLabel'\n\n{# fun Fl_Gl_Window_can_do_with_m as canDoWithM' { `Int'} -> `Bool' cToBool #}\nglWindowCanDo :: Mode -> IO Bool\nglWindowCanDo m = canDoWithM' (fromEnum m)\n\n{# fun Fl_Gl_Window_draw_super as drawSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ndrawGlWindowBase :: Ref GlWindowBase -> IO ()\ndrawGlWindowBase glWindow = withRef glWindow $ \\glWindowPtr -> drawSuper' glWindowPtr\n{# fun Fl_Gl_Window_handle_super as handleSuper' { id `Ptr ()',`Int' } -> `Int' #}\nhandleGlWindowBase :: Ref GlWindowBase -> Event -> IO (Either UnknownEvent ())\nhandleGlWindowBase glWindow event = withRef glWindow $ \\glWindowPtr -> handleSuper' glWindowPtr (fromIntegral (fromEnum event)) >>= return . successOrUnknownEvent\n{# fun Fl_Gl_Window_resize_super as resizeSuper' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\nresizeGlWindowBase :: Ref GlWindowBase -> Rectangle -> IO ()\nresizeGlWindowBase glWindow rectangle =\n let (x_pos, y_pos, width, height) = fromRectangle rectangle\n in withRef glWindow $ \\glWindowPtr -> resizeSuper' glWindowPtr x_pos y_pos width height\n{# fun Fl_Gl_Window_hide_super as hideSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nhideGlWindowBase :: Ref GlWindowBase -> IO ()\nhideGlWindowBase glWindow = withRef glWindow $ \\glWindowPtr -> hideSuper' glWindowPtr\n{# fun Fl_Gl_Window_show_super as showSuper' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\nshowWidgetGlWindowBase :: Ref GlWindowBase -> IO ()\nshowWidgetGlWindowBase glWindow = withRef glWindow $ \\glWindowPtr -> showSuper' glWindowPtr\n\n\n{# fun Fl_DerivedGl_Window_flush as flush' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Flush ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> flush' winPtr\n{# fun Fl_DerivedGl_Window_hide as hide' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Hide ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> hide' winPtr\n{# fun Fl_DerivedGl_Window_show as show' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (ShowWidget ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> show' winPtr\n{# fun Fl_DerivedGl_Window_handle as handle' { id `Ptr ()', cFromEnum `Event' } -> `Int' #}\ninstance (impl ~ (Event -> IO(Either UnknownEvent ()))) => Op (Handle ()) GlWindowBase orig impl where\n runOp _ _ self event = withRef self $ \\selfPtr -> handle' selfPtr event >>= return . successOrUnknownEvent\n{# fun Fl_DerivedGl_Window_Destroy as windowDestroy' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (IO ())) => Op (Destroy ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> windowDestroy' winPtr\n{# fun Fl_DerivedGl_Window_resize as resize' { id `Ptr ()',`Int',`Int',`Int',`Int' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Rectangle -> IO ())) => Op (Resize ()) GlWindowBase orig impl where\n runOp _ _ win rectangle' =\n let (x_pos', y_pos', width', height') = fromRectangle rectangle' in\n withRef win $ \\winPtr -> resize' winPtr x_pos' y_pos' width' height'\n\n{# fun Fl_Gl_Window_valid as valid' { id `Ptr ()' } -> `Bool' #}\ninstance (impl ~ ( IO (Bool))) => Op (GetValid ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> valid' winPtr\n{# fun Fl_Gl_Window_set_valid as setValid' { id `Ptr ()', `Bool' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Bool -> IO ())) => Op (SetValid ()) GlWindowBase orig impl where\n runOp _ _ win v = withRef win $ \\winPtr -> setValid' winPtr v\n{# fun Fl_Gl_Window_invalidate as invalidate' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Invalidate ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> invalidate' winPtr\n{# fun Fl_Gl_Window_context_valid as contextValid' { id `Ptr ()' } -> `Bool' toBool #}\ninstance (impl ~ ( IO (Bool))) => Op (GetContextValid ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> contextValid' winPtr\n{# fun Fl_Gl_Window_set_context_valid as setContextValid' { id `Ptr ()', fromBool `Bool' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ (Bool -> IO ())) => Op (SetContextValid ()) GlWindowBase orig impl where\n runOp _ _ win v = withRef win $ \\winPtr -> setContextValid' winPtr v\n{# fun Fl_Gl_Window_can_do as canDo' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ ( IO (Bool))) => Op (CanDo ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> canDo' winPtr\n{# fun Fl_Gl_Window_mode as mode' { id `Ptr ()' } -> `Int' #}\ninstance (impl ~ ( IO (Mode))) => Op (GetMode ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> mode' winPtr >>= return . toEnum\n{# fun Fl_Gl_Window_set_mode as setMode' { id `Ptr ()',`Int' } -> `Int' #}\ninstance (impl ~ (Modes -> IO ())) => Op (SetMode ()) GlWindowBase orig impl where\n runOp _ _ win a = withRef win $ \\winPtr -> setMode' winPtr (modesToInt a) >> return ()\n{# fun Fl_Gl_Window_context as context' { id `Ptr ()' } -> `Ptr ()' #}\ninstance (impl ~ ( IO (Ref FlGlContext))) => Op (GetContext ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> context' winPtr >>= toRef\n{# fun Fl_Gl_Window_set_context as setContext' { id `Ptr ()',id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Ref FlGlContext -> IO ())) => Op (SetContext ()) GlWindowBase orig impl where\n runOp _ _ win context = withRef win $ \\winPtr -> withRef context $ \\contextPtr -> setContext' winPtr contextPtr\n{# fun Fl_Gl_Window_set_context_with_destroy_flag as setContextWithDestroyFlag' { id `Ptr ()',id `Ptr ()', fromBool `Bool'} -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( Ref FlGlContext -> Bool -> IO ())) => Op (SetContextWithDestroyFlag ()) GlWindowBase orig impl where\n runOp _ _ win context destroyFlag= withRef win $ \\winPtr -> withRef context $ \\contextPtr -> setContextWithDestroyFlag' winPtr contextPtr destroyFlag\n{# fun Fl_Gl_Window_swap_buffers as swapBuffers' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (SwapBuffers ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> swapBuffers' winPtr\n{# fun Fl_Gl_Window_ortho as ortho' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (Ortho ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> ortho' winPtr\n{# fun Fl_Gl_Window_can_do_overlay as canDoOverlay' { id `Ptr ()' } -> `Bool' cToBool #}\ninstance (impl ~ ( IO (Bool))) => Op (CanDoOverlay ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> canDoOverlay' winPtr\n{# fun Fl_Gl_Window_redraw_overlay as redrawOverlay' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (RedrawOverlay ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> redrawOverlay' winPtr\n{# fun Fl_Gl_Window_hide_overlay as hideOverlay' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (HideOverlay ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> hideOverlay' winPtr\n{# fun Fl_Gl_Window_make_overlay_current as makeOverlayCurrent' { id `Ptr ()' } -> `()' supressWarningAboutRes #}\ninstance (impl ~ ( IO ())) => Op (MakeOverlayCurrent ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> makeOverlayCurrent' winPtr\n{# fun Fl_Gl_Window_pixels_per_unit as pixelsPerUnit' { id `Ptr ()'} -> `Float' #}\ninstance (impl ~ ( IO (Float))) => Op (PixelsPerUnit ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> pixelsPerUnit' winPtr\n{# fun Fl_Gl_Window_pixel_h as pixelH' { id `Ptr ()'} -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (PixelH ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> pixelH' winPtr\n{# fun Fl_Gl_Window_pixel_w as pixelW' { id `Ptr ()'} -> `Int' #}\ninstance (impl ~ ( IO (Int))) => Op (PixelW ()) GlWindowBase orig impl where\n runOp _ _ win = withRef win $ \\winPtr -> pixelW' winPtr\n\n\n-- $hierarchy\n-- @\n-- \"Graphics.UI.FLTK.LowLevel.Base.Widget\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Base.Group\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Base.Window\"\n-- |\n-- v\n-- \"Graphics.UI.FLTK.LowLevel.Base.GlWindow\"\n-- @\n\n-- $functions\n-- @\n-- canDo :: 'Ref' 'GlWindowBase' -> 'IO' ('Bool')\n--\n-- canDoOverlay :: 'Ref' 'GlWindowBase' -> 'IO' ('Bool')\n--\n-- destroy :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- flush :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- getContext :: 'Ref' 'GlWindowBase' -> 'IO' ('Ref' 'FlGlContext')\n--\n-- getContextValid :: 'Ref' 'GlWindowBase' -> 'IO' ('Bool')\n--\n-- getMode :: 'Ref' 'GlWindowBase' -> 'IO' ('Mode')\n--\n-- getValid :: 'Ref' 'GlWindowBase' -> 'IO' ('Bool')\n--\n-- handle :: 'Ref' 'GlWindowBase' -> 'Event' -> 'IO(Either' 'UnknownEvent' ())\n--\n-- hide :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- hideOverlay :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- invalidate :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- makeOverlayCurrent :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- ortho :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- pixelH :: 'Ref' 'GlWindowBase' -> 'IO' ('Int')\n--\n-- pixelW :: 'Ref' 'GlWindowBase' -> 'IO' ('Int')\n--\n-- pixelsPerUnit :: 'Ref' 'GlWindowBase' -> 'IO' ('Float')\n--\n-- redrawOverlay :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- resize :: 'Ref' 'GlWindowBase' -> 'Rectangle' -> 'IO' ()\n--\n-- setContext :: 'Ref' 'GlWindowBase' -> 'Ref' 'FlGlContext' -> 'IO' ()\n--\n-- setContextValid :: 'Ref' 'GlWindowBase' -> 'Bool' -> 'IO' ()\n--\n-- setContextWithDestroyFlag :: 'Ref' 'GlWindowBase' -> 'Ref' 'FlGlContext' -> 'Bool' -> 'IO' ()\n--\n-- setMode :: 'Ref' 'GlWindowBase' -> 'Modes' -> 'IO' ()\n--\n-- setValid :: 'Ref' 'GlWindowBase' -> 'Bool' -> 'IO' ()\n--\n-- showWidget :: 'Ref' 'GlWindowBase' -> 'IO' ()\n--\n-- swapBuffers :: 'Ref' 'GlWindowBase' -> 'IO' ()\n-- @\n","returncode":0,"stderr":"","license":"mit","lang":"C2hs Haskell"}
{"commit":"64107f47233eb7da704fa6d679f1de94ac99c737","subject":"Added some unicode to Morphology.","message":"Added some unicode to Morphology.\n\nJust for fun","repos":"BeautifulDestinations\/CV,aleator\/CV,TomMD\/CV,aleator\/CV","old_file":"CV\/Morphology.chs","new_file":"CV\/Morphology.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface, ScopedTypeVariables, UnicodeSyntax#-}\n#include \"cvWrapLEO.h\"\nmodule CV.Morphology (StructuringElement\n ,structuringElement\n ,customSE\n ,basicSE,bigSE\n ,geodesic\n ,openOp,closeOp\n ,open,close\n ,erode,dilate\n ,blackTopHat,whiteTopHat\n ,dilateOp,erodeOp,ellipseShape\n ,crossShape,rectShape) \nwhere\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.ForeignPtr\nimport Foreign.Ptr\nimport Foreign.Marshal.Array\n\nimport CV.Image \n\nimport CV.ImageOp\nimport qualified CV.ImageMath as IM\n\nimport C2HSTools\n\n-- Morphological opening\nopenOp :: StructuringElement -> ImageOperation GrayScale D32\nopenOp se = erodeOp se 1 #> dilateOp se 1 \nopen se = unsafeOperate (openOp se) \na \u25cb b = open b a\n-- a \u25cb b = (a \u2296 b) \u2295 b \n\n\n-- Morphological closing\ncloseOp :: StructuringElement -> ImageOperation GrayScale D32\ncloseOp se = dilateOp se 1 #> erodeOp se 1 \nclose se = unsafeOperate (closeOp se) \na \u25cf b = close b a\n\ngeodesic :: Image GrayScale D32 -> ImageOperation GrayScale D32 -> ImageOperation GrayScale D32\ngeodesic mask op = op #> IM.limitToOp mask\n\nblackTopHat size i = unsafePerformIO $ do\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) rectShape\n x <- runImageOperation i (closeOp se)\n return $ x `IM.sub` i\n\nwhiteTopHat size i = unsafePerformIO $ do\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) rectShape\n x <- runImageOperation i (openOp se)\n return $ i `IM.sub` x\n\nbasicSE = structuringElement (3,3) (1,1) rectShape\nbigSE = structuringElement (9,9) (4,4) rectShape\n\n---------- Low level wrapper\nrectShape = 0\ncrossShape = 1\nellipseShape = 2\ncustomShape = 100\n\n{#pointer *IplConvKernel as ConvKernel foreign newtype#}\n\ntype StructuringElement = ConvKernel\n\nforeign import ccall \"& wrapReleaseStructuringElement\" \n releaseSE :: FinalizerPtr ConvKernel\n\n\n-- Check morphology element\nisGoodSE s@(w,h) d@(x,y) | x>=0 && y>=0 \n && w>=0 && h>=0\n && x\n {#call cvCreateStructuringElementEx#}\n w h x y (fromIntegral customShape) arr\n fptr <- newForeignPtr releaseSE iptr\n return (ConvKernel fptr)\n\n{#fun cvErode as erosion \n {withGenBareImage* `BareImage'\n ,withGenBareImage* `BareImage'\n ,withConvKernel* `ConvKernel'\n ,`Int'} -> `()' #}\n{#fun cvDilate as dilation \n {withGenBareImage* `BareImage'\n ,withGenBareImage* `BareImage'\n ,withConvKernel* `ConvKernel'\n ,`Int'} -> `()' #}\n\n\nerodeOp se count = ImgOp $ \\(S img) -> erosion img img se count\ndilateOp se count = ImgOp $ \\(S img) -> dilation img img se count\n\nerode se count i = unsafeOperate (erodeOp se count) i\ndilate se count i = unsafeOperate (dilateOp se count) i\n\na \u2295 b = erode b 1 a\na \u2296 b = erode b 1 a\n \nerode' se count img = withImage img $ \\image ->\n withConvKernel se $ \\ck ->\n {#call cvErode#} (castPtr image) \n (castPtr image) \n ck count\n \ndilate' se count img = withImage img $ \\image ->\n withConvKernel se $ \\ck ->\n {#call cvDilate#} (castPtr image) \n (castPtr image) \n ck count\n","old_contents":"{-#LANGUAGE ForeignFunctionInterface, ScopedTypeVariables#-}\n#include \"cvWrapLEO.h\"\nmodule CV.Morphology (StructuringElement\n ,structuringElement\n ,customSE\n ,basicSE,bigSE\n ,geodesic\n ,openOp,closeOp\n ,open,close\n ,erode,dilate\n ,blackTopHat,whiteTopHat\n ,dilateOp,erodeOp,ellipseShape\n ,crossShape,rectShape) \nwhere\n\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.ForeignPtr\nimport Foreign.Ptr\nimport Foreign.Marshal.Array\n\nimport CV.Image \n\nimport CV.ImageOp\nimport qualified CV.ImageMath as IM\n\nimport C2HSTools\n\n-- Morphological opening\nopenOp :: StructuringElement -> ImageOperation GrayScale D32\nopenOp se = erodeOp se 1 #> dilateOp se 1 \nopen se = unsafeOperate (openOp se) \n-- Morphological closing\ncloseOp :: StructuringElement -> ImageOperation GrayScale D32\ncloseOp se = dilateOp se 1 #> erodeOp se 1 \nclose se = unsafeOperate (closeOp se) \n\ngeodesic :: Image GrayScale D32 -> ImageOperation GrayScale D32 -> ImageOperation GrayScale D32\ngeodesic mask op = op #> IM.limitToOp mask\n\nblackTopHat size i = unsafePerformIO $ do\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) rectShape\n x <- runImageOperation i (closeOp se)\n return $ x `IM.sub` i\n\nwhiteTopHat size i = unsafePerformIO $ do\n let se = structuringElement \n (size,size) (size `div` 2, size `div` 2) rectShape\n x <- runImageOperation i (openOp se)\n return $ i `IM.sub` x\n\nbasicSE = structuringElement (3,3) (1,1) rectShape\nbigSE = structuringElement (9,9) (4,4) rectShape\n\n---------- Low level wrapper\nrectShape = 0\ncrossShape = 1\nellipseShape = 2\ncustomShape = 100\n\n{#pointer *IplConvKernel as ConvKernel foreign newtype#}\n\ntype StructuringElement = ConvKernel\n\nforeign import ccall \"& wrapReleaseStructuringElement\" \n releaseSE :: FinalizerPtr ConvKernel\n\n\n-- Check morphology element\nisGoodSE s@(w,h) d@(x,y) | x>=0 && y>=0 \n && w>=0 && h>=0\n && x\n {#call cvCreateStructuringElementEx#}\n w h x y (fromIntegral customShape) arr\n fptr <- newForeignPtr releaseSE iptr\n return (ConvKernel fptr)\n\n{#fun cvErode as erosion \n {withGenBareImage* `BareImage'\n ,withGenBareImage* `BareImage'\n ,withConvKernel* `ConvKernel'\n ,`Int'} -> `()' #}\n{#fun cvDilate as dilation \n {withGenBareImage* `BareImage'\n ,withGenBareImage* `BareImage'\n ,withConvKernel* `ConvKernel'\n ,`Int'} -> `()' #}\n\n\nerodeOp se count = ImgOp $ \\(S img) -> erosion img img se count\ndilateOp se count = ImgOp $ \\(S img) -> dilation img img se count\n\nerode se count i = unsafeOperate (erodeOp se count) i\ndilate se count i = unsafeOperate (dilateOp se count) i\n\n \nerode' se count img = withImage img $ \\image ->\n withConvKernel se $ \\ck ->\n {#call cvErode#} (castPtr image) \n (castPtr image) \n ck count\n \ndilate' se count img = withImage img $ \\image ->\n withConvKernel se $ \\ck ->\n {#call cvDilate#} (castPtr image) \n (castPtr image) \n ck count\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"3ed22c5e13b08842659803fd96d0d3274f257f47","subject":"run in constant space, by using a strict fold (as before)","message":"run in constant space, by using a strict fold (as before)\n\nIgnore-this: d713170477c6c97d023420d8454706af\n\ndarcs-hash:20090916054719-9241b-c83c4d4de5e7615ad30a612456c640afdacad505.gz\n","repos":"tmcdonell\/hfx,tmcdonell\/hfx,tmcdonell\/hfx","old_file":"src\/Sequest.chs","new_file":"src\/Sequest.chs","new_contents":"{-# LANGUAGE CPP, ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Sequest\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- An implementation of the SEQUEST algorithm for fast cross-correlation based\n-- identification of protein sequences.\n--\n--\n-- References:\n--\n-- [1] J. K. Eng, B. Fischer, J. Grossmann, and M. J. MacCoss. \"A fast sequest\n-- cross correlation algorithm.\" Journal of Proteome Research,\n-- 7(10):4598-4602, 2008.\n--\n-- [2] J. K. Eng, A. L. McCormack, and I. John R. Yates. \"An approach to\n-- correlate tandem mass spectral data of peptides with amino acid sequences\n-- in a protein database.\" Journal of the American Society for Mass\n-- Spectrometry, 5(11):976-989, November 1994.\n--\n--------------------------------------------------------------------------------\n\nmodule Sequest\n (\n Match(..),\n MatchCollection,\n searchForMatches\n )\n where\n\n#include \"kernels\/kernels.h\"\n\nimport Mass\nimport Config\nimport Protein\nimport Spectrum\nimport IonSeries\n\nimport Data.List\nimport Data.Maybe\n\nimport C2HS\nimport Foreign.CUDA (DevicePtr, withDevicePtr)\nimport qualified Foreign.CUDA as G\n\n\n--------------------------------------------------------------------------------\n-- Data Structures\n--------------------------------------------------------------------------------\n\ntype MatchCollection = [Match]\n\n--\n-- A structure to store the result of a peptide\/spectrum similarity test\n--\ndata Match = Match\n {\n candidate :: Peptide, -- The fragment that was examined\n scoreXC :: Float -- Sequest cross-correlation score\n-- scoreSP :: (Int, Int) -- Matched ions \/ total ions\n }\n deriving (Eq, Show)\n\n\n--------------------------------------------------------------------------------\n-- Database search\n--------------------------------------------------------------------------------\n\n--\n-- Left fold with strict accumulator and monadic operator\n--\nfoldlM' :: Monad m => (a -> b -> m a) -> a -> [b] -> m a\nfoldlM' f z0 xs0 = go z0 xs0\n where go z [] = return z\n go z (x:xs) = do z' <- f z x\n z' `seq` go z' xs\n\n\n--\n-- Search the database for amino acid sequences within a defined mass tolerance.\n-- Only peptides which fall within this range will be considered.\n--\nsearchForMatches :: ConfigParams -> ProteinDatabase -> Spectrum -> IO MatchCollection\nsearchForMatches cp database spec = do\n specExp <- buildExpSpecXCorr cp spec\n finish `fmap` foldlM' record nomatch [ score specExp peptide |\n protein <- candidates database,\n peptide <- fragments protein\n ]\n where\n specThry b = buildThrySpecXCorr cp b (round (charge spec))\n candidates = findCandidates cp spec . map (digestProtein cp)\n finish = reverse . catMaybes\n\n record l = fmap $ tail . flip (insertBy cmp) l . Just\n n = max (numMatches cp) (numMatchesDetail cp)\n nomatch = replicate n Nothing\n\n score e p = Match p `fmap` (specThry (bnds e) p >>= sequestXC cp e)\n\n bnds (XCorrSpecExp b _) = b\n cmp (Just x) (Just y) = compare (scoreXC x) (scoreXC y)\n cmp _ _ = GT\n\n\n#if 0\nsearchForMatches :: ConfigParams -> ProteinDatabase -> Spectrum -> MatchCollection\nsearchForMatches cp database spec = finish $\n foldl' record nomatch [ score peptide |\n protein <- candidates database,\n peptide <- fragments protein\n ]\n where\n specExp = buildExpSpecXCorr cp spec\n specThry = buildThrySpecXCorr cp (charge spec)\n candidates = findCandidates cp spec . map (digestProtein cp)\n finish = reverse . catMaybes\n\n record l = tail . flip (insertBy cmp) l . Just\n n = max (numMatches cp) (numMatchesDetail cp)\n nomatch = replicate n Nothing\n\n score p = Match {\n scoreXC = sequestXC cp spec specExp (specThry p),\n candidate = p\n }\n\n cmp (Just x) (Just y) = compare (scoreXC x) (scoreXC y)\n cmp _ _ = GT\n#endif\n\n\n--\n-- Search the protein database for candidate peptides within the specified mass\n-- tolerance that should be examined by spectral cross-correlation.\n--\nfindCandidates :: ConfigParams -> Spectrum -> ProteinDatabase -> ProteinDatabase\nfindCandidates cp spec =\n filter (not.null.fragments) . map (\\p -> p {fragments = filter inrange (fragments p)})\n where\n inrange p = (mass - limit) <= pmass p && pmass p <= (mass + limit)\n mass = (precursor spec * charge spec) - ((charge spec * massH) - 1)\n limit = massTolerance cp\n\n\n--------------------------------------------------------------------------------\n-- Scoring\n--------------------------------------------------------------------------------\n\n--\n-- Score a peptide against the observed intensity spectrum. The sequest cross\n-- correlation is the dot product between the theoretical representation and the\n-- preprocessed experimental spectra.\n--\nsequestXC :: ConfigParams -> XCorrSpecExp -> XCorrSpecThry -> IO Float\nsequestXC _cp (XCorrSpecExp (m,n) d_exp) (XCorrSpecThry _ d_thry) =\n do\n G.allocaBytes bytes $ \\d_xs -> do\n zipWith_timesif d_thry d_exp d_xs len\n fold_plusf d_xs len >>= \\x -> return (x \/ 10000)\n where\n len = (n-m)\n bytes = fromIntegral len * fromIntegral (sizeOf (undefined::CFloat))\n\n\n{# fun unsafe zipWith_timesif\n { withDevicePtr* `DevicePtr CInt' ,\n withDevicePtr* `DevicePtr CFloat' ,\n withDevicePtr* `DevicePtr CFloat' ,\n `Int' } -> `()' #}\n\n{# fun unsafe fold_plusf\n { withDevicePtr* `DevicePtr CFloat' ,\n `Int' } -> `Float' #}\n\n\n#if 0\n--\n-- Explicitly de-forested array dot product [P. Walder, Deforestation, 1988]\n--\ndot :: (Ix a, Num a, Num e) => Array a e -> Array a e -> e\ndot v w = loop m 0\n where\n (m,n) = bounds v\n loop i acc | i > n = acc\n | otherwise = loop (i+1) (v!i * w!i + acc)\n\n--\n-- Score a peptide against the observed intensity spectrum. The sequest cross\n-- correlation is the dot product between the theoretical representation and the\n-- preprocessed experimental spectra.\n--\nsequestXC :: ConfigParams -> Spectrum -> XCorrSpecExp -> XCorrSpecThry -> Float\nsequestXC cp spec v sv = (dot v w) \/ 10000\n where\n w = accumArray max 0 bnds [(bin i,e) | (i,e) <- sv, inRange bnds (bin i)]\n bin mz = round (mz \/ width)\n width = if aaMassTypeMono cp then 1.0005079 else 1.0011413\n\n cutoff = 50 + precursor spec * charge spec\n (m,n) = bounds v\n bnds = (m, min n (bin cutoff))\n#endif\n\n","old_contents":"{-# LANGUAGE CPP, ForeignFunctionInterface #-}\n--------------------------------------------------------------------------------\n-- |\n-- Module : Sequest\n-- Copyright : (c) 2009 Trevor L. McDonell\n-- License : BSD\n--\n-- An implementation of the SEQUEST algorithm for fast cross-correlation based\n-- identification of protein sequences.\n--\n--\n-- References:\n--\n-- [1] J. K. Eng, B. Fischer, J. Grossmann, and M. J. MacCoss. \"A fast sequest\n-- cross correlation algorithm.\" Journal of Proteome Research,\n-- 7(10):4598-4602, 2008.\n--\n-- [2] J. K. Eng, A. L. McCormack, and I. John R. Yates. \"An approach to\n-- correlate tandem mass spectral data of peptides with amino acid sequences\n-- in a protein database.\" Journal of the American Society for Mass\n-- Spectrometry, 5(11):976-989, November 1994.\n--\n--------------------------------------------------------------------------------\n\nmodule Sequest\n (\n Match(..),\n MatchCollection,\n searchForMatches\n )\n where\n\n#include \"kernels\/kernels.h\"\n\nimport Mass\nimport Config\nimport Protein\nimport Spectrum\nimport IonSeries\n\nimport Data.List\nimport Data.Maybe\n\nimport C2HS\nimport Foreign.CUDA (DevicePtr, withDevicePtr)\nimport qualified Foreign.CUDA as G\n\n\n--------------------------------------------------------------------------------\n-- Data Structures\n--------------------------------------------------------------------------------\n\ntype MatchCollection = [Match]\n\n--\n-- A structure to store the result of a peptide\/spectrum similarity test\n--\ndata Match = Match\n {\n candidate :: Peptide, -- The fragment that was examined\n scoreXC :: Float -- Sequest cross-correlation score\n-- scoreSP :: (Int, Int) -- Matched ions \/ total ions\n }\n deriving (Eq, Show)\n\n\n--------------------------------------------------------------------------------\n-- Database search\n--------------------------------------------------------------------------------\n\n--\n-- Search the database for amino acid sequences within a defined mass tolerance.\n-- Only peptides which fall within this range will be considered.\n--\nsearchForMatches :: ConfigParams -> ProteinDatabase -> Spectrum -> IO MatchCollection\nsearchForMatches cp database spec = do\n specExp <- buildExpSpecXCorr cp spec\n scores <- sequence [ score specExp peptide |\n protein <- candidates database,\n peptide <- fragments protein\n ]\n\n return . finish $ foldl' record nomatch scores\n where\n specThry b = buildThrySpecXCorr cp b (round (charge spec))\n candidates = findCandidates cp spec . map (digestProtein cp)\n finish = reverse . catMaybes\n\n record l = tail . flip (insertBy cmp) l . Just\n n = max (numMatches cp) (numMatchesDetail cp)\n nomatch = replicate n Nothing\n\n score e p = Match p `fmap` (specThry (bnds e) p >>= sequestXC cp e)\n\n bnds (XCorrSpecExp b _) = b\n cmp (Just x) (Just y) = compare (scoreXC x) (scoreXC y)\n cmp _ _ = GT\n\n\n#if 0\nsearchForMatches :: ConfigParams -> ProteinDatabase -> Spectrum -> MatchCollection\nsearchForMatches cp database spec = finish $\n foldl' record nomatch [ score peptide |\n protein <- candidates database,\n peptide <- fragments protein\n ]\n where\n specExp = buildExpSpecXCorr cp spec\n specThry = buildThrySpecXCorr cp (charge spec)\n candidates = findCandidates cp spec . map (digestProtein cp)\n finish = reverse . catMaybes\n\n record l = tail . flip (insertBy cmp) l . Just\n n = max (numMatches cp) (numMatchesDetail cp)\n nomatch = replicate n Nothing\n\n score p = Match {\n scoreXC = sequestXC cp spec specExp (specThry p),\n candidate = p\n }\n\n cmp (Just x) (Just y) = compare (scoreXC x) (scoreXC y)\n cmp _ _ = GT\n#endif\n\n\n--\n-- Search the protein database for candidate peptides within the specified mass\n-- tolerance that should be examined by spectral cross-correlation.\n--\nfindCandidates :: ConfigParams -> Spectrum -> ProteinDatabase -> ProteinDatabase\nfindCandidates cp spec =\n filter (not.null.fragments) . map (\\p -> p {fragments = filter inrange (fragments p)})\n where\n inrange p = (mass - limit) <= pmass p && pmass p <= (mass + limit)\n mass = (precursor spec * charge spec) - ((charge spec * massH) - 1)\n limit = massTolerance cp\n\n\n--------------------------------------------------------------------------------\n-- Scoring\n--------------------------------------------------------------------------------\n\n--\n-- Score a peptide against the observed intensity spectrum. The sequest cross\n-- correlation is the dot product between the theoretical representation and the\n-- preprocessed experimental spectra.\n--\nsequestXC :: ConfigParams -> XCorrSpecExp -> XCorrSpecThry -> IO Float\nsequestXC _cp (XCorrSpecExp (m,n) d_exp) (XCorrSpecThry _ d_thry) =\n do\n G.allocaBytes bytes $ \\d_xs -> do\n zipWith_timesif d_thry d_exp d_xs len\n fold_plusf d_xs len >>= \\x -> return (x \/ 10000)\n where\n len = (n-m)\n bytes = fromIntegral len * fromIntegral (sizeOf (undefined::CFloat))\n\n\n{# fun unsafe zipWith_timesif\n { withDevicePtr* `DevicePtr CInt' ,\n withDevicePtr* `DevicePtr CFloat' ,\n withDevicePtr* `DevicePtr CFloat' ,\n `Int' } -> `()' #}\n\n{# fun unsafe fold_plusf\n { withDevicePtr* `DevicePtr CFloat' ,\n `Int' } -> `Float' #}\n\n\n#if 0\n--\n-- Explicitly de-forested array dot product [P. Walder, Deforestation, 1988]\n--\ndot :: (Ix a, Num a, Num e) => Array a e -> Array a e -> e\ndot v w = loop m 0\n where\n (m,n) = bounds v\n loop i acc | i > n = acc\n | otherwise = loop (i+1) (v!i * w!i + acc)\n\n--\n-- Score a peptide against the observed intensity spectrum. The sequest cross\n-- correlation is the dot product between the theoretical representation and the\n-- preprocessed experimental spectra.\n--\nsequestXC :: ConfigParams -> Spectrum -> XCorrSpecExp -> XCorrSpecThry -> Float\nsequestXC cp spec v sv = (dot v w) \/ 10000\n where\n w = accumArray max 0 bnds [(bin i,e) | (i,e) <- sv, inRange bnds (bin i)]\n bin mz = round (mz \/ width)\n width = if aaMassTypeMono cp then 1.0005079 else 1.0011413\n\n cutoff = 50 + precursor spec * charge spec\n (m,n) = bounds v\n bnds = (m, min n (bin cutoff))\n#endif\n\n","returncode":0,"stderr":"","license":"bsd-3-clause","lang":"C2hs Haskell"}
{"commit":"3ee910134057991ec7b0f5aeca53c19653b60129","subject":"error when cuddMakeTreeNode fails","message":"error when cuddMakeTreeNode fails\n","repos":"maweki\/haskell_cudd,adamwalker\/haskell_cudd","old_file":"CuddReorder.chs","new_file":"CuddReorder.chs","new_contents":"{-#LANGUAGE ForeignFunctionInterface #-}\n\nmodule CuddReorder where\n\nimport System.IO\nimport Foreign\nimport Foreign.Ptr\nimport Foreign.C.Types\nimport Foreign.C.String\nimport Foreign.ForeignPtr\nimport Foreign.Marshal.Array\nimport Foreign.Marshal.Utils\nimport Control.Monad\n\nimport CuddInternal\nimport CuddHook\n\n#include \n#include